AI Wiki中文/EN

Masked autoencoders

掩码自编码器

Trace visible-only encoding, restored patch positions and hidden-pixel gradients in a four-patch model.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Cover three quarters of a picture and ask a model to reconstruct the missing part. A successful answer must use relationships between what remains and what was hidden. A masked autoencoder makes this a pretraining task: the encoder sees only visible patches, while a decoder restores the full patch layout and predicts pixels. The original MAE uses an asymmetric Transformer encoder–decoder. Masked Autoencoders Are Scalable Vision Learners

There are two separate masks to track. The input mask decides what the encoder may see. The loss mask decides which predictions receive direct supervision. If hidden pixels accidentally reach the encoder, the task leaks its answer. If the loss is computed only on hidden patches, the visible-patch decoder outputs are not directly trained to match their pixels.

We will build a four-patch model with both masks visible in the code. Its tiny decoder mixes tokens by a mean rather than attention; it illustrates data flow and gradients, not the accuracy or speed of the paper’s Vision Transformer.

Definitions and derivation

Let VV be visible patch IDs and MM the complementary hidden set. Each patch xix_i has pp pixel values. Gather xix_i only for i∈Vi\in V, append its known position indicator, and encode it. Restore the original order before decoding:

hi=tanh⁡([xi,onehot⁡(i)]E) (i∈V),ti={hii∈V,mi∈M.h_i=\tanh([x_i,\operatorname{onehot}(i)]E)\ (i\in V),\qquad t_i=\begin{cases}h_i&i\in V,\\m&i\in M.\end{cases}

Here mm is one shared learned mask vector, not a separate hidden image measurement. Give the decoder its own learned positions rir_i. Our mean-mixing decoder and hidden-pixel objective are:

tˉ=1P∑iti,ai=tanh⁡(ti+tˉ+ri),x^i=aiD,L=1∣M∣p∑i∈M∥x^i−xi∥22.\bar t=\frac1P\sum_i t_i,\qquad a_i=\tanh(t_i+\bar t+r_i),\qquad \hat x_i=a_iD,\qquad L=\frac1{|M|p}\sum_{i\in M}\|\hat x_i-x_i\|_2^2.

The mask removes direct pixel gradients at visible outputs, but does not block the encoder gradient. Let gig_i be the gradient after the decoder’s tanh derivative. Mean mixing sends every output’s signal to every input token:

∂L∂x^i=21[i∈M](x^i−xi)∣M∣p,gi=(∂L∂x^iD⊤)⊙(1−ai2),∂L∂tj=gj+1P∑igi.\frac{\partial L}{\partial\hat x_i}=\frac{2\mathbf1[i\in M](\hat x_i-x_i)}{|M|p},\qquad g_i=\left(\frac{\partial L}{\partial\hat x_i}D^\top\right)\odot(1-a_i^2),\qquad \frac{\partial L}{\partial t_j}=g_j+\frac1P\sum_i g_i.

Sum hidden-token gradients into the shared mask vector; send visible-token gradients through the encoder; sum the outer products for DD. The program averages over four images and all four possible single-visible-patch masks: 16 cases. It evaluates an exact finite mask expectation, rather than drawing new random masks each step. The original paper likewise restores positions and evaluates masked-pixel MSE, but uses Transformer blocks and also studies normalized-pixel targets. Masked Autoencoders Are Scalable Vision Learners

Four two-pixel patches, with only patch 2 visible. Gray marks hidden input, not zero-valued pixels. The filled result keeps the observed visible pixels and predicts only hidden patches; all panels share the same −0.8 to 1 color scale.
Four two-pixel patches, with only patch 2 visible. Gray marks hidden input, not zero-valued pixels. The filled result keeps the observed visible pixels and predicts only hidden patches; all panels share the same −0.8 to 1 color scale.

Run the calculation

Run with CPython 3.12.4 and NumPy 1.26.4. Each constructed image has four two-pixel patches. One visible patch gives a 75% masking ratio. The 39 parameters comprise an 18-parameter encoder, a three-entry shared mask, 12 decoder positions and a six-parameter output map. With 1,800 steps at rate 0.05, hidden-pixel MSE falls from 0.430531732 to 0.002074965. The printed example shows raw decoder predictions, including the unsupervised visible output. For a displayed reconstruction, keep the actual visible patch and fill only hidden patches.

import numpy as np


def initial():return np.random.default_rng(7).normal(0,.2,39)


def unpack(theta):return theta[:18].reshape(6,3),theta[18:21],theta[21:33].reshape(4,3),theta[33:39].reshape(3,2)


def predict(patches,visible,theta,cache=False):
    patches=np.asarray(patches,dtype=float);ids=np.asarray(visible,dtype=int)
    if patches.shape!=(4,2) or not 1<=len(ids)<=3 or len(set(ids.tolist()))!=len(ids) or np.any(ids<0) or np.any(ids>=4):raise ValueError('Use four two-pixel patches and 1..3 unique visible patch IDs.')
    e,mask,pos,d=unpack(theta);features=np.c_[patches[ids],np.eye(4)[ids]];encoded=np.tanh(features@e);tokens=np.tile(mask,(4,1));tokens[ids]=encoded;hidden=np.tanh(tokens+tokens.mean(axis=0)+pos);prediction=hidden@d
    return (prediction,(features,encoded,tokens,hidden,ids)) if cache else prediction


def objective(theta):
    e,mask,pos,d=unpack(theta);loss=0.;gradient=np.zeros(39);count=0
    offsets=np.array([[-.3,.1],[-.1,-.1],[.1,.2],[.3,-.2]])
    for signal in ([ -.8,-.4],[-.4,.7],[.5,-.6],[.8,.6]):
        patches=np.array(signal)+offsets
        for visible in range(4):
            pred,(features,encoded,tokens,hidden,ids)=predict(patches,[visible],theta,True);masked=np.ones(4,dtype=bool);masked[ids]=False;error=(pred-patches)*masked[:,None];loss+=np.sum(error**2)/6;gp=2*error/6;gd=hidden.T@gp;gh=(gp@d.T)*(1-hidden**2);gt=gh+gh.sum(axis=0)/4;ge=features.T@(gt[ids]*(1-encoded**2));gm=gt[masked].sum(axis=0);gradient+=np.r_[ge.ravel(),gm,gh.ravel(),gd.ravel()];count+=1
    return loss/count,gradient/count


def train(steps=1800):
    theta=initial();start=objective(theta)[0]
    for _ in range(steps):theta-=.05*objective(theta)[1]
    return theta,start,objective(theta)[0]


if __name__=='__main__':
    t,start,end=train();patches=np.array([.5,-.6])+np.array([[-.3,.1],[-.1,-.1],[.1,.2],[.3,-.2]]);out=predict(patches,[2],t);print('masked pixel MSE before/after',round(start,9),round(end,9));print('visible IDs',[2],'encoded tokens',1,'decoder tokens',4,'prediction',out.round(6).tolist())
    corrupted=patches.copy();corrupted[[0,1,3]]+=100;print('hidden-input leakage discrepancy',float(np.max(np.abs(predict(corrupted,[2],t)-out))))
masked pixel MSE before/after 0.430531732 0.002074965
visible IDs [2] encoded tokens 1 decoder tokens 4 prediction [[0.192277, -0.388868], [0.403135, -0.589391], [2.017513, -2.040388], [0.816682, -0.702959]]
hidden-input leakage discrepancy 0.0

When the method fails

The visible patch in the printed example is actually [0.6,−0.4][0.6,-0.4], yet the decoder predicts roughly [2.02,−2.04][2.02,-2.04] there. That is consistent with the declared hidden-only loss. It would be misleading to silently score those visible predictions as if they had received the same supervision.

A low training reconstruction error does not establish a useful recognition representation. A decoder can exploit simple image regularities, and pixel MSE averages ambiguous possibilities. Evaluate the encoder on a separate task and held-out data; do not use hidden values to construct its input.

With PP patches and visible fraction vv, a real attention encoder’s token-pair term depends on (vP)2(vP)^2, but projections, feed-forward layers and the decoder still cost computation. One quarter of the tokens does not prove a measured sixteenfold speedup. Our mean decoder is linear in token count at fixed widths and is not an attention timing benchmark. Compare denoising autoencoders, whose loss need not be restricted to the corrupted positions. Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion

Exercises with answers

  1. Why does changing hidden input pixels leave predictions unchanged?

Answer 1: The encoder gathers only visible IDs; hidden values appear as targets only inside the loss.

  1. How many values enter the loss for one mask?

Answer 2: Three hidden patches times two pixels: six. The MSE divides by six.

  1. Can the encoder learn when visible-output loss is zero?

Answer 3: Yes. Its token affects the shared token mean and therefore hidden outputs.

  1. What should a completed picture show at visible locations?

Answer 4: The observed pixels; only hidden locations need decoder predictions. Report raw-output evaluation separately if desired.

Sources and next steps

Read Section 3 of MAE for visible-only encoding, shared mask tokens and the inverse permutation. Then compare the corruption/reconstruction distinction in stacked denoising autoencoders. Extend this example by withholding an entire latent signal during training, enumerating its masks at evaluation, and comparing against a mean-pixel predictor. That tests generalization rather than how well 39 parameters fit four constructed images. Masked Autoencoders Are Scalable Vision Learners; Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion

Make a prediction, then check

Where should a reconstruction keep the observed pixels?

Choose one answer

Learning objectives

  • Implement separate input and loss masks without hidden-pixel leakage.
  • Explain how masked-only errors train visible tokens and how to display reconstructions.

Prerequisites & connections

Explore related knowledge →

References

  1. Masked Autoencoders Are Scalable Vision Learners
    Kaiming He; Xinlei Chen; Saining Xie; Yanghao Li; Piotr Dollár; Ross Girshick · 2022
  2. Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion
    Pascal Vincent; Hugo Larochelle; Isabelle Lajoie; Yoshua Bengio; Pierre-Antoine Manzagol · 2010

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 tests passed per chapter: finite-difference gradients, sample covariance, teacher/center update order, hidden-input isolation, independent least squares, PSD projection, margin feasibility, tied-branch derivatives and transported factor actions as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; teaching calculations, not image benchmarks.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Computed bilingual Matplotlib 3.9.1 charts bind both SVGs and numerical samples. Teacher probabilities, hidden-only reconstruction display and declared-basis Jacobians come from executed article functions; shared color scales and interpretation limits are explicit.
  • The final MAE figure uses a vertically arranged mobile source below 600px, generated from the same immutable numerical samples. Equations, code, outputs and exercises are unchanged; locale SHA and mobile SVG dependencies rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.