It was proposed in 2021. At that time, CNNs were the mainstream in computer vision, and models that use attention, such as the Vision Transformer (ViT), were also spreading. MLP-Mixer is simpler even than a CNN, and its defining feature is that all processing is done with MLPs alone.
In other words, MLP-Mixer needs neither Self-Attention nor convolution, and it can perform tasks such as image classification with plain fully connected layers alone.
According to the paper, MLP-Mixer reaches the same level as ViT and CNNs only when it is trained on large-scale data or combined with modern regularization. With little data, it can fall short of CNNs and similar models.
In recent years, the Transformer has achieved excellent results, but its computational cost grows with the square of the sequence length (the number of patches for images), which is seen as a problem.
The computational cost of MLP-Mixer grows linearly with the number of patches, so it is lighter than the Transformer. Architectures based on MLP-Mixer, such as TSMixer and TTM built on top of it, have since been proposed.
Theory
MLP-Mixer splits an image into patches and alternately applies an MLP that mixes information across patches (Token Mixer) and an MLP that mixes the features within each patch (Channel Mixer). The pair is combined into a Mixer layer, and several Mixer layers are stacked.
Information flows as follows.
Split the image into patches of size PĆP (S patches).
Convert each patch into a token by applying the same fully connected layer to every patch as a linear transformation.
Here each token is a row vector, and each column vector corresponds to one feature. The result is a table [S Ć C] of S patches by C features.
Apply layer normalization, transpose the table, and feed the vectors along the patch direction into an MLP layer (MLP 1). (Token Mixer)
This mixes information across patches.
Transpose the output of MLP 1 back to the original shape and add the input of the Mixer layer (residual connection).
Apply layer normalization again, feed the vectors along the feature direction (row vectors) into an MLP layer (MLP 2), and add its input. (Channel Mixer)
This mixes the features within one patch.
Inserting the transpose lets the model learn from both viewpoints: across patches and across features.
Steps 3ā5 make up one Mixer layer. MLP 1 and MLP 2 are both "fully connected layer ā GELU ā fully connected layer".
After several Mixer layers, average over the patches with global average pooling and output the class with a fully connected layer.
MLP 1 reuses the same weights for every feature (channel), and MLP 2 reuses the same weights for every patch. Therefore, increasing the number of patches or features does not increase the number of parameters much.
PyTorch example
ā¶Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm
'''
Image classification task using the MNIST data
'''
# Hyperparameters
batch_size = 64 # batch size
epochs = 10 # number of epochs
learning_rate = 1e-3 # learning rate
num_blocks = 2 # number of stacked MLP-Mixer Blocks (2 layers->96.90%, 3 layers->97.35%)
# 'cuda' if CUDA is available on Windows, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
# Dataset and loaders
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
# MLP-Mixer Block
class MLPMixerBlock(nn.Module):
def __init__(self, num_patches: int, hidden_dim: int, token_dim: int, channel_dim: int):
super().__init__()
self.token_mixing = nn.Sequential(
nn.LayerNorm(num_patches),
nn.Linear(num_patches, token_dim),
nn.GELU(),
nn.Linear(token_dim, num_patches)
)
self.channel_mixing = nn.Sequential(
nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, channel_dim),
nn.GELU(),
nn.Linear(channel_dim, hidden_dim)
)
def forward(self, x):
# Transpose
y = x.permute(0, 2, 1)
# Token Mixer (MLP1)
x = x + self.token_mixing(y).permute(0, 2, 1)
# Channel Mixer (MLP2)
x = x + self.channel_mixing(x)
return x
# MLP-Mixer model
class MLPMixer(nn.Module):
def __init__(self, image_size=28, patch_size=7, hidden_dim=64, token_dim=32, channel_dim=128, num_classes=10):
super().__init__()
assert image_size % patch_size == 0
num_patches = (image_size // patch_size) ** 2
self.patch_embedding = nn.Conv2d(1, hidden_dim, kernel_size=patch_size, stride=patch_size)
self.mixer_blocks = nn.Sequential(*[
MLPMixerBlock(num_patches, hidden_dim, token_dim, channel_dim)
for _ in range(num_blocks)
])
self.layer_norm = nn.LayerNorm(hidden_dim)
self.classifier = nn.Linear(hidden_dim, num_classes)
def forward(self, x):
x = self.patch_embedding(x) # [B, hidden_dim, H', W']
x = x.flatten(2).transpose(1, 2) # [B, num_patches, hidden_dim]
x = self.mixer_blocks(x) # [B, num_patches, hidden_dim]
x = self.layer_norm(x)
x = x.mean(dim=1) # Global average pooling
return self.classifier(x)
# Training and evaluation
model = MLPMixer().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Training loop
for epoch in tqdm(range(epochs)):
model.train()
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# Evaluation
model.eval()
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print(f"Test Accuracy: {accuracy:.2f}%")
FAQ
Q. How long does training take?
A.
With epoch=5, num_blocks=3 it takes about 2 minutes; with epoch=10, num_blocks=3 it takes about 4 minutes.
Q. Is MLP-Mixer good enough for MNIST image classification?
A.
Yes, it should be. About 4 minutes of training reaches an accuracy of roughly 97%. With more epochs and tuned parameters, it should reach sufficient accuracy.
Q. How much data is needed for training?
A.
The paper states that with large amounts of data it can perform on par with the Transformer, but the amount of data needed differs by task, so it is recommended to observe how accuracy changes as the amount of data changes.