Transformers documentation

ViTMAE

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2021-11-11 在 HF papers 上发布,并于 2022-01-18 贡献给 Hugging Face Transformers。

FlashAttention SDPA

ViTMAE

ViTMAE 是一种自监督视觉模型,通过遮蔽图像的大部分区域(约 75%)进行预训练。编码器处理可见的图像块,解码器则根据编码后的图像块和掩码标记重建缺失的像素。预训练完成后,编码器可复用于图像分类或目标检测等下游任务——其性能通常优于使用监督学习训练的模型。

drawing

您可以在 AI at Meta 组织下找到所有原始的 ViTMAE 检查点。

点击右侧边栏中的 ViTMAE 模型,以查看更多将 ViTMAE 应用于视觉任务的示例。

以下示例演示了如何使用 ViTMAEForPreTraining 类重建缺失的像素。

AutoModel
import requests
import torch
from PIL import Image

from transformers import ViTImageProcessor, ViTMAEForPreTraining


url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)

processor = ViTImageProcessor.from_pretrained("facebook/vit-mae-base")
inputs = processor(image, return_tensors="pt").to(model.device)
inputs = {k: v.to(model.device) for k, v in inputs.items()}

model = ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base", attn_implementation="sdpa", device_map="auto")
with torch.no_grad():
    outputs = model(**inputs)

reconstruction = outputs.logits

备注

资源

ViTMAEConfig

class transformers.ViTMAEConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-12image_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3qkv_bias: bool = Truedecoder_num_attention_heads: int = 16decoder_hidden_size: int = 512decoder_num_hidden_layers: int = 8decoder_intermediate_size: int = 2048mask_ratio: float = 0.75norm_pix_loss: bool = False )

参数

  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_dropout_prob (Union[float, int],可选,默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-12) — 层归一化层所使用的 epsilon 值。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 224) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • decoder_num_attention_heads (int,可选,默认值为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • decoder_hidden_size (int,可选,默认为 512) — 隐藏表示的维度。
  • decoder_num_hidden_layers (int,可选,默认为 8) — 解码器中的隐藏层数量。
  • decoder_intermediate_size (int,可选,默认为 2048) — MLP 表示的维度。
  • mask_ratio (float,可选,默认值为 0.75) — 输入序列中被掩码标记的数量比例。
  • norm_pix_loss(bool,可选,默认为 False)— 是否使用归一化像素进行训练(参见论文中的表 3)。在作者的实验中,使用归一化像素提升了表征质量。

这是用于存储 ViTMAEModel 配置的类。它根据指定的参数实例化 Vit Mae 模型,并定义模型架构。使用默认值实例化配置将得到与 facebook/vit-mae-base 类似的配置。

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

示例:

>>> from transformers import ViTMAEConfig, ViTMAEModel

>>> # Initializing a ViT MAE vit-mae-base style configuration
>>> configuration = ViTMAEConfig()

>>> # Initializing a model (with random weights) from the vit-mae-base style configuration
>>> model = ViTMAEModel(configuration)

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

ViTMAEModel

class transformers.ViTMAEModel

< >

( config: ViTMAEConfig )

参数

未添加任何特定头部的裸 Vit Mae 模型,直接输出原始隐藏状态。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonenoise: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool | None = Noneattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ViTMAEModelOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 ViTImageProcessor 获取像素值。有关详细信息,请参阅 ViTImageProcessor.call()(processor_class 使用 ViTImageProcessor 处理图像)。
  • noise (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 主要用于测试目的,以控制随机性并保持可复现性
  • interpolate_pos_encoding (bool,可选,默认值为 False) — 是否对预训练的位置编码进行插值。这主要用于在更高分辨率的图像上使用模型。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

返回值

ViTMAEModelOutput 或 tuple(torch.Tensor)

ViTMAEModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(ViTMAEConfig)和输入。

ViTMAEModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

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

  • mask(形状为 (batch_size, sequence_length) 的 torch.Tensor)— 指示哪些 patch 被掩码(1)、哪些未被掩码(0)的张量。

  • ids_restore(形状为 (batch_size, sequence_length) 的 torch.LongTensor)— 包含(打乱后的)掩码补丁原始索引的张量。

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

示例:

>>> from transformers import AutoImageProcessor, ViTMAEModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/vit-mae-base")
>>> model = ViTMAEModel.from_pretrained("facebook/vit-mae-base")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state

ViTMAEForPreTraining

class transformers.ViTMAEForPreTraining

< >

( config: ViTMAEConfig )

参数

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

带有解码器的 ViTMAE 模型 Transformer,用于自监督预训练。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonenoise: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool | None = Noneattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ViTMAEForPreTrainingOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 ViTImageProcessor 获取像素值。有关详细信息,请参阅 ViTImageProcessor.call()(processor_class 使用 ViTImageProcessor 处理图像)。
  • noise (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 主要用于测试目的,以控制随机性并保持可复现性
  • interpolate_pos_encoding (bool,可选,默认值为 False) — 是否对预训练的位置编码进行插值。这主要用于在更高分辨率的图像上使用模型。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

返回值

ViTMAEForPreTrainingOutput 或 tuple(torch.Tensor)

ViTMAEForPreTrainingOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(ViTMAEConfig)和输入而定的各种元素。

ViTMAEForPreTraining 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss(形状为 (1,) 的 torch.Tensor)— 像素重建损失。

  • logits(形状为 (batch_size, sequence_length, patch_size ** 2 * num_channels) 的 torch.Tensor)— 像素重建 logits。

  • mask(形状为 (batch_size, sequence_length) 的 torch.Tensor)— 指示哪些 patch 被掩码(1)、哪些未被掩码(0)的张量。

  • ids_restore(形状为 (batch_size, sequence_length) 的 torch.LongTensor)— 包含(打乱后的)掩码补丁原始索引的张量。

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

示例:

>>> from transformers import AutoImageProcessor, ViTMAEForPreTraining
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/vit-mae-base")
>>> model = ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> loss = outputs.loss
>>> mask = outputs.mask
>>> ids_restore = outputs.ids_restore
Update on GitHub