Transformers 文档

ALBERT

ALBERT

Models Spaces

概述

ALBERT模型由Zhenzhong Lan、Mingda Chen、Sebastian Goodman、Kevin Gimpel、Piyush Sharma和Radu Soricut在ALBERT: A Lite BERT for Self-supervised Learning of Language Representations中提出。它提出了两种参数减少技术,以降低内存消耗并提高BERT的训练速度:

  • 将嵌入矩阵拆分为两个较小的矩阵。
  • 在组之间使用重复的分层。

论文的摘要如下:

在预训练自然语言表示时,增加模型大小通常会提高下游任务的性能。然而,在某些情况下,由于GPU/TPU内存限制、更长的训练时间和意外的模型退化,进一步增加模型变得困难。为了解决这些问题,我们提出了两种参数减少技术,以降低内存消耗并提高BERT的训练速度。全面的实证证据表明,我们提出的方法使得模型比原始BERT具有更好的扩展性。我们还使用了一种自监督损失,专注于建模句子间的一致性,并表明它始终有助于具有多句子输入的下游任务。因此,我们的最佳模型在GLUE、RACE和SQuAD基准测试中建立了新的最先进结果,同时与BERT-large相比具有更少的参数。

该模型由lysandre贡献。该模型的jax版本由kamalkraj贡献。原始代码可以在这里找到。

使用提示

  • ALBERT 是一个具有绝对位置嵌入的模型,因此通常建议在右侧而不是左侧填充输入。
  • ALBERT 使用重复的层,这导致内存占用较小,然而计算成本仍然与具有相同隐藏层数的 BERT 类似架构相似,因为它必须迭代相同数量的(重复)层。
  • 嵌入大小E与隐藏大小H不同,这是合理的,因为嵌入是上下文无关的(一个嵌入向量代表一个标记),而隐藏状态是上下文相关的(一个隐藏状态代表一系列标记),因此H >> E更合理。此外,嵌入矩阵很大,因为它是V x E(V是词汇表大小)。如果E < H,它的参数更少。
  • 层被分组,这些组共享参数(以节省内存)。 下一句预测被替换为句子顺序预测:在输入中,我们有两个连续的句子A和B,我们或者先输入A后输入B,或者先输入B后输入A。模型必须预测它们是否被交换了。

使用缩放点积注意力 (SDPA)

PyTorch 包含一个原生的缩放点积注意力(SDPA)操作符,作为 torch.nn.functional 的一部分。这个函数 包含了几种实现,可以根据输入和使用的硬件进行应用。更多信息请参阅 官方文档GPU 推理 页面。

默认情况下,当有可用实现时,SDPA 用于 torch>=2.1.1,但你也可以在 from_pretrained() 中设置 attn_implementation="sdpa" 来明确请求使用 SDPA。

from transformers import AlbertModel
model = AlbertModel.from_pretrained("albert/albert-base-v1", torch_dtype=torch.float16, attn_implementation="sdpa")
...

为了获得最佳加速效果,我们建议以半精度加载模型(例如 torch.float16torch.bfloat16)。

在本地基准测试(GeForce RTX 2060-8GB,PyTorch 2.3.1,操作系统 Ubuntu 20.04)中使用 float16,我们在训练和推理过程中看到了以下加速效果。

训练100次迭代

batch_size seq_len 每批次时间(eager - 秒) 每批次时间(sdpa - 秒) 加速百分比 (%) Eager 峰值内存 (MB) sdpa 峰值内存 (MB) 内存节省百分比 (%)
2 256 0.028 0.024 14.388 358.411 321.088 11.624
2 512 0.049 0.041 17.681 753.458 602.660 25.022
4 256 0.044 0.039 12.246 679.534 602.660 12.756
4 512 0.090 0.076 18.472 1434.820 1134.140 26.512
8 256 0.081 0.072 12.664 1283.825 1134.140 13.198
8 512 0.170 0.143 18.957 2820.398 2219.695 27.062

使用50批次进行推理

batch_size seq_len 每个令牌的延迟 eager (毫秒) 每个令牌的延迟 SDPA (毫秒) 加速 (%) 内存 eager (MB) 内存 BT (MB) 内存节省 (%)
4 128 0.083 0.071 16.967 48.319 48.45 -0.268
4 256 0.148 0.127 16.37 63.4 63.922 -0.817
4 512 0.31 0.247 25.473 110.092 94.343 16.693
8 128 0.137 0.124 11.102 63.4 63.66 -0.409
8 256 0.271 0.231 17.271 91.202 92.246 -1.132
8 512 0.602 0.48 25.47 186.159 152.564 22.021
16 128 0.252 0.224 12.506 91.202 91.722 -0.567
16 256 0.526 0.448 17.604 148.378 150.467 -1.388
16 512 1.203 0.96 25.365 338.293 271.102 24.784

该模型由lysandre贡献。该模型的jax版本由kamalkraj贡献。原始代码可以在这里找到。

资源

以下部分提供的资源包括官方Hugging Face和社区(由🌎表示)的资源列表,以帮助您开始使用AlBERT。如果您有兴趣提交资源以包含在此处,请随时打开Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。

Text Classification
Token Classification
Fill-Mask
Question Answering

多项选择

AlbertConfig

transformers.AlbertConfig

< >

( vocab_size = 30000 embedding_size = 128 hidden_size = 4096 num_hidden_layers = 12 num_hidden_groups = 1 num_attention_heads = 64 intermediate_size = 16384 inner_group_num = 1 hidden_act = 'gelu_new' hidden_dropout_prob = 0 attention_probs_dropout_prob = 0 max_position_embeddings = 512 type_vocab_size = 2 initializer_range = 0.02 layer_norm_eps = 1e-12 classifier_dropout_prob = 0.1 position_embedding_type = 'absolute' pad_token_id = 0 bos_token_id = 2 eos_token_id = 3 **kwargs )

参数

  • vocab_size (int, 可选, 默认为 30000) — ALBERT 模型的词汇表大小。定义了可以通过调用 AlbertModelTFAlbertModel 时传递的 inputs_ids 表示的不同标记的数量。
  • embedding_size (int, optional, defaults to 128) — 词汇嵌入的维度。
  • hidden_size (int, optional, 默认为 4096) — 编码器层和池化层的维度。
  • num_hidden_layers (int, optional, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_hidden_groups (int, 可选, 默认为 1) — 隐藏层的组数,同一组中的参数是共享的。
  • num_attention_heads (int, optional, 默认为 64) — Transformer 编码器中每个注意力层的注意力头数。
  • intermediate_size (int, optional, 默认为 16384) — Transformer 编码器中“中间”(通常称为前馈)层的维度。
  • inner_group_num (int, 可选, 默认为 1) — 注意力机制和前馈神经网络的内部重复次数。
  • hidden_act (strCallable, 可选, 默认为 "gelu_new") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""silu""gelu_new"
  • hidden_dropout_prob (float, optional, 默认为 0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, optional, defaults to 0) — 注意力概率的丢弃比率。
  • max_position_embeddings (int, optional, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值 (例如,512 或 1024 或 2048)。
  • type_vocab_size (int, 可选, 默认为 2) — 调用 AlbertModelTFAlbertModel 时传递的 token_type_ids 的词汇大小.
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。
  • classifier_dropout_prob (float, optional, defaults to 0.1) — 附加分类器的丢弃比例。
  • position_embedding_type (str, 可选, 默认为 "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.) 中的 方法 4.
  • pad_token_id (int, optional, 默认为 0) — 填充标记 id.
  • bos_token_id (int, optional, 默认为 2) — 流的开始标记 id.
  • eos_token_id (int, optional, defaults to 3) — 流结束标记的ID。

这是用于存储AlbertModelTFAlbertModel配置的配置类。它用于根据指定的参数实例化一个ALBERT模型,定义模型架构。使用默认值实例化配置将产生与ALBERT albert/albert-xxlarge-v2架构类似的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

示例:

>>> from transformers import AlbertConfig, AlbertModel

>>> # Initializing an ALBERT-xxlarge style configuration
>>> albert_xxlarge_configuration = AlbertConfig()

>>> # Initializing an ALBERT-base style configuration
>>> albert_base_configuration = AlbertConfig(
...     hidden_size=768,
...     num_attention_heads=12,
...     intermediate_size=3072,
... )

>>> # Initializing a model (with random weights) from the ALBERT-base style configuration
>>> model = AlbertModel(albert_xxlarge_configuration)

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

AlbertTokenizer

transformers.AlbertTokenizer

< >

( vocab_file do_lower_case = True remove_space = True keep_accents = False bos_token = '[CLS]' eos_token = '[SEP]' unk_token = '' sep_token = '[SEP]' pad_token = '' cls_token = '[CLS]' mask_token = '[MASK]' sp_model_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **kwargs )

参数

  • vocab_file (str) — SentencePiece 文件(通常具有 .spm 扩展名),包含实例化分词器所需的词汇表。
  • do_lower_case (bool, 可选, 默认为 True) — 是否在分词时将输入转换为小写。
  • remove_space (bool, 可选, 默认为 True) — 是否在分词时去除文本中的空格(去除字符串前后的多余空格)。
  • keep_accents (bool, optional, defaults to False) — 是否在分词时保留重音符号。
  • bos_token (str, optional, defaults to "[CLS]") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, optional, defaults to "[SEP]") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • sep_token (str, optional, defaults to "[SEP]") — 分隔符标记,用于从多个序列构建一个序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • cls_token (str, 可选, 默认为 "[CLS]") — 用于序列分类的分类器标记(对整个序列进行分类,而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • mask_token (str, optional, defaults to "[MASK]") — 用于屏蔽值的令牌。这是在训练此模型时使用的令牌,用于屏蔽语言建模。这是模型将尝试预测的令牌。
  • sp_model_kwargs (dict, optional) — Will be passed to the SentencePieceProcessor.__init__() method. The Python wrapper for SentencePiece can be used, among other things, to set:
    • enable_sampling: 启用子词正则化。

    • nbest_size: 用于unigram的采样参数。对于BPE-Dropout无效。

      • nbest_size = {0,1}: No sampling is performed.
      • nbest_size > 1: samples from the nbest_size results.
      • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.
    • alpha: 用于单字采样的平滑参数,以及BPE-dropout的合并操作丢弃概率。

  • sp_model (SentencePieceProcessor) — 用于每次转换(字符串、标记和ID)的SentencePiece处理器。

构建一个ALBERT分词器。基于SentencePiece

此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。

build_inputs_with_special_tokens

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 特殊令牌将被添加到的ID列表。
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

带有适当特殊标记的输入ID列表。

通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。一个ALBERT序列具有以下格式:

  • 单一序列: [CLS] X [SEP]
  • 序列对:[CLS] A [SEP] B [SEP]

get_special_tokens_mask

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。
  • already_has_special_tokens (bool, optional, defaults to False) — 是否已经为模型格式化了包含特殊标记的标记列表。

返回

List[int]

一个整数列表,范围在[0, 1]:1表示特殊标记,0表示序列标记。

从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model方法添加特殊标记时,会调用此方法。

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

根据给定序列的token type IDs列表。

从传递给序列对分类任务的两个序列中创建一个掩码。一个ALBERT

序列对掩码具有以下格式:

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence    | second sequence |

如果 token_ids_1None,此方法仅返回掩码的第一部分(0s)。

保存词汇表

< >

( 保存目录: str 文件名前缀: typing.Optional[str] = None )

AlbertTokenizerFast

transformers.AlbertTokenizerFast

< >

( vocab_file = None tokenizer_file = None do_lower_case = True remove_space = True keep_accents = False bos_token = '[CLS]' eos_token = '[SEP]' unk_token = '' sep_token = '[SEP]' pad_token = '' cls_token = '[CLS]' mask_token = '[MASK]' **kwargs )

参数

  • vocab_file (str) — SentencePiece 文件(通常具有 .spm 扩展名),包含实例化分词器所需的词汇表。
  • do_lower_case (bool, optional, defaults to True) — 是否在分词时将输入转换为小写。
  • remove_space (bool, 可选, 默认为 True) — 是否在分词时去除文本中的空格(去除字符串前后的多余空格)。
  • keep_accents (bool, optional, defaults to False) — 是否在分词时保留重音符号。
  • bos_token (str, optional, defaults to "[CLS]") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, 可选, 默认为 "[SEP]") — 序列结束标记。 .. 注意:: 当使用特殊标记构建序列时,这不是用于序列结束的标记。使用的标记是 sep_token.
  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为该标记。
  • sep_token (str, optional, defaults to "[SEP]") — 分隔符标记,用于从多个序列构建一个序列时使用,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • cls_token (str, 可选, 默认为 "[CLS]") — 用于序列分类的分类器标记(对整个序列进行分类,而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • mask_token (str, optional, defaults to "[MASK]") — 用于屏蔽值的令牌。这是在训练此模型时使用的令牌,用于屏蔽语言建模。这是模型将尝试预测的令牌。

构建一个“快速”的ALBERT分词器(基于HuggingFace的tokenizers库)。基于 Unigram。这个 分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考 这个超类以获取有关这些方法的更多信息。

build_inputs_with_special_tokens

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 特殊令牌将被添加到的ID列表
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

带有适当特殊标记的输入ID列表。

通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。一个ALBERT序列具有以下格式:

  • 单一序列: [CLS] X [SEP]
  • 序列对:[CLS] A [SEP] B [SEP]

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

根据给定序列的token type IDs列表。

从传递给序列对分类任务的两个序列中创建一个掩码。一个ALBERT

序列对掩码具有以下格式:

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence    | second sequence |

如果 token_ids_1 为 None,则只返回掩码的第一部分(0s)。

Albert 特定输出

transformers.models.albert.modeling_albert.AlbertForPreTrainingOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None prediction_logits: FloatTensor = None sop_logits: FloatTensor = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None attentions: 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之前每个词汇标记的分数)。
  • sop_logits (torch.FloatTensor of shape (batch_size, 2)) — 下一个序列预测(分类)头的预测分数(在SoftMax之前的真/假继续的分数)。
  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.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 when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

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

AlbertForPreTraining的输出类型。

transformers.models.albert.modeling_tf_albert.TFAlbertForPreTrainingOutput

< >

( loss: tf.Tensor = None prediction_logits: tf.Tensor = None sop_logits: tf.Tensor = None hidden_states: Tuple[tf.Tensor] | None = None attentions: Tuple[tf.Tensor] | None = None )

参数

  • prediction_logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax之前每个词汇标记的分数)。
  • sop_logits (tf.Tensor of shape (batch_size, 2)) — 下一个序列预测(分类)头的预测分数(在SoftMax之前的True/False继续的分数)。
  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.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 when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

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

TFAlbertForPreTraining 的输出类型。

Pytorch
Hide Pytorch content

AlbertModel

transformers.AlbertModel

< >

( config: AlbertConfig add_pooling_layer: bool = True )

参数

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

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

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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 (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.

    什么是token type IDs?

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

    什么是位置ID?

  • 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 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

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

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

AlbertModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, AlbertModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = AlbertModel.from_pretrained("albert/albert-base-v2")

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

>>> last_hidden_states = outputs.last_hidden_state

AlbertForPreTraining

transformers.AlbertForPreTraining

< >

( config: AlbertConfig )

参数

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

在预训练期间完成的Albert模型,顶部有两个头:一个masked language modeling头和一个sentence order prediction (classification)头。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None sentence_order_label: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.albert.modeling_albert.AlbertForPreTrainingOutputtuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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 (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.

    什么是token type IDs?

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

    什么是位置ID?

  • 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] 范围内的标记进行计算
  • sentence_order_label (torch.LongTensor of shape (batch_size,), optional) — 用于计算下一个序列预测(分类)损失的标签。输入应该是一个序列对 (参见 input_ids 文档字符串) 索引应该在 [0, 1] 中。0 表示原始顺序(序列 A,然后 序列 B),1 表示交换顺序(序列 B,然后序列 A)。

返回

transformers.models.albert.modeling_albert.AlbertForPreTrainingOutputtuple(torch.FloatTensor)

一个 transformers.models.albert.modeling_albert.AlbertForPreTrainingOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(AlbertConfig)和输入。

  • loss (可选,当提供 labels 时返回,torch.FloatTensor 形状为 (1,)) — 总损失,作为掩码语言建模损失和下一序列预测 (分类)损失的总和。

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

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

AlbertForPreTraining 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, AlbertForPreTraining
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = AlbertForPreTraining.from_pretrained("albert/albert-base-v2")

>>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)
>>> # Batch size 1
>>> outputs = model(input_ids)

>>> prediction_logits = outputs.prediction_logits
>>> sop_logits = outputs.sop_logits

AlbertForMaskedLM

class transformers.AlbertForMaskedLM

< >

( config )

参数

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

带有language modeling头部的Albert模型。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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 (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.

    什么是token type IDs?

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

    什么是位置ID?

  • 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, sequence_length), optional) — 用于计算掩码语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] 范围内(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩码), 损失仅针对标签在 [0, ..., config.vocab_size] 范围内的标记进行计算

返回

transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

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

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

AlbertForMaskedLM 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import torch
>>> from transformers import AutoTokenizer, AlbertForMaskedLM

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = AlbertForMaskedLM.from_pretrained("albert/albert-base-v2")

>>> # add mask_token
>>> inputs = tokenizer("The capital of [MASK] is Paris.", 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)
'france'
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
>>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
>>> outputs = model(**inputs, labels=labels)
>>> round(outputs.loss.item(), 2)
0.81

AlbertForSequenceClassification

transformers.AlbertForSequenceClassification

< >

( config: AlbertConfig )

参数

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

Albert 模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于 GLUE 任务。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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 (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.

    什么是token type IDs?

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

    什么是位置ID?

  • 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, optional) — 是否返回一个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.SequenceClassifierOutputtuple(torch.FloatTensor)

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

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

AlbertForSequenceClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

单标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, AlbertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("textattack/albert-base-v2-imdb")
>>> model = AlbertForSequenceClassification.from_pretrained("textattack/albert-base-v2-imdb")

>>> 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 = AlbertForSequenceClassification.from_pretrained("textattack/albert-base-v2-imdb", num_labels=num_labels)

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

多标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, AlbertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("textattack/albert-base-v2-imdb")
>>> model = AlbertForSequenceClassification.from_pretrained("textattack/albert-base-v2-imdb", 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 = AlbertForSequenceClassification.from_pretrained(
...     "textattack/albert-base-v2-imdb", 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

AlbertForMultipleChoice

transformers.AlbertForMultipleChoice

< >

( config: AlbertConfig )

参数

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

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

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.MultipleChoiceModelOutputtuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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 (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.

    什么是token type IDs?

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

    什么是位置ID?

  • 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, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的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.MultipleChoiceModelOutputtuple(torch.FloatTensor)

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

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

AlbertForMultipleChoice 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, AlbertForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = AlbertForMultipleChoice.from_pretrained("albert/albert-base-v2")

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

AlbertForTokenClassification

transformers.AlbertForTokenClassification

< >

( config: AlbertConfig )

参数

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

带有标记分类头部的Albert模型(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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 (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.

    什么是token type IDs?

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

    什么是位置ID?

  • 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.TokenClassifierOutputtuple(torch.FloatTensor)

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

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

AlbertForTokenClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, AlbertForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = AlbertForTokenClassification.from_pretrained("albert/albert-base-v2")

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

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

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

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

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

AlbertForQuestionAnswering

transformers.AlbertForQuestionAnswering

< >

( config: AlbertConfig )

参数

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

Albert 模型,顶部带有用于抽取式问答任务(如 SQuAD)的跨度分类头(在隐藏状态输出之上的线性层,用于计算 span start logitsspan end logits)。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None start_positions: typing.Optional[torch.LongTensor] = None end_positions: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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 (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.

    什么是token type IDs?

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

    什么是位置ID?

  • 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, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的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.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

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

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

AlbertForQuestionAnswering 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, AlbertForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("twmkn9/albert-base-v2-squad2")
>>> model = AlbertForQuestionAnswering.from_pretrained("twmkn9/albert-base-v2-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([12])
>>> target_end_index = torch.tensor([13])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss
>>> round(loss.item(), 2)
7.36
TensorFlow
Hide TensorFlow content

TFAlbertModel

transformers.TFAlbertModel

< >

( config: AlbertConfig *inputs **kwargs )

参数

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

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

该模型继承自 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函数一样传递输入!

调用

< >

( 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 training: Optional[bool] = False ) transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (Numpy array or tf.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 (Numpy array or tf.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.

    什么是token type IDs?

  • position_ids (Numpy array or tf.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].

    什么是位置ID?

  • head_mask (Numpy arraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (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模块在训练和评估之间有不同的行为)。

返回

transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或一个 tf.Tensor 元组(如果 传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(AlbertConfig)和输入的各种元素。

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

  • pooler_output (tf.Tensor 形状为 (batch_size, hidden_size)) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过线性层和 Tanh 激活函数进一步处理。线性层的权重是在预训练期间通过下一个句子预测(分类)目标训练的。

    这个输出通常不是输入语义内容的一个好的总结,通常更好的做法是对整个输入序列的隐藏状态序列进行平均或池化。

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

TFAlbertModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, TFAlbertModel
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = TFAlbertModel.from_pretrained("albert/albert-base-v2")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)

>>> last_hidden_states = outputs.last_hidden_state

TFAlbertForPreTraining

transformers.TFAlbertForPreTraining

< >

( config: AlbertConfig *inputs **kwargs )

参数

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

Albert 模型在顶部有两个头用于预训练:一个masked language modeling头和一个sentence order prediction(分类)头。

该模型继承自 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函数一样传递输入!

调用

< >

( 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 sentence_order_label: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) transformers.models.albert.modeling_tf_albert.TFAlbertForPreTrainingOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (Numpy array or tf.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 (Numpy array or tf.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.

    什么是token type IDs?

  • position_ids (Numpy array or tf.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].

    什么是位置ID?

  • head_mask (Numpy arraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递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模块在训练和评估之间有不同的行为)。

返回

transformers.models.albert.modeling_tf_albert.TFAlbertForPreTrainingOutputtuple(tf.Tensor)

一个 transformers.models.albert.modeling_tf_albert.TFAlbertForPreTrainingOutput 或一个由 tf.Tensor 组成的元组(如果 传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(AlbertConfig)和输入的各种元素。

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

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

TFAlbertForPreTraining 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import tensorflow as tf
>>> from transformers import AutoTokenizer, TFAlbertForPreTraining

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = TFAlbertForPreTraining.from_pretrained("albert/albert-base-v2")

>>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :]
>>> # Batch size 1
>>> outputs = model(input_ids)

>>> prediction_logits = outputs.prediction_logits
>>> sop_logits = outputs.sop_logits

TFAlbertForMaskedLM

transformers.TFAlbertForMaskedLM

< >

( config: AlbertConfig *inputs **kwargs )

参数

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

带有language modeling头部的Albert模型。

该模型继承自 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函数一样传递输入!

调用

< >

( 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.TFMaskedLMOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (Numpy array or tf.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 (Numpy array or tf.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.

    什么是token type IDs?

  • position_ids (Numpy array or tf.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].

    什么是位置ID?

  • head_mask (Numpy arraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (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 of shape (batch_size, sequence_length), optional) — 用于计算掩码语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] 范围内(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩码), 损失仅针对标签在 [0, ..., config.vocab_size] 范围内的标记进行计算

返回

transformers.modeling_tf_outputs.TFMaskedLMOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFMaskedLMOutput 或一个 tf.Tensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(AlbertConfig)和输入的各种元素。

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

TFAlbertForMaskedLM 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import tensorflow as tf
>>> from transformers import AutoTokenizer, TFAlbertForMaskedLM

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = TFAlbertForMaskedLM.from_pretrained("albert/albert-base-v2")

>>> # add mask_token
>>> inputs = tokenizer(f"The capital of [MASK] is Paris.", return_tensors="tf")
>>> logits = model(**inputs).logits

>>> # retrieve index of [MASK]
>>> mask_token_index = tf.where(inputs.input_ids == tokenizer.mask_token_id)[0][1]
>>> predicted_token_id = tf.math.argmax(logits[0, mask_token_index], axis=-1)
>>> tokenizer.decode(predicted_token_id)
'france'
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"]
>>> labels = tf.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
>>> outputs = model(**inputs, labels=labels)
>>> round(float(outputs.loss), 2)
0.81

TFAlbertForSequenceClassification

transformers.TFAlbertForSequenceClassification

< >

( config: AlbertConfig *inputs **kwargs )

参数

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

Albert 模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于 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函数一样传递输入!

调用

< >

( 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.TFSequenceClassifierOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (Numpy array or tf.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 (Numpy array or tf.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.

    什么是token type IDs?

  • position_ids (Numpy array or tf.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].

    什么是位置ID?

  • head_mask (Numpy arraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (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,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_tf_outputs.TFSequenceClassifierOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFSequenceClassifierOutput 或一个 tf.Tensor 的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,取决于 配置 (AlbertConfig) 和输入。

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

TFAlbertForSequenceClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, TFAlbertForSequenceClassification
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("vumichien/albert-base-v2-imdb")
>>> model = TFAlbertForSequenceClassification.from_pretrained("vumichien/albert-base-v2-imdb")

>>> 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 = TFAlbertForSequenceClassification.from_pretrained("vumichien/albert-base-v2-imdb", num_labels=num_labels)

>>> labels = tf.constant(1)
>>> loss = model(**inputs, labels=labels).loss
>>> round(float(loss), 2)
0.12

TFAlbertForMultipleChoice

transformers.TFAlbertForMultipleChoice

< >

( config: AlbertConfig *inputs **kwargs )

参数

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

Albert模型,顶部带有多项选择分类头(在池化输出顶部有一个线性层和一个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函数一样传递输入!

调用

< >

( 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.TFMultipleChoiceModelOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, num_choices, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (Numpy array or tf.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 (Numpy array or tf.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.

    什么是token type IDs?

  • position_ids (Numpy array or tf.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].

    什么是位置ID?

  • head_mask (Numpy arraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (tf.Tensor 形状为 (batch_size, num_choices, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True.
  • 训练 (bool, 可选, 默认为 False) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估时具有不同的行为)。
  • labels (tf.Tensor 形状为 (batch_size,), 可选) — 用于计算多项选择分类损失的标签。索引应在 [0, ..., num_choices] 范围内, 其中 num_choices 是输入张量第二维的大小。(参见上面的 input_ids

返回

transformers.modeling_tf_outputs.TFMultipleChoiceModelOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFMultipleChoiceModelOutput 或一个由 tf.Tensor 组成的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时),包含根据配置(AlbertConfig)和输入的各种元素。

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

TFAlbertForMultipleChoice 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, TFAlbertForMultipleChoice
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = TFAlbertForMultipleChoice.from_pretrained("albert/albert-base-v2")

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

TFAlbertForTokenClassification

transformers.TFAlbertForTokenClassification

< >

( config: AlbertConfig *inputs **kwargs )

参数

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

带有标记分类头部的Albert模型(在隐藏状态输出之上的线性层),例如用于命名实体识别(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函数一样传递输入!

调用

< >

( 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.TFTokenClassifierOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (Numpy array or tf.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 (Numpy array or tf.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.

    什么是token type IDs?

  • position_ids (Numpy array or tf.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].

    什么是位置ID?

  • head_mask (Numpy arraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在急切模式下使用,在图形模式下该值将始终设置为True.
  • 训练 (bool, 可选, 默认为 False) — 是否在训练模式下使用模型(某些模块如 dropout 模块在训练和评估之间有不同的行为)。
  • labels (tf.Tensor of shape (batch_size, sequence_length), optional) — 用于计算令牌分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。

返回

transformers.modeling_tf_outputs.TFTokenClassifierOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFTokenClassifierOutput 或一个 tf.Tensor 元组(如果 传递了 return_dict=False 或当 config.return_dict=False 时)包含各种元素,具体取决于 配置(AlbertConfig)和输入。

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

TFAlbertForTokenClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, TFAlbertForTokenClassification
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = TFAlbertForTokenClassification.from_pretrained("albert/albert-base-v2")

>>> 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()]
>>> labels = predicted_token_class_ids
>>> loss = tf.math.reduce_mean(model(**inputs, labels=labels).loss)

TFAlbertForQuestionAnswering

transformers.TFAlbertForQuestionAnswering

< >

( config: AlbertConfig *inputs **kwargs )

参数

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

Albert 模型,顶部带有跨度分类头,用于抽取式问答任务,如 SQuAD(在隐藏状态输出顶部有一个线性层,用于计算 span start logitsspan 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函数一样传递输入!

调用

< >

( 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.TFQuestionAnsweringModelOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

  • attention_mask (Numpy array or tf.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 (Numpy array or tf.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.

    什么是token type IDs?

  • position_ids (Numpy array or tf.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].

    什么是位置ID?

  • head_mask (Numpy arraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (tf.Tensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True.
  • 训练 (bool, 可选, 默认为 False) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估时具有不同的行为)。
  • start_positions (tf.Tensor 形状为 (batch_size,), 可选) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。
  • end_positions (tf.Tensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。

返回

transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutput 或一个 tf.Tensor 元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,具体取决于 配置 (AlbertConfig) 和输入。

  • loss (tf.Tensor 形状为 (batch_size, ), 可选, 当 start_positionsend_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 后的注意力权重,用于计算自注意力头中的加权平均值。

TFAlbertForQuestionAnswering 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, TFAlbertForQuestionAnswering
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("vumichien/albert-base-v2-squad2")
>>> model = TFAlbertForQuestionAnswering.from_pretrained("vumichien/albert-base-v2-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'
>>> # target is "nice puppet"
>>> target_start_index = tf.constant([12])
>>> target_end_index = tf.constant([13])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = tf.math.reduce_mean(outputs.loss)
>>> round(float(loss), 2)
7.36
JAX
Hide JAX content

FlaxAlbertModel

transformers.FlaxAlbertModel

< >

( config: AlbertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True **kwargs )

参数

  • config (AlbertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

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

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( input_ids attention_mask = None token_type_ids = None position_ids = None params: dict = None dropout_rng: = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPoolingtuple(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()

    什么是输入ID?

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

    什么是token type IDs?

  • position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.max_position_embeddings - 1] 之间。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPoolingtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPooling 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(AlbertConfig)和输入。

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

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

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxAlbertModel

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = FlaxAlbertModel.from_pretrained("albert/albert-base-v2")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state

FlaxAlbertForPreTraining

transformers.FlaxAlbertForPreTraining

< >

( config: AlbertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True **kwargs )

参数

  • config (AlbertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

在预训练期间完成的Albert模型,顶部有两个头:一个masked language modeling头和一个sentence order prediction (classification)头。

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( input_ids attention_mask = None token_type_ids = None position_ids = None params: dict = None dropout_rng: = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.albert.modeling_flax_albert.FlaxAlbertForPreTrainingOutputtuple(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()

    什么是输入ID?

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

    什么是token type IDs?

  • position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 位置嵌入中每个输入序列标记的位置索引。选择范围在 [0, config.max_position_embeddings - 1] 之间。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.models.albert.modeling_flax_albert.FlaxAlbertForPreTrainingOutputtuple(torch.FloatTensor)

一个 transformers.models.albert.modeling_flax_albert.FlaxAlbertForPreTrainingOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(AlbertConfig)和输入。

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

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

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

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxAlbertForPreTraining

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = FlaxAlbertForPreTraining.from_pretrained("albert/albert-base-v2")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
>>> outputs = model(**inputs)

>>> prediction_logits = outputs.prediction_logits
>>> seq_relationship_logits = outputs.sop_logits

FlaxAlbertForMaskedLM

transformers.FlaxAlbertForMaskedLM

< >

( config: AlbertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True **kwargs )

参数

  • config (AlbertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

带有language modeling头部的Albert模型。

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( input_ids attention_mask = None token_type_ids = None position_ids = None params: dict = None dropout_rng: = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_flax_outputs.FlaxMaskedLMOutputtuple(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()

    什么是输入ID?

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

    什么是token type IDs?

  • position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.max_position_embeddings - 1] 之间。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxMaskedLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxMaskedLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(AlbertConfig)和输入。

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

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

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxAlbertForMaskedLM

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2", revision="refs/pr/11")
>>> model = FlaxAlbertForMaskedLM.from_pretrained("albert/albert-base-v2", revision="refs/pr/11")

>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="jax")

>>> outputs = model(**inputs)
>>> logits = outputs.logits

FlaxAlbertForSequenceClassification

transformers.FlaxAlbertForSequenceClassification

< >

( config: AlbertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True **kwargs )

参数

  • config (AlbertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

Albert 模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于 GLUE 任务。

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( input_ids attention_mask = None token_type_ids = None position_ids = None params: dict = None dropout_rng: = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_flax_outputs.FlaxSequenceClassifierOutputtuple(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()

    什么是输入ID?

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

    什么是token type IDs?

  • position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.max_position_embeddings - 1] 之间。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxSequenceClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(AlbertConfig)和输入。

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

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

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxAlbertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = FlaxAlbertForSequenceClassification.from_pretrained("albert/albert-base-v2")

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

>>> outputs = model(**inputs)
>>> logits = outputs.logits

FlaxAlbertForMultipleChoice

transformers.FlaxAlbertForMultipleChoice

< >

( config: AlbertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True **kwargs )

参数

  • config (AlbertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

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

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( input_ids attention_mask = None token_type_ids = None position_ids = None params: dict = None dropout_rng: = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_flax_outputs.FlaxMultipleChoiceModelOutputtuple(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()

    什么是输入ID?

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

    什么是token type IDs?

  • position_ids (numpy.ndarray 形状为 (batch_size, num_choices, sequence_length), 可选) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.max_position_embeddings - 1].
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxMultipleChoiceModelOutputtuple(torch.FloatTensor)

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

  • 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 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每一层的输出)。

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(jnp.ndarray), 可选, 当传递了 output_attentions=True 或者当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每一层一个)。

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

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

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxAlbertForMultipleChoice

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = FlaxAlbertForMultipleChoice.from_pretrained("albert/albert-base-v2")

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

FlaxAlbertForTokenClassification

transformers.FlaxAlbertForTokenClassification

< >

( config: AlbertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True **kwargs )

参数

  • config (AlbertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

带有标记分类头部的Albert模型(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( input_ids attention_mask = None token_type_ids = None position_ids = None params: dict = None dropout_rng: = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_flax_outputs.FlaxTokenClassifierOutputtuple(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()

    什么是输入ID?

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

    什么是token type IDs?

  • position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.max_position_embeddings - 1] 之间。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxTokenClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxTokenClassifierOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(AlbertConfig)和输入。

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

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

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxAlbertForTokenClassification

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = FlaxAlbertForTokenClassification.from_pretrained("albert/albert-base-v2")

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

>>> outputs = model(**inputs)
>>> logits = outputs.logits

FlaxAlbertForQuestionAnswering

transformers.FlaxAlbertForQuestionAnswering

< >

( config: AlbertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True **kwargs )

参数

  • config (AlbertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

Albert 模型,顶部带有用于抽取式问答任务(如 SQuAD)的跨度分类头(在隐藏状态输出之上的线性层,用于计算 span start logitsspan end logits)。

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

该模型也是一个 flax.linen.Module 子类。将其作为 常规的 Flax linen 模块使用,并参考 Flax 文档以获取与一般使用和行为相关的所有信息。

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( input_ids attention_mask = None token_type_ids = None position_ids = None params: dict = None dropout_rng: = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_flax_outputs.FlaxQuestionAnsweringModelOutputtuple(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()

    什么是输入ID?

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

    什么是token type IDs?

  • position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.max_position_embeddings - 1] 之间。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxQuestionAnsweringModelOutputtuple(torch.FloatTensor)

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

  • 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 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每一层的输出)。

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(jnp.ndarray), 可选, 当传递了 output_attentions=True 或者当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每一层一个)。

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

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

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxAlbertForQuestionAnswering

>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
>>> model = FlaxAlbertForQuestionAnswering.from_pretrained("albert/albert-base-v2")

>>> 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
< > Update on GitHub