AI Logic

Architectures

gMLP

Updated:

Structure of gMLP. Left: the overall flow for image classification (split into 16Ɨ16 patches and embed, pass through L gMLP blocks, classify; no position embeddings). Right: inside a gMLP block (layer normalization, channel projection U, GELU, SGU, channel projection V, residual connection) and inside the SGU (split Z into Z₁ and Zā‚‚, apply layer normalization and a spatial linear projection to Zā‚‚, and multiply it element-wise with Z₁).

Background and Overview

gMLP is an MLP model that, instead of the Transformer's self-attention, mixes information across tokens with a multiplicative gate called the "Spatial Gating Unit (SGU)". Liu, Dai, So, and Le at Google introduced it in 2021 in "Pay Attention to MLPs." It matched DeiT (ViT) on image classification and matched the perplexity of a Transformer under the same pretraining as BERT.

The self-attention in a Transformer computes the weights between tokens on the fly, depending on the input. It was unclear whether this "input-dependent weights" mechanism is the essence of the Transformer's strength, or whether an MLP with fixed weights would suffice. Around the same time, MLP-Mixer and ResMLP also replaced self-attention with MLPs for images.

gMLP tested this question on both images and language. The key idea is to take the output of a linear layer along the token dimension and, rather than adding it, multiply it element-wise with the other half of the features (use it as a gate).

The paper's main results are as follows.

  • On image classification trained only on ImageNet, gMLP-B (73M parameters) reached 81.6%, nearly the same as DeiT-B (86M) at 81.8%. gMLP-S was 3 points more accurate than MLP-Mixer-B/16 with 66% fewer parameters.
  • Under the same masked language model pretraining as BERT, it reached nearly the same perplexity as a Transformer of similar size, and it scaled the same way as the model grew.
  • On a task involving sentence pairs (MNLI), it fell short of the Transformer, but aMLP, which adds a tiny single-head, 64-dimensional attention, closed the gap and surpassed the Transformer.

Architecture

gMLP stacks LL blocks of identical shape and size. The left of the figure at the top of the article shows the overall flow for image classification, and the right shows a single gMLP block and the SGU inside it.

Inputs and outputs are handled as in ViT-B/16 for images (split the image into 16Ɨ16 patches and embed them) and as in BERT for language. However, no position embeddings are used, because the linear layer inside the SGU carries the positional information of the tokens.

The gMLP block

With X∈RnƗdX \in \mathbb{R}^{n \times d} denoting the dd-dimensional representations of nn tokens, a block computes the following (Eq. (1) of the paper; residual connections, normalization, and biases omitted).

Z=σ(XU),Z~=s(Z),Y=Z~VZ = \sigma(XU), \qquad \tilde{Z} = s(Z), \qquad Y = \tilde{Z} V
  1. Apply layer normalization: Apply layer normalization to the input XX.
  2. Expand the channels: UU expands the channels from dd to dffnd_{\text{ffn}}, followed by GELU (σ\sigma). Up to this point it is the same as the first half of a Transformer MLP.
  3. Mix across tokens: The SGU (ss) exchanges information along the token dimension.
  4. Project the channels back: VV projects back to dd dimensions, and the block input is added (residual connection).

If ss is the identity, this is exactly the Transformer's position-wise MLP. In other words, gMLP is simply an MLP with a token-mixing layer inserted in the middle. The paper says it was inspired by the inverted bottleneck of MobileNetV2, which places a depthwise convolution in the middle.

The Spatial Gating Unit (SGU)

The SGU splits ZZ into two parts along the channel dimension (Z1Z_1 and Z2Z_2), builds a gate from Z2Z_2, and multiplies it into Z1Z_1 (Eqs. (2) and (4) of the paper).

fW,b(Z)=WZ+b,s(Z)=Z1āŠ™fW,b(Z2)f_{W,b}(Z) = WZ + b, \qquad s(Z) = Z_1 \odot f_{W,b}(Z_2)
  • W∈RnƗnW \in \mathbb{R}^{n \times n} is a linear projection along the token (spatial) dimension, whose size is set by the sequence length. It is shared across all channels. bb is a per-token bias.
  • āŠ™\odot is element-wise multiplication. Layer normalization is applied to Z2Z_2, the input of ff (this stabilized training for large language models).
  • To stabilize training, WW is initialized near 0 and bb to 1. At the start of training, f(Z2)ā‰ˆ1f(Z_2) \approx 1 and s(Z)ā‰ˆZ1s(Z) \approx Z_1, so each block starts out as an ordinary MLP that does not mix tokens. Information between tokens is injected gradually as training proceeds.

Because the channels are split in half, the SGU outputs dffn/2d_{\text{ffn}}/2 channels, and VV maps them back to dd.

The SGU resembles the gates in LSTM and Highway Networks and the multiplication in SENet. The difference is that the gate is computed from a projection along the token dimension, not the channel dimension. Unlike self-attention, WW does not depend on the input, but because Z1Z_1 and f(Z2)f(Z_2) are multiplied, the output contains second-order products of the inputs (of the form zizjz_i z_j).

Image classification model sizes (Table 1 of the paper)

ModelLayers LLdmodeld_{\text{model}}dffnd_{\text{ffn}}ParametersFLOPs
gMLP-Ti301287685.9M2.7B
gMLP-S30256153619.5M8.9B
gMLP-B30512307273.4M31.6B

Why the Gate Works

The paper compared different forms of the token-mixing function ss in language model pretraining (Table 3 of the paper; values are validation perplexity, lower is better).

Token mixingPerplexityParameters
BERT-base (Transformer)4.37110M
BERT-base + relative position bias4.26110M
Relative position bias only (attention content removed)5.6496M
MLP-Mixer5.34112M
Linear: s(Z)=f(Z)s(Z) = f(Z)5.1492M
Additive: s(Z)=Z+f(Z)s(Z) = Z + f(Z)4.9792M
Multiplicative: s(Z)=ZāŠ™f(Z)s(Z) = Z \odot f(Z)4.5392M
Multiplicative, split (SGU): s(Z)=Z1āŠ™f(Z2)s(Z) = Z_1 \odot f(Z_2)4.35102M

Compared with using the linear projection directly, results improve in order from additive to multiplicative to multiplicative with split channels, and the SGU came out nearly equal to the Transformer (4.26–4.37). A multiplicative gate lets each token's features be adjusted element-wise by "how much to let through," based on information gathered from other tokens. Even though the weights are fixed, the values being multiplied come from the input, which is thought to make it more expressive than addition.

Shape of the learned weights

Inspecting the learned WW shows that the model learned the following structures from data on its own.

  • Images: Rearranging each row of WW into a 14Ɨ14 image shows large weights only on nearby patches (locality) and the same shape regardless of position (translation invariance). In other words, the model learns convolution filters, not necessarily square, from data (Figure 3 of the paper).
  • Language: WW came out close to a Toeplitz matrix, with equal values along each diagonal. This corresponds to a 1D convolution spanning the whole sequence. The paper therefore restricted WW to a Toeplitz matrix from the start in its language experiments (with no change in accuracy).

Computational cost

The SGU performs n2e/2n^2 e / 2 multiply-adds (ee is the number of channels entering the SGU), comparable to the 2n2d2 n^2 d of dot-product self-attention. Both are proportional to the number of channels and to the square of the sequence length nn.

Experimental Results

ImageNet-1K classification (no extra data, accuracy %; Table 2 of the paper)

ModelTypeResolutionParametersMultiply-addsAccuracy
ResNet-152CNN22460M11.3B78.3
EfficientNet-B3CNN30012M1.8B81.6
DeiT-TiTransformer2245M1.3B72.2
DeiT-STransformer22422M4.6B79.8
DeiT-BTransformer22486M17.5B81.8
Mixer-B/16MLP22459M12.7B76.4
ResMLP-24MLP22430M6.0B79.4
gMLP-TiMLP2246M1.4B72.3
gMLP-SMLP22420M4.5B79.6
gMLP-BMLP22473M15.8B81.6

gMLP matched DeiT models of similar size and achieved better accuracy per parameter and per unit of computation than contemporary MLP models (MLP-Mixer, ResMLP). The paper states that with proper regularization, accuracy depends more on model capacity than on the presence of self-attention. On the other hand, it falls short of the best CNNs (such as NFNet) and of hybrid models combining convolution and attention.

BERT-style pretraining and fine-tuning (1M steps on English C4 data; Table 6 of the paper; SST-2 and MNLI in accuracy %, SQuAD in F1 score)

ModelParametersPerplexitySST-2MNLI-mSQuAD v1.1SQuAD v2.0
BERT-base (same setup)110M4.1793.885.690.278.6
gMLP-base130M4.2894.283.786.770.1
aMLP-base109M3.9593.485.990.780.9
BERT-large (same setup)336M3.3594.387.092.081.0
gMLP-large365M3.3294.886.289.578.3
aMLP-large316M3.1994.888.492.285.4
gMLP-xlarge941M2.8995.687.790.982.1

On SST-2, which classifies a single sentence, gMLP beats the Transformer, but it falls behind on MNLI, which judges the relationship between two sentences, and on SQuAD, which matches a question against a passage. The paper suggests that self-attention helps with "cross-sentence alignment." The gap shrinks as the model grows (on SQuAD v2.0, 8.5 points for base versus 2.7 points for large), and aMLP, which adds a tiny attention, matched or exceeded the Transformer on every task.

Scaling the model (Table 4 of the paper): As layers are added, the perplexity of both gMLP and the Transformer falls along a power law in the number of parameters, and a 357M-parameter gMLP (3.43) beat a 365M Transformer (3.47).

Practical Considerations

Keep the following points in mind when using gMLP.

  • The sequence length is fixed: Because the SGU's WW is nƗnn \times n, inputs with more tokens than at training time (the maximum length for language, the number of patches for images) cannot be handled. For language, inputs are padded to the maximum length. The paper reports that padding tokens do not need to be masked during fine-tuning, as the model quickly learns to ignore them.
  • Follow the initialization of WW and bb: Unless WW is initialized near 0 and bb to 1, training becomes unstable (Section 2.1 of the paper). Normalizing Z2Z_2 is also for stability.
  • Strong regularization is needed for images too: The paper notes that gMLP, like Transformers, tends to overfit the training data heavily, and used regularization close to DeiT's (AdamW, learning rate 1e-3, weight decay 0.05, 300 epochs, AutoAugment, Mixup, CutMix, label smoothing 0.1, and stochastic depth survival probabilities of 1.00, 0.95, and 0.80 for Ti, S, and B).
  • PyTorch has no built-in version: Writing it according to the pseudocode in Figure 1 of the paper is the safest route.

On tasks that judge the relationship between two sentences (natural language inference and question answering), gMLP scored lower than a Transformer of the same size. For such tasks, consider making the model larger or using the aMLP form, which adds a tiny single-head attention.

Comparison with Other Models

gMLP replaces self-attention with a fixed linear layer along the token dimension and a multiplicative gate. Compared along the same dimensions:

ModelToken mixingInput-dependent weightsPosition embeddingsTasks
Transformer (ViT, BERT)Self-attentionYesRequiredImages, language (variable length)
MLP-MixerTwo-layer MLP (token dimension)NoNot neededMainly images
ResMLPSingle linear layer (token dimension)NoNot neededImages, translation
gMLPGate from a linear layer (SGU)The linear layer is fixed, but the multiplied values come from the inputNot neededImages, language (fixed length)
aMLPSGU + tiny self-attentionPartlyNot neededLanguage (including tasks needing cross-sentence alignment)

Rough guidelines for choosing:

  • Exploring how far one can go without self-attention, or doing image classification with an MLP: gMLP offers a good balance of accuracy and efficiency among MLP models.
  • Variable-length inputs or very long sequences: Since the size of WW is set by the length, a Transformer is easier to work with.
  • Tasks that match sentences against each other, without adding many parameters: Adding only a tiny attention, as in aMLP, is effective.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of the gMLP block following the pseudocode in Figure 1 and Eqs. (1)-(4) of the paper
(image classification: 16Ɨ16 patches give n = 196 for 224Ɨ224; gMLP-S has d_model = 256, d_ffn = 1536, 30 layers)
"""


class SpatialGatingUnit(nn.Module):
  def __init__(self, d_ffn, seq_len):
    super().__init__()
    self.norm = nn.LayerNorm(d_ffn // 2)
    self.spatial_proj = nn.Conv1d(seq_len, seq_len, kernel_size=1)  # nƗn linear projection W along the token dimension, and per-token bias b
    nn.init.uniform_(self.spatial_proj.weight, -1e-3, 1e-3)          # initialize W near 0
    nn.init.ones_(self.spatial_proj.bias)                            # initialize b to 1 -> s(Z) ā‰ˆ Z1 at the start of training

  def forward(self, z):                          # z: [batch, n, d_ffn]
    z1, z2 = z.chunk(2, dim=-1)                  # split in half along channels
    z2 = self.spatial_proj(self.norm(z2))        # mix along tokens (Conv1d channel axis = token axis)
    return z1 * z2                               # element-wise multiplication (gate)


class GMLPBlock(nn.Module):
  def __init__(self, d_model, d_ffn, seq_len):
    super().__init__()
    self.norm = nn.LayerNorm(d_model)
    self.proj_in = nn.Linear(d_model, d_ffn)     # U
    self.act = nn.GELU()
    self.sgu = SpatialGatingUnit(d_ffn, seq_len)
    self.proj_out = nn.Linear(d_ffn // 2, d_model)  # V

  def forward(self, x):                          # x: [batch, n, d_model]
    shortcut = x
    x = self.act(self.proj_in(self.norm(x)))
    x = self.sgu(x)
    return self.proj_out(x) + shortcut


class GMLPClassifier(nn.Module):
  def __init__(self, img_size=224, patch=16, d_model=256, d_ffn=1536, depth=30, num_classes=1000):
    super().__init__()
    n = (img_size // patch) ** 2
    self.patch_embed = nn.Conv2d(3, d_model, kernel_size=patch, stride=patch)  # no position embeddings
    self.blocks = nn.Sequential(*[GMLPBlock(d_model, d_ffn, n) for _ in range(depth)])
    self.norm = nn.LayerNorm(d_model)
    self.head = nn.Linear(d_model, num_classes)

  def forward(self, img):
    x = self.patch_embed(img).flatten(2).transpose(1, 2)   # [batch, n, d_model]
    x = self.norm(self.blocks(x))
    return self.head(x.mean(dim=1))   # classify from the token average here (for simplicity)


model = GMLPClassifier()
logits = model(torch.randn(2, 3, 224, 224))     # [2, 1000]

FAQ

Q. What does the "g" in gMLP stand for?
A.

Gating. gMLP is built by adding a multiplicative gate (the Spatial Gating Unit, SGU) to basic MLP layers, hence the name.

Q. Why doesn't gMLP need position embeddings?
A.

The SGU's token-dimension linear projection WW holds a separate weight for each pair of positions, encoding "how much the token at one position affects the token at another." The positional information lives inside WW. In exchange, sequences longer than those seen during training cannot be handled.

Q. Does this mean self-attention is unnecessary?
A.

For image classification and language model pretraining, comparable accuracy and scaling were achieved without self-attention. However, on tasks requiring alignment between two sentences, the Transformer was better, and adding a tiny attention of about one head and 64 dimensions closed the gap. The paper concludes that self-attention is not essential but is a useful add-on for some tasks.

References

  1. Liu, H., Dai, Z., So, D. R., & Le, Q. V. (2021). Pay Attention to MLPs. arXiv:2105.08050.
  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. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL 2019. arXiv:1810.04805.