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
- Builds on
- 15 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 15 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Unsupervised Learning
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- 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.
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 words provides 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:
- Take a batch of images.
- 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.
- Pass all views through the same encoder and normalise the outputs to unit length, so that a dot product is a cosine similarity.
- For each view, treat finding its partner among all the other views as a classification problem.
The loss for one view whose partner is is called InfoNCE. In words: softmax over the similarities to every candidate, then minus the log of the probability given to the true partner.
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") 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 to get 9, 1, −2 and 3. Exponentiate: , , , . The partner's share is , so the loss is . This row is already almost solved. With 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 , 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
- Pretraining Large Language Models and Language Modeling and Next-Token Prediction: next-token self-supervision at the scale of large language models.
- BERT and Encoder Models: masked language modelling in depth.
- CLIP and Contrastive Learning: contrastive learning between images and text, the basis of Text-to-Image in Practice systems and Multimodal LLMs.
- Vision Transformers: the backbone of MAE and DINO.
- Sentence Embeddings: contrastive training for text retrieval.
- Autoencoders: an older form of learning from unlabelled data by reconstruction, and the root of masked autoencoders.
- Transfer Learning and Fine-Tuning: what happens after self-supervised pretraining.
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
- By hand: in the worked InfoNCE example, change the partner's similarity from 0.9 to 0.4 (keep ). What is the new loss?
- 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?- Give each line a random offset in
linesso 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 , so the loss is about 0.35.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Lil'Log
Deep, carefully referenced survey posts on diffusion, agents, RL, hallucination, attention and more.
A Simple Framework for Contrastive Learning of Visual Representations
SimCLR: two augmented views, a shared encoder and the InfoNCE loss. Shows which augmentations matter and why big batches help.
Masked Autoencoders Are Scalable Vision Learners
Hide 75% of an image's patches and reconstruct them with a Vision Transformer: BERT-style pretraining for images.
BERT: Pre-training of Deep Bidirectional Transformers
Masked language-model pretraining. It transformed NLP benchmarks overnight.
Learning Transferable Visual Models From Natural Language Supervision
CLIP: images and text in one embedding space, trained on 400M image–caption pairs.
Emerging Properties in Self-Supervised Vision Transformers
DINO: self-distillation without labels or negatives; its attention maps segment objects on their own.
Understanding Deep Learning
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