Simple Algorithm
Deep Learning · Emergence · 26 min

Masked Modeling Across Modalities

BERT, MAE, data2vec and predicting in latent space.

Hide part of the input and predict it. That one idea drives BERT, masked autoencoders, wav2vec 2.0 and the joint-embedding predictive architectures; what changes is how much is hidden and what has to be predicted: words, pixels, discrete tokens, cluster labels, or the network's own representations. This lesson compares those choices across text, images, video and speech, asks why images tolerate hiding three-quarters of the input while text hides a sixth, and proves when predicting one part of the data from another must teach a network about the label.

What you’ll learn

  • Explain the design of masked autoencoders (high masking ratio, an encoder that sees only visible patches, a light decoder, normalized pixel targets) and compute their savings in tokens and attention cost.
  • Explain why images, video and speech tolerate much higher masking ratios than text.
  • Compare prediction targets: pixels (MAE, SimMIM), discrete visual tokens (BEiT), quantized latents with a contrastive loss (wav2vec 2.0), cluster labels (HuBERT) and latent targets from a teacher (data2vec, I-JEPA, V-JEPA).
  • State and prove the conditional-independence result of Lee et al. (2021): the best predictor of the hidden part, read out linearly, recovers the label posterior.
  • Interpret the gap between linear-probe and fine-tuning results for masked-modeling features.

How much to hide

Masked language modeling (Devlin et al., 2019) picks 15% of the tokens of a text and asks the model to predict them; of those, 80% are replaced by a mask token, 10% by a random token and 10% left unchanged, to reduce the mismatch with fine-tuning, where no mask tokens appear. Pretraining Objectives Compared places it next to causal, span-corruption and prefix language modeling.

Images behave differently. A masked autoencoder (MAE; He, Chen, Xie, Li, Dollár & Girshick, 2022) splits a 224×224224\times224 image into 16×1616\times16 patches, hides a random 75% of them, and reconstructs the missing pixels. Three design choices make it work:

  • An asymmetric encoder. The ViT encoder runs on the visible patches only: no mask tokens enter it. Feeding mask tokens through the encoder instead cost 3.3 times the training FLOPs and lowered both fine-tuning and linear-probe accuracy.
  • A light decoder. Mask tokens join only in a small decoder (8 transformer blocks of width 512 by default, under a tenth of the encoder's computation per token) that is discarded after pretraining.
  • Normalized targets. Each masked patch's pixels are normalized by that patch's own mean and standard deviation before computing the squared error, which improved accuracy slightly.
Predict before you look

A 224×224224\times224 image is cut into 16×1616\times16 patches and MAE masks 75% of them. How many patch tokens does the encoder process?

Show the answer

49 tokens

(224/16)2=142=196(224/16)^2=14^2=196 patches, of which a quarter, 4949, stay visible. The encoder's per-token work (projections, MLPs) shrinks fourfold and its attention, quadratic in the number of tokens, sixteenfold. He et al. measured a wall-clock speedup of 2.8×2.8\times to 4.1×4.1\times for ViT-L and ViT-H, depending on the decoder, which is what made pretraining huge encoders affordable.

python
import torch

def random_masking(x, mask_ratio=0.75):
    # x: (B, N, D) patch embeddings; keep a random subset of patches in each image
    B, N, D = x.shape
    n_keep = int(N * (1 - mask_ratio))
    ids_shuffle = torch.rand(B, N, device=x.device).argsort(dim=1)  # random order per image
    ids_keep = ids_shuffle[:, :n_keep]
    x_visible = torch.gather(x, 1, ids_keep.unsqueeze(-1).expand(-1, -1, D))
    return x_visible, ids_shuffle   # the encoder sees x_visible; the decoder unshuffles

Sorting random noise gives an independent random permutation per image, so masking costs no more than a gather. Positional embeddings are added before masking, so each visible token still knows where it came from.

Why 75% for images but 15% for text? He et al.'s answer is redundancy. Natural images are spatially smooth, so a missing patch can often be filled in by interpolating its neighbors, a task that needs no recognition of what the image shows; hiding most of the image removes that shortcut. Language is dense: each word carries information that its neighbors do not determine, and hiding a sixth of a sentence already makes a hard task. Linear-probe accuracy rose steeply with the masking ratio up to about 75%, while fine-tuning was content with anything from 40% to 80%.

The pattern holds across modalities. Video is even more redundant: VideoMAE masked 90% to 95% of space–time patches (Tong et al., 2022). Speech sits in between: wav2vec 2.0 starts a span of 10 frames at each position with probability p=0.065p=0.065, and a frame stays visible only if none of the 10 positions up to it started a span, so the masked fraction is 1−(1−0.065)10≈49%1-(1-0.065)^{10}\approx49\%. And 15% is not sacred for text either: Wettig, Gao, Zhong & Chen (2023) found 40% masking better than 15% for BERT-large-sized models.

What to predict: pixels, tokens, clusters

MethodModalityMaskingTarget and loss
MAE (He et al., 2022)images75%, random patchesnormalized pixels of masked patches, squared error
SimMIM (Xie et al., 2022)imagesrandom, with large mask units (32×3232\times32 pixels)raw pixels, ℓ1\ell_1 loss, with a one-layer prediction head
BEiT (Bao, Dong, Piao & Wei, 2022)imagesabout 40%, in contiguous blocksdiscrete visual tokens from a pretrained discrete VAE (the DALL-E tokenizer, 8192 codes); cross-entropy
wav2vec 2.0 (Baevski, Zhou, Mohamed & Auli, 2020)speechabout 49% of frames, in spans of 10quantized latent of each masked frame, picked out from 100 distractors: a contrastive loss
HuBERT (Hsu et al., 2021)speechspans, as in wav2vec 2.0offline cluster labels of each masked frame; cross-entropy
Discrete targets (BEiT, HuBERT) turn reconstruction into classification; quantization (wav2vec 2.0) does the same inside a contrastive loss. Simple pixel regression turned out to be competitive with all of them for images.

Speech shows why the target matters. Raw audio is a continuous waveform with no natural vocabulary, so predicting it sample by sample would spend the model on acoustic detail. wav2vec 2.0 encodes the waveform with a convolutional network into one latent vector zt\mathbf z_t per 20 ms, masks spans of these, and runs a transformer over the sequence to get context vectors ct\mathbf c_t. The targets are quantized: a product quantizer with two codebooks of 320 entries, trained with a Gumbel softmax, maps each zt\mathbf z_t to qt\mathbf q_t, while the transformer still receives continuous inputs. At a masked step tt the model must pick the true qt\mathbf q_t out of K=100K=100 distractors q~\tilde{\mathbf q} drawn from other masked steps of the same utterance:

Lm=−log⁡exp⁡(cos⁡(ct,qt)/κ)∑q~∈Qtexp⁡(cos⁡(ct,q~)/κ),κ=0.1\loss_m=-\log\frac{\exp\big(\cos(\mathbf c_t,\mathbf q_t)/\kappa\big)}{\sum_{\tilde{\mathbf q}\in Q_t}\exp\big(\cos(\mathbf c_t,\tilde{\mathbf q})/\kappa\big)},\qquad\kappa=0.1
QtQ_t holds the true target and the 100 distractors. A diversity term rewards using all codebook entries, which keeps the quantizer from collapsing onto a few codes. Pretrained this way on about 53,000 hours of unlabeled audio and fine-tuned on just 10 minutes of transcribed speech, the large model reached word error rates of 4.8% and 8.2% on LibriSpeech's clean and other test sets (with a language model).

HuBERT (Hsu, Bolte, Tsai, Lakhotia, Salakhutdinov & Mohamed, 2021) replaced the contrastive task by classification against offline targets. The first round clusters standard acoustic features (MFCCs) with kk-means into 100 classes and trains the model to predict each masked frame's cluster; the second round clusters the first model's own sixth-layer features into 500 classes and trains again. Computing the loss on masked frames only worked best, at least with crude targets, and the authors stress that what matters is "consistency of the targets, not just their correctness": even crude clusters teach structure, because predicting them at masked positions forces the model to infer them from context.

Predicting in latent space

Pixels, waveforms and even discrete tokens are local targets: each says what one patch or frame looks like. LeCun (2022) argued in a position paper that reconstructing such details is the wrong job for a representation. Much of the input is unpredictable in principle (the exact texture of leaves, the noise in a recording), and a model forced to predict it spends capacity on detail no downstream task needs. A joint-embedding predictive architecture (JEPA) predicts the representation of the hidden part instead, which leaves the encoder free to discard what cannot be predicted.

data2vec (Baevski, Hsu, Xu, Babu, Gu & Auli, 2022) applies one recipe to speech, images and text. A teacher, an exponential moving average of the student, encodes the unmasked input; the target at each masked position is the average of the teacher's top KK layer outputs, each normalized (K=8K=8 for speech, 6 for images, 10 for text). The student sees the masked input and regresses those targets. Because the teacher attends over the whole input, the targets are contextualized, unlike pixels or words. Only the input encoders and masking strategies stay modality-specific.

I-JEPA (Assran et al., 2023) does this for images with no hand-crafted augmentations at all. From each image it samples four target blocks (each 15–20% of the image) and one large context block (85–100%) with the targets' regions removed. A context encoder embeds the context; a target encoder, the moving average of the context encoder, embeds the full image, and the target blocks are cut from its output; a narrow predictor transformer receives the context embedding plus mask tokens carrying the targets' positions:

LI-JEPA=1M∑i=1M ∑j∈Bi∥s^yj−sg⁡(syj)∥22,M=4 target blocks Bi\loss_{\text{I-JEPA}}=\frac1M\sum_{i=1}^M\ \sum_{j\in B_i}\Big\lVert\hat{\mathbf s}_{y_j}-\operatorname{sg}\big(\mathbf s_{y_j}\big)\Big\rVert_2^2,\qquad M=4\ \text{target blocks }B_i
syj\mathbf s_{y_j} is the target encoder's representation of patch jj and s^yj\hat{\mathbf s}_{y_j} the predictor's guess. In the authors' ablation, predicting pixels instead of representations dropped low-shot linear-probe accuracy from 66.9% to 40.7%. A ViT-H/14 trained in under 72 hours on 16 GPUs.

V-JEPA (Bardes et al., 2024) carries feature prediction to video: masked space–time regions of clips from about 2 million videos are predicted in representation space, with no pretrained image encoder, text, negatives or pixel reconstruction, and the frozen encoder is evaluated with a small attentive probe on action recognition and image classification.

Think first In data2vec and I-JEPA the targets come from the network itself. What stops student and teacher from agreeing on a constant output, and so predicting it perfectly?

Nothing in the loss: a constant encoder minimizes it, exactly as in BYOL. These methods rely on the same asymmetric dynamics, a moving-average teacher, a stop-gradient on the targets and a predictor that sees only part of the input, studied in Non-Contrastive & Self-Distillation Methods. Pixel-reconstruction methods such as MAE do not have this problem, since their targets are fixed data, which is one reason they are simpler to tune. Latent prediction buys more abstract targets at the price of a collapse risk that must be managed.

Why masked prediction teaches the label: a provable case

A pretext task never sees a label, so why should solving it help classify? Lee, Lei, Saunshi & Zhuo (2021) gave a clean sufficient condition. Split an input into a visible part X1X_1 and a hidden part X2X_2, and let Y∈{1,…,k}Y\in\{1,\dots,k\}, encoded one-hot, be the downstream label. Pretraining learns the best predictor of the hidden part, ψ⋆=arg min⁡ψE∥X2−ψ(X1)∥2\psi^\star=\argmin_\psi\E\norm{X_2-\psi(X_1)}^2, which over all functions is ψ⋆(x1)=E[X2∣X1=x1]\psi^\star(\mathbf x_1)=\E[X_2\mid X_1=\mathbf x_1].

DerivationProof
  1. E[X2∣X1]=E[E[X2∣X1,Y] ∣ X1]=E[E[X2∣Y] ∣ X1]=∑y=1kP(Y=y∣X1) μy\E[X_2\mid X_1]=\E\big[\E[X_2\mid X_1,Y]\,\big|\,X_1\big]=\E\big[\E[X_2\mid Y]\,\big|\,X_1\big]=\sum_{y=1}^kP(Y=y\mid X_1)\,\boldsymbol\mu_y

    Condition on YY inside the expectation (the tower rule), then use conditional independence to drop X1X_1:

  2. ψ⋆(X1)=A⊤f⋆(X1)\psi^\star(X_1)=A^\top f^\star(X_1)

    With one-hot YY, the vector of posteriors is f⋆(X1)=E[Y∣X1]f^\star(X_1)=\E[Y\mid X_1], so the sum is a matrix product: the pretext predictor is a fixed linear image of the label posterior.

  3. (AA⊤)−1A ψ⋆(X1)=(AA⊤)−1AA⊤f⋆(X1)=f⋆(X1)(AA^\top)^{-1}A\,\psi^\star(X_1)=(AA^\top)^{-1}AA^\top f^\star(X_1)=f^\star(X_1)

    A⊤A^\top is d2×kd_2\times k with rank kk, so it has the left inverse (AA⊤)−1A(AA^\top)^{-1}A. Applying it recovers the posterior exactly:

  4. Fitting W⋆W^\star is linear regression with kk outputs on a fixed representation, hence the O~(kσ2/n2)\tilde{\mathcal O}(k\sigma^2/n_2) rate. Exact independence is rare, so the paper's main results allow approximate independence given YY and latent variables ZZ (style, pose, position), paying an extra approximation error that grows with the remaining dependence. The intuition for colorization or inpainting: once the class and a few latent factors are known, the hidden part tells you little more about the visible part, so the cheapest way to predict one from the other is to infer the class.

Check your understanding

You design a pretext task that predicts the average color of an image's outer border from its center. In your dataset that average is nearly the same for every class. What does the theorem say?

  1. The guarantee applies, since the border and the center are independent given the class
  2. The guarantee fails: the class-conditional means of the target are nearly identical, so AA is far from rank kk and the posterior cannot be read off linearly
  3. The guarantee applies with even fewer labels, because the target is so simple
  4. The theorem says nothing, because it only covers text
Show the answer

B. The guarantee fails: the class-conditional means of the target are nearly identical, so AA is far from rank kk and the posterior cannot be read off linearly

The proof inverts A⊤A^\top, whose columns are the class-conditional means μy\boldsymbol\mu_y. If those means barely differ, ψ⋆\psi^\star carries almost no trace of the posterior and no linear head can extract it. Conditional independence alone is not enough: the hidden part must also depend on the class.

Probes versus fine-tuning

Masked-modeling features behave differently under the two standard evaluations. With a ViT-L, MAE reached 75.8% ImageNet accuracy with a linear probe, behind the contrastive MoCo v3's 77.6%, but 85.9% after fine-tuning against MoCo v3's 84.1%. He et al. concluded that "linear probing and fine-tuning results are largely uncorrelated", and their ablations show where the gap comes from:

MAE ablation (ViT-L)Fine-tuningLinear probe
decoder depth 184.8%65.5%
decoder depth 8 (default)84.9%73.5%
mask tokens fed to the encoder84.2%59.6%
fine-tune only the last block—81.0% (from 73.5%)
With a shallow decoder, the encoder's last layers must do the reconstruction themselves and become "more specialized for reconstruction, but are less relevant for recognition", in the authors' words. Fine-tuning accuracy barely changes; the linear probe drops eight points.

The lesson is that a probe measures how linearly a representation exposes the labels, not how much it contains. Methods that add an image-level objective to masked prediction, such as iBOT and DINOv2 (Non-Contrastive & Self-Distillation Methods), were designed in part to get features that are both strong under a frozen probe and strong after fine-tuning.

Key takeaways

  • Masked modeling hides part of the input and predicts it. MAE masks 75% of image patches, encodes only the visible quarter (49 of 196 tokens) and reconstructs normalized pixels with a light decoder; mask tokens never enter the encoder.
  • Redundancy sets the masking ratio: about 15–40% for text, 75% for images, 90–95% for video, about half of speech frames.
  • Targets range from pixels (MAE, SimMIM) and discrete tokens (BEiT) to quantized latents in a contrastive loss (wav2vec 2.0), offline cluster labels (HuBERT) and a teacher's contextualized representations (data2vec, I-JEPA, V-JEPA), which trade pixel detail for collapse risk.
  • If the visible and hidden parts are independent given the label and the hidden part's mean varies with the class, the best predictor of the hidden part, read out linearly, gives the exact label posterior (Lee et al., 2021).
  • Linear probes and fine-tuning disagree for masked-modeling features: MAE trails contrastive methods under a probe but leads after fine-tuning, and a shallow decoder pushes reconstruction into the encoder's last layers.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does MAE hide 75% of an image's patches when BERT hides only 15% of a text's tokens?

  1. Images are larger, so more patches must be hidden to save compute
  2. Images are spatially redundant, so a lightly masked image can be completed by interpolating neighbors; heavy masking removes that shortcut, while text is dense enough that 15% is already hard
  3. Vision transformers cannot process more than a quarter of the patches
  4. The 75% was chosen to match the 80/10/10 rule of BERT
Show the answer

B. Images are spatially redundant, so a lightly masked image can be completed by interpolating neighbors; heavy masking removes that shortcut, while text is dense enough that 15% is already hard

He et al. argue that images have heavy spatial redundancy, so a low ratio makes the pretext task solvable by low-level interpolation; linear-probe accuracy rose with the ratio up to about 75%. Video, even more redundant, tolerates 90–95%, and text benefits from somewhat more than 15% in large models.

Question 2

In a masked autoencoder, where do the mask tokens for the hidden patches enter the network?

  1. Only in the decoder; the encoder processes the visible patches alone
  2. At the encoder's input, in place of each hidden patch
  3. Nowhere: hidden patches are simply dropped and never predicted
  4. In both encoder and decoder, as in BERT
Show the answer

A. Only in the decoder; the encoder processes the visible patches alone

The encoder sees only the 25% of visible patches, which is where the savings come from; the light decoder receives the encoded patches plus mask tokens (with positional embeddings) and reconstructs. Feeding mask tokens through the encoder cost 3.3 times the FLOPs and lowered accuracy.

Question 3

What are the prediction targets in HuBERT's first round of training?

  1. The raw waveform samples of the masked frames
  2. Phoneme labels from a speech recognizer trained on transcribed data
  3. kk-means cluster labels of standard acoustic features (MFCCs) of the masked frames
  4. The teacher network's average top-layer representation
Show the answer

C. kk-means cluster labels of standard acoustic features (MFCCs) of the masked frames

HuBERT clusters MFCCs into 100 classes offline and trains the model to classify masked frames into them; the next round re-clusters the model's own sixth-layer features into 500 classes. Even crude but consistent targets teach structure, because the model must infer them from context.

Question 4

Under X1⊥ ⁣ ⁣ ⁣⊥X2∣YX_1\indep X_2\mid Y with a rank-kk matrix of class-conditional means E[X2∣Y=y]\E[X_2\mid Y=y], what does a linear head on ψ⋆(X1)=E[X2∣X1]\psi^\star(X_1)=\E[X_2\mid X_1] achieve?

  1. Only an approximation of the posterior, with an error that does not vanish
  2. Nothing in general: linear heads need contrastive features
  3. The label itself, without error, for every input
  4. The exact label posterior E[Y∣X1]\E[Y\mid X_1], so few labeled examples (on the order of the number of classes) suffice
Show the answer

D. The exact label posterior E[Y∣X1]\E[Y\mid X_1], so few labeled examples (on the order of the number of classes) suffice

Conditional independence gives ψ⋆=A⊤f⋆\psi^\star=A^\top f^\star, and the rank condition lets (AA⊤)−1A(AA^\top)^{-1}A invert it: f⋆=W⋆ψ⋆f^\star=W^\star\psi^\star exactly. The labeled data are needed only to fit this kk-output linear map.

Question 5

I-JEPA predicts the target encoder's representations of hidden blocks instead of their pixels. What does it gain, and what does it risk?

  1. It gains speed only; the features are the same as MAE's
  2. It gains targets free of unpredictable pixel detail, and risks collapse, since a constant representation would be perfectly predictable
  3. It gains exact likelihoods, and risks overfitting
  4. It gains the ability to use labels, and risks label noise
Show the answer

B. It gains targets free of unpredictable pixel detail, and risks collapse, since a constant representation would be perfectly predictable

Representation targets let the encoder discard detail that cannot be predicted, and the ablation showed pixel targets far worse for low-shot probing. But targets produced by the network itself can collapse, so I-JEPA relies on a moving-average target encoder and a stop-gradient.

Further reading

  • K. He, X. Chen, S. Xie, Y. Li, P. Dollár & R. Girshick, "Masked autoencoders are scalable vision learners," CVPR (2022).
  • A. Baevski, Y. Zhou, A. Mohamed & M. Auli, "wav2vec 2.0: a framework for self-supervised learning of speech representations," NeurIPS (2020).
  • A. Baevski, W.-N. Hsu, Q. Xu, A. Babu, J. Gu & M. Auli, "data2vec: a general framework for self-supervised learning in speech, vision and language," ICML (2022).
  • M. Assran et al., "Self-supervised learning from images with a joint-embedding predictive architecture," CVPR (2023).
  • J. D. Lee, Q. Lei, N. Saunshi & J. Zhuo, "Predicting what you already know helps: provable self-supervised learning," NeurIPS (2021).