Masked autoencoders
掩码自编码器
Trace visible-only encoding, restored patch positions and hidden-pixel gradients in a four-patch model.
masked-autoencodersStart 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 be visible patch IDs and the complementary hidden set. Each patch has pixel values. Gather only for , append its known position indicator, and encode it. Restore the original order before decoding:
Here is one shared learned mask vector, not a separate hidden image measurement. Give the decoder its own learned positions . Our mean-mixing decoder and hidden-pixel objective are:
The mask removes direct pixel gradients at visible outputs, but does not block the encoder gradient. Let be the gradient after the decoder’s tanh derivative. Mean mixing sends every output’s signal to every input token:
Sum hidden-token gradients into the shared mask vector; send visible-token gradients through the encoder; sum the outer products for . 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
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 , yet the decoder predicts roughly 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 patches and visible fraction , a real attention encoder’s token-pair term depends on , 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
- 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.
- How many values enter the loss for one mask?
Answer 2: Three hidden patches times two pixels: six. The MSE divides by six.
- Can the encoder learn when visible-output loss is zero?
Answer 3: Yes. Its token affects the shared token mean and therefore hidden outputs.
- 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?
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
- Masked Autoencoders Are Scalable Vision Learners
Kaiming He; Xinlei Chen; Saining Xie; Yanghao Li; Piotr Dollár; Ross Girshick · 2022 - 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:
- Masked Autoencoders Are Scalable Vision Learners · Physical pages 3–4, Section 3: visible-only encoder, shared mask tokens, decoder positions, hidden-only pixel MSE and inverse shuffling.
- Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion · Sections 2–3: corruption, reconstruction and denoising criterion; distinction from hidden-position-only loss.
Related topics