Transformers 文档

PoolFormer

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

PoolFormer

PyTorch

概述

PoolFormer 模型是由 Sea AI Labs 在 MetaFormer is Actually What You Need for Vision 中提出的。这项工作的目标不是设计复杂的 token mixer 以实现 SOTA 性能,而是为了证明 transformer 模型的竞争力主要源于通用架构 MetaFormer。

论文摘要如下:

Transformers 在计算机视觉任务中展现了巨大的潜力。一种普遍的看法是,它们基于注意力的 token mixer 模块对其能力贡献最大。然而,最近的研究表明,transformers 中基于注意力的模块可以被空间 MLP 替代,并且得到的模型仍然表现良好。基于这一观察,我们假设 transformers 的通用架构,而不是特定的 token mixer 模块,对模型的性能更为重要。为了验证这一点,我们特意将 transformers 中的注意力模块替换为极其简单的空间池化算子,仅进行最基本的 token 混合。令人惊讶的是,我们观察到,衍生模型 PoolFormer 在多个计算机视觉任务上取得了有竞争力的性能。例如,在 ImageNet-1K 上,PoolFormer 实现了 82.1% 的 top-1 准确率,超过了经过良好调优的视觉 transformer/MLP 类基线 DeiT-B/ResMLP-B24 0.3%/1.1% 的准确率,同时参数减少了 35%/52%,MACs 减少了 48%/60%。PoolFormer 的有效性验证了我们的假设,并促使我们提出“MetaFormer”的概念,这是一种从 transformers 中抽象出来的通用架构,而没有指定 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。

图像分类

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

PoolFormerConfig

class 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, 可选, 默认为 3) — 输入图像中的通道数。
  • patch_size (int, 可选, 默认为 16) — 输入 patch 的尺寸。
  • stride (int, 可选, 默认为 16) — 输入 patch 的步幅。
  • pool_size (int, 可选, 默认为 3) — pooling 窗口的大小。
  • mlp_ratio (float, 可选, 默认为 4.0) — MLP 输出中的通道数与输入中的通道数的比率。
  • depths (list, 可选, 默认为 [2, 2, 6, 2]) — 每个编码器块的深度。
  • hidden_sizes (list, 可选, 默认为 [64, 128, 320, 512]) — 每个编码器块的隐藏层尺寸。
  • patch_sizes (list, 可选, 默认为 [7, 3, 3, 3]) — 每个编码器块的输入 patch 尺寸。
  • strides (list, 可选, 默认为 [4, 2, 2, 2]) — 每个编码器块的输入 patch 步幅。
  • padding (list, 可选, 默认为 [2, 1, 1, 1]) — 每个编码器块的输入 patch 填充。
  • num_encoder_blocks (int, 可选, 默认为 4) — 编码器块的数量。
  • drop_path_rate (float, 可选, 默认为 0.0) — dropout 层的 dropout 率。
  • hidden_act (str, 可选, 默认为 "gelu") — 隐藏层的激活函数。
  • use_layer_scale (bool, 可选, 默认为 True) — 是否使用层缩放。
  • layer_scale_init_value (float, 可选, 默认为 1e-05) — 层缩放的初始值。
  • initializer_range (float, 可选, 默认为 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

class transformers.PoolFormerFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

预处理图像或一批图像。

PoolFormerImageProcessor

class transformers.PoolFormerImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None crop_pct: int = 0.9 resample: Resampling = <Resampling.BICUBIC: 3> 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] 可选, 默认为 {"shortest_edge" -- 224}): 调整大小后图像的尺寸。可以被 preprocess 方法中的 size 重写。如果 crop_pct 未设置:

    • size 是 {"height": h, "width": w}: 图像被调整大小为 (h, w)
    • size 是 {"shortest_edge": s}: 图像的最短边被调整为 s,同时保持宽高比。

    如果 crop_pct 已设置:

    • size 是 {"height": h, "width": w}: 图像被调整大小为 (int(floor(h/crop_pct)), int(floor(w/crop_pct)))
    • size 是 {"height": c, "width": c}: 图像的最短边被调整为 int(floor(c/crop_pct),同时保持宽高比。
    • size 是 {"shortest_edge": c}: 图像的最短边被调整为 int(floor(c/crop_pct),同时保持宽高比。
  • 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, optional, defaults to True) — 控制是否对图像进行归一化处理。 可以被 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatList[float], optional, defaults to IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,则使用的均值。 这是一个浮点数或浮点数列表,其长度等于图像中的通道数。 可以被 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatList[float], optional, defaults to IMAGENET_STANDARD_STD) — 如果对图像进行归一化,则使用的标准差。 这是一个浮点数或浮点数列表,其长度等于图像中的通道数。 可以被 preprocess 方法中的 image_std 参数覆盖。

构建 PoolFormer 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['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 = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • images (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, optional, defaults to self.crop_pct) — 要裁剪的图像百分比。 仅当 do_resize 设置为 True 时有效。
  • resample (int, optional, defaults to 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, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的缩放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化处理。
  • image_mean (floatList[float], optional, defaults to self.image_mean) — 图像均值。
  • image_std (floatList[float], optional, defaults to self.image_std) — 图像标准差。
  • return_tensors (strTensorType, optional) — 返回的张量类型。 可以是以下之一:
    • Unset: 返回 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, optional, defaults to ChannelDimension.FIRST) — 输出图像的通道维度格式。 可以是以下之一:
    • ChannelDimension.FIRST: 格式为 (num_channels, height, width) 的图像。
    • ChannelDimension.LAST: 格式为 (height, width, num_channels) 的图像。
  • input_data_format (ChannelDimensionstr, optional) — 输入图像的通道维度格式。 如果未设置,则通道维度格式将从输入图像中推断。 可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 格式为 (num_channels, height, width) 的图像。
    • "channels_last"ChannelDimension.LAST: 格式为 (height, width, num_channels) 的图像。
    • "none"ChannelDimension.NONE: 格式为 (height, width) 的图像。

预处理单张或批量图像。

PoolFormerModel

class transformers.PoolFormerModel

< >

( config )

参数

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

裸 PoolFormer 模型 Transformer,输出原始隐藏状态,顶部没有任何特定的头部。 此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解所有与常规用法和行为相关的事项。

forward

< >

( 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.BaseModelOutputWithNoAttentiontorch.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), optional, 当传递 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

class transformers.PoolFormerForImageClassification

< >

( config )

参数

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

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

此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( 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,形状为 (batch_size, num_channels, height, width)) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 PoolFormerImageProcessor.call()
  • labels (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 中。如果 config.num_labels == 1,则计算回归损失(均方误差损失),如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。

返回值

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontorch.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
< > 在 GitHub 上更新