Transformers documentation

SwiftFormer

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

and get access to the augmented documentation experience

to get started

该模型于 2023-03-27 在 HF papers 上发布,并于 2023-05-12 贡献给 Hugging Face Transformers。

SwiftFormer

概述

SwiftFormer 模型由 Abdelrahman Shaker、Muhammad Maaz、Hanoona Rasheed、Salman Khan、Ming-Hsuan Yang 和 Fahad Shahbaz Khan 在 SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications 中提出。

SwiftFormer 论文提出了一种新颖的高效加法注意力机制,该机制有效地将自注意力计算中的二次矩阵乘法操作替换为线性逐元素乘法。基于此构建了一系列名为 “SwiftFormer” 的模型,在准确率和移动端推理速度方面均达到了最先进的性能。即使其小型变体,在 iPhone 14 上仅 0.8 ms 延迟的情况下,也能达到 78.5% 的 ImageNet1K top-1 准确率,相比 MobileViT-v2 更准确且速度快 2 倍。

该论文的摘要如下:

自注意力机制已成为各类视觉应用中捕获全局上下文的默认选择。然而,其计算复杂度随图像分辨率呈二次方增长,这限制了它在实时应用中的使用,尤其是在资源受限的移动设备上部署时。尽管已有混合方法被提出,旨在结合卷积和自注意力的优势以获得更好的速度与精度平衡,但自注意力中昂贵的矩阵乘法操作仍然是瓶颈。在本工作中,我们提出了一种新颖的高效加法注意力机制,有效地将二次方矩阵乘法操作替换为线性逐元素乘法。我们的设计表明,键值交互可以被一个线性层替换,而不会牺牲任何精度。与之前的最先进方法不同,我们的高效自注意力公式使其能够在网络的所有阶段使用。利用我们提出的高效加法注意力,我们构建了一系列名为“SwiftFormer”的模型,在精度和移动推理速度方面均达到了最先进的性能。我们的小型变体在 iPhone 14 上仅以 0.8 毫秒的延迟实现了 78.5% 的 ImageNet-1K top-1 精度,比 MobileViT-v2 更准确且速度快 2 倍。

该模型由 shehan97 贡献。原始代码可在此处找到。

SwiftFormerConfig

类 transformers.SwiftFormerConfig

< >

( 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 = Noneimage_size: int | list[int] | tuple[int, int] = 224num_channels: int = 3depths: list[int] | tuple[int, ...] = (3, 3, 6, 4)embed_dims: list[int] | tuple[int, ...] = (48, 56, 112, 220)mlp_ratio: int = 4downsamples: list[bool] | tuple[bool, ...] = (True, True, True, True)hidden_act: str = 'gelu'down_patch_size: int | list[int] | tuple[int, int] = 3down_stride: int = 2down_pad: int = 1drop_path_rate: float | int = 0.0drop_mlp_rate: float | int = 0.0drop_conv_encoder_rate: float | int = 0.0use_layer_scale: bool = Truelayer_scale_init_value: float = 1e-05batch_norm_eps: float = 1e-05 )

参数

  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 224) — 每张图片的尺寸(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • depths (Union[list[int], tuple[int, ...]],可选,默认为 (3, 3, 6, 4)) — Transformer 中每一层的深度。
  • embed_dims (list[int],可选,默认为 [48, 56, 112, 220]) — 每个阶段的嵌入维度
  • mlp_ratio (int,可选,默认为 4) — MLP 隐藏层维度与嵌入维度的比值。
  • downsamples (list[bool],可选,默认为 [True, True, True, True]) — 是否在两个阶段之间对输入进行下采样。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • down_patch_size (int,可选,默认为 3) — 下采样层中 patch 的大小。
  • down_stride (int,可选,默认为 2) — 下采样层中卷积核的步长。
  • down_pad (int,可选,默认为 1) — 下采样层中的填充。
  • drop_path_rate (Union[float, int],可选,默认为 0.0) — 用于 patch fusion 的 drop path 比率。
  • drop_mlp_rate (float,可选,默认值为 0.0) — SwiftFormer 中 MLP 组件的 Dropout 率。
  • drop_conv_encoder_rate (float,可选,默认值为 0.0) — SwiftFormer 中 ConvEncoder 组件的 Dropout 率。
  • use_layer_scale (bool,可选,默认为 True) — 是否对 token mixer 的输出进行缩放。
  • layer_scale_init_value (float, 可选,默认为 1e-05) — 用于自注意力层的缩放值。base 模型使用 0.1,large 模型使用 1e-6。设置为 0 可禁用 layer scale。
  • batch_norm_eps (float,可选,默认为 1e-05) — 批归一化层使用的 epsilon 值。

这是用于存储 SwiftFormerModel 配置的类。它根据指定的参数实例化 Swiftformer 模型,并定义模型架构。使用默认值实例化配置将生成与 MBZUAI/swiftformer-xs 类似的配置。

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

示例:

>>> from transformers import SwiftFormerConfig, SwiftFormerModel

>>> # Initializing a SwiftFormer swiftformer-base-patch16-224 style configuration
>>> configuration = SwiftFormerConfig()

>>> # Initializing a model (with random weights) from the swiftformer-base-patch16-224 style configuration
>>> model = SwiftFormerModel(configuration)

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

SwiftFormerModel

class transformers.SwiftFormerModel

< >

( config: SwiftFormerConfig )

参数

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

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

该模型继承自 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 ) → BaseModelOutputWithNoAttention or tuple(torch.Tensor)

参数

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

返回值

BaseModelOutputWithNoAttention 或 tuple(torch.Tensor)

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

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

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

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

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

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

示例:

SwiftFormerForImageClassification

class transformers.SwiftFormerForImageClassification

< >

( config: SwiftFormerConfig )

参数

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

带有图像分类头的 Swiftformer 模型,例如用于 ImageNet。

该模型继承自 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 ) → ImageClassifierOutputWithNoAttention or tuple(torch.Tensor)

参数

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

返回值

ImageClassifierOutputWithNoAttention 或 tuple(torch.Tensor)

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

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

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

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

示例:

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("MBZUAI/swiftformer-xs")
>>> model = SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs")

>>> 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])
...
Update on GitHub