Transformers 文档

MobileViTV2

MobileViTV2

概述

MobileViTV2模型由Sachin Mehta和Mohammad Rastegari在Separable Self-attention for Mobile Vision Transformers中提出。

MobileViTV2 是 MobileViT 的第二个版本,通过将 MobileViT 中的多头自注意力替换为可分离自注意力构建而成。

论文的摘要如下:

移动视觉变换器(MobileViT)可以在多个移动视觉任务中实现最先进的性能,包括分类和检测。尽管这些模型的参数较少,但与基于卷积神经网络的模型相比,它们的延迟较高。MobileViT中的主要效率瓶颈是变换器中的多头自注意力(MHA),它需要O(k2)的时间复杂度,其中k是标记(或补丁)的数量。此外,MHA需要昂贵的操作(例如,批处理矩阵乘法)来计算自注意力,这影响了资源受限设备上的延迟。本文介绍了一种具有线性复杂度(即O(k))的可分离自注意力方法。该方法的一个简单而有效的特点是它使用逐元素操作来计算自注意力,使其成为资源受限设备的良好选择。改进后的模型MobileViTV2在多个移动视觉任务上达到了最先进的水平,包括ImageNet对象分类和MS-COCO对象检测。MobileViTV2拥有约300万个参数,在ImageNet数据集上实现了75.6%的top-1准确率,比MobileViT高出约1%,同时在移动设备上运行速度快了3.2倍。

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

使用提示

  • MobileViTV2 更像是一个 CNN 而不是 Transformer 模型。它不处理序列数据,而是处理批量图像。与 ViT 不同,它没有嵌入。骨干模型输出一个特征图。
  • 可以使用MobileViTImageProcessor来为模型准备图像。请注意,如果您自己进行预处理,预训练的检查点期望图像以BGR像素顺序(而不是RGB)排列。
  • 可用的图像分类检查点是在ImageNet-1k(也称为ILSVRC 2012,包含130万张图像和1,000个类别)上预训练的。
  • 分割模型使用了一个DeepLabV3头。可用的语义分割检查点是在PASCAL VOC上预训练的。

MobileViTV2Config

transformers.MobileViTV2Config

< >

( num_channels = 3 image_size = 256 patch_size = 2 expand_ratio = 2.0 hidden_act = 'swish' conv_kernel_size = 3 output_stride = 32 classifier_dropout_prob = 0.1 initializer_range = 0.02 layer_norm_eps = 1e-05 aspp_out_channels = 512 atrous_rates = [6, 12, 18] aspp_dropout_prob = 0.1 semantic_loss_ignore_index = 255 n_attn_blocks = [2, 4, 3] base_attn_unit_dims = [128, 192, 256] width_multiplier = 1.0 ffn_multiplier = 2 attn_dropout = 0.0 ffn_dropout = 0.0 **kwargs )

参数

  • num_channels (int, optional, defaults to 3) — 输入通道的数量。
  • image_size (int, optional, defaults to 256) — 每张图片的大小(分辨率)。
  • patch_size (int, optional, defaults to 2) — 每个补丁的大小(分辨率)。
  • expand_ratio (float, optional, 默认为 2.0) — MobileNetv2 层的扩展因子。
  • hidden_act (strfunction, 可选, 默认为 "swish") — Transformer编码器和卷积层中的非线性激活函数(函数或字符串)。
  • conv_kernel_size (int, optional, 默认为 3) — MobileViTV2 层中卷积核的大小。
  • output_stride (int, optional, 默认为 32) — 输出空间分辨率与输入图像分辨率的比率。
  • classifier_dropout_prob (float, optional, defaults to 0.1) — 附加分类器的丢弃比例。
  • initializer_range (float, 可选, 默认值为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-05) — 层归一化层使用的epsilon值。
  • aspp_out_channels (int, optional, defaults to 512) — 用于语义分割的ASPP层中的输出通道数。
  • atrous_rates (List[int], 可选, 默认为 [6, 12, 18]) — 用于ASPP层进行语义分割的扩张(空洞)因子。
  • aspp_dropout_prob (float, optional, defaults to 0.1) — 用于语义分割的ASPP层的丢弃比率。
  • semantic_loss_ignore_index (int, optional, defaults to 255) — 语义分割模型的损失函数忽略的索引。
  • n_attn_blocks (List[int], optional, defaults to [2, 4, 3]) — 每个MobileViTV2Layer中的注意力块的数量
  • base_attn_unit_dims (List[int], 可选, 默认为 [128, 192, 256]) — 每个MobileViTV2Layer中注意力块维度的基础乘数
  • width_multiplier (float, 可选, 默认为 1.0) — MobileViTV2 的宽度乘数。
  • ffn_multiplier (int, 可选, 默认为 2) — MobileViTV2 的 FFN 乘数。
  • attn_dropout (float, optional, defaults to 0.0) — 注意力层中的dropout。
  • ffn_dropout (float, optional, defaults to 0.0) — FFN层之间的dropout。

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

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

示例:

>>> from transformers import MobileViTV2Config, MobileViTV2Model

>>> # Initializing a mobilevitv2-small style configuration
>>> configuration = MobileViTV2Config()

>>> # Initializing a model from the mobilevitv2-small style configuration
>>> model = MobileViTV2Model(configuration)

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

MobileViTV2Model

transformers.MobileViTV2Model

< >

( config: MobileViTV2Config expand_output: bool = True )

参数

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

裸的MobileViTV2模型输出原始隐藏状态,没有任何特定的头部。 这个模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 MobileViTImageProcessor.call().
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

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

  • last_hidden_state (torch.FloatTensor 形状为 (batch_size, num_channels, height, width)) — 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.FloatTensor 形状为 (batch_size, hidden_size)) — 在空间维度上进行池化操作后的最后一层隐藏状态。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, num_channels, height, width)

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

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

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

示例:

>>> from transformers import AutoImageProcessor, MobileViTV2Model
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
>>> model = MobileViTV2Model.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")

>>> inputs = image_processor(image, return_tensors="pt")

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

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 512, 8, 8]

MobileViTV2ForImageClassification

transformers.MobileViTV2ForImageClassification

< >

( config: MobileViTV2Config )

参数

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

MobileViTV2模型,顶部带有图像分类头(在池化特征之上的线性层),例如用于ImageNet。

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

前进

< >

( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None labels: typing.Optional[torch.Tensor] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 MobileViTImageProcessor.call().
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失)。如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

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

  • 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, num_channels, height, width)。模型在每个阶段输出的隐藏状态(也称为特征图)。

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

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

示例:

>>> from transformers import AutoImageProcessor, MobileViTV2ForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
>>> model = MobileViTV2ForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")

>>> inputs = image_processor(image, return_tensors="pt")

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

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
tabby, tabby cat

MobileViTV2ForSemanticSegmentation

transformers.MobileViTV2ForSemanticSegmentation

< >

( config: MobileViTV2Config )

参数

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

MobileViTV2 模型,顶部带有语义分割头,例如用于 Pascal VOC。

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

前进

< >

( pixel_values: 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.SemanticSegmenterOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 MobileViTImageProcessor.call().
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size, height, width), optional) — 用于计算损失的真实语义分割图。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.SemanticSegmenterOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 分类(或回归,如果 config.num_labels==1)损失。

  • logits (torch.FloatTensor 形状为 (batch_size, config.num_labels, logits_height, logits_width)) — 每个像素的分类分数。

    返回的 logits 不一定与作为输入传递的 pixel_values 大小相同。这是 为了避免在用户需要将 logits 调整回原始图像大小时进行两次插值并损失一些质量。您应始终检查 logits 的形状并根据需要调整大小。

  • hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为 (batch_size, patch_size, hidden_size)

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

  • attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每层一个)形状为 (batch_size, num_heads, patch_size, sequence_length)

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

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

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

示例:

>>> import requests
>>> import torch
>>> from PIL import Image
>>> from transformers import AutoImageProcessor, MobileViTV2ForSemanticSegmentation

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
>>> model = MobileViTV2ForSemanticSegmentation.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")

>>> inputs = image_processor(images=image, return_tensors="pt")

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

>>> # logits are of shape (batch_size, num_labels, height, width)
>>> logits = outputs.logits
< > Update on GitHub