Search

Search papers and lessons

Masked Autoencoders Are Scalable Vision Learners (MAE)

Kaiming He, Xinlei Chen, Saining Xie et al. · 2021

MAE hides 75 percent of an image's patches, encodes only the visible quarter with a vision transformer, and trains a small decoder to rebuild the hidden pixels, a simple label-free recipe that scales.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Representation learning
  • Sign in to see your progress

TL;DR

Masked autoencoders (MAE) show that a plain reconstruction task, scaled up, teaches a vision transformer useful features without any labels. The method hides most of an image's square patches, 75 percent of them at random, and asks the model to rebuild only the hidden pixels. The encoder sees just the visible quarter, which makes pre-training several times faster than the alternatives.

Where you'll see it: as the self-supervised pre-training step for large vision transformers, before fine-tuning on a labelled task such as ImageNet classification, COCO detection or ADE20K segmentation.

The problem

By 2021 vision models were large enough to overfit a million images, and the strongest pre-training recipes still needed hundreds of millions of labelled images, many of them not publicly available. Language had already solved this. GPT predicts the next token and BERT predicts masked tokens, and both learn from raw text. Those models now reach over a hundred billion parameters.

Masked image methods existed before the paper, including denoising autoencoders, Context Encoders and iGPT, but they lagged far behind the language results. The authors ask what makes masked autoencoding different between vision and language, and give three answers.

  1. The architecture was different. Convolutional networks dominated vision, and it was not obvious how to insert a mask token or a positional embedding into a convolution. Vision transformers remove this obstacle.
  2. The information density is different. Words are dense with meaning, so predicting a few missing words forces real language understanding. Pixels are highly redundant. A missing patch can often be guessed from its neighbours with no understanding of objects at all.
  3. The decoder plays a different role. In BERT the decoder can be a single linear layer. For images the reconstruction target is pixels, which are far from semantic, so the decoder's design strongly changes how semantic the learned representation is.

Key idea

The paper answers these three points with three design choices.

  • Mask most of the image. Hide 75 percent of the patches, far more than the 15 percent used in BERT. The task then cannot be solved by copying neighbours.
  • Use an asymmetric encoder and decoder. The encoder is a full vision transformer that sees only the visible patches, with no mask tokens. The decoder is small. It receives the encoded visible patches together with a shared mask token at every hidden position, and predicts the pixels.
  • Reconstruct pixels, and only the hidden ones. The loss is the mean squared error on the masked patches. A variant normalises each target patch by its own mean and standard deviation.
flowchart LR
  I[Image: 196 patches] --> M[Keep 49 random patches, hide 147]
  M --> E[ViT encoder on the 49 visible patches]
  E --> A[Add mask tokens at the 147 hidden positions]
  A --> D[Small decoder on all 196 positions]
  D --> R[Predicted pixels for the hidden patches]
  R --> L[Mean squared error on hidden patches only]

After pre-training the decoder is discarded. The encoder then runs on complete, unmasked images for recognition, and its output feeds a classifier or a fine-tuned head.

The payoff is speed. The encoder processes a quarter of the tokens, so most of the compute is saved. The paper reports pre-training speed-ups of at least 3 times, and this is what makes very large models affordable to train.

The method

Masking

The image is cut into non-overlapping patches, as in the vision transformer. A standard 224 by 224 image with 16 by 16 patches gives N=14×14=196N = 14 \times 14 = 196 patches. The method samples a random subset of them without replacement, from a uniform distribution. If mm is the masking ratio, the number of visible patches is (1−m)N(1 - m)N, and the default is m=0.75m = 0.75.

The uniform distribution avoids a centre bias, where the middle of the image would be masked more often. The paper also compares two structured schemes. Block-wise masking, which removes large contiguous regions, works at 50 percent but degrades at 75 percent. Grid-wise masking, which keeps one patch in every four, makes an easier task whose learned representation is weaker. Simple random sampling works best.

The encoder

The encoder is a standard ViT applied only to the visible tokens. Each visible patch is linearly projected and given a fixed sine-cosine positional embedding. The tokens then pass through transformer blocks, each with self-attention and an MLP, both using layer normalisation. The encoder ends with a layer normalisation. Because it never sees a mask token, its training inputs match its inputs at deployment, where every token is a real patch.

The decoder

The decoder takes the full set of NN positions. Each hidden position holds one shared, learned mask token, and every position gets a positional embedding so that the decoder knows where each patch sits. Without the positional embedding, a mask token would carry no information about its location.

The decoder is deliberately small. Its default has 8 transformer blocks and width 512, and it uses under 10 percent of the compute per token of the encoder. The paper reports 9 percent of the FLOPs per token against a ViT-L encoder with 24 blocks and width 1024. The last layer is a linear map to the 768 pixel values of a 16×16×316 \times 16 \times 3 patch.

The reconstruction target

Let xi\mathbf{x}_i be the pixel values of patch ii, and let y^i\hat{\mathbf{y}}_i be the decoder's prediction for it. The loss averages the squared error over the masked patches MM and over the D=768D = 768 pixel values of each patch:

L=1∣M∣∑i∈M1D∥y^i−yi∥22\mathcal{L} = \frac{1}{|M|} \sum_{i \in M} \frac{1}{D} \left\lVert \hat{\mathbf{y}}_i - \mathbf{y}_i \right\rVert_2^2

The target yi\mathbf{y}_i is either the raw pixels, yi=xi\mathbf{y}_i = \mathbf{x}_i, or the normalised pixels. The normalised version uses μi\mu_i and σi\sigma_i, the mean and standard deviation of the pixel values inside patch ii:

yi=xi−μiσi\mathbf{y}_i = \frac{\mathbf{x}_i - \mu_i}{\sigma_i}

Restricting the loss to masked patches is a result-driven choice, in the paper's words. Adding the visible patches costs about half a percent of accuracy. The normalised target improves representation quality. Two other targets were tried. Predicting the first 96 principal components of each patch made accuracy worse. Predicting discrete tokens from the BEiT dVAE gave no benefit over normalised pixels, while adding a separate tokeniser pre-training stage, so the pixel target stays simpler.

Implementation

The implementation needs no sparse operations. Each patch becomes a token. The tokens are shuffled randomly, and the last part of the list is dropped according to the masking ratio. That leaves the encoder's input, which is equivalent to sampling patches without replacement. After encoding, mask tokens are appended and the whole list is unshuffled back into the original patch order, and the decoder runs on it.

Example
Where the speed comes from

Take the standard setup: a 224 by 224 image, 16 by 16 patches, and a masking ratio of 0.75.

  1. Total patches: N=196N = 196.
  2. Visible patches seen by the encoder: 0.25×196=490.25 \times 196 = 49.
  3. Self-attention compares every pair of tokens. With all 196 tokens that is 1962=38,416196^2 = 38{,}416 pairs.
  4. With only the 49 visible tokens that is 492=2,40149^2 = 2{,}401 pairs.
  5. Ratio of attention work: 38,416/2,401=1638{,}416 / 2{,}401 = 16.
  6. The linear layers scale with the token count, so they do 196/49=4196 / 49 = 4 times less work.

Interpretation: the encoder does about four times less linear work and sixteen times less attention work than it would on every patch. The decoder still processes all 196 positions, which is why it has to be small. The paper measures the real effect on wall-clock time, shown in the results below. Its ViT-L speed-up is 2.8 times with an 8-block decoder and 3.7 times with a single block.

Results

The main results use ImageNet-1K, which has about 1.3 million labelled images, for both pre-training and fine-tuning. The paper compares against supervised pre-training and the self-supervised methods that were state of the art at the time.

ModelSupervised, from scratch (ImageNet-1K, top-1 %)MAE, ImageNet-1K only (fine-tuned, top-1 %)
ViT-B/1682.383.6
ViT-L/1682.685.9
ViT-H/1483.186.9
ViT-H/14 at 448 pxn/a87.8

The 87.8 percent result was the best reported with only ImageNet-1K data, above a previous best of 87.1 percent that used a more advanced network. BEiT, the token-prediction method, reached 85.2 percent with ViT-L, and its pixel-trained reproduction reached 83.5. The 83.5 figure is the paper's reproduction, not BEiT's own report.

Several other findings matter.

  • Masking ratio. The best ratio for both fine-tuning and linear probing is 75 percent. For fine-tuning, any ratio from 40 to 80 percent works well. For linear probing the accuracy gap across ratios is large, up to about 20 points (54.6 against 73.5).
  • Decoder depth. One decoder block gives 84.8 percent fine-tuned accuracy but only 65.5 percent linear probing accuracy. Eight blocks give 84.9 and 73.5. Fine-tuning hides the difference because it can adapt the encoder's last layers, while a linear probe cannot.
  • Mask tokens in the encoder. If the encoder is given mask tokens, linear probing accuracy falls by 14 percent. Training FLOPs fall by 3.3 times when they are removed.
  • Linear probing is weak. MAE ViT-L reaches 75.8 percent under linear probing, against 77.6 for the contrastive MoCo v3. Partial fine-tuning shows that MAE features are non-linearly strong. Tuning just the last block lifts ViT-L from 73.5 to 81.0 percent, and MAE beats MoCo v3 by 2.6 points when four blocks are tuned.
  • Transfer. With a ViT-L backbone, COCO box AP is 53.3 for MAE against 49.3 for supervised pre-training, and ADE20K segmentation mIoU is 53.6 against 49.9. The paper also reports better robustness: on ImageNet-A, ViT-H with MAE scores 68.2 against 33.1 for supervised training.
  • Data augmentation. Random cropping alone works, and training with no augmentation other than a centre crop still works reasonably well. Contrastive methods depend heavily on augmentation, so this is a real difference.
  • Schedule. Linear probing keeps improving up to 1600 epochs with no sign of saturation. The 800-epoch ablations are the standard point of comparison.

On the cost side, the paper reports that training ViT-L for 1600 epochs on 128 TPU-v3 cores took about 31 hours, against 36 hours for MoCo v3 trained for 300 epochs on the same hardware.

Why it mattered

The paper showed that the BERT recipe transfers to vision once the architecture and the decoder are chosen carefully. It did not need a tokeniser, which BEiT needed from a separately trained model. Pixel targets made the method simple to implement and cheap to run, so it became practical to train ViT-H-sized models on ImageNet alone.

The result also changed what a good self-supervised vision method has to do. The features are strong when a non-linear head is tuned, even though they are weak under linear probing. Linear separability is therefore a poor single measure of representation quality. The discussion section says the authors expect vision to follow the same scaling path that language has followed. They also say images and language are different signals, so the difference must be handled carefully. Reconstructing pixels does not require the model to recover semantic units such as objects, but the reconstructions in the paper's figures are still holistic. The authors hypothesise that the model learns visual concepts anyway.

Reading guide

Read these sections in order. The prerequisites matter for the parts shown.

  1. Section 1, Introduction. Needs Masked Language Modeling for BERT and GPT, Convolutional Neural Network for the CNN baseline, and Vision Transformer (ViT) for the architecture that removes the convolution obstacle.
  2. Section 2, Related work. Needs Self-Supervised Learning for the pretext-task framing and Contrastive Learning for the methods the paper contrasts itself with.
  3. Section 3, Masking and the encoder. Needs Vision Transformer (ViT) for patch embeddings, Positional Encoding for the sine-cosine embeddings, and Transformer, Layer Normalization and Residual Connection for the block structure.
  4. Section 3, Decoder and reconstruction target. Needs Encoder-Decoder Architecture for the asymmetric design, Mean Squared Error for the loss, and Masked Autoencoder for the general recipe.
  5. Section 4, ImageNet experiments. Needs Fine-Tuning for end-to-end training, Transfer Learning for why pre-training helps, Representation Learning for what linear probing measures, and Batch Normalization for the normalisation layer placed before the linear probe.
  6. Section 4.3, Partial fine-tuning. Needs Fine-Tuning again, with the idea of freezing all but the last few blocks.
  7. Section 5, Transfer learning. Needs Transfer Learning and Convolutional Neural Network for the detection and segmentation backbones it is compared with.
  8. Appendix A, hyperparameters. Needs Adam Optimizer for AdamW, L2 Regularization for weight decay, Data Augmentation for RandAugment and mixup, and the regularisers, such as mixup and drop path, that the paper turns off for linear probing.

Check yourself

QuestionWhat fraction of patches does MAE hide by default, and which part of the model ever sees the mask tokens?Show answer

It hides 75 percent of the patches. The mask tokens are seen only by the decoder. The encoder processes only the visible patches, which keeps its training inputs identical to the real, unmasked images it runs on at test time.

QuestionA 224 by 224 image is cut into 16 by 16 patches and the masking ratio is 0.75. How many tokens does the encoder process, and what is the base learning rate after the linear scaling rule for a batch of 4096, given that the paper's base is 1.5e-4?Show answer

The encoder processes 0.25×196=490.25 \times 196 = 49 tokens. The paper scales the learning rate as lr=base lr×batch size/256\text{lr} = \text{base lr} \times \text{batch size} / 256, so the learning rate is 1.5×10−4×4096/256=1.5×10−4×16=2.4×10−31.5 \times 10^{-4} \times 4096 / 256 = 1.5 \times 10^{-4} \times 16 = 2.4 \times 10^{-3}.

QuestionWhy does the loss use only the masked patches, and what does that choice give up?Show answer

The task is to predict what is hidden, so the loss is placed where the prediction is needed. The visible patches are already the encoder's input, and predicting them would be a near-trivial copy that dilutes the hard signal. The cost is that the model gets no direct training signal on visible pixels. The paper measured that including them lowers accuracy by about half a percent, so the trade is worth it.

QuestionTwo patches have pixel values (0.2, 0.6) and (0.7, 1.1). Both have normalised targets (-1, 1). What does the normalised target remove, and why is that useful?Show answer

It removes each patch's mean brightness and its contrast, which is the standard deviation of its pixels. What is left is the internal pattern, the relative differences between pixels. This is useful because overall brightness varies a lot between images and is easy to predict wrongly, so the encoder spends its capacity on structure. The paper reports that normalised targets improve the representation.

QuestionA team has 50,000 unlabelled satellite tiles and wants to pre-train a ViT with MAE before fine-tuning on a small labelled set. Which parts of the model do they keep, which masking ratio do they start with, and why might a linear probe underrate their result?Show answer

They keep the encoder and discard the decoder after pre-training. They start with the default 75 percent masking, because the paper finds that ratio best in its ImageNet experiments, and they should check it on their own data, since satellite tiles may be less redundant than ImageNet photographs. A linear probe can underrate the result because MAE features are weak under linear probing but strong once a non-linear head or some blocks are tuned. The team should evaluate with partial or full fine-tuning instead.

Sources

Read the full paper

Kaiming He, Xinlei Chen, Saining Xie et al., 2021. arXiv:2111.06377