---
local: poolformer
sections:
- local: overview
  title: Overview
- local: transformers.PoolFormerConfig
  title: PoolFormerConfig
- local: transformers.PoolFormerFeatureExtractor
  title: PoolFormerFeatureExtractor
- local: transformers.PoolFormerModel
  title: PoolFormerModel
- local: transformers.PoolFormerForImageClassification
  title: PoolFormerForImageClassification
title: PoolFormer
---
<script>
import Tip from "./Tip.svelte";
import Youtube from "./Youtube.svelte";
import Docstring from "./Docstring.svelte";
import CodeBlock from "./CodeBlock.svelte";
import CodeBlockFw from "./CodeBlockFw.svelte";
import DocNotebookDropdown from "./DocNotebookDropdown.svelte";
import IconCopyLink from "./IconCopyLink.svelte";
export let fw: "pt" | "tf"
</script>
<!--Copyright 2022 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->

<h1 id="poolformer">PoolFormer</h1>

<h2 id="overview">Overview</h2>

The PoolFormer model was proposed in [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418)  by Sea AI Labs. Instead of designing complicated token mixer to achieve SOTA performance, the target of this work is to demonstrate the competence of transformer models largely stem from the general architecture MetaFormer.

The abstract from the paper is the following:

*Transformers have shown great potential in computer vision tasks. A common belief is their attention-based token mixer module contributes most to their competence. However, recent works show the attention-based module in transformers can be replaced by spatial MLPs and the resulted models still perform quite well. Based on this observation, we hypothesize that the general architecture of the transformers, instead of the specific token mixer module, is more essential to the model's performance. To verify this, we deliberately replace the attention module in transformers with an embarrassingly simple spatial pooling operator to conduct only the most basic token mixing. Surprisingly, we observe that the derived model, termed as PoolFormer, achieves competitive performance on multiple computer vision tasks. For example, on ImageNet-1K, PoolFormer achieves 82.1% top-1 accuracy, surpassing well-tuned vision transformer/MLP-like baselines DeiT-B/ResMLP-B24 by 0.3%/1.1% accuracy with 35%/52% fewer parameters and 48%/60% fewer MACs. The effectiveness of PoolFormer verifies our hypothesis and urges us to initiate the concept of "MetaFormer", a general architecture abstracted from transformers without specifying the token mixer. Based on the extensive experiments, we argue that MetaFormer is the key player in achieving superior results for recent transformer and MLP-like models on vision tasks. This work calls for more future research dedicated to improving MetaFormer instead of focusing on the token mixer modules. Additionally, our proposed PoolFormer could serve as a starting baseline for future MetaFormer architecture design.*

The figure below illustrates the architecture of SegFormer. Taken from the [original paper](https://arxiv.org/abs/2111.11418).

<img width="600" src="https://user-images.githubusercontent.com/15921929/142746124-1ab7635d-2536-4a0e-ad43-b4fe2c5a525d.png"/>


Tips:

- PoolFormer has a hierarchical architecture, where instead of Attention, a simple Average Pooling layer is present. All checkpoints of the model can be found on the [hub](https://huggingface.co/models?other=poolformer).
- One can use [PoolFormerFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerFeatureExtractor) to prepare images for the model.
- As most models, PoolFormer comes in different sizes, the details of which can be found in the table below.

| **Model variant** | **Depths**    | **Hidden sizes**    | **Params (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                  |

This model was contributed by [heytanay](https://huggingface.co/heytanay). The original code can be found [here](https://github.com/sail-sg/poolformer).

<h2 id="transformers.PoolFormerConfig">PoolFormerConfig</h2>

<div class="docstring">

<docstring><name>class transformers.PoolFormerConfig</name><anchor>transformers.PoolFormerConfig</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/poolformer/configuration_poolformer.py#L29</source><parameters>[{"name": "num_channels", "val": " = 3"}, {"name": "patch_size", "val": " = 16"}, {"name": "stride", "val": " = 16"}, {"name": "pool_size", "val": " = 3"}, {"name": "mlp_ratio", "val": " = 4.0"}, {"name": "depths", "val": " = [2, 2, 6, 2]"}, {"name": "hidden_sizes", "val": " = [64, 128, 320, 512]"}, {"name": "patch_sizes", "val": " = [7, 3, 3, 3]"}, {"name": "strides", "val": " = [4, 2, 2, 2]"}, {"name": "padding", "val": " = [2, 1, 1, 1]"}, {"name": "num_encoder_blocks", "val": " = 4"}, {"name": "drop_path_rate", "val": " = 0.0"}, {"name": "hidden_act", "val": " = 'gelu'"}, {"name": "use_layer_scale", "val": " = True"}, {"name": "layer_scale_init_value", "val": " = 1e-05"}, {"name": "initializer_range", "val": " = 0.02"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **num_channels** (`int`, *optional*, defaults to 3) --
  The number of channels in the input image.
- **patch_size** (`int`, *optional*, defaults to 16) --
  The size of the input patch.
- **stride** (`int`, *optional*, defaults to 16) --
  The stride of the input patch.
- **pool_size** (`int`, *optional*, defaults to 3) --
  The size of the pooling window.
- **mlp_ratio** (`float`, *optional*, defaults to 4.0) --
  The ratio of the number of channels in the output of the MLP to the number of channels in the input.
- **depths** (`list`, *optional*, defaults to `[2, 2, 6, 2]`) --
  The depth of each encoder block.
- **hidden_sizes** (`list`, *optional*, defaults to `[64, 128, 320, 512]`) --
  The hidden sizes of each encoder block.
- **patch_sizes** (`list`, *optional*, defaults to `[7, 3, 3, 3]`) --
  The size of the input patch for each encoder block.
- **strides** (`list`, *optional*, defaults to `[4, 2, 2, 2]`) --
  The stride of the input patch for each encoder block.
- **padding** (`list`, *optional*, defaults to `[2, 1, 1, 1]`) --
  The padding of the input patch for each encoder block.
- **num_encoder_blocks** (`int`, *optional*, defaults to 4) --
  The number of encoder blocks.
- **drop_path_rate** (`float`, *optional*, defaults to 0.0) --
  The dropout rate for the dropout layers.
- **hidden_act** (`str`, *optional*, defaults to `"gelu"`) --
  The activation function for the hidden layers.
- **use_layer_scale** (`bool`, *optional*, defaults to `True`) --
  Whether to use layer scale.
- **layer_scale_init_value** (`float`, *optional*, defaults to 1e-5) --
  The initial value for the layer scale.
- **initializer_range** (`float`, *optional*, defaults to 0.02) --
  The initializer range for the weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

This is the configuration class to store the configuration of [PoolFormerModel](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerModel). It is used to instantiate a
PoolFormer model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the PoolFormer
[sail/poolformer_s12](https://huggingface.co/sail/poolformer_s12) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the
documentation from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) for more information.




Example:

```python
>>> from transformers import PoolFormerModel, PoolFormerConfig

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

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

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


</div>

<h2 id="transformers.PoolFormerFeatureExtractor">PoolFormerFeatureExtractor</h2>

<div class="docstring">

<docstring><name>class transformers.PoolFormerFeatureExtractor</name><anchor>transformers.PoolFormerFeatureExtractor</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/poolformer/feature_extraction_poolformer.py#L38</source><parameters>[{"name": "do_resize_and_center_crop", "val": " = True"}, {"name": "size", "val": " = 224"}, {"name": "resample", "val": " = 3"}, {"name": "crop_pct", "val": " = 0.9"}, {"name": "do_normalize", "val": " = True"}, {"name": "image_mean", "val": " = None"}, {"name": "image_std", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **do_resize_and_center_crop** (`bool`, *optional*, defaults to `True`) --
  Whether to resize the shortest edge of the image and center crop the input to a certain `size`.
- **size** (`int` or `Tuple(int)`, *optional*, defaults to 224) --
  Center crop the input to the given size. If a tuple is provided, it should be (width, height). If only an
  integer is provided, then the input will be center cropped to (size, size). Only has an effect if
  `do_resize_and_center_crop` is set to `True`.
- **resample** (`int`, *optional*, defaults to `PIL.Image.BICUBIC`) --
  An optional resampling filter. This can be one of `PIL.Image.NEAREST`, `PIL.Image.BOX`,
  `PIL.Image.BILINEAR`, `PIL.Image.HAMMING`, `PIL.Image.BICUBIC` or `PIL.Image.LANCZOS`. Only has an effect
  if `do_resize_and_center_crop` is set to `True`.
- **crop_pct** (`float`, *optional*, defaults to `0.9`) --
  The percentage of the image to crop from the center. Only has an effect if `do_resize_and_center_crop` is
  set to `True`.
- **do_normalize** (`bool`, *optional*, defaults to `True`) --
  Whether or not to normalize the input with `image_mean` and `image_std`.
- **image_mean** (`List[int]`, defaults to `[0.485, 0.456, 0.406]`) --
  The sequence of means for each channel, to be used when normalizing images.
- **image_std** (`List[int]`, defaults to `[0.229, 0.224, 0.225]`) --
  The sequence of standard deviations for each channel, to be used when normalizing images.</paramsdesc><paramgroups>0</paramgroups></docstring>

Constructs a PoolFormer feature extractor.

This feature extractor inherits from [FeatureExtractionMixin](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin) which contains most of the main methods. Users
should refer to this superclass for more information regarding those methods.





<div class="docstring">
<docstring><name>\_\_call\_\_</name><anchor>transformers.PoolFormerFeatureExtractor.__call__</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/poolformer/feature_extraction_poolformer.py#L89</source><parameters>[{"name": "images", "val": ": typing.Union[PIL.Image.Image, numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]]"}, {"name": "return_tensors", "val": ": typing.Union[str, transformers.file_utils.TensorType, NoneType] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **images** (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`) --
  The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
  number of channels, H and W are image height and width.

- **return_tensors** (`str` or [TensorType](/docs/transformers/pr_15592/en/internal/file_utils#transformers.TensorType), *optional*, defaults to `'np'`) --
  If set, will return tensors of a particular framework. Acceptable values are:

  - `'tf'`: Return TensorFlow `tf.constant` objects.
  - `'pt'`: Return PyTorch `torch.Tensor` objects.
  - `'np'`: Return NumPy `np.ndarray` objects.
  - `'jax'`: Return JAX `jnp.ndarray` objects.</paramsdesc><paramgroups>0</paramgroups><rettype>[BatchFeature](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.BatchFeature)</rettype><retdesc>A [BatchFeature](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.BatchFeature) with the following fields:

- **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,
  width).</retdesc></docstring>

Main method to prepare for the model one or several image(s).

<Tip warning=&amp;lcub;true}>

NumPy arrays and PyTorch tensors are converted to PIL images when resizing, so the most efficient is to pass
PIL images.

</Tip>








</div></div>

<h2 id="transformers.PoolFormerModel">PoolFormerModel</h2>

<div class="docstring">

<docstring><name>class transformers.PoolFormerModel</name><anchor>transformers.PoolFormerModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/poolformer/modeling_poolformer.py#L360</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([PoolFormerConfig](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerConfig)) -- Model configuration class with all the parameters of the model.
  Initializing with a config file does not load the weights associated with the model, only the
  configuration. Check out the [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.PoolFormerModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/poolformer/modeling_poolformer.py#L373</source><parameters>[{"name": "pixel_values", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) --
  Pixel values. Pixel values can be obtained using [PoolFormerFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerFeatureExtractor). See
  [PoolFormerFeatureExtractor.__call__()](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerFeatureExtractor.__call__) for details.</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.models.poolformer.modeling_poolformer.PoolFormerModelOutput`or `tuple(torch.FloatTensor)`</rettype><retdesc>A `transformers.models.poolformer.modeling_poolformer.PoolFormerModelOutput`or a tuple of
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([PoolFormerConfig](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerConfig)) and inputs.

- **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.

- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
  plus the initial embedding outputs.</retdesc></docstring>
The [PoolFormerModel](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerModel) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>







Example:

```python
>>> from transformers import PoolFormerFeatureExtractor, PoolFormerModel
>>> import torch
>>> from datasets import load_dataset

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

>>> feature_extractor = PoolFormerFeatureExtractor.from_pretrained("sail/poolformer_s12")
>>> model = PoolFormerModel.from_pretrained("sail/poolformer_s12")

>>> inputs = feature_extractor(image, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 197, 768]
```


</div></div>

<h2 id="transformers.PoolFormerForImageClassification">PoolFormerForImageClassification</h2>

<div class="docstring">

<docstring><name>class transformers.PoolFormerForImageClassification</name><anchor>transformers.PoolFormerForImageClassification</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/poolformer/modeling_poolformer.py#L423</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([PoolFormerConfig](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerConfig)) -- Model configuration class with all the parameters of the model.
  Initializing with a config file does not load the weights associated with the model, only the
  configuration. Check out the [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

PoolFormer Model transformer with an image classification head on top

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.PoolFormerForImageClassification.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/poolformer/modeling_poolformer.py#L439</source><parameters>[{"name": "pixel_values", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) --
  Pixel values. Pixel values can be obtained using [PoolFormerFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerFeatureExtractor). See
  [PoolFormerFeatureExtractor.__call__()](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerFeatureExtractor.__call__) for details.

- **labels** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  `config.num_labels > 1` a classification loss is computed (Cross-Entropy).</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.models.poolformer.modeling_poolformer.PoolFormerClassifierOutput`or `tuple(torch.FloatTensor)`</rettype><retdesc>A `transformers.models.poolformer.modeling_poolformer.PoolFormerClassifierOutput`or a tuple of
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([PoolFormerConfig](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerConfig)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Classification (or regression if config.num_labels==1) loss.
- **logits** (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`) -- Classification (or regression if config.num_labels==1) scores (before SoftMax).
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, num_channels, height, width)`.

  Hidden-states of the model at the output of each layer plus the initial embedding outputs.</retdesc></docstring>
The [PoolFormerForImageClassification](/docs/transformers/pr_15592/en/model_doc/poolformer#transformers.PoolFormerForImageClassification) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>







Example:

```python
>>> from transformers import PoolFormerFeatureExtractor, PoolFormerForImageClassification
>>> import torch
>>> from datasets import load_dataset

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

>>> feature_extractor = PoolFormerFeatureExtractor.from_pretrained("sail/poolformer_s12")
>>> model = PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12")

>>> inputs = feature_extractor(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'
```


</div></div>
