Transformers 文档

池化变换器

PoolFormer

概述

PoolFormer模型是由Sea AI Labs在MetaFormer is Actually What You Need for Vision中提出的。这项工作不是通过设计复杂的token mixer来实现SOTA性能,而是旨在展示transformer模型的能力主要源于通用架构MetaFormer。

论文的摘要如下:

Transformer在计算机视觉任务中展现了巨大的潜力。普遍认为,其基于注意力的token mixer模块对其能力贡献最大。然而,最近的研究表明,Transformer中的基于注意力的模块可以被空间MLPs取代,并且所得到的模型仍然表现良好。基于这一观察,我们假设Transformer的通用架构,而不是特定的token mixer模块,对模型的性能更为关键。为了验证这一点,我们故意将Transformer中的注意力模块替换为一个极其简单的空间池化操作符,仅进行最基本的token混合。令人惊讶的是,我们观察到,由此衍生的模型,称为PoolFormer,在多个计算机视觉任务上取得了竞争性的性能。例如,在ImageNet-1K上,PoolFormer达到了82.1%的top-1准确率,超过了经过良好调整的视觉Transformer/MLP类基线DeiT-B/ResMLP-B24,准确率分别提高了0.3%/1.1%,同时减少了35%/52%的参数和48%/60%的MACs。PoolFormer的有效性验证了我们的假设,并促使我们提出了“MetaFormer”的概念,这是一种从Transformer中抽象出来的通用架构,不指定token mixer。基于广泛的实验,我们认为MetaFormer是最近Transformer和MLP类模型在视觉任务中取得优异结果的关键因素。这项工作呼吁未来的研究更多地致力于改进MetaFormer,而不是专注于token mixer模块。此外,我们提出的PoolFormer可以作为未来MetaFormer架构设计的起点基线。

下图展示了PoolFormer的架构。取自原始论文

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

使用提示

  • PoolFormer 具有分层架构,其中使用简单的平均池化层代替了注意力机制。该模型的所有检查点都可以在 hub 上找到。
  • 可以使用PoolFormerImageProcessor来为模型准备图像。
  • 与大多数模型一样,PoolFormer 也有不同的尺寸,具体细节可以在下表中找到。
模型变体 深度 隐藏层大小 参数 (M) ImageNet-1k Top 1
s12 [2, 2, 6, 2] [64, 128, 320, 512] 12 77.2
s24 [4, 4, 12, 4] [64, 128, 320, 512] 21 80.3
s36 [6, 6, 18, 6] [64, 128, 320, 512] 31 81.4
m36 [6, 6, 18, 6] [96, 192, 384, 768] 56 82.1
m48 [8, 8, 24, 8] [96, 192, 384, 768] 73 82.5

资源

一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用PoolFormer。

Image Classification

如果您有兴趣提交资源以包含在此处,请随时打开一个 Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。

PoolFormerConfig

transformers.PoolFormerConfig

< >

( num_channels = 3 patch_size = 16 stride = 16 pool_size = 3 mlp_ratio = 4.0 depths = [2, 2, 6, 2] hidden_sizes = [64, 128, 320, 512] patch_sizes = [7, 3, 3, 3] strides = [4, 2, 2, 2] padding = [2, 1, 1, 1] num_encoder_blocks = 4 drop_path_rate = 0.0 hidden_act = 'gelu' use_layer_scale = True layer_scale_init_value = 1e-05 initializer_range = 0.02 **kwargs )

参数

  • num_channels (int, optional, defaults to 3) — 输入图像中的通道数。
  • patch_size (int, optional, defaults to 16) — 输入补丁的大小。
  • stride (int, optional, 默认为 16) — 输入补丁的步幅.
  • pool_size (int, 可选, 默认为 3) — 池化窗口的大小。
  • mlp_ratio (float, optional, 默认为 4.0) — MLP 输出通道数与输入通道数的比率。
  • depths (list, 可选, 默认为 [2, 2, 6, 2]) — 每个编码器块的深度。
  • hidden_sizes (list, 可选, 默认为 [64, 128, 320, 512]) — 每个编码器块的隐藏大小。
  • patch_sizes (list, optional, defaults to [7, 3, 3, 3]) — 每个编码器块的输入补丁的大小。
  • strides (list, 可选, 默认为 [4, 2, 2, 2]) — 每个编码器块的输入补丁的步幅。
  • padding (list, 可选, 默认为 [2, 1, 1, 1]) — 每个编码器块的输入补丁的填充。
  • num_encoder_blocks (int, optional, 默认为 4) — 编码器块的数量。
  • drop_path_rate (float, optional, defaults to 0.0) — dropout层的dropout率。
  • hidden_act (str, optional, defaults to "gelu") — 隐藏层的激活函数。
  • use_layer_scale (bool, optional, defaults to True) — 是否使用层缩放.
  • layer_scale_init_value (float, optional, defaults to 1e-05) — 层比例的初始值。
  • initializer_range (float, optional, 默认为 0.02) — 权重的初始化范围。

这是用于存储PoolFormerModel配置的配置类。它用于根据指定的参数实例化一个PoolFormer模型,定义模型架构。使用默认值实例化配置将产生类似于PoolFormer sail/poolformer_s12架构的配置。

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

示例:

>>> from transformers import PoolFormerConfig, PoolFormerModel

>>> # Initializing a PoolFormer sail/poolformer_s12 style configuration
>>> configuration = PoolFormerConfig()

>>> # Initializing a model (with random weights) from the sail/poolformer_s12 style configuration
>>> model = PoolFormerModel(configuration)

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

PoolFormerFeatureExtractor

transformers.PoolFormerFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

预处理一张图像或一批图像。

PoolFormerImageProcessor

transformers.PoolFormerImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None crop_pct: int = 0.9 resample: Resampling = do_center_crop: bool = True crop_size: typing.Dict[str, int] = None rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_rescale: bool = True do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。可以在 preprocess 方法中被 do_resize 覆盖。
  • size (Dict[str, int] optional, defaults to {"shortest_edge" -- 224}): Size of the image after resizing. Can be overridden by size in the preprocess method. If crop_pct is unset:
    • size is {"height": h, "width": w}: the image is resized to (h, w).
    • size is {"shortest_edge": s}: the shortest edge of the image is resized to s whilst maintaining the aspect ratio.

    如果设置了crop_pct:

    • size is {"height": h, "width": w}: the image is resized to (int(floor(h/crop_pct)), int(floor(w/crop_pct)))
    • size is {"height": c, "width": c}: the shortest edge of the image is resized to int(floor(c/crop_pct) whilst maintaining the aspect ratio.
    • size is {"shortest_edge": c}: the shortest edge of the image is resized to int(floor(c/crop_pct) whilst maintaining the aspect ratio.
  • crop_pct (float, 可选, 默认为 0.9) — 从图像中心裁剪的百分比。可以在 preprocess 方法中被 crop_pct 覆盖。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BICUBIC) — 如果调整图像大小,则使用的重采样过滤器。可以在 preprocess 方法中通过 resample 覆盖此设置。
  • do_center_crop (bool, 可选, 默认为 True) — 是否对图像进行中心裁剪。如果输入尺寸在任何一边小于 crop_size,图像将用0填充,然后进行中心裁剪。可以在 preprocess 方法中通过 do_center_crop 进行覆盖。
  • crop_size (Dict[str, int], 可选, 默认为 {"height" -- 224, "width": 224}): 应用中心裁剪后的图像大小。仅在 do_center_crop 设置为 True 时有效。可以通过 preprocess 方法中的 crop_size 参数进行覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以在 preprocess 方法中通过 rescale_factor 参数覆盖此值。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 rescale_factor 来重新缩放图像。可以在 preprocess 方法中通过 do_rescale 参数进行覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 控制是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 参数进行覆盖。
  • image_mean (floatList[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (floatList[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以在 preprocess 方法中通过 image_std 参数进行覆盖。

构建一个PoolFormer图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] do_resize: bool = None size: typing.Dict[str, int] = None crop_pct: int = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • 图像 (ImageInput) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置 do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小.
  • size (Dict[str, int], optional, defaults to self.size) — 应用调整大小后的图像尺寸。
  • crop_pct (float, 可选, 默认为 self.crop_pct) — 裁剪图像的百分比。仅在 do_resize 设置为 True 时有效。
  • resample (int, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举 PILImageResampling 之一,只有在 do_resize 设置为 True 时才会生效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否对图像进行中心裁剪。
  • crop_size (Dict[str, int], optional, defaults to self.crop_size) — 应用中心裁剪后的图像大小。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的重新缩放因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化处理.
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 图像均值.
  • image_std (float or List[float], optional, defaults to self.image_std) — 图像标准差.
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • 未设置:返回一个 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回一个类型为 tf.Tensor 的批次。
    • TensorType.PYTORCH'pt':返回一个类型为 torch.Tensor 的批次。
    • TensorType.NUMPY'np':返回一个类型为 np.ndarray 的批次。
    • TensorType.JAX'jax':返回一个类型为 jax.numpy.ndarray 的批次。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

预处理一张图像或一批图像。

PoolFormerModel

transformers.PoolFormerModel

< >

( config )

参数

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

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

前进

< >

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

参数

返回

transformers.modeling_outputs.BaseModelOutputWithNoAttentiontuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithNoAttention 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(PoolFormerConfig)和输入的各种元素。

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

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

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

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

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

示例:

>>> from transformers import AutoImageProcessor, PoolFormerModel
>>> 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("sail/poolformer_s12")
>>> model = PoolFormerModel.from_pretrained("sail/poolformer_s12")

>>> 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, 7, 7]

PoolFormerForImageClassification

transformers.PoolFormerForImageClassification

< >

( config )

参数

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

PoolFormer 模型转换器,顶部带有图像分类头

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

前进

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_hidden_states: typing.Optional[bool] = 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获取。详情请参见 PoolFormerImageProcessor.call().
  • 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 时),包含各种 元素,具体取决于配置(PoolFormerConfig)和输入。

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

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

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

示例:

>>> from transformers import AutoImageProcessor, PoolFormerForImageClassification
>>> 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("sail/poolformer_s12")
>>> model = PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12")

>>> 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
< > Update on GitHub