◆ AI All-in-One

Level 3 In-Depth AI · Deep Learning

Self-Supervised Learning

Learning from unlabelled data by turning the data into its own labels. Predict the next word, fill in a hidden patch, or match two views of the same photo. This is how foundation models are trained.

Level
●●●●● Intermediate
Reading
14 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Unsupervised LearningNeural Networks

This leads to

—
The full path from zero — 15 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Unsupervised Learning
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Self-Supervised Learning

Read them roughly in this order. See it on the concept map →

Why it matters

Supervised learning needs labels, and labels are expensive. ImageNet's 1.28 million training images, each tagged with one of 1,000 classes, took years of crowd-sourced work. Labelling medical scans needs doctors. Labelling legal text needs lawyers. Meanwhile, unlabelled data is almost free: trillions of words of web text, billions of photos and videos, endless hours of audio.

Self-supervised learning (SSL) gets the best of both. It invents a supervised task whose labels come from the data itself: hide part of the input and ask the network to predict it. No human labels anything, yet the network is trained with the same machinery as ordinary supervised learning: a loss, Backpropagation and Gradient Descent. To solve the invented task well, the network has to learn a great deal about the structure of the data. Those learned representations then transfer to the tasks you actually care about.

This is the engine of modern AI. Every GPT-style language model is pretrained by self-supervision: predict the next token, over and over, on trillions of tokens (Meta reported training Llama 3 on over 15 trillion). BERT learned by filling in blanked-out words. CLIP learned to match 400 million images with their captions from the web. Self-supervised image models such as DINOv2 provide general-purpose visual features. A foundation model is essentially a large network pretrained with self-supervision and then adapted, by Fine-Tuning or prompting, to many tasks.

The intuition

How do children learn? Mostly not from labelled examples. They watch the world and constantly predict: what happens if I drop this cup, what word comes next in the song, what the hidden side of a toy looks like. When a prediction is wrong, they learn. Nobody hands them a label. The world itself provides the answer a moment later.

Self-supervised learning does the same thing with data. Take an example, hide or change part of it, and train a network to recover what was hidden from what remains. The invented task is called a pretext task. Nobody cares about the pretext task for its own sake. It is a pretext for learning good internal representations.

1 · Predict the next tokenGPT and every chatbot LLM the cat sat on the mat label = the word that actually came next 2 · Fill in what was hiddenBERT (words), MAE (image patches) the [MASK] sat on the mat label = “cat”, the word that was theremost patches hidden 3 · Match two viewsSimCLR; CLIP (image ↔ caption) encoder same image:pull togetherother images:push apart two random crops / colour changes of one photo
Fig. 1 Three families of self-supervised pretext tasks. Predict the next token from the ones before (GPT). Fill in hidden words or image patches (BERT, masked autoencoders). Match two randomly altered views of the same image, while telling them apart from other images (contrastive learning, as in SimCLR; CLIP does the same with images and their captions).

Why does this produce useful knowledge? To predict the word after "The capital of France is", a model must know some geography. To fill in a masked patch of a photo of a dog, it must know what dogs look like. To recognise two crops of the same photo as "the same thing", even after recolouring, it must look past pixel details to what the picture shows. The pretext task forces understanding.

Key idea Self-supervised learning creates labels from the data itself, by hiding part of each example and predicting it, or by matching different views of the same example. It needs no human labelling, so it scales to the whole internet. The representations it learns are the starting point for nearly every modern model.

How it works

There are three main families. All of them end the same way: keep the trained network (or its encoder), throw away whatever was specific to the pretext task, and use the learned representations downstream.

1. Predicting the next token (autoregressive)

The simplest pretext task for text: given the words so far, predict the next one. A sentence of nn words provides n−1n - 1 training examples for free. From "the cat sat on the mat":

Input Label
the cat
the cat sat
the cat sat on
the cat sat on the
the cat sat on the mat

The loss is the cross-entropy of the predicted probability of the true next word, averaged over every position of every document. This is language modelling, and it is how GPT-style models are pretrained. Its great advantage is that the trained model can generate. Repeatedly predicting the next token writes text.

2. Filling in what was hidden (masked modelling)

Masked modelling hides random parts of the input and predicts them from everything else, looking both left and right.

  • BERT (2018) replaces 15% of the tokens in each sentence (mostly with a special [MASK] token) and predicts the originals. Seeing both sides of the gap gives rich representations for understanding tasks such as classification and search.
  • Masked autoencoders (MAE, 2021) apply the same idea to images. They cut an image into patches, hide 75% of them, and train a Vision Transformers to reconstruct the missing pixels. Hiding so much makes the task hard enough to require real understanding, and it also makes training fast, because the encoder only processes the visible quarter.

Older pretext tasks for images worked the same way in spirit: predict the relative position of two patches, solve a jigsaw of shuffled tiles, recolour a grey-scale image, or predict how much an image was rotated.

3. Contrastive learning

Contrastive learning doesn't predict missing pieces at all. It learns an embedding space in which different views of the same thing are close and views of different things are far apart.

SimCLR (Chen, Kornblith, Norouzi and Hinton, 2020) is the clearest example:

  1. Take a batch of NN images.
  2. Make two random augmented views of each one: random crops, flips, colour changes and blur (Data Augmentation). The two views of the same image are a positive pair. Every view of any other image is a negative.
  3. Pass all 2N2N views through the same encoder and normalise the outputs to unit length, so that a dot product is a cosine similarity.
  4. For each view, treat finding its partner among all the other views as a classification problem.
0.9 0.1 −0.2 0.3 dog, view 1dog 0.2 0.8 0.0 −0.1 cat, view 1cat −0.1 0.3 0.9 0.2 car, view 1car 0.1 0.0 0.2 0.7 tree, view 1tree view 2 of each image cosine similarity of every pair in a batch of 4 diagonal: positive pairs two views of the same image → make these similarities high off-diagonal: negatives views of different images → make these low the loss (InfoNCE) treat each row as a classification: softmax over the row, the correct “class” is the diagonal entry example numbers; real batches hold hundreds or thousands of images
Fig. 2 The similarity matrix for a batch of four images. Rows are the first view of each image, columns the second. The diagonal holds the positive pairs, whose similarity the loss pushes up. Everything else is a negative pair, pushed down.

The loss for one view zi\mathbf{z}_i whose partner is zj\mathbf{z}_j is called InfoNCE. In words: softmax over the similarities to every candidate, then minus the log of the probability given to the true partner.

ℓi=−log⁡exp⁡(zi⋅zj/τ)∑k≠iexp⁡(zi⋅zk/τ)\ell_i = -\log \frac{\exp(\mathbf{z}_i \cdot \mathbf{z}_j / \tau)}{\sum_{k \ne i} \exp(\mathbf{z}_i \cdot \mathbf{z}_k / \tau)}

The $\mathbf{z}$s are the normalised embeddings, so each dot product is a cosine similarity between −1 and 1. The sum runs over all other views in the batch. τ\tau ("tau") is a temperature, a small number like 0.1 that sharpens the softmax.

A worked example. Take the "dog" row of the figure: similarities 0.9 (its partner), 0.1, −0.2 and 0.3. Divide by τ=0.1\tau = 0.1 to get 9, 1, −2 and 3. Exponentiate: e9≈8,103e^9 \approx 8{,}103, e1≈2.7e^1 \approx 2.7, e−2≈0.14e^{-2} \approx 0.14, e3≈20.1e^3 \approx 20.1. The partner's share is 8,103/8,126≈0.9978{,}103 / 8{,}126 \approx 0.997, so the loss is −ln⁡0.997≈0.003-\ln 0.997 \approx 0.003. This row is already almost solved. With τ=1\tau = 1 instead, the same similarities would give the partner only 43% and a loss of 0.85. The temperature decides how sharply the loss separates near-misses from the true partner.

What the encoder must learn is whatever survives the augmentations. Crops, colour changes and blur destroy pixel-level detail but keep what is in the picture. Choosing the augmentations is therefore choosing what the representation should ignore.

CLIP applies the same loss to a different kind of pair: an image and its caption. The positives are 400 million image–text pairs collected from the web, and the result is a shared space for pictures and language (CLIP and Contrastive Learning).

Collapse, and how to avoid it

There is a trap. If the goal is only "make two views of the same image similar", the encoder can cheat by giving every image the same output. All similarities are then 1 and the job looks done. This is called representation collapse. Contrastive methods prevent it with negatives: matching everything to everything is punished. That is why SimCLR needs large batches, up to 8,192 images, to get plenty of negatives. MoCo (He and colleagues, 2019) instead keeps a queue of embeddings from recent batches.

Remarkably, some methods avoid collapse without negatives. BYOL (2020) and DINO (2021) train a student network to match a teacher network whose weights are a slowly moving average of the student's. Together with tricks such as an extra predictor layer or centring the outputs, this asymmetry is enough to keep the representations from collapsing. DINO's successor DINOv2 (2023) is a widely used general-purpose image backbone.

How do you know it worked? Linear probing

Self-supervised representations are judged by how useful they are for real tasks. The standard test is the linear probe: freeze the pretrained encoder, train only a linear classifier on top using labelled data, and measure accuracy. If a simple linear layer can read off the classes, the encoder has organised the data well. SimCLR reached 76.5% top-1 accuracy on ImageNet this way, matching a ResNet-50 trained fully supervised on the same labels. Fine-tuning the whole encoder on a small labelled set is the other common test.

Why self-supervision powers foundation models

  • Scale. Labels are the bottleneck of supervised learning. Self-supervision removes it, so models can learn from essentially all available data. Scaling Laws showed that language-model loss keeps falling smoothly as data, model size and compute grow.
  • Generality. A pretext task like "predict the next token" covers a huge range of skills: grammar, facts, arithmetic, code, style. The representations aren't tied to one label set.
  • Reuse. One expensive pretraining run serves thousands of downstream uses via Transfer Learning.

Yann LeCun's often-quoted cake analogy, from a 2016 talk, sums up the view: if intelligence is a cake, most of it is learning without labels, supervised learning is only the icing, and reinforcement learning the cherry on top.

In code

First, how the labels come from the data itself, in plain Python:

import random

random.seed(3)
text = "the cat sat on the mat".split()

# 1. Next-token prediction (GPT): every prefix predicts the word that follows it
for i in range(1, len(text)):
    print(" ".join(text[:i]), "->", text[i])

# 2. Masked prediction (BERT): hide ~15% of words, predict them from both sides
masked = list(text)
hidden = random.sample(range(len(text)), k=max(1, round(0.15 * len(text))))
for i in hidden:
    masked[i] = "[MASK]"
print(" ".join(masked), "->", {i: text[i] for i in hidden})

# the -> cat
# the cat -> sat
# the cat sat -> on
# the cat sat on -> the
# the cat sat on the -> mat
# the [MASK] sat on the mat -> {1: 'cat'}

Now a miniature SimCLR in PyTorch. The data are 16 × 16 images of lines in four orientations. The labels exist, but the encoder never sees them. It only learns to match two randomly shifted, noisy views of each image. Afterwards a linear probe trained on just 20 labelled images tests what it learned:

import torch
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)
def lines(n):                                    # 16x16 images of a line: | - \ /  (labels kept aside)
    y = torch.randint(4, (n,)); X = torch.zeros(n, 16, 16); r = torch.arange(16)
    for i in range(n):
        if y[i] == 0: X[i, :, 8] = 1
        if y[i] == 1: X[i, 8, :] = 1
        if y[i] == 2: X[i, r, r] = 1
        if y[i] == 3: X[i, r, 15 - r] = 1
    return X, y
def augment(X):                                  # a random shift (one per batch) plus pixel noise
    s = torch.randint(-4, 5, (2,)).tolist()
    return torch.roll(X, shifts=s, dims=(1, 2)) + 0.3 * torch.rand_like(X)

encoder = nn.Sequential(nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 32))
X_unlabelled, _ = lines(4000)                    # pretend we have no labels for these
opt = torch.optim.Adam(encoder.parameters(), lr=1e-3)
for step in range(1001):
    x = X_unlabelled[torch.randint(4000, (128,))]
    z1 = F.normalize(encoder(augment(x)), dim=1)          # two views of the same 128 images
    z2 = F.normalize(encoder(augment(x)), dim=1)
    logits = z1 @ z2.T / 0.1                              # cosine similarity of every pair / temperature
    loss = F.cross_entropy(logits, torch.arange(128))     # InfoNCE: match each view to its partner
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 500 == 0:
        print(f"step {step:4d}  contrastive loss {loss.item():.3f}")

# Linear probe: freeze the encoder, train a linear classifier on just 20 labelled examples
def probe(enc):
    Xl, yl = lines(20); Xt, yt = lines(1000)
    with torch.no_grad():
        fl, ft = enc(augment(Xl)), enc(augment(Xt))
    clf = nn.Linear(32, 4); o = torch.optim.Adam(clf.parameters(), lr=1e-2)
    for _ in range(300):
        l = F.cross_entropy(clf(fl), yl); o.zero_grad(); l.backward(); o.step()
    return (clf(ft).argmax(1) == yt).float().mean().item()

torch.manual_seed(1)
random_encoder = nn.Sequential(nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 32))
print(f"linear probe, random encoder:          {probe(random_encoder):.3f}")
print(f"linear probe, self-supervised encoder: {probe(encoder):.3f}")

# step    0  contrastive loss 5.249
# step  500  contrastive loss 3.485
# step 1000  contrastive loss 3.465
# linear probe, random encoder:          0.352
# linear probe, self-supervised encoder: 1.000

The encoder was never told there are four kinds of line, yet a linear classifier on its features is perfect after 20 labelled examples. On features from an untrained encoder of the same shape, it reaches 35%.

Notice also that the contrastive loss stops near 3.465. That is ln⁡32\ln 32, and it is not a coincidence. Our toy dataset has only four distinct images, so each batch of 128 contains about 32 identical copies of each. The loss can't tell a view's true partner apart from the other 31 copies, so the best it can do is spread the probability evenly over them. These are false negatives: "different" examples that are really the same. They are a real issue in contrastive learning, for example with near-duplicate photos on the web.

Common pitfalls

  • Weak augmentations. If the two views are too similar, the task is trivially solved by matching low-level details such as exact colours. SimCLR found strong colour distortion and random cropping essential.
  • Collapse. If the loss drops to a suspiciously low value very fast, or every embedding looks the same, the model may have collapsed. Check the spread of the embeddings: the standard deviation across a batch should not be near zero.
  • Small batches in contrastive learning. Too few negatives makes the task too easy. Use bigger batches, a memory queue (MoCo) or a non-contrastive method.
  • Confusing "self-supervised" with "no human input". The data are human-made, and so is the choice of pretext task and augmentations. Both shape what the model learns, including its biases.
  • Judging by pretext loss. A lower pretext loss does not always mean better features. Evaluate with a linear probe or fine-tuning on a downstream task.

Watch out Self-supervised models learn whatever is in their data, at enormous scale and without anyone reviewing the examples. Web text and images contain stereotypes, private information, copyrighted material and misinformation, and all of it can end up in the representations and outputs. See Bias and Fairness and Privacy, Data and Copyright.

Where it leads

A bit of history

The idea of learning by predicting your own input is old. Autoencoders date from the 1980s, and word2vec (2013) was self-supervised in all but name (Word Embeddings). The term "self-supervised" became popular in computer vision around 2015–2018, with pretext tasks such as predicting patch positions (Doersch and colleagues, 2015), jigsaw puzzles (2016), colourisation (2016) and rotation prediction (2018). Language took off first at scale: ELMo, GPT and BERT in 2018 showed that pretraining on raw text, then fine-tuning, beat task-specific models across the board. For images, contrastive methods closed the gap with supervised pretraining around 2019–2020 (MoCo, SimCLR), followed by non-contrastive BYOL and DINO and the masked autoencoder in 2021. CLIP (2021) joined images and text. By the mid-2020s, essentially every frontier model began with large-scale self-supervised pretraining.

Try it

  1. By hand: in the worked InfoNCE example, change the partner's similarity from 0.9 to 0.4 (keep τ=0.1\tau = 0.1). What is the new loss?
  2. In the SimCLR code, remove the noise from augment (keep only the shift). Does the linear probe still work? Then remove the shift too, so the two views are identical. What happens to the loss, and to the probe?
  3. Give each line a random offset in lines so that no two images are identical. Where does the contrastive loss settle now?

Hint for 1: the logits become 4, 1, −2, 3. The partner's share is e4/(e4+e1+e−2+e3)≈54.6/77.5≈0.70e^4 / (e^4 + e^1 + e^{-2} + e^3) \approx 54.6 / 77.5 \approx 0.70, so the loss is about 0.35.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. The sentence 'the cat sat on the mat' is used for next-token prediction. How many training examples does it provide?

  2. A contrastive encoder's loss drops very low almost immediately, and every image gets nearly the same embedding. What has happened?

  3. In SimCLR, a view's similarity to its partner is 0.9 and to three other views is 0.1, −0.2 and 0.3. With τ = 0.1, roughly what is the InfoNCE loss for this view?

  4. You want to know whether your self-supervised image encoder learned useful features. What is the standard test?

  5. In contrastive learning, what does choosing the augmentations (crops, colour changes, blur) actually decide?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Lil'Log

Lilian Weng · Advanced · Free

Deep, carefully referenced survey posts on diffusion, agents, RL, hallucination, attention and more.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/self-supervised-learning.md