AI Logic

Self-Supervised Learning

Masked Autoencoder (MAE)

Updated:

MAE training flow. The left side shows an image split into patches, 75% randomly masked, only the visible 25% passed through the encoder (ViT), mask tokens added, pixels reconstructed by a lightweight decoder, and a mean squared error computed only on the masked patches. The right side shows, for an 8 Γ— 8 = 64-patch example, a schematic of (1) all patches, (2) the 16 patches left after masking, and (3) the decoder input (16 features and 48 mask tokens), along with the computation breakdown: the encoder processes only 16 patches, while the decoder processes all 64 but is lightweight

Background and Overview

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.

  1. Split the image into non-overlapping patches of equal size (16Γ—16 pixels for ViT-L/16).
  2. Select patches uniformly at random and remove 75% of them (sampling without replacement).
  3. Pass the remaining 25% of patches through the encoder (ViT) after adding a linear embedding and position embeddings.
  4. 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.
  5. Pass them through the decoder, whose final linear layer outputs the pixel values of each patch.
  6. 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\mathcal{M} the set of removed patches, xix_i the original pixels of patch ii, and x^i\hat{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=1∣Mβˆ£βˆ‘i∈Mβˆ₯x^iβˆ’xiβˆ₯22\mathcal{L} = \frac{1}{|\mathcal{M}|} \sum_{i \in \mathcal{M}} \left\| \hat{x}_i - x_i \right\|_2^2

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 ratio10%30%50%75%90%
Fine-tuning83.2%83.4%84.9%84.9%83.0%
Linear evaluation54.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):

SettingFine-tuningLinear evaluation
Default (decoder with 8 blocks and 512 dims, pixel reconstruction, random masking at 75%)84.9%73.5%
Decoder with 1 block84.8%65.5%
Mask tokens fed into the encoder84.2%59.6%
Per-patch normalized pixels as the reconstruction target85.4%73.9%
No data augmentation84.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):

MethodPretraining dataViT-BViT-LViT-H
No pretraining (paper authors' implementation)β€”82.3%82.6%83.1%
DINOImageNet-1K82.8%β€”β€”
MoCo v3ImageNet-1K83.2%84.1%β€”
BEiTImageNet-1K + 250M images for the tokenizer83.2%85.2%β€”
MAEImageNet-1K83.6%85.9%86.9%

Fine-tuning ViT-H on 448Γ—448 images gave 87.8%.

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\beta_1 = 0.9, Ξ²2=0.95\beta_2 = 0.95), a base learning rate of 1.5Γ—10βˆ’41.5 \times 10^{-4} (Γ—batchΒ size/256\times \text{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.

MethodPretext taskNetworks usedDependence on data augmentationStrengths and weaknesses of the features
SimCLR, MoCoDiscriminate two views (with negatives)Encoder (MoCo also uses a moving-average encoder)HighStrong in linear evaluation
BYOL, DINOMatch the outputs of two views (no negatives)Online and moving-average networksHigh (DINO pairs well with ViT)Strong in linear evaluation and k-NN
BEiTPredict the image tokens of hidden patchesViT + a separately trained tokenizer (dVAE)LowStrong in fine-tuning
MAEReconstruct the pixels of hidden patchesAsymmetric encoder and decoderLowStrong 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.

References

  1. He, K., Chen, X., Xie, S., Li, Y., DollΓ‘r, P., & Girshick, R. (2022). Masked Autoencoders Are Scalable Vision Learners. CVPR 2022, 16000–16009. arXiv:2111.06377.
  2. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.
  3. Bao, H., Dong, L., & Wei, F. (2021). BEiT: BERT Pre-Training of Image Transformers. arXiv:2106.08254.
  4. Official implementation (facebookresearch/mae)