Search

Search papers and lessons

Self-Supervised Learning

Level 3 · 13 min read

Self-supervised learning creates its own labels from unlabelled data by hiding part of the input and asking the model to predict it, so it can learn from far more data than anyone has labelled.

On this page

  • Colour = topic mix
  • Calculus
  • Linear algebra
  • Probability
  • Neural network basics
  • Representation learning
  • Learning basics
  • Sign in to see your progress

TL;DR

Self-supervised learning is training on unlabelled data by manufacturing the labels from the data itself. Hide part of an input, such as a word in a sentence or a patch of an image, and train the model to predict the hidden part from what remains. The answer is always available, so no human has to label anything.

The features the model learns to make those predictions are useful for other tasks. A model that can fill in a missing word has to understand grammar and meaning, and those learned features can then be reused with a small labelled set.

Where you'll see it: in BERT-style language models pretrained on raw text, in image encoders pretrained on unlabelled photos before fine-tuning, and in the sentence embeddings used for search.

Intuition

The answer is hidden inside the input

Labelling is expensive. Someone has to look at each photo and write "dog", or read each paragraph and mark its sentiment. The web, by contrast, holds vast amounts of text and images that nobody has labelled. Self-supervised learning asks a simple question: can the data supply its own answers?

Take a sentence such as "the cat sat on the mat". Cover the word "sat" and ask the model to guess it from "the cat ___ on the mat". The correct answer is the word that was covered, so the training signal is free. Nobody had to write "sat" as a label; it was already in the text.

The name is a little misleading. The learning is supervised in form, because there is a target and a loss, but the targets are created automatically from the raw data. The task used to create them is called a pretext task. The pretext task is only a means. What we keep is the representation the model builds while solving it.

flowchart LR
  A["Unlabelled data"] --> B["Hide part of the input"]
  B --> C["Model predicts the hidden part"]
  A --> D["Hidden part is the target"]
  C --> E["Loss compares prediction with target"]
  D --> E
  E --> F["Learned representation"]
  F --> G["Fine-tune on a small labelled task"]

Why the features transfer

To predict a masked word well, a model has to know which words fit a context. To tell two crops of the same photo apart from crops of other photos, it has to recognise what the photo is of. These skills are general. The representation learned on the pretext task becomes the starting point for a downstream task such as classification, which is why this idea sits so close to Transfer Learning.

The plot below shows why the training loss pushes the model in the right direction. If the model assigns probability pp to the correct hidden word, the loss is −ln⁡p-\ln p. A confident correct guess costs almost nothing, and a confident wrong one costs a lot.

0.20.40.60.8101234probability p given to the correct answerloss
  • loss = -ln p
Assigning probability 0.6 to the hidden word costs about 0.51. Assigning 0.1 costs about 2.30. The loss rewards confident correct guesses.

The math

The general recipe

Let xx be an unlabelled example. A transformation TT produces a corrupted or partial view x~=T(x)\tilde{x} = T(x), and the model fθf_\theta must recover a target t(x)t(x) derived from xx:

θ^=arg⁡min⁡θ  1N∑j=1NL(fθ(x~j), t(xj)).\hat{\theta} = \arg\min_{\theta} \; \frac{1}{N} \sum_{j=1}^{N} L\big(f_\theta(\tilde{x}_j), \, t(x_j)\big).

The loss LL is ordinary supervised loss. What changes is that the pairs (x~j,t(xj))(\tilde{x}_j, t(x_j)) come from the data, not from a human. Everything that makes supervised training work, including Gradient Descent and a Loss Function, applies unchanged.

Masked prediction

For a sequence x1,…,xTx_1, \dots, x_T, choose a set of positions MM to hide. The model sees the rest and predicts each hidden token. The loss is

Lmask(θ)=−∑t∈Mlog⁡pθ(xt∣x∖M),L_{\text{mask}}(\theta) = -\sum_{t \in M} \log p_\theta\big(x_t \mid x_{\setminus M}\big),

where x∖Mx_{\setminus M} denotes the visible tokens. Each term is the Cross-Entropy Loss of the correct token under the model's Softmax output. Masked language modelling, used by BERT, follows this formula. Masked autoencoders for images apply the same idea to patches.

Contrastive learning

A different family asks the model to make two views of the same example similar and views of different examples dissimilar. Given an anchor embedding zz, one positive z+z^+ (another view of the same example), and negatives z1−,…,zK−z^-_1, \dots, z^-_K, the InfoNCE loss is

LNCE=−log⁡exp⁡(s(z,z+)/τ)exp⁡(s(z,z+)/τ)+∑k=1Kexp⁡(s(z,zk−)/τ),L_{\text{NCE}} = -\log \frac{\exp\big(s(z, z^+)/\tau\big)}{\exp\big(s(z, z^+)/\tau\big) + \sum_{k=1}^{K} \exp\big(s(z, z^-_k)/\tau\big)},

where ss is a similarity score, often the cosine similarity, and τ>0\tau \gt 0 is a temperature that controls how sharply the scores are compared. The fraction is a Softmax over the candidates, so the loss is small when the positive scores much higher than every negative. This is the form used in the contrastive methods of Contrastive Learning.

Why more negatives help

The denominator contains one term per negative. With more negatives, the model has to separate the positive from a larger crowd, so the learned features must carry finer distinctions. This is one reason contrastive methods use large batches.

Worked examples

Example
One masked word, by hand

Sentence: "the cat sat on the mat". Hide "sat" and let the model output probabilities over candidate words for that position. Suppose it gives "sat" probability 0.60.6, "slept" 0.30.3 and "ran" 0.10.1.

  1. The correct token is "sat", so the loss is −ln⁡(0.6)-\ln(0.6).
  2. Compute ln⁡(0.6)≈−0.5108\ln(0.6) \approx -0.5108, so the loss is 0.5110.511.
  3. Suppose the model had given "sat" only 0.10.1. The loss would be −ln⁡(0.1)≈2.303-\ln(0.1) \approx 2.303.
  4. Averaged over the masked positions in a longer text, these numbers are the quantity training pushes down.
  5. A model that gives "slept" more weight than "sat" is penalised, because "sat" is what the text actually says.

Interpretation: the loss is zero only when the model is certain of the true word. Nothing in the calculation needed a human label, only the original sentence.

Example
A contrastive loss with three candidates

An anchor embedding is compared with one positive and two negatives. Use τ=1\tau = 1 and the similarity scores s(z,z+)=2.0s(z, z^+) = 2.0, s(z,z1−)=0.5s(z, z^-_1) = 0.5 and s(z,z2−)=−1.0s(z, z^-_2) = -1.0.

  1. Exponentiate each score: e2.0≈7.389e^{2.0} \approx 7.389, e0.5≈1.649e^{0.5} \approx 1.649 and e−1.0≈0.368e^{-1.0} \approx 0.368.
  2. Sum the three terms: 7.389+1.649+0.368≈9.4067.389 + 1.649 + 0.368 \approx 9.406.
  3. The probability that the positive is picked out is 7.389/9.406≈0.7867.389 / 9.406 \approx 0.786.
  4. The loss is −ln⁡(0.786)≈0.241-\ln(0.786) \approx 0.241.
  5. Now suppose the first negative had similarity 2.02.0 as well. The positive's share drops to 7.389/(7.389+7.389+0.368)≈0.4887.389 / (7.389 + 7.389 + 0.368) \approx 0.488, and the loss rises to about 0.7180.718.

Interpretation: the loss is small when the positive stands out from the negatives. A negative that looks almost identical to the anchor is the hardest case, and it is the one that most shapes the learned features.

Tradeoffs and failure modes

Self-supervised learning pays off when unlabelled data is plentiful and labelled data is scarce. It is a poor fit when the labelled set is already large and the target is narrow, since a supervised model trained directly may do as well with less compute.

SituationWhat goes wrongBetter choice
Pretext task is too easyThe model solves it with shortcuts, such as low-level texture, and learns littleHarder masking, stronger augmentation
Pretext task is unrelated to the targetFeatures do not transferChoose a pretext task that needs the target's skills
Contrastive batch is smallToo few negatives, weak featuresLarger batches or a memory bank
False negativesTwo examples of the same class are pushed apartSample negatives more carefully or use a supervised signal
Pretraining data differs from deploymentFeatures fit the wrong domainPretrain on closer data or [[transfer-learning

Two failure modes are worth knowing. The first is collapse: a model can make all representations identical, which gives zero loss on some objectives. Contrastive methods use negatives, and some newer methods use asymmetric designs and stop-gradient tricks, to prevent this. The second is evaluating only on the pretext task. A model that predicts masked words well may still be a poor classifier, so the honest test is always the downstream task. Augmentations, a form of Data Augmentation, are central to creating the two views that contrastive methods need, and a bad choice of augmentation changes what the model learns.

History

The idea of predicting parts of a signal from other parts is old. Early work on word embeddings used this principle implicitly. Word2vec, published by Mikolov and colleagues in 2013, trained a model to predict a word from its neighbours, and the vectors it learned captured meaning well enough to become standard.

Pretraining on unlabelled text became mainstream with BERT in 2018, from Devlin and colleagues. BERT used masked language modelling, the task described above, on large text corpora and then fine-tuned the model on many labelled tasks. It set new results across a wide range of language benchmarks and made the pretrain then fine-tune pattern the default for text. Denoising autoencoders, which reconstruct an input from a corrupted copy, predate it and share the same basic move.

In vision, the same pattern took longer. Pretext tasks such as predicting image rotations, solving jigsaw puzzles from shuffled patches, and colouring grayscale photos were tried in the late 2010s, but they lagged behind supervised pretraining on ImageNet. Contrastive methods, such as SimCLR in 2020, and masked autoencoders in 2021 closed much of that gap. Self-supervision is now common in vision, speech and text, because it lets models learn from data that no one has labelled.

Check yourself

QuestionRecall: what is a pretext task, and what is the final goal of training with one?Show answer

A pretext task is an automatically generated prediction problem, such as guessing a masked word, whose labels come from the data itself. The goal is not to solve the pretext task for its own sake but to learn a representation that is useful for downstream tasks, which are then solved with a small amount of labelled data.

QuestionComputation: a masked model gives the correct token probability 0.250.25. What is the loss for that position, to three decimal places?Show answer

The loss is −ln⁡(0.25)=ln⁡4≈1.386-\ln(0.25) = \ln 4 \approx 1.386.

QuestionWhy: why do contrastive methods need negatives, and what would go wrong if they used only positive pairs?Show answer

With only positive pairs, the easiest way to make the positives similar is to make every representation the same, which gives a perfect score and teaches nothing. Negatives push different examples apart and prevent this collapse, so the features must keep information that distinguishes one example from another.

QuestionApplied: a team has one million unlabelled product photos and 2,000 labelled ones for a defect classifier. Should they start from self-supervised pretraining, and what should they check?Show answer

Probably yes: the unlabelled photos are plentiful, and 2,000 labels are few for training a deep model from scratch. They should pretrain on photos that resemble the factory images, fine-tune on the 2,000 labelled examples, and compare against training only on the labelled set. They should hold out a test set of labelled defects, since accuracy on the pretext task says little about defect detection.

Sources