Transformers 文档

YOSO

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

YOSO

概述

YOSO 模型在You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling中提出
由 Zhanpeng Zeng、Yunyang Xiong、Sathya N. Ravi、Shailesh Acharya、Glenn Fung、Vikas Singh 提出。YOSO 通过基于局部敏感哈希 (LSH) 的伯努利抽样方案来近似标准 softmax 自注意力。原则上,所有伯努利随机变量都可以通过单个哈希进行采样。

该论文的摘要如下

基于 Transformer 的模型广泛应用于自然语言处理 (NLP) 领域。Transformer 模型的核心是自注意力机制,它捕获输入序列中 token 对的交互,并且与序列长度呈二次方关系。在较长序列上训练此类模型的成本很高。在本文中,我们展示了基于局部敏感哈希 (LSH) 的伯努利抽样注意力机制,将此类模型的二次复杂度降低到线性复杂度。我们通过将自注意力视为与伯努利随机变量相关的各个 token 的总和来绕过二次成本,原则上,这些随机变量可以通过单个哈希一次性采样(尽管在实践中,这个数字可能是一个小的常数)。这导致了一种有效的抽样方案来估计自注意力,该方案依赖于 LSH 的特定修改(以支持在 GPU 架构上部署)。我们在具有标准 512 序列长度的 GLUE 基准上评估了我们的算法,我们看到了相对于标准预训练 Transformer 的良好性能。在长程竞技场 (LRA) 基准上,为了评估长序列的性能,我们的方法实现了与 softmax 自注意力一致的结果,但具有显着的加速和内存节省,并且通常优于其他有效的自注意力方法。我们的代码可在此 https URL 获取

此模型由novice03贡献。原始代码可以在此处找到。

使用技巧

  • YOSO 注意力算法通过自定义 CUDA 内核实现,这些内核是用 CUDA C++ 编写的函数,可以在 GPU 上并行执行多次。
  • 这些内核提供了一个 fast_hash 函数,该函数使用快速哈达玛变换来近似查询和键的随机投影。 使用这些哈希码,lsh_cumulation 函数通过基于 LSH 的伯努利抽样来近似自注意力。
  • 要使用自定义内核,用户应设置 config.use_expectation = False。 为了确保内核成功编译,用户必须安装正确版本的 PyTorch 和 cudatoolkit。 默认情况下,config.use_expectation = True,它使用 YOSO-E,并且不需要编译 CUDA 内核。
drawing YOSO 注意力算法。 摘自原始论文

资源

YosoConfig

class transformers.YosoConfig

< >

( vocab_size = 50265 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.1 attention_probs_dropout_prob = 0.1 max_position_embeddings = 4096 type_vocab_size = 1 initializer_range = 0.02 layer_norm_eps = 1e-12 position_embedding_type = 'absolute' use_expectation = True hash_code_len = 9 num_hash = 64 conv_window = None use_fast_hash = True lsh_backward = True pad_token_id = 1 bos_token_id = 0 eos_token_id = 2 **kwargs )

参数

  • vocab_size (int, 可选的, 默认为 50265) — YOSO 模型的词汇表大小。 定义了在调用 YosoModel 时传递的 inputs_ids 可以表示的不同 token 的数量。
  • hidden_size (int, 可选的, 默认为 768) — 编码器层和池化器层的维度。
  • num_hidden_layers (int, 可选的, 默认为 12) — Transformer 编码器中隐藏层的数量。
  • num_attention_heads (int, 可选的, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数。
  • intermediate_size (int, 可选的, 默认为 3072) — Transformer 编码器中“中间”(即,前馈)层的维度。
  • hidden_act (strfunction, 可选的, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。 如果是字符串,则支持 "gelu""relu""selu""gelu_new"
  • hidden_dropout_prob (float, 可选的, 默认为 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, 可选的, 默认为 0.1) — 注意力概率的 dropout 比率。
  • max_position_embeddings (int, 可选的, 默认为 512) — 此模型可能使用的最大序列长度。 通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。
  • type_vocab_size (int, 可选的, 默认为 2) — 调用 YosoModel 时传递的 token_type_ids 的词汇表大小。
  • initializer_range (float, 可选的, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选的, 默认为 1e-12) — 层归一化层使用的 epsilon 值。
  • position_embedding_type (str, 可选的, 默认为 "absolute") — 位置嵌入的类型。 从 "absolute""relative_key""relative_key_query" 中选择一个。
  • use_expectation (bool, 可选的, 默认为 True) — 是否使用 YOSO Expectation。 覆盖 num_hash 的任何效果。
  • hash_code_len (int, 可选的, 默认为 9) — 哈希函数生成的哈希码的长度。
  • num_hash (int, 可选的, 默认为 64) — YosoSelfAttention 中使用的哈希函数数量。
  • conv_window (int, 可选的) — 深度卷积的内核大小。
  • use_fast_hash (bool, 可选的, 默认为 False) — 是否使用自定义 cuda 内核,该内核通过哈达玛变换执行快速随机投影。
  • lsh_backward (bool, 可选的, 默认为 True) — 是否使用局部敏感哈希执行反向传播。

这是用于存储 YosoModel 配置的配置类。 它用于根据指定的参数实例化 YOSO 模型,从而定义模型架构。 使用默认值实例化配置将产生与 YOSO uw-madison/yoso-4096 架构类似的配置。

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

示例

>>> from transformers import YosoConfig, YosoModel

>>> # Initializing a YOSO uw-madison/yoso-4096 style configuration
>>> configuration = YosoConfig()

>>> # Initializing a model (with random weights) from the uw-madison/yoso-4096 style configuration
>>> model = YosoModel(configuration)

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

YosoModel

class transformers.YosoModel

< >

( config )

参数

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

基础 YOSO 模型 Transformer,输出原始的隐藏状态,没有附加任何特定的头部。 此模型是 PyTorch torch.nn.Module 的子类。 您可以将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与其通用用法和行为相关的所有事项。

forward

< >

( input_ids: Optional = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.BaseModelOutputWithCrossAttentions or tuple(torch.FloatTensor)

参数

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

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

    什么是输入 IDs?

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 用于避免在 padding token 索引上执行 attention 的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 tokens 未被掩盖
    • 0 表示 tokens 被掩盖

    什么是 attention masks?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 片段 tokens 索引,用于指示输入的第一个和第二个部分。 索引在 [0, 1] 中选择:

    • 0 对应于 *句子 A* token,
    • 1 对应于 *句子 B* token。

    什么是 token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 位置 embeddings 中每个输入序列 token 的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于使 self-attention 模块中选定的 heads 失效的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 head 未被掩盖
    • 0 表示 head 被掩盖
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部 embedding 查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回 tensors 下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回 tensors 下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通 tuple。

返回

transformers.modeling_outputs.BaseModelOutputWithCrossAttentions or tuple(torch.FloatTensor)

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

  • last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的 hidden-states 序列。

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — torch.FloatTensor 的 tuple(如果模型有 embedding 层,则为 embeddings 的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出的 hidden-states,加上可选的初始 embedding 输出。

  • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — torch.FloatTensor 的 tuple(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    attention softmax 之后的 attention 权重,用于计算 self-attention heads 中的加权平均值。

  • cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True and config.add_cross_attention=True is passed or when config.output_attentions=True) — torch.FloatTensor 的 tuple(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    decoder 的 cross-attention 层的 attention 权重,在 attention softmax 之后,用于计算 cross-attention heads 中的加权平均值。

YosoModel forward 方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, YosoModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/yoso-4096")
>>> model = YosoModel.from_pretrained("uw-madison/yoso-4096")

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

>>> last_hidden_states = outputs.last_hidden_state

YosoForMaskedLM

class transformers.YosoForMaskedLM

< >

( config )

参数

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

YOSO 模型,顶部带有 language modeling head。 此模型是 PyTorch torch.nn.Module 的子类。 您可以将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与其通用用法和行为相关的所有事项。

forward

< >

( input_ids: Optional = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.MaskedLMOutput or tuple(torch.FloatTensor)

参数

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

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

    什么是输入 IDs?

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 用于避免在 padding token 索引上执行 attention 的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 tokens 未被掩盖
    • 0 表示 tokens 被掩盖

    什么是 attention masks?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 片段 tokens 索引,用于指示输入的第一个和第二个部分。 索引在 [0, 1] 中选择:

    • 0 对应于 *句子 A* token,
    • 1 对应于 *句子 B* token。

    什么是 token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 位置 embeddings 中每个输入序列 token 的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于使 self-attention 模块中选定的 heads 失效的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 head 未被掩盖
    • 0 表示 head 被掩盖
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部 embedding 查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回 tensors 下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 用于计算掩码语言建模损失的标签。 索引应在 [-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 时),包含各种元素,具体取决于配置 (YosoConfig) 和输入。

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

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

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — torch.FloatTensor 的 tuple(如果模型有 embedding 层,则为 embeddings 的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出的 hidden-states,加上可选的初始 embedding 输出。

  • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — torch.FloatTensor 的 tuple(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    attention softmax 之后的 attention 权重,用于计算 self-attention heads 中的加权平均值。

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

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

示例

>>> from transformers import AutoTokenizer, YosoForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/yoso-4096")
>>> model = YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096")

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

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

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

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

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

>>> outputs = model(**inputs, labels=labels)

YosoForSequenceClassification

class transformers.YosoForSequenceClassification

< >

( config )

参数

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

YOSO 模型转换器,顶部带有序列分类/回归头(池化输出顶部的线性层),例如用于 GLUE 任务。 此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。

forward

< >

( input_ids: Optional = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列标记的索引。

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

    什么是输入 ID?

  • attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length)可选) — 用于避免在 padding 标记索引上执行注意力的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩码
    • 0 表示标记已被掩码

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 分段标记索引,用于指示输入的第一个和第二个部分。 索引在 [0, 1] 中选择:

    • 0 对应于 句子 A 标记,
    • 1 对应于 句子 B 标记。

    什么是 token 类型 ID?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 位置嵌入中每个输入序列标记的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是位置 ID?

  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads)可选) — 用于使自注意力模块的选定 head 失效的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 head 未被掩码
    • 0 表示 head 已被掩码
  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)可选) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。
  • labels (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算序列分类/回归损失的标签。 索引应在 [0, ..., config.num_labels - 1] 中。 如果 config.num_labels == 1,则计算回归损失(均方误差损失),如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。

返回

transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

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

  • 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), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — torch.FloatTensor 的 tuple(如果模型有 embedding 层,则为 embeddings 的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出的 hidden-states,加上可选的初始 embedding 输出。

  • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — torch.FloatTensor 的 tuple(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    attention softmax 之后的 attention 权重,用于计算 self-attention heads 中的加权平均值。

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

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

单标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, YosoForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/yoso-4096")
>>> model = YosoForSequenceClassification.from_pretrained("uw-madison/yoso-4096")

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

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

>>> predicted_class_id = logits.argmax().item()

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = YosoForSequenceClassification.from_pretrained("uw-madison/yoso-4096", num_labels=num_labels)

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

多标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, YosoForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/yoso-4096")
>>> model = YosoForSequenceClassification.from_pretrained("uw-madison/yoso-4096", 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 = YosoForSequenceClassification.from_pretrained(
...     "uw-madison/yoso-4096", 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

YosoForMultipleChoice

class transformers.YosoForMultipleChoice

< >

( config )

参数

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

YOSO 模型,顶部带有用于多项选择分类的 head(池化输出顶部的线性层和一个 softmax),例如用于 RocStories/SWAG 任务。 此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。

forward

< >

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

参数

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

    索引可以通过 AutoTokenizer 获得。 详见 PreTrainedTokenizer.encode()PreTrainedTokenizer.call() 以了解详情。

    什么是输入 IDs?

  • attention_mask (torch.FloatTensor of shape (batch_size, num_choices, sequence_length), optional) — 用于避免在 padding token 索引上执行 attention 的 Mask。 Mask 值在 [0, 1] 中选择:

    • 1 表示 tokens 未被 Mask
    • 0 表示 tokens 被 Mask

    什么是 attention masks?

  • token_type_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length), optional) — Segment token 索引,用于指示输入的第一部分和第二部分。 索引在 [0, 1] 中选择:

    • 0 对应于 sentence A token,
    • 1 对应于 sentence B token。

    什么是 token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length), optional) — 位置嵌入中每个输入序列 tokens 的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于 nullify self-attention 模块的选定 heads 的 Mask。 Mask 值在 [0, 1] 中选择:

    • 1 表示 head 未被 Mask
    • 0 表示 head 被 Mask
  • inputs_embeds (torch.FloatTensor of shape (batch_size, num_choices, sequence_length, hidden_size), optional) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通 tuple。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算多项选择分类损失的标签。 索引应在 [0, ..., num_choices-1] 中,其中 num_choices 是输入 tensors 的第二个维度的大小。 (参见上面的 input_ids

返回

transformers.modeling_outputs.MultipleChoiceModelOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor of shape (1,), optional, 当提供 labels 时返回) — 分类损失。

  • logits (torch.FloatTensor of shape (batch_size, num_choices)) — num_choices 是输入 tensors 的第二个维度。 (参见上面的 input_ids)。

    分类得分(在 SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — torch.FloatTensor 的 tuple(如果模型有 embedding 层,则为 embeddings 的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出的 hidden-states,加上可选的初始 embedding 输出。

  • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — torch.FloatTensor 的 tuple(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    attention softmax 之后的 attention 权重,用于计算 self-attention heads 中的加权平均值。

YosoForMultipleChoice forward 方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, YosoForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/yoso-4096")
>>> model = YosoForMultipleChoice.from_pretrained("uw-madison/yoso-4096")

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

YosoForTokenClassification

class transformers.YosoForTokenClassification

< >

( config )

参数

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

YOSO 模型,顶部带有一个 token 分类头(hidden-states 输出顶部的线性层),例如,用于命名实体识别 (NER) 任务。 此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch Module,并参阅 PyTorch 文档,以了解与常规用法和行为相关的所有事项。

forward

< >

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

参数

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

    索引可以通过 AutoTokenizer 获得。 详见 PreTrainedTokenizer.encode()PreTrainedTokenizer.call() 以了解详情。

    什么是输入 IDs?

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 用于避免在 padding token 索引上执行 attention 的 Mask。 Mask 值在 [0, 1] 中选择:

    • 1 表示 tokens 未被 Mask
    • 0 表示 tokens 被 Mask

    什么是 attention masks?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token 索引,用于指示输入的第一部分和第二部分。 索引在 [0, 1] 中选择:

    • 0 对应于 sentence A token,
    • 1 对应于 sentence B token。

    什么是 token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 位置嵌入中每个输入序列 tokens 的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于 nullify self-attention 模块的选定 heads 的 Mask。 Mask 值在 [0, 1] 中选择:

    • 1 表示 head 未被 Mask
    • 0 表示 head 被 Mask
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是一个普通的元组。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),*可选*) — 用于计算 token 分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

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

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

  • logits (torch.FloatTensor,形状为 (batch_size, sequence_length, config.num_labels)) — 分类得分 (SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — torch.FloatTensor 的 tuple(如果模型有 embedding 层,则为 embeddings 的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出的 hidden-states,加上可选的初始 embedding 输出。

  • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — torch.FloatTensor 的 tuple(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    attention softmax 之后的 attention 权重,用于计算 self-attention heads 中的加权平均值。

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

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

示例

>>> from transformers import AutoTokenizer, YosoForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/yoso-4096")
>>> model = YosoForTokenClassification.from_pretrained("uw-madison/yoso-4096")

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

YosoForQuestionAnswering

class transformers.YosoForQuestionAnswering

< >

( config )

参数

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

YOSO 模型,顶部带有 span 分类头,用于抽取式问答任务,如 SQuAD (在 hidden-states 输出之上添加线性层以计算 span start logits 和 span end logits)。此模型是 PyTorch torch.nn.Module 子类。可将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规使用和行为相关的所有事项。

forward

< >

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

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列 tokens 的索引。

    索引可以使用 AutoTokenizer 获得。请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call() 以了解详情。

    什么是 input IDs?

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

    • 1 表示 tokens 未被掩盖
    • 0 表示 tokens 已被掩盖

    什么是 attention masks?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length),*可选*) — Segment token 索引,用于指示输入的第一个和第二个部分。索引在 [0, 1] 中选择:

    • 0 对应于 sentence A token,
    • 1 对应于 sentence B token。

    什么是 token type IDs?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length),*可选*) — 每个输入序列 tokens 在 position embeddings 中的位置索引。在 [0, config.max_position_embeddings - 1] 范围内选择。

    什么是 position IDs?

  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads),*可选*) — 用于使 self-attention 模块的选定 head 无效的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 head 未被掩盖
    • 0 表示 head 已被掩盖
  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size),*可选*) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望比模型的内部 embedding lookup matrix 更精细地控制如何将 *input_ids* 索引转换为关联的向量,这将非常有用。
  • output_attentions (bool, *可选*) — 是否返回所有 attention 层的 attention tensors。有关更多详细信息,请参阅返回 tensors 下的 attentions
  • output_hidden_states (bool, *可选*) — 是否返回所有层的 hidden states。有关更多详细信息,请参阅返回 tensors 下的 hidden_states
  • return_dict (bool, *可选*) — 是否返回 ModelOutput 而不是一个普通的元组。
  • start_positions (torch.LongTensor,形状为 (batch_size,),*可选*) — 用于计算 token 分类损失的已标记 span 起始位置(索引)的标签。位置被限制在序列的长度 (sequence_length) 内。序列之外的位置不计入损失计算。
  • end_positions (torch.LongTensor,形状为 (batch_size,),*可选*) — 用于计算 token 分类损失的已标记 span 结束位置(索引)的标签。位置被限制在序列的长度 (sequence_length) 内。序列之外的位置不计入损失计算。

返回

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor,形状为 (1,),*可选*,当提供 labels 时返回) — 总 span 抽取损失是起始和结束位置的 Cross-Entropy 之和。

  • start_logits (torch.FloatTensor,形状为 (batch_size, sequence_length)) — Span-start 得分 (SoftMax 之前)。

  • end_logits (torch.FloatTensor,形状为 (batch_size, sequence_length)) — Span-end 得分 (SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — torch.FloatTensor 的 tuple(如果模型有 embedding 层,则为 embeddings 的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出的 hidden-states,加上可选的初始 embedding 输出。

  • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — torch.FloatTensor 的 tuple(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    attention softmax 之后的 attention 权重,用于计算 self-attention heads 中的加权平均值。

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

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

示例

>>> from transformers import AutoTokenizer, YosoForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/yoso-4096")
>>> model = YosoForQuestionAnswering.from_pretrained("uw-madison/yoso-4096")

>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"

>>> inputs = tokenizer(question, text, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()

>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]

>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss
< > 更新 on GitHub