AI Logic

Architectures

ResMLP

Updated:

Architecture of ResMLP. The left side shows the overall flow (the image is split into 196 patches of 16×16, embedded with a per-patch linear layer, passed through L ResMLP layers, then averaged after Aff and classified with a linear layer). The right side shows the inside of a ResMLP layer (a residual block of Aff, transpose, cross-patch linear layer A, transpose, and Aff, and a residual block of Aff, a 2-layer MLP, and Aff), along with the inside of the MLP and the Aff equation.

Background and overview

ResMLP is a residual network that replaces the self-attention of ViT with "a single linear layer across patches" and classifies images using only fully connected layers and GELU. It was published in 2021 by Touvron and colleagues at Facebook AI. It comes from the same research group as DeiT and emphasizes reaching good accuracy when trained on ImageNet-1K alone.

ViT showed that images can be classified even after removing the assumptions built into convolutions, such as "look at nearby pixels" and "produce the same features when the position shifts". ResMLP pushes this trend further, examining how much accuracy remains when even attention, whose weights depend on the data, is removed. Google published MLP-Mixer around the same time with a very similar idea. The differences are as follows.

  • The patch-mixing part is a single linear layer: MLP-Mixer uses a 2-layer MLP, whereas ResMLP uses a linear layer with no hidden layer.
  • Aff instead of normalization: instead of layer normalization, which computes statistics, it uses a simple transformation that learns only a per-channel scale and shift.
  • Training on ImageNet-1K alone: MLP-Mixer assumed large-scale pretraining on ImageNet-21k or JFT-300M, whereas ResMLP trains on ImageNet-1K alone using DeiT's training recipe (strong data augmentation and, optionally, knowledge distillation).

The main results of the paper are as follows.

  • Trained on ImageNet-1K alone, ResMLP-S24 reached 79.4% accuracy and ResMLP-B24 reached 81.0%.
  • Knowledge distillation from a CNN improved results substantially, with ResMLP-B24/8 reaching 83.6%.
  • Viewing the weights of the learned linear layers as images revealed convolution-like local patterns in the shallow layers.

Architecture

ResMLP has almost the same skeleton as ViT; only the blocks inside differ. The left side of the figure at the top of the article shows the overall flow, and the right side shows the inside of one ResMLP layer.

An image flows through the following steps (ResMLP-S12 with a 224×224 input).

  1. Split into patches: the image is cut into N×N=14×14=196N \times N = 14 \times 14 = 196 non-overlapping 16×16 patches.
  2. Embed: the same linear layer is applied to each patch, producing a dd-dimensional vector (384 for S12).
  3. Stack ResMLP layers: the vectors pass through LL ResMLP layers of the same shape (12 for S12).
  4. Average and classify: the vectors of the 196 patches are averaged (global average pooling) and classified with a linear layer. The loss is cross-entropy.

Inside a ResMLP layer

Let XX be the d×N2d \times N^2 matrix of patch vectors. A ResMLP layer consists of the following two residual blocks (Eqs. (2) and (3) of the paper).

Z=X+Aff((A Aff(X)⊤)⊤)Z = X + \mathrm{Aff}\Bigl(\bigl(A\,\mathrm{Aff}(X)^{\top}\bigr)^{\top}\Bigr) Y=Z+Aff(C GELU(B Aff(Z)))Y = Z + \mathrm{Aff}\bigl(C\,\mathrm{GELU}(B\,\mathrm{Aff}(Z))\bigr)
  • Cross-patch linear layer (first equation): AA is an N2×N2N^2 \times N^2 matrix (196×196 for S12) applied with the same weights to every channel. Information is exchanged between patches here. There is no nonlinear activation.
  • Cross-channel MLP (second equation): two fully connected layers, BB (d→4dd \to 4d) and CC (4d→d4d \to d), with GELU in between. It is applied with the same weights to every patch and has the same form as the position-wise MLP in a Transformer.

Aff: a transformation that replaces normalization

ResMLP does not use layer normalization or batch normalization. Instead, it uses a transformation that only learns a per-channel scale α\alpha and shift β\beta (Eq. (1) of the paper).

Affα,β(x)=Diag(α) x+β\mathrm{Aff}_{\alpha, \beta}(x) = \mathrm{Diag}(\alpha)\,x + \beta

Aff is placed at the start and end of each residual block. The first Aff replaces layer normalization and starts from α=1\alpha = 1, β=0\beta = 0. The last Aff plays nearly the same role as LayerScale, with α\alpha starting from a small value. Because it computes no mean or variance, at inference it can be absorbed into the weights of the adjacent linear layer, adding no computation.

Differences from ViT

The paper summarizes the differences from ViT in the following four points.

AspectViTResMLP
How patches are mixedSelf-attention (weights depend on the input)Linear layer (fixed weights, determined only by position)
Positional informationAdds learned position embeddingsNone (the linear layer has separate weights for each patch position)
Whole-image representation[class] tokenMean of the patches
NormalizationLayer normalizationAff (no statistics)

Model sizes (Tables 1 and 3 of the paper)

ModelLayers LLWidth ddPatchParametersGFLOPs
ResMLP-S121238416×1615M3.0
ResMLP-S242438416×1630M6.0
ResMLP-B242476816×16116M23.0
ResMLP-B24/8247688×8129M100.2

The cross-patch linear layer AA is a table that says, for each output patch, how much weight it gives to each of the other patches when summing them. Like attention, it sees the whole image at once, but its weights do not change with the input and are determined only by patch positions.

Training recipe

ResMLP uses DeiT's training recipe almost unchanged. Because its architecture makes few assumptions about images, strong data augmentation and regularization are essential to suppress overfitting.

ItemValue (Section 3.1 and Table 3 of the paper)
OptimizationLAMB, learning rate 5×10−35 \times 10^{-3}, Weight Decay 0.2
Epochs400
Data augmentation and regularizationSame as DeiT (RandAugment, Mixup, CutMix, Random Erasing, Stochastic Depth, etc.)
Initial value of the last AffA small value depending on depth (following CaiT's LayerScale)
Knowledge distillation (if used)Teacher is RegNetY-16GF (same as DeiT)

The training recipe has a large effect. With the conventional ResNet recipe (SGD, 90 epochs, step decay), ResMLP-S12 reached only 69.2%, 7.4 points below the 76.6% obtained with DeiT's recipe (Tables 3 and D.1 of the paper). Removing DeiT's training components one at a time, accuracy dropped from 75.9% to 73.2% when RandAugment was removed, and to 72.1% when the optimizer was then switched to SGD; these two had the largest effects.

In addition, accuracy kept improving with more epochs up to about 800 (ResMLP-S36: 79.3% at 300 epochs → 80.4% at 800 epochs, Table D.2 of the paper). Whereas DeiT plateaus at around 400 epochs, ResMLP needs to be trained longer.

What the linear layer learns

In ResMLP, patches are mixed by a linear layer, so each row of the learned weights AA can be viewed directly as a 14×14 image. The paper visualized these and observed the following (Figures 2 and 3 of the paper).

  • Shallow layers resemble convolutions: each patch's weights were large only for nearby patches, and had the same shape shifted slightly for each patch. These are the same characteristics as convolution filters. Shapes elongated vertically or horizontally were also seen.
  • Deep layers look at themselves and the whole image: roughly the last 7 layers had a sharp peak at their own patch, with weights spread broadly and thinly over the other patches.
  • Most weights are small: counting the fraction of entries smaller than 5% of the maximum showed that the patch-mixing linear layers were sparser (mostly near 0) than the channel MLPs.

In other words, even though ResMLP has none of the assumptions of convolution, it learns convolution-like local processing from the data on its own. As an everyday analogy, it is like a delivery driver who was never told to "visit houses in order from the nearest", but after many deliveries discovers on their own a route that covers nearby houses together.

Based on this observation, the paper also experimented with replacing the linear layer with a 3×3 convolution (Table 3 of the paper).

Patch-mixing partParametersGFLOPsAccuracy (%)
None (no patch mixing)14.9M2.856.5
Linear layer (ResMLP-S12)15.4M3.076.6
2-layer MLP18.6M4.377.3
Ordinary 3×3 convolution30.8M6.077.3
3×3 depthwise convolution14.9M2.876.3
3×3 depthwise separable convolution16.7M3.277.0

Without patch mixing, accuracy drops by 20 points, so exchanging information between patches is essential. On the other hand, using an MLP or a convolution for mixing gives only small gains, and a single linear layer was a well-balanced choice relative to parameters and computation.

Experimental results

ImageNet-1K classification (trained on ImageNet-1K only, 224×224 input. Throughput is images per second on a V100. Table 1 of the paper)

ModelTypeParametersGFLOPsThroughputAccuracy (%)
RegNetY-4GFCNN21M4.0861.080.0
EfficientNet-B3CNN12M1.8661.881.1
DeiT-STransformer22M4.6940.479.8
DeiT-BTransformer86M17.5292.381.8
ResMLP-S12MLP15M3.01415.176.6
ResMLP-S24MLP30M6.0715.479.4
ResMLP-B24MLP116M23.0231.381.0

As the paper itself acknowledges, its accuracy-to-computation trade-off does not match CNNs or Transformers. Still, given that an MLP with few structural constraints gets this far, the paper argues that with enough data and modern training recipes, differences in layer design do not decisively determine accuracy.

With different training recipes (Table 3 of the paper; ImageNet-1K validation data)

ModelTraining recipeAccuracy (%)
ResMLP-S12Standard76.6
ResMLP-S12Knowledge distillation77.8
ResMLP-S24Standard79.4
ResMLP-S24Self-supervised pretraining with DINO → fine-tuning79.9
ResMLP-S24Knowledge distillation80.8
ResMLP-B24/8Knowledge distillation83.6
ResMLP-B24/8Pretraining on ImageNet-21k84.4

As with DeiT, knowledge distillation from a CNN gives large gains. The paper suggests that the CNN teacher may act as additional regularization that suppresses the MLP's overfitting.

Machine translation: a Sequence to Sequence model that replaces the self-attention of the encoder and decoder with ResMLP layers reached BLEU 26.8 (12 layers) on WMT 2014 English–German translation, close to the 27.3 of Transformer (base) (Table 5 of the paper). In the decoder, AA is made triangular so that it cannot see future words.

Practical considerations

Keep the following points in mind when using ResMLP.

  • The input size is fixed: the size of the patch-mixing linear layer AA, such as 196×196, is determined by the number of patches. Images at a resolution different from training cannot be input as is. For variable-length sequences (translation), the paper pads with zeros and uses only the needed part of AA.
  • Do not cut corners on the training recipe: the conventional recipe loses more than 7 points. Combine strong data augmentation, LAMB, longer training (400–800 epochs), and, if possible, knowledge distillation.
  • Smaller patches sharply increase computation: going from 16×16 to 8×8 patches raises ResMLP-S12 from 76.6% to 79.1%, while computation grows from 3.0 to 14.0 GFLOPs (Table 3 of the paper).
  • Not built into PyTorch: torchvision does not include ResMLP. Write it following the pseudocode in Appendix C of the paper, or use the timm library, which provides the official pretrained weights.

ResMLP tended to be less accurate than CNNs or DeiT at the same computation, and to overfit the ImageNet validation data somewhat more (Figure 4 of the paper). It is better suited to research asking "how much are attention and convolution really needed" and to settings that need a structurally simple model whose weights are easy to visualize, than to practical settings where accuracy or efficiency comes first.

Comparison with other models

ResMLP is an MLP-based model that replaces ViT's self-attention with a linear layer. Compared from the same perspectives:

ModelHow patches are mixedDo the weights depend on the input?NormalizationAssumed training
ViTSelf-attentionYesLayer normalizationLarge-scale pretraining
DeiTSelf-attentionYesLayer normalizationImageNet-1K and knowledge distillation
MLP-Mixer2-layer MLP (across patches)NoLayer normalizationLarge-scale pretraining
ResMLPSingle linear layer (across patches)NoAffImageNet-1K and knowledge distillation
gMLPGating with a linear layerPartly (multiplicative gate)Layer normalizationImageNet-1K

Guidelines for choosing:

  • For accuracy and speed: at the same computation, CNNs (ConvNeXt and others) and DeiT give better results.
  • For a simple model without attention: ResMLP does not even use normalization statistics and is among the simplest architectures. Its learned weights can be viewed as images, which also makes it well suited to studying what a model has learned.
  • For higher accuracy within the MLP family: gMLP, which adds gating to patch mixing, reports accuracy on par with DeiT at a similar number of parameters.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small ResMLP implementation following Eqs. (1)–(3) and the pseudocode in Appendix C of the paper
(ResMLP-S12: 16×16 patches, d = 384, 12 layers)
"""


class Affine(nn.Module):
  """Aff(x) = α ⊙ x + β. Computes no mean or variance"""

  def __init__(self, dim, init=1.0):
    super().__init__()
    self.alpha = nn.Parameter(init * torch.ones(dim))
    self.beta = nn.Parameter(torch.zeros(dim))

  def forward(self, x):
    return self.alpha * x + self.beta


class ResMLPLayer(nn.Module):
  def __init__(self, num_patches, dim, post_init=0.1):
    super().__init__()
    self.pre1 = Affine(dim)                                # first Aff (starts at α=1, β=0)
    self.cross_patch = nn.Linear(num_patches, num_patches)  # A: cross-patch linear layer (shared across all channels)
    self.post1 = Affine(dim, post_init)                    # last Aff (starts from a small α, like LayerScale)
    self.pre2 = Affine(dim)
    self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))  # B → GELU → C
    self.post2 = Affine(dim, post_init)

  def forward(self, x):                                     # x: [batch, patches, d]
    z = x + self.post1(self.cross_patch(self.pre1(x).transpose(1, 2)).transpose(1, 2))  # Eq. (2)
    return z + self.post2(self.mlp(self.pre2(z)))                                        # Eq. (3)


class ResMLP(nn.Module):
  def __init__(self, img_size=224, patch=16, dim=384, depth=12, num_classes=1000, post_init=0.1):
    super().__init__()
    n = (img_size // patch) ** 2                            # 196
    self.patch_embed = nn.Conv2d(3, dim, kernel_size=patch, stride=patch)  # same computation as a per-patch linear layer
    self.layers = nn.Sequential(*[ResMLPLayer(n, dim, post_init) for _ in range(depth)])
    self.norm = Affine(dim)
    self.head = nn.Linear(dim, num_classes)

  def forward(self, img):                                   # img: [batch, 3, 224, 224]
    x = self.patch_embed(img).flatten(2).transpose(1, 2)    # [batch, 196, 384]
    x = self.norm(self.layers(x))
    return self.head(x.mean(dim=1))                         # mean over patches → classify


model = ResMLP()
logits = model(torch.randn(2, 3, 224, 224))                 # [2, 1000]
# In the paper, the initial value of the last Aff depends on depth (following CaiT's LayerScale). 0.1 is one example for 12 layers

# To use pretrained weights (timm):
# import timm
# model = timm.create_model("resmlp_12_224", pretrained=True)

FAQ

Q. How does ResMLP differ from MLP-Mixer?
A.

There are three main differences. For patch mixing, MLP-Mixer uses a 2-layer MLP, while ResMLP uses a single linear layer. For normalization, MLP-Mixer uses layer normalization, while ResMLP uses Aff, which uses no statistics. For the assumed training, MLP-Mixer relies on pretraining on large-scale data, while ResMLP uses ImageNet-1K alone plus knowledge distillation.

Q. Without position embeddings, how does it know where patches are?
A.

It does. The cross-patch linear layer AA has a separate weight for each pair of output and input patches, so which position the information came from is encoded in the weights. In the paper, adding position embeddings did not change accuracy either.

Q. Why can it be trained without layer normalization?
A.

The paper speculates that replacing self-attention with a linear layer made training stable. The paper compares normalizations in two places, and the results point in opposite directions. In the exploratory experiments during the design phase (Appendix A), switching to Aff, which computes no statistics, was 0.4 points better than layer normalization. In the ablation of the final ResMLP-S12 (Table 3), however, replacing Aff with layer normalization gave 77.7%, higher than the 76.6% with Aff. Which is better depends on the setting. The paper chose Aff to keep the design simple, without relying on batch or channel statistics.

References

  1. Touvron, H., Bojanowski, P., Caron, M., Cord, M., El-Nouby, A., Grave, E., Izacard, G., Joulin, A., Synnaeve, G., Verbeek, J., & Jégou, H. (2021). ResMLP: Feedforward networks for image classification with data-efficient training. arXiv:2105.03404.
  2. Tolstikhin, I., et al. (2021). MLP-Mixer: An all-MLP Architecture for Vision. NeurIPS 2021. arXiv:2105.01601.
  3. Touvron, H., et al. (2021). Training data-efficient image transformers & distillation through attention. ICML 2021. arXiv:2012.12877.
  4. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.