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 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 , 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 task | Input → target | What 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 applied | the same, for all tiles at once |
| Colorization (Zhang, Isola & Efros, 2016) | grayscale image → its colors | knowing what objects are (grass is green, sky is blue) |
| Rotation (Gidaris, Singh & Komodakis, 2018) | image rotated by 0°, 90°, 180° or 270° → the angle | knowing which way up objects normally appear |
| Skip-gram (Mikolov et al., 2013) | a word → the words around it | word meaning, as captured by usage |
| Next-token prediction | a text prefix → the next token | syntax, facts and much more: the pretext task of GPT-style models |
You train rotation prediction on a large collection of satellite images of farmland, which have no natural "up". What do you expect?
- Excellent features, since rotation prediction works on any images
- 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
- The network will learn to classify crops, because crops have a typical orientation
- 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 images in a batch is augmented twice by random crops, flips, color distortion and blur. The encoder (a ResNet) gives , a small MLP projection head gives , and the loss treats each view's partner as the one correct answer among the other views. With cosine similarities and partner , the per-view loss is
Write for the softmax weight of candidate . Differentiating with respect to each similarity:
Gradient descent therefore raises the positive's similarity with strength and lowers each negative's with strength . The pushes on the negatives add up to exactly the pull on the positive, and they are shared out in proportion to :
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 the weights become uniform and every negative is pushed equally; as the loss tends to a hinge on the single hardest negative:
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.
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 classificationThe whole loss is a cross-entropy over a similarity matrix. Its cost, for the matrix, is small next to the encoder's forward passes.
SimCLR's default batch has images. How many negatives does each view's loss term contain?
Show the answer
8190 negatives
There are views. Excluding the view itself and its partner leaves 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 ; the positive key and the negatives come from a key encoder , and the negatives are keys from earlier batches, kept in a first-in-first-out queue ( 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:
CLIP (Radford et al., 2021) applies the same loss across modalities. An image encoder and a text encoder map a batch of image–caption pairs to unit vectors and ; the matching pairs on the diagonal of the similarity matrix are the positives, every other entry a negative, and the cross-entropy runs over rows and columns:
Why does MoCo update its key encoder as a slow moving average instead of training it by backpropagation like the query encoder?
- Backpropagating through the key encoder would double the memory, and that is the only reason
- The negatives in the queue were encoded at earlier steps; a slowly changing key encoder keeps them comparable with the current queries
- The moving average acts as weight decay and prevents overfitting
- 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 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 () failed to train.
Collapse, and learning without negatives
Every two-view method faces the same trivial solution. Complete collapse, 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:
| Method | Training signal | What 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 network | asymmetry: 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 average | the 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 image | centering 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 identity | off-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' embeddings | a hinge keeps every dimension's standard deviation above a target; a covariance penalty decorrelates dimensions |
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:
| Protocol | What is trained | What it measures |
|---|---|---|
| Linear probe | a linear classifier on frozen features, usually on ImageNet | how much label information is linearly available |
| -nearest neighbors | nothing: each test image takes a weighted vote of the labels of its nearest training embeddings ( in DINO) | the local neighborhood structure of the embedding space |
| Fine-tuning | all weights, starting from the pretrained ones | quality as an initialization |
| Low-shot | a probe or fine-tuning with 1% or 10% of the labels | label efficiency |
| Transfer | heads for other datasets and tasks, such as detection and segmentation | how 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 before the head beat the head's output by more than 10% under a linear probe, because the loss makes 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 candidates. Its gradient pulls the positive with strength and pushes each negative with strength : 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, -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.
In the InfoNCE loss with temperature , which negative receives the strongest push away from the anchor?
- All negatives are pushed equally, whatever is
- The negative least similar to the anchor, since it contributes the most to the loss
- The negative most similar to the anchor, and the lower is, the more the push concentrates on it
- 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 is, the more the push concentrates on it
The gradient on negative is with , so the most similar negatives get most of the push, and a small sharpens the softmax until nearly all of it goes to the hardest one. As the loss becomes a hinge on that single negative.
SimCLR trains with a projection head but hands the downstream task the features before the head. Why?
- The head's output has fewer dimensions, and linear probes need many dimensions
- The contrastive loss makes invariant to the augmentations, discarding information such as color that still holds; probed more than 10% better
- The head is randomly reinitialized after training, so its outputs are meaningless
- and are equally good; using only saves computation
Show the answer
B. The contrastive loss makes invariant to the augmentations, discarding information such as color that still holds; probed more than 10% better
The loss rewards 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.
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?
- Dimensional collapse: the embeddings use only a low-dimensional subspace
- Complete collapse
- A sign of a perfect representation, since the information is compressed
- 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.
Masked-autoencoder features trail contrastive features under a linear probe but beat them after fine-tuning. What is the best reading?
- The linear-probe result is a bug; the protocols should always agree
- MAE features contain less information than contrastive features
- Fine-tuning results are meaningless because every weight changes
- 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
- Non-Contrastive & Self-Distillation Methods · BYOL, SimSiam, DINO, Barlow Twins and VICReg, and how far they avoid collapse without negatives.
- Comparing Representations Across Networks · CKA, model stitching and the hypothesis that large models converge on similar representations.
- Masked Modeling Across Modalities · BERT, MAE, data2vec and predicting in latent space.
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).