A photo of a dog, zoomed in on its head and then tinted orange, is still a photo of that dog. Can a network learn from that fact alone, with no label at all?
P5.10 started from weights trained on 1.28 million labelled photos that somebody had to label. This lesson gets features from unlabelled pictures with four methods: contrastive learning (SimCLR and MoCo), a self-distilling teacher (DINO) and masked image modelling (MAE).
The idea: make labels from the data
Self-supervised learning invents a task, called a pretext task, whose answer is already inside the data. Nobody labels anything. The network solves the pretext task, and while doing so it has to build features that describe the image. Afterwards you throw the pretext task away and keep the encoder (the network that turns an image into a feature vector).
How do you know the features are any good? You test them on a real task, in the two ways of P5.10:
- Linear probe: freeze the encoder and train only a new linear head on labelled images. The probe measures how easily the labels can be read off the features. (This is the same meaning as in P5.10.)
- Fine-tuning: start from the encoder and train all or some layers on the labelled task.
DINO also reports a k-NN test: label an image by its nearest neighbours in feature space (P3.B1), with no training.
Three families share this recipe, and they differ in the pretext task:
- Contrastive: two views of the same image must have similar features, and views of different images must not.
- Self-distillation (DINO): a student network must match the output of a teacher network, which is a slow average of the student, on another view of the same image.
- Masked image modelling (MAE): hide most of the image and predict what is missing.
Contrastive learning: pull together, push apart
Take one image and make two random augmented views of it, for example two different crops with different colour changes. The augmentations themselves are in P4.18 and P5.7, so we only use them here. The two views form a positive pair: they should have similar features. Every view of every other image in the same batch is a negative: it should have different features.
The encoder maps each view to a vector and we compare vectors by cosine similarity, the dot product of the vectors scaled to length 1 (P1.B3):
It is for the same direction, for perpendicular and for opposite. Every embedding is a point on a sphere (a circle, with two numbers).
A worked example with four views
Take a batch of images, and , and two views of each: , , , . Suppose the encoder, with two output numbers, put them at angles , , and on the circle. The cosines of with the others are for , for and for .
For the view , the question is a multiple choice: of the other three views, which is its partner? Turn the three similarities into scores by dividing by a temperature (take ), and apply softmax (P3.A8) to get probabilities:
- scores , and (, and );
- probabilities for , for and for .
The loss for this view is minus the log of the probability of the right partner: . That is a cross-entropy loss (P1.E3) where the “classes” are the other views and the correct class is the partner. Doing the same for all four views gives , , and , and the mean is . This loss is called NT-Xent, short for normalized temperature-scaled cross-entropy (Chen and co-authors, SimCLR). It is the InfoNCE loss of P1.E5 with cosine similarity inside. The code cell below runs it.
In general, for a batch of images there are views, and each view has candidates, of which one is the partner and are negatives. The loss for view , whose partner is , is
and the training loss is the mean of over all views.
What the temperature does
The same four points at three (the cell prints them):
- : mean loss (a small spreads the scores apart, so the softmax is nearly certain).
- : mean loss .
- : mean loss (cosines only range from to , so the probabilities stay spread out).
A small makes the softmax sharp, and the loss then cares mostly about the negatives that are closest to the view (the hardest ones), because only they have a large share of the probability. A large treats all negatives more equally. One consequence: loss values at different temperatures cannot be compared, because the floor differs. In SimCLR’s own comparison (ResNet-50, 100 epochs, batch size 4096, linear probe on ImageNet) the temperature mattered: gave 64.4% top-1, gave 60.7% and gave 58.0% (and gave 59.7%, so smaller is not always better).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first cosine printed is the view with itself (). The last line previews the next section: when every view has the same embedding, the loss is , whatever is.
See it: pull together, push apart
Four code-drawn images, each with two augmented views, become points on a circle. Move the slider through the training steps of a real, tiny contrastive run.
Things to try:
- With negatives and , press Back to step 0 and then slide to about step 16. In this run the two views of every image move together (mean positive cosine about ) and the images spread around the circle, so the mean cosine between different images falls from to . The ideal for four images spread apart is , and the run ends close to it at .
- Set and slide to step 120: the loss ends near . At it levels off near , close to the collapsed value , because even a perfect layout only reaches about there. Judge the picture and the cosines, not the loss.
- Switch to No negatives and slide to step 16 or later. The pairs are as close as ever (positive cosine above ), but all four images have collapsed onto the same small arc of the circle: the mean cosine between different images is at step 16. The positives-only loss is near its best possible value, , while the embedding has forgotten which image is which.
The widget is a stand-in, not a real image encoder (the note under it says how). Its random “colour jitter” is what the encoder must learn to ignore, the job of real augmentations. The run was trained offline with tests/data/P5.16-train.py.
Why positives alone are not enough: collapse
Look at the positives-only run again. The loss only asks “make the two views of one image agree”. The cheapest way to satisfy that is to ignore the input and output the same vector for everything: then every pair agrees perfectly. This is collapse (also called a trivial solution or a constant embedding), and the loss cannot tell it apart from a useful encoder.
Negatives forbid it. If all views had the same embedding, every candidate would look like the partner, the softmax would be uniform over views, and the loss would be , which is the loss of a blind guess among the candidates (the cell above: for ). Any embedding that ranks the partner above the others does better. To lower the loss the encoder must make the partner closer than the others, which needs different images to land in different places.
The widget run is one seed, and over 8 seeds of this toy model positives-only collapsed in 6 of 8 (script in the repository). It shows the mechanism, not real networks.
SimCLR: a simple recipe
SimCLR (Chen, Kornblith, Norouzi and Hinton, ICML 2020) is the setup above with a ResNet encoder, and its paper studied which parts matter.
- Augmentations decide what the encoder learns. Two views of one image are positive, so whatever differs between them becomes something the features must ignore. The paper found that composing augmentations is critical, and that one composition stands out: random crop plus random colour distortion. It conjectured the reason: with crops alone, the pixel-intensity histograms of two crops of one image are similar, and histograms alone are enough to tell images apart, so the network can solve the task with colour statistics and learn little else.
- A projection head. Between the encoder output and the loss sits a small network , giving . The loss is computed on , but after training the head is thrown away and is used. The paper found a nonlinear head (one hidden layer) gave about 3 points better linear-probe accuracy than a linear head and more than 10 points better than no head, and that was better than by more than 10 points. Its conjecture is that is trained to ignore things the augmentations change, such as colour, which a later task may need.
- Large batches. Every other image in the batch is a negative, so a bigger batch means more negatives. The paper used batch sizes from 256 to 8192; at 8192 each positive pair has 16,382 negative examples.
- Result. ResNet-50 (the usual width), 1000 epochs: 69.3% top-1 with a linear probe on ImageNet. A ResNet-50 four times wider (375 M parameters instead of 24 M): 76.5%, about the level of a standard supervised ResNet-50 (the paper’s supervised baseline gets 76.3%). At the standard width the supervised network is still ahead (76.3% against 69.3%).
MoCo: many negatives without a huge batch
A big batch needs a lot of memory. MoCo (Momentum Contrast, He, Fan, Wu, Xie and Girshick, CVPR 2020) gets many negatives another way. It treats learning as a dictionary look-up: a view’s encoded vector is the query , and the vectors of other images are keys in a dictionary. Two ideas make a big, useful dictionary:
- A queue. The keys from the most recent batches are kept in a queue of fixed length (65,536 in the paper’s main ResNet-50 setup): the newest batch is added and the oldest removed. The dictionary size is then decoupled from the batch size, which was 256 there.
- A momentum encoder. The keys are produced by a second encoder whose weights are a slow moving average of the main one: with close to 1 (0.999 by default). Why: the keys in the queue were computed by encoders from many steps ago, and if the encoder changed fast, old keys would be incomparable with new queries. A slowly moving key encoder keeps the queue consistent. The paper reports that without it () the training loss oscillated and failed to converge, and that worked better than (59.0% against 55.2%, in an ablation with a queue of 4096 keys). Gradients flow only through the query, not the keys.
With a ResNet-50, 200 epochs and batch size 256, MoCo reached 60.6% top-1 with a linear probe on ImageNet in the paper (SimCLR’s 69.3% above was with a longer, larger-batch run, so the two numbers are not an equal comparison). The momentum idea comes back in DINO below.
DINO: no negatives, a teacher that is a slow average
DINO (Caron and co-authors, ICCV 2021) drops negatives completely. Two networks with the same architecture look at different views of one image:
- the student gets all the views, and is trained by gradient descent;
- the teacher gets only the large views and is not trained by gradient: its weights are an exponential moving average of the student’s (the same momentum update as MoCo, with the momentum rate going from 0.996 towards 1).
Both output a probability distribution over numbers, and the student is trained to match the teacher’s distribution with a cross-entropy loss, for views of the same image. The teacher is built from the student’s past, which is why the paper calls this self-distillation with no labels. The multi-crop idea feeds the student also several small crops, while the teacher sees only the two large ones, so the student learns “small piece to whole image” matches.
Avoiding collapse: centring and sharpening
With no negatives, what stops the output being constant? DINO applies two small operations to the teacher’s output:
- Centring subtracts a running average of the teacher’s outputs, so no single output dimension can dominate for every image.
- Sharpening divides by a small temperature before the softmax (the paper uses 0.04 to 0.07 for the teacher against 0.1 for the student), making the teacher’s distribution peaked.
The paper states that they work in opposite directions: centring alone pushes towards a flat (uniform) output, sharpening alone pushes towards one dimension winning, and applying both balances them. In the paper’s ablation, DINO without the momentum teacher (centring and sharpening alone) fell to 0.1% (ViT-S/16, 300 epochs). The paper describes centring and sharpening as enough to avoid collapse when a momentum teacher is present; it does not claim a proof of why.
A tiny version you can run: three images, four output numbers, where dimension 0 is large for every image.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Reading it: without centring every image picks dimension 0 (collapse), sharpening alone makes that certain, centring alone leaves the outputs flat (maximum about , near the uniform ), and together each image picks its own dimension confidently. Real DINO uses a running average over batches for the centre.
What DINO showed
All of these numbers are on ImageNet with no labels used for pretraining, and a Vision Transformer (P5.15):
- A ViT-Base with patches reached 80.1% top-1 in linear evaluation and 77.4% with k-NN. A small ViT gave 78.3% with k-NN (the abstract).
- Attention maps. The paper looks at the self-attention of the class token in the last layer of a ViT trained with DINO. These maps, without any segmentation training, highlight objects and give rough object masks. Thresholding the map to keep 60% of its mass and comparing with ground-truth masks on PASCAL VOC12 (Jaccard similarity, intersection over union), the best head of a ViT-S/16 scored 45.9, against 27.3 for a supervised ViT of the same size and 22.0 for a random network. The maps are not trained to be masks and the best head is picked, so this shows that object information is in the features, not a finished segmentation method.
BYOL (Grill and co-authors, 2020) is a related method with no negatives that reported 74.3% with a linear probe on ImageNet using a ResNet-50.
MAE: hide most of the image, predict the pixels
The third family comes straight from language. BERT hides a few words and predicts them, so MAE (Masked Autoencoders, He and co-authors, CVPR 2022) hides patches of an image and predicts them. The image is cut into a grid of squares (the patches of P5.15) and a random subset is masked.
- The encoder (a ViT) sees only the visible patches. It never sees mask placeholders, which is what makes it cheap.
- A light decoder gets the encoded visible patches plus a learned mask token for each missing patch, with position information, and predicts the pixel values of the missing patches.
- The loss is the squared error on the masked patches only. The paper found that normalizing each patch’s pixels (its own mean and standard deviation) first gave better features.
- After pretraining the decoder is thrown away, and the encoder is used on full images.
At 75% masking, patches are hidden and are seen. Attention compares every token with every other, so 196 to 49 tokens takes the pairs from to , a sixteenth. The paper reports a training speedup of 3 times or more.
Why so much masking?
BERT hides about 15% of its tokens. MAE found that for images the best ratios were far higher: 75% worked well for both linear probing and fine-tuning. The reason the paper gives is redundancy. Language is dense, so predicting a few missing words needs real understanding. A missing image patch can mostly be filled in from its neighbours by extending lines and textures, so a low ratio is solved without learning about objects. Hiding most of the image removes that shortcut. (BERT and other text objectives are in P7.10.)
What MAE showed
All on ImageNet-1K, with a vanilla ViT (conditions matter):
- ViT-Large, 800 epochs of pretraining, 75% masking: fine-tuned 84.9% top-1, but a linear probe only 73.5%. The paper itself notes MAE features are less linearly separable than those of a contrastive method (MoCo v3), yet become stronger once even a little is fine-tuned: tuning one extra Transformer block lifted ViT-L from 73.5% to 81.0%.
- ViT-Huge, 1600 epochs: 86.9% at and 87.8% when fine-tuned at , the best result among methods using only ImageNet-1K data at the time of the paper.
- The same ViT-L trained from scratch reached 82.5% in the paper’s implementation.
So linear-probe accuracy is only one way to judge features: a method can score lower on it and still be a better starting point for fine-tuning.
CLIP (P8.13) also uses a contrastive loss, but its positive pair is an image and its caption, not two views.
Three ways to see it
Intuition
Contrastive learning is a game of “spot the twin”: given one cropped, recoloured photo and a line-up of others, pick the other version of the same photo. To win you must notice what stays the same under cropping and recolouring, the object, and ignore the rest. With no negatives the game is only “say these two look alike”, and the lazy strategy is to call everything alike. MAE is a jigsaw with 75% of the pieces missing. The picture breaks where the network uses whatever lowers the loss, which can be a shortcut such as colour.
Math
For the views with unit embeddings and partner , define the scores and the softmax probabilities . The loss is
It is a softmax cross-entropy, so (P3.A8) the derivative with respect to a score is
The partner is pulled with strength and each negative is pushed with strength . In the worked example, view at has for its partner, so the pull is , and the pushes are on and on (they add up to ). Negatives that are close to the view have the largest , so they are pushed the hardest, and a small makes this concentration stronger. When the embeddings are all equal, and .
P1.E5 shows that, in expectation and under assumptions, is a lower bound on the mutual information between the two views. That bound can never exceed , which is here, so a small batch limits what it can certify. It says nothing guaranteed about the quality of the features.
DINO: the student’s softmax output is trained to match the teacher’s centred, sharpened output with cross-entropy , and the teacher is a moving average of the student. MAE: mean squared pixel error over the masked patches only, .
Code
The same loss in PyTorch (static: PyTorch is not available in the browser), checked against the NumPy cell above. Shapes are .
import math, torch, torch.nn.functional as F
def nt_xent(z, tau):
z = F.normalize(z, dim=1)
n = z.shape[0] // 2
s = z @ z.T / tau
s = s.masked_fill(torch.eye(2 * n, dtype=torch.bool), float("-inf"))
target = torch.cat([torch.arange(n, 2 * n), torch.arange(0, n)])
return F.cross_entropy(s, target)
a = torch.tensor([0., 90., 20., 110.]) * math.pi / 180
z = torch.stack([a.cos(), a.sin()], dim=1)
print(round(nt_xent(z, 0.5).item(), 4), round(nt_xent(z, 0.1).item(), 4))0.291 0.0014A training step: make two views of each image, encode and project all views, compute this loss, then backward() and the optimizer (P2.7). After training, drop the projection head.
Common mistakes
Quiz
Check your understanding
In a contrastive batch of images, each with two augmented views, how many negatives does one view have in the NT-Xent loss?
There are views. Remove the view itself and its partner, and the remaining views are negatives (the partner is the positive, so there are candidates). Using one view per other image would give , but NT-Xent uses both views of each. Counting the partner as a negative contradicts its role as the target. The loss uses all of the other views, not one random one.
You train an encoder with a loss that only asks the two views of one image to have high cosine similarity, with no negatives and nothing else. What is the most likely failure?
A constant output makes every positive pair agree exactly, and the loss cannot tell this from a useful encoder, so training can slide into it (the widget with negatives switched off shows it). The positive term pulls the views together, so they do not drift apart. Cosine similarity ignores length, so it does not reward growing vectors. Augmentations are present in this setup, and memorizing is not the failure this loss invites.
In SimCLR, what is done with the projection head after pretraining?
The paper found the layer before the head gave better linear-probe accuracy than the head output by more than 10 points, and conjectures that the head output loses information (such as colour) that the loss taught it to ignore. The head is trained, it is just not the part used afterwards. Both views go through the encoder as well, so the head is not the only part that sees them.
Why does MoCo give its key encoder a slow moving average of the query encoder, instead of using the query encoder directly?
Queue entries were produced by older versions of the encoder. If the encoder changed quickly, old keys would be incomparable with new queries, and the paper reports that with no momentum () training failed to converge. A moving average has the same number of parameters as the encoder. Running the encoder twice is not a limitation, and the augmentations are still needed.
MAE masks about 75% of the image patches, while BERT hides about 15% of the tokens. What reason does the MAE paper give for the high ratio on images?
The paper argues images carry heavy spatial redundancy, so a low masking ratio can be solved by interpolating from neighbours without learning about objects. The pixel-count option is wrong, since an image has far more pixels than a sentence has tokens. The encoder does see the visible patches, so the decoder claim is wrong. MAE has no contrastive loss and no negatives.
Exercises
- Using the four views of the worked example, at , at , at and at , compute by hand the loss of the view at . The cosines of with , and are , and (use and ).
Show answer
The scores are , and , so the exponentials are , and , which sum to . The partner probability is , and the loss is . It matches the printed row of the code cell at ( for the third view). - A batch has images with two views each. How many candidates does each view have in NT-Xent, and what is the loss if all embeddings are identical?
Show answer
candidates, of which are negatives. With identical embeddings the softmax is uniform, so the loss is , whatever is. - An MAE uses a patch grid and masks 75% of the patches. How many patches does the encoder see, and how many do the masked ones number? What does the encoder see at a 15% ratio, as in BERT?
Show answer
are masked and are visible. At 15%, are masked () and are visible, so the saving is small.
Next: P5.17 shows how small, deliberate changes to a picture can fool a network. P8.13 uses the pull-together, push-apart loss for images and text.