MAE (Masked Autoencoder) is a self-supervised learning method that learns features by splitting an image into patches, randomly hiding most of them (75% by default), and reconstructing the pixels of the hidden patches from the rest. It was proposed by He et al. at Facebook AI Research in 2021 and presented at CVPR 2022. A ViT-Huge pretrained only on ImageNet-1K images reaches a top-1 accuracy of 87.8% after fine-tuning, the highest among methods that use only ImageNet-1K.
In language, pretraining by masking, as in BERT, which hides parts of a sentence and predicts them, had been highly successful. The same idea had been tried on images before, but without comparable success. The paper attributes part of the reason to a difference in information density. Words in a sentence are packed with meaning, so hiding just a few makes a hard problem, whereas neighboring pixels in an image are very similar, so a small hidden area can be filled in from its surroundings.
MAE therefore raises the masking ratio to 75%, creating a problem that cannot be solved merely by extending surrounding patterns. It also uses an asymmetric architecture in which the encoder receives only the visible 25% of patches, greatly reducing training computation. As an analogy, it is like removing three quarters of the pieces from a jigsaw puzzle and practicing imagining the whole picture from the remaining pieces alone.
Unlike methods such as SimCLR and DINO that compare two views, MAE only reconstructs within a single image, so it uses no negatives, no second view, and no moving-average network.
Theory (Training Procedure and Loss)
Like an autoencoder, MAE consists of an encoder and a decoder. However, it is an asymmetric architecture in which the two clearly differ in size and role.
Encoder: a ViT. It processes only the visible patches and receives no mask tokens. After training, it is used for downstream tasks.
Decoder: a Transformer narrower and shallower than the encoder (8 blocks and 512 dimensions by default, with per-token computation about 9% of that of a ViT-L encoder). It is used only to reconstruct pixels during pretraining.
Training repeats the following steps.
Split the image into non-overlapping patches of equal size (16Γ16 pixels for ViT-L/16).
Select patches uniformly at random and remove 75% of them (sampling without replacement).
Pass the remaining 25% of patches through the encoder (ViT) after adding a linear embedding and position embeddings.
Append to the encoder output as many mask tokens (a single learned vector shared across all patches) as there are removed patches, restore the original order, and add position embeddings to all tokens.
Pass them through the decoder, whose final linear layer outputs the pixel values of each patch.
Compute the mean squared error between the reconstructed and original pixels only for the removed patches, and update the encoder and decoder.
Written as a formula, with M the set of removed patches, xiβ the original pixels of patch i, and x^iβ the reconstructed pixels, the loss in step 6 is as follows (the paper defines it in prose; the formula is a summary for this article).
L=β£Mβ£1βiβMβββ₯x^iββxiββ₯22β
The paper also examines a variant whose reconstruction target is per-patch normalized pixels (normalized by the mean and standard deviation of all pixels in the patch) and reports that it yields better representations.
Steps 2β4 can be implemented without any special sparse operations. Randomly shuffling the tokens of all patches and discarding the last 75% is equivalent to sampling without replacement. After encoding, appending the mask tokens at the end and undoing the shuffle puts every token back in its correct position.
The figure at the top illustrates this flow. The left side shows the path from the image through patches, masking, the encoder, mask tokens, and the decoder to the loss; the right side is a schematic with 8Γ8 patches showing which patches enter the encoder and the decoder.
Computing the loss only on the removed patches follows the same idea as BERT. According to a footnote in the paper, computing the loss on all pixels lowered accuracy by about 0.5%, so this choice is based on results.
Why a High Masking Ratio and an Asymmetric Architecture Work
MAE's performance and speed come from the following three design choices.
High masking ratio: hiding 75% means the image cannot be reconstructed just by extending surrounding lines and patterns, so the model must capture the overall shape of objects and scenes. The paper suggests that this "reasoning-like" behavior leads to learning useful representations. The ratio is far higher than BERT's typical 15% or the 20β50% used in earlier image research.
No mask tokens in the encoder: the encoder processes only 25% of all patches, greatly reducing computation and memory. Also, since real-world input images contain no mask tokens, there is no mismatch between pretraining and deployment inputs. In the paper's comparison, feeding mask tokens into the encoder lowered linear evaluation by 14 points and increased computation (FLOPs) 3.3-fold.
Random masking: selecting uniformly at random avoids biases such as always hiding the center of the image, keeping the problem moderately difficult even at a high masking ratio. Hiding large blocks was too hard (reconstructions became blurry), while keeping one in four patches on a regular grid was too easy, and both gave worse representations.
Another feature is its low dependence on data augmentation. Contrastive learning, which compares two views, becomes trivially solvable without strong data augmentation (according to the paper, using only cropping lowers accuracy by 13% for BYOL and 28% for SimCLR). In MAE, the random mask that changes every time plays the role of data augmentation, so cropping alone suffices, and training works even with no data augmentation at all.
MAE features shine in fine-tuning rather than linear evaluation. In the paper, linear evaluation of ViT-L gave 73.5%, lower than the contrastive method MoCo v3. On the other hand, fine-tuning just the last Transformer block raised it to 81.0%, and every setting that fine-tuned one or more blocks outperformed MoCo v3. It is not well suited to freezing the features and adding only a linear classifier.
Experimental Results
The paper's experiments center on pretraining on ImageNet-1K and evaluation by fine-tuning and linear evaluation (top-1 accuracy). Unless otherwise noted, they use ViT-L/16 pretrained for 800 epochs.
Masking ratio (Figure 5 of the paper):
Masking ratio
10%
30%
50%
75%
90%
Fine-tuning
83.2%
83.4%
84.9%
84.9%
83.0%
Linear evaluation
54.6%
61.7%
69.9%
73.5%
66.1%
Fine-tuning works well over a wide range of 40β80%, while linear evaluation keeps improving up to 75%.
Design comparisons (Table 1 of the paper):
Setting
Fine-tuning
Linear evaluation
Default (decoder with 8 blocks and 512 dims, pixel reconstruction, random masking at 75%)
84.9%
73.5%
Decoder with 1 block
84.8%
65.5%
Mask tokens fed into the encoder
84.2%
59.6%
Per-patch normalized pixels as the reconstruction target
85.4%
73.9%
No data augmentation
84.0%
65.7%
Block-wise masking (75%)
82.8%
63.9%
A deeper decoder helps linear evaluation but has little effect on fine-tuning. Even a 1-block decoder reaches a high 84.8% with fine-tuning.
Comparison with other self-supervised methods (Table 3 of the paper, fine-tuning, 1600 epochs, reconstructing normalized pixels):
Training speed (Table 2 of the paper, 128 TPU v3 cores, 800 epochs): compared with feeding mask tokens into the encoder, training is 2.8 times faster for ViT-L, 3.7 times faster with a 1-block decoder, and 3.5β4.1 times faster for ViT-H. Training ViT-L for 1600 epochs takes 31 hours, less than 300 epochs of MoCo v3 (36 hours).
Transfer: on COCO object detection (Mask R-CNN, Table 4 of the paper), ViT-L reaches AP 53.3, 4.0 points above supervised pretraining (49.3). On ADE20K semantic segmentation (UperNet, Table 5), ViT-L reaches mIoU 53.6, 3.7 points above supervised pretraining (49.9).
Practical Considerations
Pretraining settings (Table 8 in the paper's appendix): AdamW (Ξ²1β=0.9, Ξ²2β=0.95), a base learning rate of 1.5Γ10β4 (ΓbatchΒ size/256), weight decay of 0.05, a minibatch of 4096, and a cosine learning rate schedule with a warmup over the first 40 epochs. Data augmentation is only random cropping (and horizontal flipping); color jittering is not used because it lowers accuracy.
Training length: accuracy rises the longer training runs, and linear evaluation had not plateaued even at 1600 epochs (fine-tuning gives 84.9% at 800 epochs and 85.1% at 1600 epochs). Since the encoder sees only 25% of all patches per epoch, plan for more epochs than with contrastive learning.
Fine-tuning: use layer-wise learning rate decay. For linear evaluation, remove all regularization (Mixup, CutMix, drop path, color jittering, weight decay) and apply batch normalization without affine parameters to the features before feeding them into the linear classifier.
[CLS] token: to match the ViT design, one auxiliary token is added to the encoder input during pretraining and used as the class token for fine-tuning and linear evaluation. Average pooling performs about the same.
The decoder is used only during pretraining and discarded for downstream tasks. Making the decoder deeper and wider barely improves fine-tuning accuracy and only adds computation. Conversely, if the features are used for linear evaluation, a decoder that is too shallow (65.5% with 1 block) causes the last encoder layers to specialize in reconstruction, so keep a reasonable depth (the default 8 blocks).
Comparison with Other Methods
The table compares MAE with other self-supervised learning methods from the same perspectives.
Strong in fine-tuning; trains fast even for large models
MAE belongs to the same "hide and predict" family as BEiT, but it is simpler because it needs no tokenizer pretraining and reconstructs raw pixels. In the paper's comparison, it achieved higher accuracy than BEiT and trained 3.5 times faster per epoch.
As a rule of thumb, MAE is well suited to pretraining a large ViT without labels and then fine-tuning it for detection, segmentation, and similar tasks. If the features will be used frozen with a linear classifier or for nearest-neighbor search, methods that compare two views, such as DINO, are a better fit.
PyTorch example
βΆShow code
python
import torch
import torch.nn as nn
"""
A small implementation of MAE pretraining written to follow Section 3 of the paper.
Encoder: a ViT that processes only visible patches. Decoder: a narrow, shallow Transformer.
Loss: mean squared error on pixels of removed patches only (target is per-patch normalized pixels).
Position embeddings are learned here for simplicity (the paper uses fixed sin-cos embeddings).
"""
def patchify(imgs, p):
# (B, 3, H, W) β (B, num_patches, p*p*3)
B, C, H, W = imgs.shape
x = imgs.reshape(B, C, H // p, p, W // p, p)
return x.permute(0, 2, 4, 3, 5, 1).reshape(B, (H // p) * (W // p), p * p * C)
class MAE(nn.Module):
def __init__(self, img_size=224, patch=16, enc_dim=768, enc_depth=12, dec_dim=512, dec_depth=8, heads=8):
super().__init__()
self.patch = patch
n = (img_size // patch) ** 2
self.embed = nn.Linear(patch * patch * 3, enc_dim) # Linear patch embedding
self.enc_pos = nn.Parameter(torch.zeros(1, n, enc_dim))
layer = lambda d: nn.TransformerEncoderLayer(d, heads, 4 * d, batch_first=True, norm_first=True)
self.encoder = nn.TransformerEncoder(layer(enc_dim), enc_depth)
self.enc_norm = nn.LayerNorm(enc_dim)
self.to_dec = nn.Linear(enc_dim, dec_dim) # Match encoder and decoder widths
self.mask_token = nn.Parameter(torch.zeros(1, 1, dec_dim)) # One vector shared across all patches
self.dec_pos = nn.Parameter(torch.zeros(1, n, dec_dim))
self.decoder = nn.TransformerEncoder(layer(dec_dim), dec_depth)
self.dec_norm = nn.LayerNorm(dec_dim)
self.to_pixels = nn.Linear(dec_dim, patch * patch * 3) # Output pixels for each patch
def forward(self, imgs, mask_ratio=0.75):
target = patchify(imgs, self.patch) # (B, N, p*p*3)
B, N, _ = target.shape
x = self.embed(target) + self.enc_pos
# Shuffle randomly and keep the first 25% (uniform sampling without replacement)
keep = int(N * (1 - mask_ratio))
shuffle = torch.rand(B, N, device=imgs.device).argsort(dim=1)
restore = shuffle.argsort(dim=1)
ids_keep = shuffle[:, :keep]
x = torch.gather(x, 1, ids_keep.unsqueeze(-1).expand(-1, -1, x.size(-1)))
x = self.enc_norm(self.encoder(x)) # The encoder sees only visible patches
# Append mask tokens at the end and undo the shuffle
x = self.to_dec(x)
x = torch.cat([x, self.mask_token.expand(B, N - keep, -1)], dim=1)
x = torch.gather(x, 1, restore.unsqueeze(-1).expand(-1, -1, x.size(-1))) + self.dec_pos
pred = self.to_pixels(self.dec_norm(self.decoder(x))) # (B, N, p*p*3)
# Target: per-patch normalized pixels
mean, var = target.mean(dim=-1, keepdim=True), target.var(dim=-1, keepdim=True)
target = (target - mean) / (var + 1e-6).sqrt()
mask = torch.ones(B, N, device=imgs.device) # 1 = removed patch
mask[:, :keep] = 0
mask = torch.gather(mask, 1, restore)
loss = ((pred - target) ** 2).mean(dim=-1) # Mean squared error per patch
return (loss * mask).sum() / mask.sum() # Average over removed patches only
model = MAE(enc_depth=2, dec_depth=2) # Kept shallow for illustration. The paper's default decoder has 8 blocks
optimizer = torch.optim.AdamW(model.parameters(), lr=1.5e-4 * 8 / 256, betas=(0.9, 0.95), weight_decay=0.05)
model.train()
imgs = torch.randn(8, 3, 224, 224)
loss = model(imgs)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# For downstream tasks, use only embed, enc_pos, encoder, and enc_norm, and discard the decoder.
# For fine-tuning and evaluation, do not mask; feed all patches into the encoder
FAQ
Q. Why hide as much as 75%?
A.
Neighboring pixels in an image are very similar and redundant, so hiding only a little lets the model reconstruct the image just by extending surrounding patterns, and it does not learn good features. In the paper, linear evaluation accuracy kept rising from 54.6% at a 10% masking ratio to 73.5% at 75%. Fine-tuning gave good results over a wide range of 40β80%. Compared with the typical 15% masking ratio of BERT in language, this is very high.
Q. How does MAE differ from an autoencoder?
A.
Like an autoencoder, it encodes with an encoder and restores with a decoder. The differences are that it hides most of the input and reconstructs it from the rest, that it uses an asymmetric architecture in which only visible patches enter the encoder and the decoder is small, and that the loss is computed only on the hidden parts. In the paper, computing the loss on all pixels lowered accuracy by about 0.5%.
Q. Can it be used with convolutional networks such as ResNet?
A.
The paper experiments only with ViT. MAE's computational speed relies on the ViT property of passing only the visible patches to the encoder as tokens. Convolutional networks process images as grids, so as is, they cannot extract only the visible patches to reduce computation.