Simple Algorithm
Deep Learning · Representation · 24 min

Self-Supervised Learning

Pretext tasks, contrastive learning and masked prediction: labels from the data itself.

ImageNet's 1.28 million training labels took years of human effort; unlabeled photos, recordings and text exist by the billions. Self-supervised learning turns raw data into its own teacher. Here you'll derive the contrastive loss and its gradient, see what temperature, batch size, momentum encoders and projection heads are for, and meet the other two routes to labels-free features: self-distillation and masked prediction.

What you’ll learn

  • Explain what a pretext task is, analyze classic ones (context, jigsaw, colorization, rotation, word2vec), and spot shortcut solutions.
  • Write the InfoNCE (NT-Xent) loss, derive its gradient, and explain the roles of temperature, batch size, augmentations and the projection head.
  • Compare how SimCLR, MoCo and CLIP obtain their negatives, including MoCo's queue and momentum encoder.
  • Distinguish complete from dimensional collapse, and say how non-contrastive and masked-prediction methods avoid the trivial solution.
  • Evaluate a representation by linear probing, k-nearest neighbors, fine-tuning and transfer, and explain why the protocols can disagree.

Pretext tasks: inventing a supervisor

Self-supervised learning trains an encoder fθf_{\boldsymbol\theta} on a pretext task: a prediction problem whose targets are computed from the unlabeled input itself. Nobody cares about the pretext task. What is kept is the representation h=fθ(x)\mathbf h=f_{\boldsymbol\theta}(\mathbf x), which is then reused on the tasks that matter (Fine-Tuning & Transfer). A pretext task is good if solving it forces the encoder to capture what those downstream tasks need, and bad if it has a cheap shortcut.

Pretext taskInput → targetWhat solving it requires
Context prediction (Doersch, Gupta & Efros, 2015)two patches of an image → their relative position (one of 8)recognizing object parts and their layout
Jigsaw (Noroozi & Favaro, 2016)9 shuffled tiles → which of a fixed set of permutations was appliedthe same, for all tiles at once
Colorization (Zhang, Isola & Efros, 2016)grayscale image → its colorsknowing what objects are (grass is green, sky is blue)
Rotation (Gidaris, Singh & Komodakis, 2018)image rotated by 0°, 90°, 180° or 270° → the angleknowing which way up objects normally appear
Skip-gram (Mikolov et al., 2013)a word → the words around itword meaning, as captured by usage
Next-token predictiona text prefix → the next tokensyntax, facts and much more: the pretext task of GPT-style models
Every row manufactures labels for free. The last two show that language models are self-supervised learners too. Skip-gram with negative sampling scores each true (word, context) pair above a few randomly sampled ones: already a contrastive loss.
Check your understanding

You train rotation prediction on a large collection of satellite images of farmland, which have no natural "up". What do you expect?

  1. Excellent features, since rotation prediction works on any images
  2. Poor features: the rotation of such an image is mostly unpredictable from its content, so the task cannot be solved by recognizing anything, and a network may latch onto artifacts instead
  3. The network will learn to classify crops, because crops have a typical orientation
  4. Training will diverge, since the loss has no minimum
Show the answer

B. Poor features: the rotation of such an image is mostly unpredictable from its content, so the task cannot be solved by recognizing anything, and a network may latch onto artifacts instead

Rotation prediction works on photographs because people, animals and buildings have a canonical orientation, and detecting it requires recognizing them. Without a canonical orientation the targets are close to unpredictable from content, so any learnable signal comes from incidental cues such as borders, lighting or sensor artifacts. A pretext task transfers only when solving it requires the knowledge you want.

The contrastive loss

Rather than predicting one hand-picked property, contrastive learning asks the network to recognize which inputs belong together. In SimCLR (Chen, Kornblith, Norouzi & Hinton, 2020) each of NN images in a batch is augmented twice by random crops, flips, color distortion and blur. The encoder (a ResNet) gives h=f(x)\mathbf h=f(\mathbf x), a small MLP projection head gives z=g(h)\mathbf z=g(\mathbf h), and the loss treats each view's partner as the one correct answer among the other 2N−12N-1 views. With cosine similarities sak=za⊤zk/(∥za∥∥zk∥)s_{ak}=\mathbf z_a^\top\mathbf z_k/(\norm{\mathbf z_a}\norm{\mathbf z_k}) and partner p(a)p(a), the per-view loss is

ℓa=−log⁡exp⁡(sa,p(a)/τ)∑k≠aexp⁡(sak/τ),L=12N∑a=12Nℓa\ell_a=-\log\frac{\exp(s_{a,p(a)}/\tau)}{\sum_{k\ne a}\exp(s_{ak}/\tau)},\qquad \loss=\frac1{2N}\sum_{a=1}^{2N}\ell_a
The InfoNCE loss, called NT-Xent (normalized temperature-scaled cross-entropy) by SimCLR: a softmax classifier over 2N−12N-1 candidates, with the positive as the label and the other 2(N−1)2(N-1) views as negatives. It was introduced as a lower bound on mutual information (van den Oord, Li & Vinyals, 2018), though tighter bounds turn out not to give better features (Tschannen et al., 2020).
DerivationWhat the gradient does
  1. ∂ℓa∂sak=1τ(πak−1[k=p(a)])\frac{\partial\ell_a}{\partial s_{ak}}=\frac1\tau\big(\pi_{ak}-\mathbb 1[k=p(a)]\big)

    Write πak=exp⁡(sak/τ)/∑m≠aexp⁡(sam/τ)\pi_{ak}=\exp(s_{ak}/\tau)\big/\sum_{m\ne a}\exp(s_{am}/\tau) for the softmax weight of candidate kk. Differentiating ℓa=−sa,p/τ+log⁡∑k≠aesak/τ\ell_a=-s_{a,p}/\tau+\log\sum_{k\ne a}e^{s_{ak}/\tau} with respect to each similarity:

  2. ∑k≠a, p(a)πakτ=1−πa,pτ\sum_{k\ne a,\,p(a)}\frac{\pi_{ak}}\tau=\frac{1-\pi_{a,p}}\tau

    Gradient descent therefore raises the positive's similarity with strength (1−πa,p)/τ(1-\pi_{a,p})/\tau and lowers each negative's with strength πak/τ\pi_{ak}/\tau. The pushes on the negatives add up to exactly the pull on the positive, and they are shared out in proportion to esak/τe^{s_{ak}/\tau}:

  3. ℓa → τ→0  1τmax⁡(0, max⁡k≠a, p(a)sak−sa,p(a))\ell_a\ \xrightarrow{\ \tau\to0\ }\ \frac1\tau\max\Big(0,\ \max_{k\ne a,\,p(a)}s_{ak}-s_{a,p(a)}\Big)

    So the loss is hardness-aware: negatives that already look similar to the anchor get most of the push (Wang & Liu, 2021). The temperature sets how concentrated that is. As τ→∞\tau\to\infty the weights become uniform and every negative is pushed equally; as τ→0\tau\to0 the loss tends to a hinge on the single hardest negative:

  4. Asymptotically, the loss rewards two things at once (Wang & Isola, 2020): alignment, positives close together, and uniformity, all embeddings spread evenly over the sphere. The second is what rules out the collapsed solution.

python
import torch
import torch.nn.functional as F

def nt_xent(z1, z2, tau=0.1):
    # z1, z2: (N, d) projections of two augmented views of the same N images
    n = z1.shape[0]
    z = F.normalize(torch.cat([z1, z2]), dim=1)            # 2N unit vectors
    logits = z @ z.T / tau                                  # cosine similarity / tau
    self_mask = torch.eye(2 * n, dtype=torch.bool, device=z.device)
    logits = logits.masked_fill(self_mask, float('-inf'))   # a view is not its own candidate
    partner = torch.cat([torch.arange(n, 2 * n), torch.arange(n)]).to(z.device)
    return F.cross_entropy(logits, partner)                 # (2N-1)-way classification

The whole loss is a cross-entropy over a 2N×2N2N\times2N similarity matrix. Its cost, O(N2d)\order{N^2d} for the matrix, is small next to the encoder's forward passes.

Predict before you look

SimCLR's default batch has N=4096N=4096 images. How many negatives does each view's loss term contain?

Show the answer

8190 negatives

There are 2N=81922N=8192 views. Excluding the view itself and its partner leaves 2(N−1)=81902(N-1)=8190 negatives. Chen et al. varied the batch from 256 to 8192 and found that larger batches, which bring more negatives, helped most when training was short.

Negatives at scale: MoCo and CLIP

In-batch negatives tie the number of negatives to the batch size, and SimCLR's batches of thousands of images need many accelerators. MoCo (He, Fan, Wu, Xie & Girshick, 2020) decouples the two. Each query view is encoded by the trained encoder fqf_q; the positive key and the negatives come from a key encoder fkf_k, and the negatives are keys from earlier batches, kept in a first-in-first-out queue (K=65,536K=65{,}536 by default). Keys computed many steps ago must still be comparable with today's queries, so the key encoder is not trained by backpropagation. It is a slowly moving average of the query encoder, a momentum encoder:

θk←m θk+(1−m) θq,m=0.999\boldsymbol\theta_k\leftarrow m\,\boldsymbol\theta_k+(1-m)\,\boldsymbol\theta_q,\qquad m=0.999
With m=0m=0, so that the key encoder copies the query encoder every step, the loss oscillated and training failed; with m=0.9m=0.9, linear-probe accuracy fell from 59.0% to 55.2% in the authors' ablation. A slowly changing key encoder keeps the queue consistent.

CLIP (Radford et al., 2021) applies the same loss across modalities. An image encoder and a text encoder map a batch of NN image–caption pairs to unit vectors ui\mathbf u_i and vj\mathbf v_j; the matching pairs on the diagonal of the N×NN\times N similarity matrix are the positives, every other entry a negative, and the cross-entropy runs over rows and columns:

LCLIP=−12N∑i=1N[log⁡eui⊤vi/τ∑jeui⊤vj/τ+log⁡eui⊤vi/τ∑jeuj⊤vi/τ]\loss_{\text{CLIP}}=-\frac1{2N}\sum_{i=1}^N\left[\log\frac{e^{\mathbf u_i^\top\mathbf v_i/\tau}}{\sum_je^{\mathbf u_i^\top\mathbf v_j/\tau}}+\log\frac{e^{\mathbf u_i^\top\mathbf v_i/\tau}}{\sum_je^{\mathbf u_j^\top\mathbf v_i/\tau}}\right]
CLIP learned τ\tau itself, starting from 0.070.07 and capping the logit scale 1/τ1/\tau at 100100 for stability, with batches of 32,768 pairs drawn from 400 million. A class name becomes a classifier: embed "a photo of a {label}." for every label and pick the label whose text vector is nearest to the image's: zero-shot classification.
Check your understanding

Why does MoCo update its key encoder as a slow moving average instead of training it by backpropagation like the query encoder?

  1. Backpropagating through the key encoder would double the memory, and that is the only reason
  2. The negatives in the queue were encoded at earlier steps; a slowly changing key encoder keeps them comparable with the current queries
  3. The moving average acts as weight decay and prevents overfitting
  4. Momentum makes the key encoder's outputs identical to the query encoder's, so positives match exactly
Show the answer

B. The negatives in the queue were encoded at earlier steps; a slowly changing key encoder keeps them comparable with the current queries

A queue of 65,53665{,}536 keys spans hundreds of batches. If the key encoder changed quickly, old keys and new queries would live in different coordinate systems and the classification over the queue would be meaningless. The authors' ablation confirms it: copying the encoder every step (m=0m=0) failed to train.

Collapse, and learning without negatives

Every two-view method faces the same trivial solution. Complete collapse, f(x)=cf(\mathbf x)=\mathbf c for all inputs, makes the two views of every image agree perfectly. Negatives rule it out, but they are not the only option, and avoiding complete collapse is not the end of the story: in dimensional collapse the embeddings still vary but only within a low-dimensional subspace, so the covariance matrix of the embeddings has many eigenvalues near zero. It has been measured in non-contrastive methods (Hua et al., 2021) and even in contrastive ones (Jing, Vincent, LeCun & Tian, 2022). Both are forms of representation collapse.

Since 2020, several families have learned strong features with no negatives at all:

MethodTraining signalWhat keeps it from collapsing
BYOL (Grill et al., 2020)an online network plus a small predictor regresses the projection of another view computed by a target networkasymmetry: the predictor, a stop-gradient on the target, whose weights are an exponential moving average of the online ones
SimSiam (Chen & He, 2021)the same with one shared encoder and no moving averagethe predictor and the stop-gradient; without the stop-gradient it collapses
DINO (Caron et al., 2021)self-distillation: a student matches the softmax output of a moving-average teacher on other crops of the imagecentering and sharpening the teacher's outputs
Barlow Twins (Zbontar et al., 2021)the cross-correlation matrix between the two views' embeddings, over the batch, is pushed toward the identityoff-diagonal terms decorrelate the dimensions, so they cannot all carry the same thing
VICReg (Bardes, Ponce & LeCun, 2022)mean squared distance between the two views' embeddingsa hinge keeps every dimension's standard deviation above a target; a covariance penalty decorrelates dimensions
The first three work by an architectural asymmetry, the last two by a regularizer on the batch statistics of the embeddings. Non-Contrastive & Self-Distillation Methods derives why each one works, and how far.
Think first BYOL's loss is minimized perfectly by a constant encoder, and nothing pushes embeddings apart. Why does training not find that minimum?

Because BYOL is not doing gradient descent on its loss at all: the stop-gradient treats the target as a constant at every step, and the target's weights follow a moving average rather than the gradient. The joint update is therefore not the descent direction of the loss (its authors conjecture that it descends no fixed objective at all), and collapsed points need not attract it. Analyses of linear versions show the predictor's eigenvectors aligning with those of the embeddings' correlation matrix, and identify when the dynamics avoid collapse and when they do not (Tian, Chen & Ganguli, 2021). A complete theory for deep nonlinear networks is still missing; that is one of the questions of the Emergence lesson.

Masked prediction sidesteps collapse differently. BERT (Devlin et al., 2019) hides 15% of the tokens of a text and predicts them (masked language modeling). A masked autoencoder (He et al., 2022) hides 75% of an image's patches, runs the encoder on the visible quarter only, and reconstructs the missing pixels with a light decoder. Because the targets are the data themselves, a constant output cannot score well. Methods that predict representations instead of raw data, such as data2vec and I-JEPA, gain more abstract targets at the price of a collapse risk, which they manage with moving-average teachers (Masked Modeling Across Modalities).

Measuring what was learned

A pretext loss says little about the representation's value, so self-supervised methods are judged by what the frozen or adapted encoder does on labeled tasks. The standard protocols measure different things:

ProtocolWhat is trainedWhat it measures
Linear probea linear classifier on frozen features, usually on ImageNethow much label information is linearly available
kk-nearest neighborsnothing: each test image takes a weighted vote of the labels of its kk nearest training embeddings (k=20k=20 in DINO)the local neighborhood structure of the embedding space
Fine-tuningall weights, starting from the pretrained onesquality as an initialization
Low-shota probe or fine-tuning with 1% or 10% of the labelslabel efficiency
Transferheads for other datasets and tasks, such as detection and segmentationhow general the features are

The protocols can disagree sharply. He et al. (2022) found that for masked autoencoders "linear probing and fine-tuning results are largely uncorrelated": their features trailed contrastive ones under a linear probe yet led after fine-tuning, and tuning only the last transformer block raised accuracy from 73.5% to 81.0%. Their features are rich but not linearly arranged. The projection head creates a similar trap: SimCLR's features h\mathbf h before the head beat the head's output z\mathbf z by more than 10% under a linear probe, because the loss makes z\mathbf z invariant to the augmentations and so throws away information, such as color, that downstream tasks may need.

As a reference point, a linear classifier on SimCLR's features reached 76.5% top-1 accuracy on ImageNet, matching a fully supervised ResNet-50, though with a ResNet-50 four times as wide (Chen et al., 2020). The gap between self-supervised and supervised features was closing fast.

Key takeaways

  • A pretext task manufactures labels from unlabeled data (context, rotation, colorization, masked or next-token prediction); it helps only if solving it requires the knowledge downstream tasks need, and it must be checked for shortcuts.
  • InfoNCE is a softmax classification of the positive among 2N−12N-1 candidates. Its gradient pulls the positive with strength (1−πa,p)/τ(1-\pi_{a,p})/\tau and pushes each negative with strength πak/τ\pi_{ak}/\tau: a hardness-aware loss whose focus is set by the temperature.
  • SimCLR takes its negatives from large batches, MoCo from a queue encoded by a slowly moving momentum encoder, and CLIP from the other captions and images in a batch of image–text pairs.
  • Collapse is the enemy: complete (one point) or dimensional (a low-rank subspace). Negatives, architectural asymmetry with stop-gradients, variance and covariance penalties, and reconstruction targets are the main defenses.
  • Representations are judged by linear probes, kk-NN, fine-tuning, low-shot and transfer protocols, which can disagree; features before the projection head are the ones to keep.

Check yourself

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

Question 1

In the InfoNCE loss with temperature τ\tau, which negative receives the strongest push away from the anchor?

  1. All negatives are pushed equally, whatever τ\tau is
  2. The negative least similar to the anchor, since it contributes the most to the loss
  3. The negative most similar to the anchor, and the lower τ\tau is, the more the push concentrates on it
  4. The positive, which is pushed away when it is too close
Show the answer

C. The negative most similar to the anchor, and the lower τ\tau is, the more the push concentrates on it

The gradient on negative kk is πak/τ\pi_{ak}/\tau with πak∝esak/τ\pi_{ak}\propto e^{s_{ak}/\tau}, so the most similar negatives get most of the push, and a small τ\tau sharpens the softmax until nearly all of it goes to the hardest one. As τ→0\tau\to0 the loss becomes a hinge on that single negative.

Question 2

SimCLR trains with a projection head gg but hands the downstream task the features h\mathbf h before the head. Why?

  1. The head's output z\mathbf z has fewer dimensions, and linear probes need many dimensions
  2. The contrastive loss makes z\mathbf z invariant to the augmentations, discarding information such as color that h\mathbf h still holds; h\mathbf h probed more than 10% better
  3. The head is randomly reinitialized after training, so its outputs are meaningless
  4. h\mathbf h and z\mathbf z are equally good; using h\mathbf h only saves computation
Show the answer

B. The contrastive loss makes z\mathbf z invariant to the augmentations, discarding information such as color that h\mathbf h still holds; h\mathbf h probed more than 10% better

The loss rewards z\mathbf z for ignoring whatever the augmentations change. The head absorbs that invariance, so the layer below can keep information the pretext task did not need but downstream tasks might.

Question 3

A self-supervised encoder outputs 256-dimensional embeddings. They differ from image to image, and no two images get the same vector, but the covariance matrix of the embeddings has only about 20 eigenvalues that are not close to zero. What is this?

  1. Dimensional collapse: the embeddings use only a low-dimensional subspace
  2. Complete collapse
  3. A sign of a perfect representation, since the information is compressed
  4. Overfitting to the augmentations
Show the answer

A. Dimensional collapse: the embeddings use only a low-dimensional subspace

The representation has not collapsed to a point, but it varies only along about 20 directions, so most of its 256 dimensions are wasted. Decorrelation penalties such as Barlow Twins' and VICReg's covariance term target exactly this.

Question 4

Masked-autoencoder features trail contrastive features under a linear probe but beat them after fine-tuning. What is the best reading?

  1. The linear-probe result is a bug; the protocols should always agree
  2. MAE features contain less information than contrastive features
  3. Fine-tuning results are meaningless because every weight changes
  4. The protocols measure different things: MAE features hold the information, but not in a linearly separable arrangement
Show the answer

D. The protocols measure different things: MAE features hold the information, but not in a linearly separable arrangement

A linear probe asks how much is linearly available; fine-tuning asks how good a starting point the weights are. He et al. found the two largely uncorrelated for MAE, and tuning just the last block already closed much of the gap. Report several protocols.

Go deeper

Further reading

  • T. Chen, S. Kornblith, M. Norouzi & G. Hinton, "A simple framework for contrastive learning of visual representations," ICML (2020).
  • K. He, H. Fan, Y. Wu, S. Xie & R. Girshick, "Momentum contrast for unsupervised visual representation learning," CVPR (2020).
  • A. Radford et al., "Learning transferable visual models from natural language supervision," ICML (2021).
  • R. Balestriero et al., "A cookbook of self-supervised learning," arXiv:2304.12210 (2023).