TExcelTAD

Self-Supervised Learning

How did large language models learn so much without anyone labelling trillions of words? The trick is to make the data label itself. In self-supervised learning the training targets are created automatically from the raw data: hide part of an example and ask the model to predict the hidden part. No human annotation is needed, so the amount of training data is limited only by the amount of raw data.

The idea: pretext tasks

A pretext task turns unlabelled data into input-target pairs:

Data Pretext task Input Target
text next-token prediction (GPT-style) the words so far the next word
text masked language modelling (BERT-style) a sentence with some words hidden the hidden words
images masked image modelling an image with patches hidden the hidden patches
images contrastive learning two random crops of the same photo "these two belong together" vs other photos
audio masked or future prediction a recording with gaps the missing parts
time series forecasting past values the next value

Technically the model is trained exactly like a supervised one, with inputs, targets and a loss. The difference is where the targets come from. Some books therefore treat self-supervised learning as a kind of unsupervised learning; others list it separately, as this course does.

Labels from the text itself

The smallest possible language model predicts the next character from the current one. Every character in the text provides a training pair: the character, and the character after it.

python · try it yourself
from collections import Counter, defaultdict

text = ("the cat sat on the mat. the dog sat on the log. "
        "the cat saw the dog. the dog saw the cat on the mat.")

# The labels come from the text itself: every character's label is the character after it.
pairs = list(zip(text, text[1:]))
print("training pairs made from", len(text), "characters:", len(pairs))
print("first five:", pairs[:5])

counts = defaultdict(Counter)
for current, nxt in pairs:
    counts[current][nxt] += 1

def predict_next(ch):
    return counts[ch].most_common(1)[0][0]

for ch in ["t", "h", "c", "."]:
    best = counts[ch].most_common(2)
    print(f"after {ch!r}: most likely {predict_next(ch)!r}   counts {best}")

# Generate by predicting the next character again and again.
out = "th"
for _ in range(20):
    out += predict_next(out[-1])
print("generated:", repr(out))
training pairs made from 100 characters: 99
first five: [('t', 'h'), ('h', 'e'), ('e', ' '), (' ', 'c'), ('c', 'a')]
after 't': most likely 'h'   counts [('h', 9), (' ', 5)]
after 'h': most likely 'e'   counts [('e', 9)]
after 'c': most likely 'a'   counts [('a', 3)]
after '.': most likely ' '   counts [(' ', 3)]
generated: 'the the the the the th'

A 100-character text gave 99 labelled training pairs, and no person labelled anything. The model learned real regularities ("t" is usually followed by "h", "h" always by "e"), but generation loops on "the the the": a model that sees only one previous character has almost no memory. Large language models do the same thing, predicting the next token, with networks that look at thousands of previous tokens and train on trillions of them. The How LLMs Work lesson of the ai-llm course and the Language Modeling lesson of math-deep-learning continue this story.

Labels from images: predict the hidden half

The same trick works for images. We ignore the digit labels completely, hide the right half of each 8 × 8 image and train a model to predict it from the left half.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge

images = load_digits().images / 16.0                   # 1797 images; we ignore the digit labels
left = images[:, :, :4].reshape(len(images), -1)       # input: the left half (32 pixels)
right = images[:, :, 4:].reshape(len(images), -1)      # target: the hidden right half (32 pixels)

L_train, L_test, R_train, R_test = train_test_split(left, right, test_size=0.3, random_state=0)
model = Ridge(alpha=1.0).fit(L_train, R_train)
print("pretext task: predict the right half from the left half")
print("R^2 on held-out images:", round(model.score(L_test, R_test), 3))

baseline = np.mean((R_test - R_train.mean(axis=0)) ** 2)
learned = np.mean((R_test - model.predict(L_test)) ** 2)
print(f"pixel MSE: average image {baseline:.4f}, learned model {learned:.4f}")
pretext task: predict the right half from the left half
R^2 on held-out images: 0.233
pixel MSE: average image 0.0802, learned model 0.0581

Even a linear model learns something about how digits are drawn: its error on held-out images (0.0581) is about 28 % lower than guessing the average right half (0.0802). A linear model is far too weak to do this well. Deep networks trained on such pretext tasks learn rich internal representations of images: edges, strokes, shapes and eventually objects.

Why it matters: pretraining, then fine-tuning

The pretext task is rarely the goal. Its value lies in what the model learns along the way. The modern recipe is:

  1. Pretrain a large model with a self-supervised task on huge amounts of raw data (web text, photos, audio).
  2. Fine-tune it, or use its internal features, for the task you actually care about, with a small labelled data set.

This is why a sentiment classifier can now be built from a few hundred labelled reviews: the pretrained language model already "knows" English. The Training Strategies course covers pretraining and fine-tuning, and NLP, Transformers & LLMs the language models built this way.

Pitfalls

  • A pretext task that is too easy. If the hidden part can be predicted by a shortcut (for example a watermark, or a timestamp that reveals the next value), the model learns the shortcut instead of useful structure.
  • Measuring the pretext task instead of the real task. Lower masked-prediction loss does not guarantee better results downstream. Evaluate on the task you need, with real labels.
  • Inheriting the data's problems. A model pretrained on web text absorbs its biases, errors and private information. Data sourcing and filtering matter as much as in supervised learning.

Practice

  1. Name a self-supervised pretext task for a year of hourly electricity-meter readings.
Answer

Predict the next hour's reading from the previous 24 or 168 hours (forecasting), or hide random hours and predict them from the surrounding ones (masking). Both create unlimited training pairs from the raw readings.

  1. The character model generated "the the the". What would you change so that it can produce "the cat"?
Answer

Give it more context: predict the next character from the previous two, three or more characters (an n-gram model), so that "the " can be followed by different words depending on what came before, and sample from the counts instead of always taking the most common. Neural language models take this to thousands of characters or tokens.

Test yourself

Where do the training targets come from in self-supervised learning?

  1. Human annotators
  2. The raw data itself, by hiding part of it
  3. A reward signal
  4. A test set

Which pretext task is used to pretrain GPT-style language models?

  1. Image rotation prediction
  2. Next-token prediction
  3. Clustering
  4. Sentiment labels

How many training pairs does next-character prediction create from a 100-character text?

  1. 1
  2. 50
  3. 99
  4. 100

What is the usual purpose of self-supervised pretraining?

  1. To solve the pretext task for its own sake
  2. To learn general representations that are then fine-tuned on a small labelled task
  3. To avoid any evaluation
  4. To replace data cleaning