Search

Search papers and lessons

Masked Autoencoder

Level 4 · 11 min read

A masked autoencoder hides most of an image's patches, encodes only the visible ones with a vision transformer, and trains a small decoder to rebuild the hidden pixels.

On this page

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

TL;DR

A masked autoencoder (MAE) cuts an image into square patches and hides about three quarters of them at random. A vision transformer encodes only the visible quarter, and a small decoder then fills in the hidden patches with predicted pixel values. The loss is measured only on the hidden patches, so the encoder must learn what the picture looks like in order to guess what is missing. After pre-training, the decoder is thrown away and the encoder is used on whole, unmasked images.

Where you'll see it: as the self-supervised pre-training step for vision transformers, before fine-tuning on a labelled dataset such as ImageNet, and in later masked image models that follow the same recipe.

Intuition

Filling in a torn photograph

Imagine a photograph with three quarters of it covered by random torn-out squares. You can still tell it is a dog on a beach. To fill the holes you need to know what dogs look like, what sand looks like, and how a body continues behind a leg. The task forces you to learn the structure of the scene, because copying the nearest pixel does not work when the holes are large.

That is the idea behind the masked autoencoder. Hiding most of the image removes the redundancy that makes the task easy. Neighbouring patches look alike, so a model can often interpolate from the edges of a hole. With most patches gone, interpolation fails, and the model has to predict whole objects and textures from context.

The trick that makes this cheap is to show the encoder only the visible patches. The encoder does most of the work, and it sees a quarter of the tokens. The hidden patches are represented only by a shared placeholder vector, handled by a small decoder that does not need to be large because its output is only used for training.

flowchart LR
  I[Image split into 196 patches] --> M[Randomly keep 25 percent]
  M --> E[ViT encoder on 49 visible patches]
  E --> A[Add mask tokens and positions]
  A --> D[Small decoder on all 196 positions]
  D --> R[Predicted pixels for hidden patches]
  R --> L[MSE on hidden patches only]

The math

Split an image into NN non-overlapping patches. Each patch ii holds a vector of pixel values xi\mathbf{x}_i. For a 224×224224 \times 224 image cut into 16×1616 \times 16 patches, N=14×14=196N = 14 \times 14 = 196, and each patch has 16×16×3=76816 \times 16 \times 3 = 768 values, counting the three colour channels.

Sample a set VV of visible patch indices, uniformly at random, with ∣V∣=(1−m)N|V| = (1 - m)N, where mm is the masking ratio. The paper's default is m=0.75m = 0.75. Let MM be the complement, the masked set.

Definition: Masked autoencoder objective

Given the visible patches {xi:i∈V}\{\mathbf{x}_i : i \in V\}, the encoder fθf_\theta produces latent vectors for the visible patches only. The decoder gϕg_\phi receives those latent vectors together with a shared learned vector m\mathbf{m} at every masked position, and predicts the pixels of every patch. The loss compares predictions with targets on the masked patches only:

L(θ,ϕ)=1∣M∣∑i∈M∥gϕ(fθ(xV),m)i−yi∥22,\mathcal{L}(\theta, \phi) = \frac{1}{|M|} \sum_{i \in M} \left\lVert g_\phi\big(f_\theta(\mathbf{x}_V), \mathbf{m}\big)_i - \mathbf{y}_i \right\rVert_2^2 ,

where yi\mathbf{y}_i is the target for patch ii and ∥⋅∥22\lVert \cdot \rVert_2^2 here denotes the mean (not the sum) of the squared differences over the patch's pixel values, so the loss is a per-pixel mean squared error.

The loss is the mean squared error that MSE defines, averaged over the masked patches. Visible patches contribute nothing, which is a design choice. Computing the loss over all patches gave a small drop in accuracy in the paper's experiments, so the authors kept the masked-only loss.

The target

Two targets are studied. The simple one is the raw pixel values, so yi=xi\mathbf{y}_i = \mathbf{x}_i. The better one normalises each patch by its own statistics. Let μi\mu_i and σi\sigma_i be the mean and standard deviation of the pixel values inside patch ii. Then

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

Normalising removes the patch's brightness and contrast, so the model learns structure rather than matching overall intensity. The paper reports that the normalised target improves the representation.

Positions and the encoder

Each visible patch is linearly projected into a vector and given a positional embedding, as in the ViT. The encoder is a stack of transformer blocks applied to the ∣V∣|V| visible tokens only. The encoder never sees a mask token. This matters because at test time every token is real, so the encoder should be trained on real tokens too.

The decoder receives all NN positions. Each masked position gets the shared vector m\mathbf{m}, and every position gets its positional embedding so that the decoder knows where each hidden patch sits. The decoder's last layer is a linear map from the decoder width to the 768 pixel values of a patch.

Worked examples

Example
The masked loss on four pixels

Take a toy image with four masked patches, each holding two pixel values. Predictions and true values are:

patchtrue valuespredicted values
A(0.2, 0.6)(0.1, 0.5)
B(0.9, 0.7)(0.6, 0.7)
C(0.4, 0.4)(0.4, 0.5)
D(0.8, 0.2)(0.8, 0.2)
  1. Squared errors for patch A: (0.1)2=0.01(0.1)^2 = 0.01 and (0.1)2=0.01(0.1)^2 = 0.01.
  2. Patch B: (0.3)2=0.09(0.3)^2 = 0.09 and 00.
  3. Patch C: 00 and (0.1)2=0.01(0.1)^2 = 0.01.
  4. Patch D: 00 and 00.
  5. Total squared error over the masked pixels: 0.01+0.01+0.09+0+0+0.01+0+0=0.120.01 + 0.01 + 0.09 + 0 + 0 + 0.01 + 0 + 0 = 0.12.
  6. There are 4×2=84 \times 2 = 8 masked pixel values, so the loss is 0.12/8=0.0150.12 / 8 = 0.015.

Interpretation: patch B dominates the loss, because its error is large. Patch D is predicted exactly and contributes nothing. A visible patch with a large error would not appear in this sum at all, since the loss only sees masked patches.

Example
Normalising a patch target

Take a single 22-pixel patch with true values x=(0.2,0.6)\mathbf{x} = (0.2, 0.6).

  1. Mean: μ=(0.2+0.6)/2=0.4\mu = (0.2 + 0.6) / 2 = 0.4.
  2. Deviations from the mean: −0.2-0.2 and +0.2+0.2.
  3. Variance: ((−0.2)2+(0.2)2)/2=0.04\big((-0.2)^2 + (0.2)^2\big) / 2 = 0.04, so σ=0.2\sigma = 0.2.
  4. Normalised target: y=(−0.2/0.2, 0.2/0.2)=(−1, 1)\mathbf{y} = (-0.2 / 0.2,\ 0.2 / 0.2) = (-1,\ 1).

Interpretation: the target now says only that the first pixel is one standard deviation below the patch mean and the second is one above. A patch that is uniformly brighter, with values (0.7,1.1)(0.7, 1.1), has the same normalised target (−1,1)(-1, 1). The model is not asked to recover brightness, only the pattern inside the patch.

Example
Why the encoder is cheap

Use the standard setup: a 224×224224 \times 224 image, 16×1616 \times 16 patches, so N=196N = 196 tokens, and a mask ratio of 0.750.75.

  1. Visible tokens for the encoder: 0.25×196=490.25 \times 196 = 49.
  2. Self-attention compares every pair of tokens, so its cost grows with the square of the sequence length. Attention pairs with the full set: 1962=38416196^2 = 38416.
  3. Attention pairs with the visible set: 492=240149^2 = 2401.
  4. Ratio: 38416/2401=1638416 / 2401 = 16.
  5. The linear layers, which cost in proportion to the number of tokens, shrink by 196/49=4196 / 49 = 4.

Interpretation: the encoder does about four times less linear-layer work and sixteen times less attention work than it would on the full image. The decoder still processes all 196 tokens, which is why the paper makes it small. Its default has about nine percent of the compute per token of the ViT-L encoder.

For wall-clock training time, the paper (Table 2) measures the speed-up against an encoder that processes mask tokens: 2.8 times for ViT-L and 3.5 times for ViT-H with the default 8-block decoder, and 3.7 times and 4.1 times with a one-block decoder.

Tradeoffs and failure modes

The masking ratio is the main knob, and the best value is surprisingly high. Language models mask around 15 percent of tokens. The MAE paper finds that about 75 percent works best for images. Images have far more local redundancy than text, so a lower ratio leaves too much to interpolation.

SituationProblemBetter choice
Masking too littleThe task is solvable by copying neighbours, so the encoder learns littleRaise the masking ratio toward 75 percent
Masking too much on small imagesToo few visible patches remain for any useful contextKeep the ratio high but check the patch count
Encoder uses mask tokensTrain and test inputs differ, and linear probing drops sharplyDrop mask tokens from the encoder, as MAE does
Loss over all patchesEasier, and the paper reports slightly lower accuracyLoss on masked patches only
Pixel targets with no normalisationThe model spends capacity on brightness and contrastNormalise each patch target
Linear probing as the evaluationPixel-trained features are less linearly separable than fine-tuned onesFine-tune for the headline number, and report probing separately

Two caveats matter in practice. First, the representation quality depends on the evaluation. Linear probing and full fine-tuning respond differently to the masking ratio, so a result from one should not be read as a result from the other. Second, pixel reconstruction is a different task from recognition. The decoder must be deep enough to handle the reconstruction specialisation, or the encoder's last layers are pulled toward pixels.

The method also depends on the patch grid. Very small patches make the task harder and the sequence longer. Very large patches leave little to reconstruct per token. The paper's defaults are the standard ViT settings, and they should be the starting point for new work.

History

Autoencoders that reconstruct their input are much older than the transformer. Denoising autoencoders, which learn to reconstruct a clean input from a corrupted one, were studied by Vincent and colleagues in 2008. Masking as a form of corruption came into wide use with language. BERT, in 2018, hid about 15 percent of the tokens in a text and trained a transformer to recover them, which made masked prediction the standard pre-training task for language.

Vision was slower to follow. Convolutional networks were hard to combine with the mask token, since a convolution has no obvious way to treat a missing patch. The vision transformer changed that in 2020 by making images into sequences of patches, where a missing patch is just another token. Several masked image methods followed, including approaches that predict discrete visual tokens rather than pixels.

He and colleagues published the masked autoencoder in late 2021. Their paper showed that a plain pixel-reconstruction objective, with a high masking ratio and an asymmetric encoder and decoder, scales with model size and pre-training data. A vanilla ViT-Huge reached 87.8 percent top-1 accuracy on ImageNet-1K after fine-tuning at 448-pixel resolution (86.9 percent at 224), using only ImageNet-1K data. The method caught on because it is simple, needs no labels, and is fast enough to train very large vision models.

Check yourself

QuestionIn one sentence, why does the MAE encoder see only the visible patches rather than the whole image with mask tokens?Show answer

Because the encoder is used on whole, unmasked images at test time, and feeding it mask tokens during training would create a mismatch between training and deployment. Dropping the mask tokens also makes the encoder much cheaper, since it processes about a quarter of the tokens. The mask tokens are handed to the lightweight decoder instead.

QuestionA 224×224224 \times 224 image is cut into 16×1616 \times 16 patches and the masking ratio is 0.750.75. How many visible tokens does the encoder process?Show answer

There are 14×14=19614 \times 14 = 196 patches in total, and 0.25×196=490.25 \times 196 = 49 are visible. The encoder processes 49 tokens. The decoder still sees all 196 positions, but it is small.

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

The task is to predict what is hidden, so the loss is computed where the prediction is needed. The encoder already receives the visible patches as input, so predicting them is a near-trivial task that would add a weak signal and dilute the hard one. The cost of this choice is that the model gets no direct training signal on visible pixels. The paper found the masked-only loss gave slightly better accuracy.

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

It removes the patch's mean brightness and its contrast, which is the standard deviation of its pixel values. The model still has to predict the internal pattern, the difference between the pixels. This is useful because overall brightness varies a lot across images and is easy to get wrong, so the encoder can spend its capacity on structure. The paper reports that normalised targets improve the representation.

QuestionWhy does a high masking ratio work for images when a 15 percent ratio is standard for language?Show answer

Neighbouring pixels in an image are highly correlated, so a small hidden patch can be filled in by interpolating from its neighbours, and the task teaches little. Words in a text carry more information each, and the context is less redundant. A high masking ratio removes the easy interpolation, so the model must use the image's larger structure to predict what is missing.

Sources