Transformers 文档

MobileViTV2

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2022 年 6 月 6 日发布在 HF papers 上,并于 2023 年 6 月 2 日贡献给 Hugging Face Transformers。

MobileViTV2

概述

MobileViTV2 模型由 Sachin Mehta 和 Mohammad Rastegari 在《移动视觉 Transformer 的可分离自注意力机制》(Separable Self-attention for Mobile Vision Transformers)中提出。

MobileViTV2 是 MobileViT 的第二个版本,通过用“可分离自注意力机制”(separable self-attention)替换 MobileViT 中的“多头自注意力机制”(multi-headed self-attention)而构建。

论文摘要如下:

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

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

使用技巧

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

MobileViTV2Config

class transformers.MobileViTV2Config

< >

( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None num_channels: int = 3 image_size: int | list[int] | tuple[int, int] = 256 patch_size: int | list[int] | tuple[int, int] = 2 expand_ratio: float = 2.0 hidden_act: str = 'swish' conv_kernel_size: int = 3 output_stride: int = 32 classifier_dropout_prob: float | int = 0.1 initializer_range: float = 0.02 layer_norm_eps: float = 1e-05 aspp_out_channels: int = 512 atrous_rates: list[int] | tuple[int, ...] = (6, 12, 18) aspp_dropout_prob: float | int = 0.1 semantic_loss_ignore_index: int = 255 n_attn_blocks: list[int] | tuple[int, ...] = (2, 4, 3) base_attn_unit_dims: list[int] | tuple[int, ...] = (128, 192, 256) width_multiplier: float | int = 1.0 ffn_multiplier: int = 2 attn_dropout: float | int = 0.0 ffn_dropout: float | int = 0.0 )

参数

  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]], 可选, 默认为 256) — 每个图像的大小(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]], 可选, 默认为 2) — 每个补丁(patch)的大小(分辨率)。
  • expand_ratio (float, 可选, 默认为 2.0) — 用于设置扩展输出维度的扩展比例。
  • hidden_act (str, 可选, 默认为 swish) — 解码器中的非线性激活函数(函数或字符串)。例如:"gelu""relu""silu" 等。
  • conv_kernel_size (int, 可选, 默认为 3) — 卷积核的大小。
  • output_stride (int, 可选, 默认为 32) — 输入特征图与输出特征图空间分辨率之间的比率。
  • classifier_dropout_prob (Union[float, int], 可选, 默认为 0.1) — 分类器的丢弃率(dropout ratio)。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-05) — 层归一化(layer normalization)层使用的 epsilon 值。
  • aspp_out_channels (int, 可选, 默认为 512) — 用于语义分割的 ASPP 层中的输出通道数。
  • atrous_rates (list[int], 可选, 默认为 [6, 12, 18]) — 用于语义分割的 ASPP 层中的扩张(空洞)系数。
  • aspp_dropout_prob (float, 可选, 默认为 0.1) — 用于语义分割的 ASPP 层的丢弃率。
  • semantic_loss_ignore_index (int, 可选, 默认为 255) — 语义分割模型损失函数忽略的索引。
  • n_attn_blocks (list[int], 可选, 默认为 [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 (Union[float, int], 可选, 默认为 0.0) — 注意力概率的丢弃率。
  • ffn_dropout (float, 可选, 默认为 0.0) — FFN 层之间的丢弃率。

这是用于存储 MobileViTV2Model 配置的配置类。它用于根据指定的参数实例化 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

class transformers.MobileViTV2Model

< >

( config: MobileViTV2Config expand_output: bool = True )

参数

  • config (MobileViTV2Config) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • expand_output (bool, 可选, 默认为 True) — 是否扩展模型的输出。如果为 True,模型除了输出隐藏状态外,还将输出池化特征。如果为 False,则仅返回隐藏状态。

原始的 Mobilevitv2 模型,输出未经任何特定头部处理的原始隐藏状态。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.Tensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor, 可选) — 对应于输入图像的张量。像素值可以使用 MobileViTImageProcessor 获取。详情请参阅 MobileViTImageProcessor.__call__()processor_class 使用 MobileViTImageProcessor 来处理图像)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请查看返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是普通的元组。

返回

BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一个 BaseModelOutputWithPoolingAndNoAttention 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),具体取决于配置(MobileViTV2Config)和输入,包含各种元素。

MobileViTV2Model 的前向传播方法,覆盖了 __call__ 特殊方法。

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

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

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

  • hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每层的一个输出),形状为 (batch_size, num_channels, height, width)

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

示例

MobileViTV2ForImageClassification

class transformers.MobileViTV2ForImageClassification

< >

( config: MobileViTV2Config )

参数

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

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

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.Tensor | None = None output_hidden_states: bool | None = None labels: torch.Tensor | None = None return_dict: bool | None = None **kwargs ) ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor, 可选) — 对应于输入图像的张量。像素值可以使用 MobileViTImageProcessor 获取。详情请参阅 MobileViTImageProcessor.__call__()processor_class 使用 MobileViTImageProcessor 来处理图像)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请查看返回张量下的 hidden_states
  • labels (形状为 (batch_size,)torch.LongTensor, 可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方误差损失)。如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是普通的元组。

返回

ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

一个 ImageClassifierOutputWithNoAttention 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),具体取决于配置(MobileViTV2Config)和输入,包含各种元素。

MobileViTV2ForImageClassification 的前向传播方法,覆盖了 __call__ 特殊方法。

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

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。
  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。
  • hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每阶段的一个输出),形状为 (batch_size, num_channels, height, width)。模型在每个阶段输出的隐藏状态(也称为特征图)。

示例

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

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

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

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

MobileViTV2ForSemanticSegmentation

class transformers.MobileViTV2ForSemanticSegmentation

< >

( config: MobileViTV2Config )

参数

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

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

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.Tensor | None = None labels: torch.Tensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) SemanticSegmenterOutputtuple(torch.FloatTensor)

参数

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

返回

SemanticSegmenterOutputtuple(torch.FloatTensor)

一个 SemanticSegmenterOutput 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),具体取决于配置(MobileViTV2Config)和输入,包含各种元素。

MobileViTV2ForSemanticSegmentation 的前向传播方法,覆盖了 __call__ 特殊方法。

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

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

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

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

  • hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每层的一个输出),形状为 (batch_size, patch_size, hidden_size)

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

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

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

示例

>>> import httpx
>>> from io import BytesIO
>>> import torch
>>> from PIL import Image
>>> from transformers import AutoImageProcessor, MobileViTV2ForSemanticSegmentation

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

© . This site is unofficial and not affiliated with Hugging Face, Inc.