BERT
概述
BERT模型由Jacob Devlin、Ming-Wei Chang、Kenton Lee和Kristina Toutanova在BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding中提出。它是一个双向变压器,通过结合掩码语言建模目标和下一句预测在多伦多书籍语料库和维基百科组成的大规模语料库上进行预训练。
论文的摘要如下:
我们介绍了一种新的语言表示模型,称为BERT,它代表来自变压器的双向编码器表示。与最近的语言表示模型不同,BERT旨在通过在所有层中联合调节左右上下文,从未标记的文本中预训练深度双向表示。因此,预训练的BERT模型只需一个额外的输出层即可微调,以创建用于广泛任务的最先进模型,例如问答和语言推理,而无需进行大量的任务特定架构修改。
BERT在概念上简单,但在实证上非常强大。它在十一个自然语言处理任务中取得了新的最先进结果,包括将GLUE分数推至80.5%(绝对提高了7.7个百分点),MultiNLI准确率至86.7%(绝对提高了4.6个百分点),SQuAD v1.1问答测试F1至93.2(绝对提高了1.5个百分点)以及SQuAD v2.0测试F1至83.1(绝对提高了5.1个百分点)。
使用提示
BERT 是一个带有绝对位置嵌入的模型,因此通常建议在右侧而不是左侧填充输入。
BERT 是通过掩码语言建模(MLM)和下一句预测(NSP)目标进行训练的。它在预测掩码标记和一般自然语言理解(NLU)方面非常有效,但在文本生成方面并不最优。
通过使用随机掩码来破坏输入,更准确地说,在预训练期间,给定百分比的标记(通常为15%)被以下方式掩码:
- a special mask token with probability 0.8
- a random token different from the one masked with probability 0.1
- the same token with probability 0.1
模型必须预测原始句子,但还有第二个目标:输入是两个句子A和B(中间有一个分隔符)。有50%的概率,这两个句子在语料库中是连续的,剩下的50%它们是不相关的。模型需要预测这两个句子是否是连续的。
使用缩放点积注意力 (SDPA)
PyTorch 包含一个原生的缩放点积注意力(SDPA)操作符,作为 torch.nn.functional
的一部分。这个函数
包含了几种实现,可以根据输入和使用的硬件进行应用。更多信息请参阅
官方文档
或 GPU 推理
页面。
默认情况下,当有可用实现时,SDPA 用于 torch>=2.1.1
,但你也可以在 from_pretrained()
中设置 attn_implementation="sdpa"
来明确请求使用 SDPA。
from transformers import BertModel
model = BertModel.from_pretrained("bert-base-uncased", torch_dtype=torch.float16, attn_implementation="sdpa")
...
为了获得最佳加速效果,我们建议以半精度加载模型(例如 torch.float16
或 torch.bfloat16
)。
在本地基准测试(A100-80GB,CPUx12,RAM 96.6GB,PyTorch 2.2.0,操作系统 Ubuntu 22.04)中使用float16
时,我们在训练和推理过程中看到了以下加速效果。
训练
batch_size | seq_len | 每批次时间(eager - 秒) | 每批次时间(sdpa - 秒) | 加速百分比 (%) | Eager 峰值内存 (MB) | sdpa 峰值内存 (MB) | 内存节省百分比 (%) |
---|---|---|---|---|---|---|---|
4 | 256 | 0.023 | 0.017 | 35.472 | 939.213 | 764.834 | 22.800 |
4 | 512 | 0.023 | 0.018 | 23.687 | 1970.447 | 1227.162 | 60.569 |
8 | 256 | 0.023 | 0.018 | 23.491 | 1594.295 | 1226.114 | 30.028 |
8 | 512 | 0.035 | 0.025 | 43.058 | 3629.401 | 2134.262 | 70.054 |
16 | 256 | 0.030 | 0.024 | 25.583 | 2874.426 | 2134.262 | 34.680 |
16 | 512 | 0.064 | 0.044 | 46.223 | 6964.659 | 3961.013 | 75.830 |
推理
batch_size | seq_len | 每个令牌的延迟 eager (毫秒) | 每个令牌的延迟 SDPA (毫秒) | 加速 (%) | 内存 eager (MB) | 内存 BT (MB) | 内存节省 (%) |
---|---|---|---|---|---|---|---|
1 | 128 | 5.736 | 4.987 | 15.022 | 282.661 | 282.924 | -0.093 |
1 | 256 | 5.689 | 4.945 | 15.055 | 298.686 | 298.948 | -0.088 |
2 | 128 | 6.154 | 4.982 | 23.521 | 314.523 | 314.785 | -0.083 |
2 | 256 | 6.201 | 4.949 | 25.303 | 347.546 | 347.033 | 0.148 |
4 | 128 | 6.049 | 4.987 | 21.305 | 378.895 | 379.301 | -0.107 |
4 | 256 | 6.285 | 5.364 | 17.166 | 443.209 | 444.382 | -0.264 |
资源
一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用BERT。如果您有兴趣提交资源以包含在此处,请随时打开一个Pull Request,我们将对其进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
- 一篇关于BERT文本分类在不同语言中的应用的博客文章。
- 一个用于微调BERT(及其同类)进行多标签文本分类的笔记本。
- 一个关于如何使用PyTorch微调BERT进行多标签分类的笔记本。🌎
- 一个关于如何使用BERT进行摘要的EncoderDecoder模型预热启动的笔记本。
- BertForSequenceClassification 由这个 示例脚本 和 笔记本 支持。
- TFBertForSequenceClassification 由这个 示例脚本 和 笔记本 支持。
- FlaxBertForSequenceClassification 由这个 示例脚本 和 笔记本 支持。
- 文本分类任务指南
- 一篇关于如何使用Hugging Face Transformers与Keras:微调非英语BERT进行命名实体识别的博客文章。
- 一个用于微调BERT进行命名实体识别的笔记本,在标记化过程中仅使用每个单词的第一个字片。要将单词的标签传播到所有字片,请参阅此版本的笔记本。
- BertForTokenClassification 由这个 示例脚本 和 笔记本 支持。
- TFBertForTokenClassification 由这个 示例脚本 和 笔记本 支持。
- FlaxBertForTokenClassification 由这个 example script 支持。
- Token classification 🤗 Hugging Face 课程的章节。
- Token分类任务指南
- BertForMaskedLM 由这个 示例脚本 和 笔记本 支持。
- TFBertForMaskedLM 由这个 示例脚本 和 笔记本 支持。
- FlaxBertForMaskedLM 由这个 示例脚本 和 笔记本 支持。
- Masked language modeling 🤗 Hugging Face 课程的章节。
- Masked language modeling task guide
- BertForQuestionAnswering 由这个 示例脚本 和 笔记本 支持。
- TFBertForQuestionAnswering 由这个 示例脚本 和 笔记本 支持。
- FlaxBertForQuestionAnswering 由这个 example script 支持。
- Question answering 章节来自 🤗 Hugging Face 课程。
- 问答任务指南
多项选择
- BertForMultipleChoice 由这个 示例脚本 和 笔记本 支持。
- TFBertForMultipleChoice 由这个 示例脚本 和 笔记本 支持。
- 多项选择任务指南
⚡️ 推理
- 一篇关于如何使用Hugging Face Transformers和AWS Inferentia加速BERT推理的博客文章。
- 一篇关于如何在GPU上使用DeepSpeed-Inference加速BERT推理的博客文章。
⚙️ 预训练
🚀 部署
- 一篇关于如何使用Convert Transformers to ONNX with Hugging Face Optimum的博客文章。
- 一篇关于如何在AWS上Setup Deep Learning environment for Hugging Face Transformers with Habana Gaudi的博客文章。
- 一篇关于使用Hugging Face Transformers、Amazon SageMaker和Terraform模块自动扩展BERT的博客文章。
- 一篇关于Serverless BERT with HuggingFace, AWS Lambda, and Docker的博客文章。
- 一篇关于Hugging Face Transformers BERT fine-tuning using Amazon SageMaker and Training Compiler的博客文章。
- 一篇关于使用Transformers和Amazon SageMaker进行BERT任务特定知识蒸馏的博客文章。
BertConfig
类 transformers.BertConfig
< source >( vocab_size = 30522 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.1 attention_probs_dropout_prob = 0.1 max_position_embeddings = 512 type_vocab_size = 2 initializer_range = 0.02 layer_norm_eps = 1e-12 pad_token_id = 0 position_embedding_type = 'absolute' use_cache = True classifier_dropout = None **kwargs )
参数
- vocab_size (
int
, 可选, 默认为 30522) — BERT模型的词汇表大小。定义了调用BertModel或TFBertModel时传递的inputs_ids
可以表示的不同标记的数量。 - hidden_size (
int
, optional, 默认为 768) — 编码器层和池化层的维度。 - num_hidden_layers (
int
, 可选, 默认为 12) — Transformer 编码器中的隐藏层数量。 - num_attention_heads (
int
, optional, defaults to 12) — Transformer编码器中每个注意力层的注意力头数。 - intermediate_size (
int
, optional, 默认为 3072) — Transformer 编码器中“中间”(通常称为前馈)层的维度。 - hidden_act (
str
或Callable
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, optional, 默认为 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, optional, defaults to 0.1) — 注意力概率的丢弃比例。 - max_position_embeddings (
int
, optional, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512、1024 或 2048)。 - type_vocab_size (
int
, 可选, 默认为 2) — 调用 BertModel 或 TFBertModel 时传递的token_type_ids
的词汇大小. - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。 - layer_norm_eps (
float
, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。 - position_embedding_type (
str
, optional, 默认为"absolute"
) — 位置嵌入的类型。选择"absolute"
,"relative_key"
,"relative_key_query"
中的一个。对于 位置嵌入,使用"absolute"
。有关"relative_key"
的更多信息,请参阅 Self-Attention with Relative Position Representations (Shaw et al.)。 有关"relative_key_query"
的更多信息,请参阅 Improve Transformer Models with Better Relative Position Embeddings (Huang et al.) 中的 Method 4。 - is_decoder (
bool
, 可选, 默认为False
) — 模型是否用作解码器。如果为False
,则模型用作编码器。 - use_cache (
bool
, 可选, 默认为True
) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)。仅在config.is_decoder=True
时相关。 - classifier_dropout (
float
, optional) — 分类头的丢弃比率。
这是用于存储BertModel或TFBertModel配置的配置类。它用于根据指定的参数实例化BERT模型,定义模型架构。使用默认值实例化配置将产生与BERT google-bert/bert-base-uncased架构类似的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import BertConfig, BertModel
>>> # Initializing a BERT google-bert/bert-base-uncased style configuration
>>> configuration = BertConfig()
>>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
>>> model = BertModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
BertTokenizer
类 transformers.BertTokenizer
< 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
, 可选, 默认为True
) — 是否在WordPiece之前进行基本的分词。 - never_split (
Iterable
, 可选) — 在分词过程中永远不会被分割的标记集合。仅在do_basic_tokenize=True
- unk_token (
str
, optional, defaults to"[UNK]"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。 - sep_token (
str
, optional, defaults to"[SEP]"
) — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。 - pad_token (
str
, optional, defaults to"[PAD]"
) — 用于填充的标记,例如在批处理不同长度的序列时使用。 - cls_token (
str
, 可选, 默认为"[CLS]"
) — 用于序列分类的分类器标记(对整个序列进行分类,而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。 - mask_token (
str
, optional, defaults to"[MASK]"
) — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。 - tokenize_chinese_chars (
bool
, optional, defaults toTrue
) — Whether or not to tokenize Chinese characters.这可能应该为日语停用(参见此 issue)。
- strip_accents (
bool
, optional) — 是否去除所有重音符号。如果未指定此选项,则将由lowercase
的值决定(如原始BERT中所示)。 - clean_up_tokenization_spaces (
bool
, 可选, 默认为True
) — 是否在解码后清理空格,清理包括移除可能的额外空格等潜在问题。
构建一个BERT分词器。基于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]
通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。BERT序列的格式如下:
- 单一序列:
[CLS] X [SEP]
- 序列对:
[CLS] A [SEP] B [SEP]
get_special_tokens_mask
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) → List[int]
从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model
方法添加特殊标记时,会调用此方法。
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递给序列对分类任务的两个序列中创建一个掩码。一个BERT序列
如果 token_ids_1
是 None
,此方法仅返回掩码的第一部分(0s)。
BertTokenizerFast
类 transformers.BertTokenizerFast
< source >( 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
) — 是否在分词时将输入转换为小写。 - unk_token (
str
, optional, defaults to"[UNK]"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。 - sep_token (
str
, optional, defaults to"[SEP]"
) — 分隔符标记,用于从多个序列构建一个序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。 - pad_token (
str
, optional, defaults to"[PAD]"
) — 用于填充的标记,例如在批处理不同长度的序列时使用。 - cls_token (
str
, 可选, 默认为"[CLS]"
) — 用于序列分类的分类器标记(对整个序列进行分类,而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。 - mask_token (
str
, optional, defaults to"[MASK]"
) — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。 - clean_text (
bool
, optional, defaults toTrue
) — 是否在分词前通过移除任何控制字符并用经典空格替换所有空格来清理文本。 - tokenize_chinese_chars (
bool
, 可选, 默认为True
) — 是否对中文字符进行分词。对于日语,可能需要停用此功能(参见 此问题)。 - strip_accents (
bool
, 可选) — 是否去除所有重音符号。如果未指定此选项,则将由lowercase
的值决定(如原始BERT中所示)。 - wordpieces_prefix (
str
, optional, defaults to"##"
) — 子词的前缀。
构建一个“快速”的BERT分词器(由HuggingFace的tokenizers库支持)。基于WordPiece。
这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。
build_inputs_with_special_tokens
< source >( token_ids_0 token_ids_1 = 无 ) → List[int]
通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。BERT序列的格式如下:
- 单一序列:
[CLS] X [SEP]
- 序列对:
[CLS] A [SEP] B [SEP]
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递给序列对分类任务的两个序列中创建一个掩码。一个BERT序列
如果 token_ids_1
是 None
,此方法仅返回掩码的第一部分(0s)。
TFBertTokenizer
类 transformers.TFBertTokenizer
< source >( vocab_list: typing.List do_lower_case: bool cls_token_id: int = None sep_token_id: int = None pad_token_id: int = None padding: str = 'longest' truncation: bool = True max_length: int = 512 pad_to_multiple_of: int = None return_token_type_ids: bool = True return_attention_mask: bool = True use_fast_bert_tokenizer: bool = True **tokenizer_kwargs )
参数
- vocab_list (
list
) — 包含词汇的列表。 - do_lower_case (
bool
, optional, defaults toTrue
) — 是否在分词时将输入转换为小写。 - cls_token_id (
str
, 可选, 默认为"[CLS]"
) — 用于序列分类的分类器标记(对整个序列进行分类,而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。 - sep_token_id (
str
, 可选, 默认为"[SEP]"
) — 分隔符令牌,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊令牌构建的序列的最后一个令牌。 - pad_token_id (
str
, 可选, 默认为"[PAD]"
) — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。 - padding (
str
, 默认为"longest"
) — 使用的填充类型。可以是"longest"
,仅在批次中最长的样本上进行填充, 或 `“max_length”`,将所有输入填充到分词器支持的最大长度。 - 截断 (
bool
, 可选, 默认为True
) — 是否将序列截断到最大长度。 - max_length (
int
, 可选, 默认为512
) — 序列的最大长度,用于填充(如果padding
是“max_length”)和/或截断(如果truncation
是True
)。 - pad_to_multiple_of (
int
, optional, defaults toNone
) — 如果设置,序列将被填充为此值的倍数。 - return_token_type_ids (
bool
, 可选, 默认为True
) — 是否返回 token_type_ids. - return_attention_mask (
bool
, optional, defaults toTrue
) — 是否返回attention_mask. - use_fast_bert_tokenizer (
bool
, 可选, 默认为True
) — 如果为 True,将使用 Tensorflow Text 中的 FastBertTokenizer 类。如果为 False,将使用 BertTokenizer 类。BertTokenizer 支持一些额外的选项,但速度较慢且无法导出到 TFLite.
这是一个用于BERT的图内分词器。它应该与其他分词器类似地初始化,使用from_pretrained()
方法。它也可以通过from_tokenizer()
方法初始化,该方法从现有的标准分词器对象导入设置。
与其他的 Hugging Face 分词器不同,图内分词器实际上是 Keras 层,设计为在模型调用时运行,而不是在预处理期间运行。因此,它们的选项比标准的分词器类稍微有限。当你想要创建一个从 tf.string
输入直接到输出的端到端模型时,它们最为有用。
from_pretrained
< source >( pretrained_model_name_or_path: typing.Union[str, os.PathLike] *init_inputs **kwargs )
从预训练的分词器实例化一个TFBertTokenizer
。
from_tokenizer
< source >( tokenizer: PreTrainedTokenizerBase **kwargs )
从现有的Tokenizer
初始化一个TFBertTokenizer
。
Bert 特定输出
类 transformers.models.bert.modeling_bert.BertForPreTrainingOutput
< source >( 损失: typing.Optional[torch.FloatTensor] = None 预测逻辑: FloatTensor = None 序列关系逻辑: FloatTensor = None 隐藏状态: typing.Optional[typing.Tuple[torch.FloatTensor]] = None 注意力: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )
参数
- loss (可选, 当提供
labels
时返回,torch.FloatTensor
形状为(1,)
) — 总损失,作为掩码语言建模损失和下一个序列预测(分类)损失的总和。 - prediction_logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax之前每个词汇标记的分数)。 - seq_relationship_logits (
torch.FloatTensor
of shape(batch_size, 2)
) — 下一个序列预测(分类)头的预测分数(在SoftMax之前的True/False继续的分数)。 - hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.注意力权重在注意力softmax之后,用于计算自注意力头中的加权平均值。
BertForPreTraining的输出类型。
类 transformers.models.bert.modeling_tf_bert.TFBertForPreTrainingOutput
< source >( loss: tf.Tensor | None = None prediction_logits: tf.Tensor = None seq_relationship_logits: tf.Tensor = None hidden_states: Optional[Union[Tuple[tf.Tensor], tf.Tensor]] = None attentions: Optional[Union[Tuple[tf.Tensor], tf.Tensor]] = None )
参数
- prediction_logits (
tf.Tensor
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax之前每个词汇标记的分数)。 - seq_relationship_logits (
tf.Tensor
of shape(batch_size, 2)
) — 下一个序列预测(分类)头的预测分数(在SoftMax之前的真/假继续分数)。 - hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.注意力权重在注意力softmax之后,用于计算自注意力头中的加权平均值。
TFBertForPreTraining的输出类型。
类 transformers.models.bert.modeling_flax_bert.FlaxBertForPreTrainingOutput
< source >( prediction_logits: 数组 = 无 seq_relationship_logits: 数组 = 无 hidden_states: 可选[元组[jax.数组]] = 无 attentions: 可选[元组[jax.数组]] = 无 )
参数
- prediction_logits (
jnp.ndarray
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax之前每个词汇标记的分数)。 - seq_relationship_logits (
jnp.ndarray
of shape(batch_size, 2)
) — 下一个序列预测(分类)头的预测分数(在SoftMax之前的真/假继续分数)。 - hidden_states (
tuple(jnp.ndarray)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple ofjnp.ndarray
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(jnp.ndarray)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple ofjnp.ndarray
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.注意力权重在注意力softmax之后,用于计算自注意力头中的加权平均值。
BertForPreTraining的输出类型。
“返回一个新对象,用新值替换指定的字段。
BertModel
类 transformers.BertModel
< source >( config add_pooling_layer = True )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的Bert模型转换器输出原始隐藏状态,没有任何特定的头部。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
该模型可以表现为编码器(仅具有自注意力)以及解码器,在这种情况下,在自注意力层之间添加了一层交叉注意力,遵循了Ashish Vaswani、Noam Shazeer、Niki Parmar、Jakob Uszkoreit、Llion Jones、Aidan N. Gomez、Lukasz Kaiser和Illia Polosukhin在Attention is all you need中描述的架构。
要作为解码器使用,模型需要使用配置中的is_decoder
参数初始化为True
。要在Seq2Seq模型中使用,模型需要同时使用is_decoder
参数和add_cross_attention
参数初始化为True
;然后在前向传递中需要输入encoder_hidden_states
。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.Tensor] = None encoder_attention_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
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.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - encoder_hidden_states (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 编码器最后一层输出的隐藏状态序列。如果模型配置为解码器,则在交叉注意力中使用。 - encoder_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_length)
, optional) — 用于避免在编码器输入的填充标记索引上执行注意力机制的掩码。如果模型配置为解码器,则在交叉注意力中使用此掩码。掩码值在[0, 1]
中选择:- 1 表示 未掩码 的标记,
- 0 表示 掩码 的标记。
- past_key_values (
tuple(tuple(torch.FloatTensor))
of lengthconfig.n_layers
with each tuple having 4 tensors of shape(batch_size, num_heads, sequence_length - 1, embed_size_per_head)
) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。
返回
transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (
torch.FloatTensor
形状为(batch_size, hidden_size)
) — 序列的第一个标记(分类标记)在经过用于辅助预训练任务的层进一步处理后的最后一层隐藏状态。例如,对于BERT系列模型,这返回经过线性层和tanh激活函数处理后的分类标记。线性层的权重是在预训练期间通过下一句预测(分类)目标训练的。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力softmax后的注意力权重,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
和config.add_cross_attention=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的交叉注意力层的注意力权重,在注意力softmax后,用于计算交叉注意力头中的加权平均值。
-
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) — 由tuple(torch.FloatTensor)
组成的元组,长度为config.n_layers
,每个元组包含2个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量,并且如果config.is_encoder_decoder=True
则还有2个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外张量。包含预先计算的隐藏状态(自注意力块中的键和值,并且如果
config.is_encoder_decoder=True
则在交叉注意力块中),可用于(参见past_key_values
输入)加速顺序解码。
BertModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, BertModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = BertModel.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
BertForPreTraining
类 transformers.BertForPreTraining
< source >( config )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Bert模型在预训练期间完成的两个头部:一个masked language modeling
头部和一个next sentence prediction (classification)
头部。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None next_sentence_label: 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.models.bert.modeling_bert.BertForPreTrainingOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
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.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, optional) — Whether or not to return a ModelOutput instead of a plain tuple.标签(形状为
(batch_size, sequence_length)
的torch.LongTensor
,可选): 用于计算掩码语言建模损失的标签。索引应在[-100, 0, ..., config.vocab_size]
范围内(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略(掩码), 损失仅针对标签在[0, ..., config.vocab_size]
范围内的标记计算。 next_sentence_label(形状为(batch_size,)
的torch.LongTensor
,可选): 用于计算下一句预测(分类)损失的标签。输入应为序列对(参见input_ids
文档字符串)。索引应在[0, 1]
范围内:- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
kwargs (
Dict[str, any]
, optional, defaults to{}
): Used to hide legacy arguments that have been deprecated.
返回
transformers.models.bert.modeling_bert.BertForPreTrainingOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.bert.modeling_bert.BertForPreTrainingOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
loss (可选,当提供
labels
时返回,torch.FloatTensor
形状为(1,)
) — 总损失,作为掩码语言建模损失和下一序列预测 (分类)损失的总和。 -
prediction_logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
seq_relationship_logits (
torch.FloatTensor
形状为(batch_size, 2)
) — 下一序列预测(分类)头的预测分数(SoftMax 之前真/假继续的分数)。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
BertForPreTraining 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, BertForPreTraining
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> prediction_logits = outputs.prediction_logits
>>> seq_relationship_logits = outputs.seq_relationship_logits
BertLMHeadModel
类 transformers.BertLMHeadModel
< source >( config )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Bert 模型,顶部带有language modeling
头,用于 CLM 微调。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.Tensor] = None encoder_attention_mask: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.List[torch.Tensor]] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **loss_kwargs ) → transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
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.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - encoder_hidden_states (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 编码器最后一层输出的隐藏状态序列。如果模型配置为解码器,则在交叉注意力中使用。 - encoder_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在编码器输入的填充标记索引上执行注意力操作的掩码。如果模型配置为解码器,则在交叉注意力中使用此掩码。掩码值在[0, 1]
中选择:- 1 表示 未掩码 的标记,
- 0 表示 掩码 的标记。
- labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算从左到右语言建模损失(下一个词预测)的标签。索引应在[-100, 0, ..., config.vocab_size]
范围内(参见input_ids
文档字符串)。索引设置为-100
的 标记将被忽略(掩码),损失仅计算标签在[0, ..., config.vocab_size]
范围内的标记 - past_key_values (
tuple(tuple(torch.FloatTensor))
of lengthconfig.n_layers
with each tuple having 4 tensors of shape(batch_size, num_heads, sequence_length - 1, embed_size_per_head)
) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。
返回
transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失(用于下一个标记预测)。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的交叉注意力权重,用于计算交叉注意力头中的加权平均值。
-
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 由长度为config.n_layers
的torch.FloatTensor
元组组成的元组,每个元组包含自注意力和交叉注意力层的缓存键, 值状态,如果模型用于编码器-解码器设置。仅在config.is_decoder = True
时相关。包含预计算的隐藏状态(注意力块中的键和值),可用于(参见
past_key_values
输入)以加速顺序解码。
BertLMHeadModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> import torch
>>> from transformers import AutoTokenizer, BertLMHeadModel
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = BertLMHeadModel.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs, labels=inputs["input_ids"])
>>> loss = outputs.loss
>>> logits = outputs.logits
BertForMaskedLM
类 transformers.BertForMaskedLM
< source >( config )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
带有语言建模
顶部的Bert模型。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.Tensor] = None encoder_attention_mask: typing.Optional[torch.Tensor] = None labels: 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.MaskedLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
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.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算掩码语言建模损失的标签。索引应在[-100, 0, ..., config.vocab_size]
范围内(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略(掩码), 损失仅针对标签在[0, ..., config.vocab_size]
范围内的标记进行计算
返回
transformers.modeling_outputs.MaskedLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.MaskedLMOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 掩码语言建模(MLM)损失。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
BertForMaskedLM 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, BertForMaskedLM
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = BertForMaskedLM.from_pretrained("google-bert/bert-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)
'paris'
>>> 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)
0.88
BertForNextSentencePrediction
类 transformers.BertForNextSentencePrediction
< source >( config )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
带有next sentence prediction (classification)
头的Bert模型。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) → transformers.modeling_outputs.NextSentencePredictorOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
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.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回的张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算下一个序列预测(分类)损失的标签。输入应该是一个序列对 (参见input_ids
文档字符串)。索引应该在[0, 1]
范围内:- 0 表示序列 B 是序列 A 的延续,
- 1 表示序列 B 是一个随机序列。
返回
transformers.modeling_outputs.NextSentencePredictorOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.NextSentencePredictorOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供next_sentence_label
时返回) — 下一个序列预测(分类)损失。 -
logits (
torch.FloatTensor
形状为(batch_size, 2)
) — 下一个序列预测(分类)头的预测分数(在 SoftMax 之前的 True/False 继续的分数)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
BertForNextSentencePrediction 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, BertForNextSentencePrediction
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
>>> logits = outputs.logits
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
BertForSequenceClassification
类 transformers.BertForSequenceClassification
< source >( config )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Bert模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于GLUE任务。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: 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.SequenceClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
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.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算序列分类/回归损失的标签。索引应在[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
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
BertForSequenceClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
单标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, BertForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("textattack/bert-base-uncased-yelp-polarity")
>>> model = BertForSequenceClassification.from_pretrained("textattack/bert-base-uncased-yelp-polarity")
>>> 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]
'LABEL_1'
>>> # 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 = BertForSequenceClassification.from_pretrained("textattack/bert-base-uncased-yelp-polarity", num_labels=num_labels)
>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
0.01
多标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, BertForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("textattack/bert-base-uncased-yelp-polarity")
>>> model = BertForSequenceClassification.from_pretrained("textattack/bert-base-uncased-yelp-polarity", 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 = BertForSequenceClassification.from_pretrained(
... "textattack/bert-base-uncased-yelp-polarity", 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
BertForMultipleChoice
类 transformers.BertForMultipleChoice
< source >( config )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Bert模型,顶部带有多项选择分类头(在池化输出之上的线性层和softmax),例如用于RocStories/SWAG任务。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: 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.MultipleChoiceModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, num_choices, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, num_choices, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, num_choices, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算多项选择分类损失的标签。索引应在[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
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
BertForMultipleChoice 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, BertForMultipleChoice
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = BertForMultipleChoice.from_pretrained("google-bert/bert-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."
>>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
>>> encoding = tokenizer([prompt, prompt], [choice0, 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
BertForTokenClassification
类 transformers.BertForTokenClassification
< source >( config )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Bert模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: 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.TokenClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
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.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算令牌分类损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。
返回
transformers.modeling_outputs.TokenClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.TokenClassifierOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
BertForTokenClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, BertForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> model = BertForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> 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
['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC']
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
0.01
BertForQuestionAnswering
类 transformers.BertForQuestionAnswering
< source >( config )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
用于抽取式问答任务(如SQuAD)的Bert模型,顶部带有跨度分类头(在隐藏状态输出之上的线性层,用于计算span start logits
和span end logits
)。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: 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
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
or(batch_size, sequence_length, target_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.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
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.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length
)。序列之外的位置不会被考虑用于计算损失。 - end_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length
)。序列之外的位置不会被考虑用于计算损失。
返回
transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
BertForQuestionAnswering 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, BertForQuestionAnswering
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("deepset/bert-base-cased-squad2")
>>> model = BertForQuestionAnswering.from_pretrained("deepset/bert-base-cased-squad2")
>>> 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)
'a nice puppet'
>>> # 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)
7.41
TFBertModel
类 transformers.TFBertModel
< source >( config: BertConfig add_pooling_layer: bool = True *inputs **kwargs )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的Bert模型转换器输出原始隐藏状态,没有任何特定的头部。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 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函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None encoder_hidden_states: np.ndarray | tf.Tensor | None = None encoder_attention_mask: np.ndarray | tf.Tensor | None = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingAndCrossAttentions 或 tuple(tf.Tensor)
参数
- input_ids (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
orDict[str, np.ndarray]
and each example must have the shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.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.
- token_type_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
np.ndarray
ortf.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.max_position_embeddings - 1]
. - head_mask (
np.ndarray
或tf.Tensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在急切模式下使用,在图模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为 `False“) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。 - encoder_hidden_states (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 编码器最后一层输出的隐藏状态序列。如果模型配置为解码器,则在交叉注意力中使用。 - encoder_attention_mask (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在编码器输入的填充标记索引上执行注意力操作的掩码。如果模型配置为解码器,则在交叉注意力中使用此掩码。掩码值在[0, 1]
中选择:- 1 表示 未掩码 的标记,
- 0 表示 掩码 的标记。
- past_key_values (
Tuple[Tuple[tf.Tensor]]
长度为config.n_layers
) — 包含预计算的注意力块的关键和值隐藏状态。可用于加速解码。 如果使用了past_key_values
,用户可以选择仅输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去的关键值状态提供给此模型的),而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。在训练期间设置为False
,在生成期间设置为True
返回
transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingAndCrossAttentions 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingAndCrossAttentions 或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时),包含根据配置(BertConfig)和输入的各种元素。
-
last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (
tf.Tensor
形状为(batch_size, hidden_size)
) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过线性层和 Tanh 激活函数进一步处理。线性层的权重是在预训练期间通过下一个句子预测(分类)目标训练的。这个输出通常不是输入语义内容的一个好的总结,通常最好对整个输入序列的隐藏状态序列进行平均或池化。
-
past_key_values (
List[tf.Tensor]
, 可选, 当use_cache=True
被传递或当config.use_cache=True
时返回) — 长度为config.n_layers
的tf.Tensor
列表,每个张量的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
。包含预计算的隐藏状态(注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入输出 + 一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型每层输出的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器交叉注意力层的注意力权重,在注意力 softmax 后,用于计算交叉注意力头中的加权平均值。
TFBertModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFBertModel
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = TFBertModel.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)
>>> last_hidden_states = outputs.last_hidden_state
TFBertForPreTraining
类 transformers.TFBertForPreTraining
< source >( config: BertConfig *inputs **kwargs )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
在预训练期间完成的带有两个顶部的Bert模型:
一个masked language modeling
头部和一个next sentence prediction (classification)
头部。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 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函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: 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 next_sentence_label: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.models.bert.modeling_tf_bert.TFBertForPreTrainingOutput 或 tuple(tf.Tensor)
参数
- input_ids (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
orDict[str, np.ndarray]
and each example must have the shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.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.
- token_type_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
np.ndarray
ortf.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.max_position_embeddings - 1]
. - head_mask (
np.ndarray
或tf.Tensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
np.ndarray
或tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为 `False“) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。 - labels (
tf.Tensor
形状为(batch_size, sequence_length)
, 可选) — 用于计算掩码语言建模损失的标签。索引应在[-100, 0, ..., config.vocab_size]
范围内(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略(掩码), 损失仅针对标签在[0, ..., config.vocab_size]
范围内的标记进行计算 - next_sentence_label (
tf.Tensor
of shape(batch_size,)
, optional) — 用于计算下一个序列预测(分类)损失的标签。输入应该是一个序列对 (参见input_ids
文档字符串) 索引应该在[0, 1]
中:- 0 表示序列 B 是序列 A 的延续,
- 1 表示序列 B 是一个随机序列。
- kwargs (
Dict[str, any]
, 可选, 默认为{}
) — 用于隐藏已被弃用的旧参数.
返回
transformers.models.bert.modeling_tf_bert.TFBertForPreTrainingOutput 或 tuple(tf.Tensor)
一个 transformers.models.bert.modeling_tf_bert.TFBertForPreTrainingOutput 或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,具体取决于
配置 (BertConfig) 和输入。
-
prediction_logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
seq_relationship_logits (
tf.Tensor
形状为(batch_size, 2)
) — 下一个序列预测(分类)头的预测分数(SoftMax 之前的真/假继续的分数)。 -
hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFBertForPreTraining 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> import tensorflow as tf
>>> from transformers import AutoTokenizer, TFBertForPreTraining
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = TFBertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
>>> input_ids = tokenizer("Hello, my dog is cute", add_special_tokens=True, return_tensors="tf")
>>> # Batch size 1
>>> outputs = model(input_ids)
>>> prediction_logits, seq_relationship_logits = outputs[:2]
TFBertModelLMHeadModel
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None encoder_hidden_states: np.ndarray | tf.Tensor | None = None encoder_attention_mask: np.ndarray | tf.Tensor | None = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None use_cache: Optional[bool] = 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 **kwargs ) → transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions 或 tuple(tf.Tensor)
返回
transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions 或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时),包含根据配置(BertConfig)和输入的各种元素。
-
loss (
tf.Tensor
形状为(n,)
,可选,其中 n 是非掩码标签的数量,当提供labels
时返回) — 语言建模损失(用于下一个标记预测)。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器交叉注意力层的注意力权重,在注意力 softmax 后,用于计算交叉注意力头中的加权平均值。
-
past_key_values (
List[tf.Tensor]
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) —tf.Tensor
列表,长度为config.n_layers
,每个张量形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含预计算的隐藏状态(注意力块中的键和值),可用于(参见
past_key_values
输入)以加速顺序解码。
encoder_hidden_states (tf.Tensor
形状为 (batch_size, sequence_length, hidden_size)
, 可选):
编码器最后一层输出的隐藏状态序列。如果模型配置为解码器,则在交叉注意力中使用。
encoder_attention_mask (tf.Tensor
形状为 (batch_size, sequence_length)
, 可选):
用于避免在编码器输入的填充标记索引上执行注意力的掩码。如果模型配置为解码器,则在交叉注意力中使用此掩码。掩码值在 [0, 1]
中选择:
- 1 表示 未屏蔽 的标记,
- 0 表示被屏蔽的标记。
past_key_values (Tuple[Tuple[tf.Tensor]]
长度为 config.n_layers
)
包含预计算的注意力块的关键和值隐藏状态。可用于加速解码。
如果使用了 past_key_values
,用户可以选择仅输入最后一个 decoder_input_ids
(那些没有将其过去的关键值状态提供给此模型的)形状为 (batch_size, 1)
,而不是所有形状为 (batch_size, sequence_length)
的 decoder_input_ids
。
use_cache (bool
, 可选, 默认为 True
):
如果设置为 True
,past_key_values
关键值状态将被返回,并可用于加速解码(参见 past_key_values
)。在训练期间设置为 False
,在生成期间设置为 True
。
labels (tf.Tensor
或 np.ndarray
形状为 (batch_size, sequence_length)
, 可选):
用于计算交叉熵分类损失的标签。索引应在 [0, ..., config.vocab_size - 1]
范围内。
示例:
>>> from transformers import AutoTokenizer, TFBertLMHeadModel
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = TFBertLMHeadModel.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)
>>> logits = outputs.logits
TFBertForMaskedLM
类 transformers.TFBertForMaskedLM
< source >( config: BertConfig *inputs **kwargs )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
带有语言建模
顶部的Bert模型。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 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函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: 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 (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
orDict[str, np.ndarray]
and each example must have the shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.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.
- token_type_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
np.ndarray
ortf.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.max_position_embeddings - 1]
. - head_mask (
np.ndarray
或tf.Tensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
np.ndarray
或tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为 `False“) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。 - labels (
tf.Tensor
或np.ndarray
形状为(batch_size, sequence_length)
, 可选) — 用于计算掩码语言建模损失的标签。索引应在[-100, 0, ..., config.vocab_size]
范围内(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略(掩码), 损失仅针对标签在[0, ..., config.vocab_size]
范围内的标记进行计算
返回
transformers.modeling_tf_outputs.TFMaskedLMOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFMaskedLMOutput 或一个 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置(BertConfig)和输入的各种元素。
-
loss (
tf.Tensor
形状为(n,)
,可选,其中 n 是非掩码标签的数量,当提供labels
时返回) — 掩码语言建模(MLM)损失。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFBertForMaskedLM 的前向方法,覆盖了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFBertForMaskedLM
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = TFBertForMaskedLM.from_pretrained("google-bert/bert-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)
>>> tokenizer.decode(predicted_token_id)
'paris'
TFBertForNextSentencePrediction
类 transformers.TFBertForNextSentencePrediction
< source >( config: BertConfig *inputs **kwargs )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
带有next sentence prediction (classification)
头的Bert模型。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 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函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: 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 next_sentence_label: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFNextSentencePredictorOutput 或 tuple(tf.Tensor)
参数
- input_ids (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
orDict[str, np.ndarray]
and each example must have the shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.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.
- token_type_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
np.ndarray
ortf.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.max_position_embeddings - 1]
. - head_mask (
np.ndarray
或tf.Tensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
np.ndarray
或tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。此参数只能在急切模式下使用,在图形模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在急切模式下使用,在图形模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为 `False`) — 是否在训练模式下使用模型(一些模块如 dropout 模块在训练和评估之间有不同的行为)。
返回
transformers.modeling_tf_outputs.TFNextSentencePredictorOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFNextSentencePredictorOutput 或一个由 tf.Tensor
组成的元组(如果
return_dict=False
被传递或当 config.return_dict=False
时),包含根据配置(BertConfig)和输入的各种元素。
-
loss (
tf.Tensor
形状为(n,)
, 可选, 其中 n 是非掩码标签的数量,当提供next_sentence_label
时返回) — 下一句预测损失。 -
logits (
tf.Tensor
形状为(batch_size, 2)
) — 下一序列预测(分类)头的预测分数(在 SoftMax 之前的 True/False 继续的分数)。 -
hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由tf.Tensor
组成的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由tf.Tensor
组成的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFBertForNextSentencePrediction 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> import tensorflow as tf
>>> from transformers import AutoTokenizer, TFBertForNextSentencePrediction
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = TFBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="tf")
>>> logits = model(encoding["input_ids"], token_type_ids=encoding["token_type_ids"])[0]
>>> assert logits[0][0] < logits[0][1] # the next sentence was random
TFBertForSequenceClassification
类 transformers.TFBertForSequenceClassification
< source >( config: BertConfig *inputs **kwargs )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Bert模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于GLUE任务。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 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函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: 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 (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
orDict[str, np.ndarray]
and each example must have the shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.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.
- token_type_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
np.ndarray
ortf.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.max_position_embeddings - 1]
. - head_mask (
np.ndarray
或tf.Tensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
np.ndarray
或tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在急切模式下使用,在图形模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为 `False“) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。 - labels (
tf.Tensor
或np.ndarray
形状为(batch_size,)
, 可选) — 用于计算序列分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。如果config.num_labels == 1
,则计算回归损失(均方损失),如果config.num_labels > 1
,则计算分类损失(交叉熵)。
返回
transformers.modeling_tf_outputs.TFSequenceClassifierOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFSequenceClassifierOutput 或一个 tf.Tensor
的元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,取决于
配置 (BertConfig) 和输入。
-
loss (
tf.Tensor
形状为(batch_size, )
, 可选, 当labels
提供时返回) — 分类(或回归,如果 config.num_labels==1)损失。 -
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
的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFBertForSequenceClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFBertForSequenceClassification
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("ydshieh/bert-base-uncased-yelp-polarity")
>>> model = TFBertForSequenceClassification.from_pretrained("ydshieh/bert-base-uncased-yelp-polarity")
>>> 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])
>>> model.config.id2label[predicted_class_id]
'LABEL_1'
>>> # 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 = TFBertForSequenceClassification.from_pretrained("ydshieh/bert-base-uncased-yelp-polarity", num_labels=num_labels)
>>> labels = tf.constant(1)
>>> loss = model(**inputs, labels=labels).loss
>>> round(float(loss), 2)
0.01
TFBertForMultipleChoice
类 transformers.TFBertForMultipleChoice
< source >( config: BertConfig *inputs **kwargs )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Bert模型,顶部带有多项选择分类头(在池化输出之上的线性层和softmax),例如用于RocStories/SWAG任务。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 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函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: 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 (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
orDict[str, np.ndarray]
and each example must have the shape(batch_size, num_choices, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.Tensor
of shape(batch_size, num_choices, 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.
- token_type_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
. - head_mask (
np.ndarray
或tf.Tensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, num_choices, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。 - 训练 (
bool
, 可选, 默认为 `False`) — 是否在训练模式下使用模型(一些模块如 dropout 模块在训练和评估之间有不同的行为)。 - labels (
tf.Tensor
或np.ndarray
形状为(batch_size,)
, 可选) — 用于计算多项选择分类损失的标签。索引应在[0, ..., num_choices]
范围内, 其中num_choices
是输入张量第二维的大小。(参见上面的input_ids
)
返回
transformers.modeling_tf_outputs.TFMultipleChoiceModelOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFMultipleChoiceModelOutput 或一个由 tf.Tensor
组成的元组(如果
return_dict=False
被传递或当 config.return_dict=False
时),包含根据配置(BertConfig)和输入的各种元素。
-
loss (
tf.Tensor
形状为 (batch_size, ), 可选, 当提供labels
时返回) — 分类损失。 -
logits (
tf.Tensor
形状为(batch_size, num_choices)
) — num_choices 是输入张量的第二维度。(见上面的 input_ids)。分类分数(在 SoftMax 之前)。
-
hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由tf.Tensor
组成的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由tf.Tensor
组成的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力权重在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
TFBertForMultipleChoice 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFBertForMultipleChoice
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = TFBertForMultipleChoice.from_pretrained("google-bert/bert-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
TFBertForTokenClassification
类 transformers.TFBertForTokenClassification
< source >( config: BertConfig *inputs **kwargs )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Bert模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 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函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: 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 (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
orDict[str, np.ndarray]
and each example must have the shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.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.
- token_type_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
np.ndarray
ortf.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.max_position_embeddings - 1]
. - head_mask (
np.ndarray
或tf.Tensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为 `False“) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。 - labels (
tf.Tensor
或np.ndarray
形状为(batch_size, sequence_length)
, 可选) — 用于计算令牌分类损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。
返回
transformers.modeling_tf_outputs.TFTokenClassifierOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFTokenClassifierOutput 或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时),包含根据配置(BertConfig)和输入的各种元素。
-
loss (
tf.Tensor
形状为(n,)
, 可选, 其中 n 是未屏蔽标签的数量,当提供labels
时返回) — 分类损失。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.num_labels)
) — 分类分数(在 SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFBertForTokenClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFBertForTokenClassification
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> model = TFBertForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> 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()]
>>> predicted_tokens_classes
['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC']
TFBertForQuestionAnswering
类 transformers.TFBertForQuestionAnswering
< source >( config: BertConfig *inputs **kwargs )
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
用于抽取式问答任务(如SQuAD)的Bert模型,顶部带有跨度分类头(在隐藏状态输出之上的线性层,用于计算span start logits
和span end logits
)。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 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函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: 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 (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
orDict[str, np.ndarray]
and each example must have the shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.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.
- token_type_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
np.ndarray
ortf.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.max_position_embeddings - 1]
. - head_mask (
np.ndarray
或tf.Tensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为 `False“) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。 - start_positions (
tf.Tensor
或np.ndarray
,形状为(batch_size,)
,可选) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length
)。序列之外的位置不会用于计算损失。 - end_positions (
tf.Tensor
或np.ndarray
,形状为(batch_size,)
,可选) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length
)。序列之外的位置不会用于计算损失。
返回
transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutput 或一个 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置(BertConfig)和输入的各种元素。
-
loss (
tf.Tensor
形状为(batch_size, )
, 可选, 当提供了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
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFBertForQuestionAnswering 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFBertForQuestionAnswering
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("ydshieh/bert-base-cased-squad2")
>>> model = TFBertForQuestionAnswering.from_pretrained("ydshieh/bert-base-cased-squad2")
>>> 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]
>>> tokenizer.decode(predict_answer_tokens)
'a nice puppet'
FlaxBertModel
类 transformers.FlaxBertModel
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
裸的Bert模型转换器输出原始隐藏状态,没有任何特定的头部。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 位置嵌入中每个输入序列标记的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
numpy.ndarray
形状为(batch_size, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPooling 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
last_hidden_state (
jnp.ndarray
形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (
jnp.ndarray
形状为(batch_size, hidden_size)
) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过线性层和Tanh激活函数进一步处理。线性层的权重是在预训练期间通过下一个句子预测(分类)目标进行训练的。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入层的输出,一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力softmax后的注意力权重,用于计算自注意力头中的加权平均值。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertModel
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertModel.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
FlaxBertForPreTraining
类 transformers.FlaxBertForPreTraining
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
Bert模型在预训练期间完成的两个头部:一个masked language modeling
头部和一个next sentence prediction (classification)
头部。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 位置嵌入中每个输入序列标记的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
numpy.ndarray
形状为(batch_size, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.models.bert.modeling_flax_bert.FlaxBertForPreTrainingOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.bert.modeling_flax_bert.FlaxBertForPreTrainingOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
prediction_logits (
jnp.ndarray
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
seq_relationship_logits (
jnp.ndarray
形状为(batch_size, 2)
) — 下一个序列预测(分类)头的预测分数(SoftMax 之前的真/假继续的分数)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertForPreTraining
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
>>> outputs = model(**inputs)
>>> prediction_logits = outputs.prediction_logits
>>> seq_relationship_logits = outputs.seq_relationship_logits
FlaxBertForCausalLM
类 transformers.FlaxBertForCausalLM
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
带有语言建模头部的Bert模型(在隐藏状态输出之上的线性层),例如用于自回归任务。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
numpy.ndarray
形状为(batch_size, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
logits (
jnp.ndarray
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入层的输出 + 一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的交叉注意力权重,用于计算交叉注意力头中的加权平均值。
-
past_key_values (
tuple(tuple(jnp.ndarray))
, 可选, 当传递了use_cache=True
或当config.use_cache=True
时返回) — 由长度为config.n_layers
的jnp.ndarray
元组组成的元组,每个元组包含自注意力和交叉注意力层的缓存键、值 状态,如果模型用于编码器-解码器设置。 仅在config.is_decoder = True
时相关。包含预计算的隐藏状态(注意力块中的键和值),可用于(参见
past_key_values
输入)以加速顺序解码。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertForCausalLM
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertForCausalLM.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
>>> outputs = model(**inputs)
>>> # retrieve logts for next token
>>> next_token_logits = outputs.logits[:, -1]
FlaxBertForMaskedLM
类 transformers.FlaxBertForMaskedLM
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
带有语言建模
顶部的Bert模型。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
numpy.ndarray
形状为(batch_size, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- return_dict (
bool
, optional) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.modeling_flax_outputs.FlaxMaskedLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxMaskedLMOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
logits (
jnp.ndarray
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertForMaskedLM
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertForMaskedLM.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="jax")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
FlaxBertForNextSentencePrediction
类 transformers.FlaxBertForNextSentencePrediction
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
带有next sentence prediction (classification)
头的Bert模型。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
numpy.ndarray
形状为(batch_size, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_flax_outputs.FlaxNextSentencePredictorOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxNextSentencePredictorOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
logits (
jnp.ndarray
形状为(batch_size, 2)
) — 下一个序列预测(分类)头的预测分数(在 SoftMax 之前的 True/False 继续的分数)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入的输出 + 一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertForNextSentencePrediction
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="jax")
>>> outputs = model(**encoding)
>>> logits = outputs.logits
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
FlaxBertForSequenceClassification
类 transformers.FlaxBertForSequenceClassification
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
Bert模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于GLUE任务。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, 可选) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
. - head_mask (
numpy.ndarray
形状为(batch_size, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- 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
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
logits (
jnp.ndarray
形状为(batch_size, config.num_labels)
) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入的输出 + 一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertForSequenceClassification.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
FlaxBertForMultipleChoice
类 transformers.FlaxBertForMultipleChoice
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
Bert模型,顶部带有多项选择分类头(在池化输出之上的线性层和softmax),例如用于RocStories/SWAG任务。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, num_choices, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
numpy.ndarray
of shape(batch_size, num_choices, 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, num_choices, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, num_choices, sequence_length)
, optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
numpy.ndarray
形状为(batch_size, num_choices, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- 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
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
logits (
jnp.ndarray
形状为(batch_size, num_choices)
) — num_choices 是输入张量的第二维度。(见上面的 input_ids)。分类分数(在 SoftMax 之前)。
-
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入的输出 + 一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力权重在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertForMultipleChoice
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertForMultipleChoice.from_pretrained("google-bert/bert-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
FlaxBertForTokenClassification
类 transformers.FlaxBertForTokenClassification
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
Bert模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 位置嵌入中每个输入序列标记的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
numpy.ndarray
形状为(batch_size, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- 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
时),包含各种
元素,具体取决于配置(BertConfig)和输入。
-
logits (
jnp.ndarray
形状为(batch_size, sequence_length, config.num_labels)
) — 分类分数(在 SoftMax 之前)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入层的输出 + 一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力权重在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertForTokenClassification
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertForTokenClassification.from_pretrained("google-bert/bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
FlaxBertForQuestionAnswering
类 transformers.FlaxBertForQuestionAnswering
< source >( config: BertConfig input_shape: 类型.元组 = (1, 1) seed: 整数 = 0 dtype: 数据类型 =
参数
- config (BertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
用于抽取式问答任务(如SQuAD)的Bert模型,顶部带有跨度分类头(在隐藏状态输出之上的线性层,用于计算span start logits
和span end logits
)。
该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。
该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids attention_mask = None token_type_ids = None position_ids = None head_mask = None encoder_hidden_states = None encoder_attention_mask = None params: dict = None dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.
- token_type_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
numpy.ndarray
形状为(batch_size, sequence_length)
,可选) -- 用于屏蔽注意力模块中选定头部的掩码。掩码值在
[0, 1]` 中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_flax_outputs.FlaxQuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxQuestionAnsweringModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,取决于配置(BertConfig)和输入。
-
start_logits (
jnp.ndarray
形状为(batch_size, sequence_length)
) — 跨度开始分数(在 SoftMax 之前)。 -
end_logits (
jnp.ndarray
形状为(batch_size, sequence_length)
) — 跨度结束分数(在 SoftMax 之前)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由jnp.ndarray
组成的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由jnp.ndarray
组成的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力权重在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
FlaxBertPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxBertForQuestionAnswering
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = FlaxBertForQuestionAnswering.from_pretrained("google-bert/bert-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