Transformers documentation

MobileViTV2

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

该模型于 2022-06-06 在 HF papers 上发布,并于 2023-06-02 贡献至 Hugging Face Transformers。

MobileViTV2

概述

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

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

该论文的摘要如下:

移动视觉 Transformer(MobileViT)在包括分类和检测在内的多种移动视觉任务中均能取得最先进的性能。尽管这些模型的参数量较少,但与基于卷积神经网络的模型相比,其延迟较高。MobileViT 中主要的效率瓶颈在于 Transformer 中的多头自注意力(MHA),其时间复杂度相对于 token(或 patch)数量 k 呈 O(k2) 增长。此外,MHA 在计算自注意力时需要执行代价高昂的操作(例如按批次进行的矩阵乘法),这会影响资源受限设备上的延迟。本文提出了一种具有线性复杂度(即 O(k))的可分离自注意力方法。该方法的简单而有效的特点在于,它使用逐元素操作来计算自注意力,因此非常适合资源受限的设备。改进后的模型 MobileViTV2 在包括 ImageNet 目标分类和 MS-COCO 目标检测在内的多项移动视觉任务中达到了最先进水平。MobileViTV2 拥有约三百万个参数,在 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

< >

( 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 = Nonenum_channels: int = 3image_size: int | list[int] | tuple[int, int] = 256patch_size: int | list[int] | tuple[int, int] = 2expand_ratio: float = 2.0hidden_act: str = 'swish'conv_kernel_size: int = 3output_stride: int = 32classifier_dropout_prob: float | int = 0.1initializer_range: float = 0.02layer_norm_eps: float = 1e-05aspp_out_channels: int = 512atrous_rates: list[int] | tuple[int, ...] = (6, 12, 18)aspp_dropout_prob: float | int = 0.1semantic_loss_ignore_index: int = 255n_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.0ffn_multiplier: int = 2attn_dropout: float | int = 0.0ffn_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 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • aspp_out_channels (int,可选,默认为 512) — 用于语义分割的 ASPP 层中的输出通道数。
  • atrous_rates (list[int],可选,默认为 [6, 12, 18]) — 用于语义分割中 ASPP 层的膨胀(空洞)卷积因子。
  • aspp_dropout_prob (float,可选,默认值为 0.1) — 用于语义分割的 ASPP 层的 dropout 比率。
  • 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) — 注意力概率的 dropout 比率。
  • ffn_dropout (float, 可选,默认为 0.0) — FFN 层之间的 dropout。

这是用于存储 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: MobileViTV2Configexpand_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: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)

参数

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

返回值

BaseModelOutputWithPoolingAndNoAttention 或 tuple(torch.FloatTensor)

BaseModelOutputWithPoolingAndNoAttention 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MobileViTV2Config)和输入。

MobileViTV2Model 的 forward 方法会重写 __call__ 特殊方法。

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

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

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

  • hidden_states (tuple(torch.FloatTensor),可选,在传入 output_hidden_states=True 或 config.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: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonelabels: typing.Optional[torch.Tensor] = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 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 而不是普通元组。

返回值

ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)

一个 ImageClassifierOutputWithNoAttention 或 torch.FloatTensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(MobileViTV2Config)和输入。

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

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

  • loss (torch.FloatTensor,形状为 (1,),可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。
  • logits(形状为 (batch_size, config.num_labels) 的 torch.FloatTensor)— 分类(或当 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)。模型在每个阶段输出处的隐藏状态(也称为特征图)。

示例:

>>> 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: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → SemanticSegmenterOutput or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 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 而不是普通元组。

返回值

SemanticSegmenterOutput 或 tuple(torch.FloatTensor)

一个 SemanticSegmenterOutput 或 torch.FloatTensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MobileViTV2Config)和输入。

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

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

  • loss (torch.FloatTensor,形状为 (1,),可选,当提供 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),可选,在传入 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from huggingface_hub.utils 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
Update on GitHub