Transformers 文档

MRA

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

MRA

PyTorch

概述

MRA 模型在 用于近似自注意力机制的多分辨率分析 (MRA) 一文中提出,作者为 Zhanpeng Zeng, Sourav Pal, Jeffery Kline, Glenn M Fung 和 Vikas Singh。

论文摘要如下:

Transformer 已成为自然语言处理和视觉领域许多任务的首选模型。最近关于更高效地训练和部署 Transformer 的努力已经确定了许多近似自注意力矩阵的策略,自注意力矩阵是 Transformer 架构中的关键模块。有效的想法包括各种预先指定的稀疏模式、低秩基展开及其组合。在本文中,我们重新审视了经典的多分辨率分析 (MRA) 概念,例如小波,其在这种设置中的潜在价值迄今为止仍未被充分探索。我们表明,基于经验反馈和受现代硬件和实现挑战启发的简单近似和设计选择,最终产生了一种基于 MRA 的自注意力方法,该方法在大多数感兴趣的标准中都具有出色的性能。我们进行了一系列广泛的实验,并证明这种多分辨率方案优于大多数高效的自注意力提案,并且对于短序列和长序列都很有利。代码可在 https://github.com/mlpen/mra-attention 获取。

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

MraConfig

class transformers.MraConfig

< >

( 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 = 512 type_vocab_size = 1 initializer_range = 0.02 layer_norm_eps = 1e-05 position_embedding_type = 'absolute' block_per_row = 4 approx_mode = 'full' initial_prior_first_n_blocks = 0 initial_prior_diagonal_n_blocks = 0 pad_token_id = 1 bos_token_id = 0 eos_token_id = 2 **kwargs )

参数

  • vocab_size (int, 可选, 默认为 50265) — Mra 模型的词汇表大小。定义了在调用 MraModel 时传递的 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, 可选, 默认为 1) — 调用 MraModel 时传递的 token_type_ids 的词汇表大小。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-5) — layer normalization 层使用的 epsilon 值。
  • position_embedding_type (str, 可选, 默认为 "absolute") — 位置嵌入的类型。选择 "absolute", "relative_key", "relative_key_query" 之一。
  • block_per_row (int, 可选, 默认为 4) — 用于设置高分辨率比例的预算。
  • approx_mode (str, 可选, 默认为 "full") — 控制是否同时使用低分辨率和高分辨率近似。设置为 "full" 以同时使用低分辨率和高分辨率,设置为 "sparse" 以仅使用低分辨率。
  • initial_prior_first_n_blocks (int, 可选, 默认为 0) — 初始的块数量,这些块使用高分辨率。
  • initial_prior_diagonal_n_blocks (int, 可选, 默认为 0) — 对角块的数量,这些对角块使用高分辨率。

这是用于存储 MraModel 配置的配置类。它用于根据指定的参数实例化 MRA 模型,定义模型架构。使用默认值实例化配置将产生与 Mra uw-madison/mra-base-512-4 架构类似的配置。

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

示例

>>> from transformers import MraConfig, MraModel

>>> # Initializing a Mra uw-madison/mra-base-512-4 style configuration
>>> configuration = MraConfig()

>>> # Initializing a model (with random weights) from the uw-madison/mra-base-512-4 style configuration
>>> model = MraModel(configuration)

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

MraModel

class transformers.MraModel

< >

( config )

参数

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

裸 MRA 模型 Transformer,输出原始隐藏状态,顶部没有任何特定的 head。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

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

参数

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

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

    什么是输入 IDs?

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

    • 1 表示 未被 mask 的 token,
    • 0 表示 已被 mask 的 token。

    什么是 attention masks?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于指示输入的第一部分和第二部分的分段 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) — 位置嵌入中每个输入序列 token 的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于置空自注意力模块中选定 head 的 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 weights。 在返回的 tensors 下查看 attentions 以获得更多详细信息。
  • output_hidden_states (bool, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的 hidden_states

return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯 tuple。

返回值

transformers.modeling_outputs.BaseModelOutputWithCrossAttentionstuple(torch.FloatTensor)

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

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

    hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型有嵌入层,则为嵌入的输出 + 每层输出一个) ,形状为 (batch_size, sequence_length, hidden_size)

  • 模型在每一层输出的 Hidden-states,加上可选的初始嵌入输出。

    attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的 Tuple (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

  • 注意力 softmax 之后的 Attention weights,用于计算自注意力 head 中的加权平均值。

    cross_attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=Trueconfig.add_cross_attention=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的 Tuple (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

解码器的 cross-attention 层的 Attention weights,在 attention softmax 之后,用于计算 cross-attention head 中的加权平均值。

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

示例

>>> from transformers import AutoTokenizer, MraModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/mra-base-512-4")
>>> model = MraModel.from_pretrained("uw-madison/mra-base-512-4")

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

>>> last_hidden_states = outputs.last_hidden_state

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

MraForMaskedLM

class transformers.MraForMaskedLM

( config )

参数

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

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

forward

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_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)) — 词汇表中输入序列 token 的索引。

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

    什么是 input IDs?

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

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

    什么是 attention masks?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于指示输入的第一部分和第二部分的分段 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) — 位置嵌入中每个输入序列 token 的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于置空自注意力模块中选定 head 的 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_hidden_states (bool, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯 tuple。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算 masked language modeling loss 的标签。 索引应在 [-100, 0, ..., config.vocab_size] 中 (参见 input_ids 文档字符串)。 索引设置为 -100 的 Token 将被忽略 (masked),loss 仅针对标签在 [0, ..., config.vocab_size] 中的 token 计算。

return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯 tuple。

transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor of shape (1,), optional, 当提供 labels 时返回) — Masked language modeling (MLM) loss。

  • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — language modeling head 的预测分数 (SoftMax 之前每个词汇表 token 的分数)。

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

    hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型有嵌入层,则为嵌入的输出 + 每层输出一个) ,形状为 (batch_size, sequence_length, hidden_size)

  • 模型在每一层输出的 Hidden-states,加上可选的初始嵌入输出。

    attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的 Tuple (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

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

示例

>>> from transformers import AutoTokenizer, MraForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/mra-base-512-4")
>>> model = MraForMaskedLM.from_pretrained("uw-madison/mra-base-512-4")

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

MraForSequenceClassification

class transformers.MraForSequenceClassification

< >

( config )

参数

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

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

forward

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)

参数

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

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

    What are input IDs?

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

    What are attention masks?

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

    What are 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].

    What are position IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,
    • 0 indicates the head is masked.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
  • labels (torch.LongTensor of shape (batch_size,), optional) — Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯 tuple。

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

A transformers.modeling_outputs.SequenceClassifierOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (MraConfig) and inputs.

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Classification (or regression if config.num_labels==1) loss.

  • logits (torch.FloatTensor of shape (batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax).

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

    hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型有嵌入层,则为嵌入的输出 + 每层输出一个) ,形状为 (batch_size, sequence_length, hidden_size)

  • 模型在每一层输出的 Hidden-states,加上可选的初始嵌入输出。

    attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的 Tuple (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

The MraForSequenceClassification forward method, overrides the __call__ special method.

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

Example of single-label classification

>>> import torch
>>> from transformers import AutoTokenizer, MraForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/mra-base-512-4")
>>> model = MraForSequenceClassification.from_pretrained("uw-madison/mra-base-512-4")

>>> 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 = MraForSequenceClassification.from_pretrained("uw-madison/mra-base-512-4", num_labels=num_labels)

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

Example of multi-label classification

>>> import torch
>>> from transformers import AutoTokenizer, MraForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/mra-base-512-4")
>>> model = MraForSequenceClassification.from_pretrained("uw-madison/mra-base-512-4", 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 = MraForSequenceClassification.from_pretrained(
...     "uw-madison/mra-base-512-4", 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

MraForMultipleChoice

class transformers.MraForMultipleChoice

< >

( config )

参数

  • config (MraConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

MRA Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks. This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.MultipleChoiceModelOutput or tuple(torch.FloatTensor)

参数

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

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

    What are input IDs?

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

    What are attention masks?

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

    What are 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].

    What are position IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,
    • 0 indicates the head is masked.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, num_choices, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 更多细节请查看返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯粹的元组。
  • labels (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算多项选择分类损失的标签。 索引应在 [0, ..., num_choices-1] 中,其中 num_choices 是输入张量第二个维度的大小。(参见上面的 input_ids

return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯 tuple。

transformers.modeling_outputs.MultipleChoiceModelOutputtuple(torch.FloatTensor)

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

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

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

    分类得分(在 SoftMax 之前)。

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

    hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型有嵌入层,则为嵌入的输出 + 每层输出一个) ,形状为 (batch_size, sequence_length, hidden_size)

  • 模型在每一层输出的 Hidden-states,加上可选的初始嵌入输出。

    attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的 Tuple (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

MraForMultipleChoice 前向方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, MraForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/mra-base-512-4")
>>> model = MraForMultipleChoice.from_pretrained("uw-madison/mra-base-512-4")

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

MraForTokenClassification

class transformers.MraForTokenClassification

< >

( config )

参数

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

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

forward

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.TokenClassifierOutputtuple(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 在位置嵌入中的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

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

    • 1 表示 head 未被掩码
    • 0 表示 head 被掩码
  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)可选) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您想要比模型的内部嵌入查找矩阵更好地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 更多细节请查看返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯粹的元组。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 用于计算 token 分类损失的标签。 索引应在 [0, ..., config.num_labels - 1] 中。

return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯 tuple。

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

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

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

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

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

    hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型有嵌入层,则为嵌入的输出 + 每层输出一个) ,形状为 (batch_size, sequence_length, hidden_size)

  • 模型在每一层输出的 Hidden-states,加上可选的初始嵌入输出。

    attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的 Tuple (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

MraForTokenClassification 前向方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, MraForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/mra-base-512-4")
>>> model = MraForTokenClassification.from_pretrained("uw-madison/mra-base-512-4")

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

MraForQuestionAnswering

class transformers.MraForQuestionAnswering

< >

( config )

参数

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

带有 span 分类头的 MRA 模型,用于抽取式问答任务,如 SQuAD(隐藏状态输出顶部的线性层,用于计算 span start logitsspan end logits)。 此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与通用用法和行为相关的所有事项。

forward

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None start_positions: typing.Optional[torch.Tensor] = None end_positions: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = 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)可选) — 位置嵌入中每个输入序列标记的位置索引。 在范围 [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_hidden_states (bool可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是纯元组。
  • start_positions (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算标记分类损失的带标签跨度的起始位置(索引)的标签。 位置被限制为序列的长度 (sequence_length)。 序列之外的位置不计入损失计算。
  • end_positions (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算标记分类损失的带标签跨度的结束位置(索引)的标签。 位置被限制为序列的长度 (sequence_length)。 序列之外的位置不计入损失计算。

return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯 tuple。

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor,形状为 (1,)可选,当提供 labels 时返回) — 总跨度提取损失是起始位置和结束位置的交叉熵损失之和。

  • start_logits (torch.FloatTensor,形状为 (batch_size, sequence_length)) — 跨度起始得分(SoftMax 之前)。

  • end_logits (torch.FloatTensor,形状为 (batch_size, sequence_length)) — 跨度结束得分(SoftMax 之前)。

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

    hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型有嵌入层,则为嵌入的输出 + 每层输出一个) ,形状为 (batch_size, sequence_length, hidden_size)

  • 模型在每一层输出的 Hidden-states,加上可选的初始嵌入输出。

    attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的 Tuple (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

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

示例

>>> from transformers import AutoTokenizer, MraForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("uw-madison/mra-base-512-4")
>>> model = MraForQuestionAnswering.from_pretrained("uw-madison/mra-base-512-4")

>>> 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
< > 在 GitHub 上更新