TExcelTAD
Home › Training Strategies: Transfer, Fine-Tuning, Semi-Supervised, Active, Online & Distributed › Self-Supervised Pretraining: Pretext Tasks and Masked Modelling

Self-Supervised Pretraining: Pretext Tasks and Masked Modelling

Transfer learning needs a pretrained model, and someone had to pretrain it. For photos and English text, public backbones exist. For seismic traces, retinal scans, machine logs or a low-resource language, they often do not, yet unlabelled data in those domains is usually plentiful: sensors record all day, hospitals archive every scan, servers keep every log line. Self-supervised pretraining turns that unlabelled data into a backbone. It invents a supervised task whose labels come from the data itself (a pretext task), trains a network on it, and keeps the network's inner layers as features for the real task.

ML Foundations introduced the idea. This lesson builds a masked-modelling pretrainer from scratch, shows when its features help, and shows a pretext task that does not help.

The workflow

stage 1: pretext task, unlabelled data the pump [MASK] at night encoder pretext head "failed"= label stage 2: real task, few labels "the pump failed at night" (whole input) encoder task head "alarm" keep the encoder dropped later frozen (linear probe) or fine-tuned
  1. Collect unlabelled data from the target domain, as much as compute allows.
  2. Choose a pretext task whose labels can be computed from the input alone, and which can only be solved by understanding the input.
  3. Pretrain an encoder plus a small pretext head on it. This is the expensive step: real models train for days.
  4. Throw away the pretext head and keep the encoder.
  5. Adapt to the labelled task: a linear probe on frozen features (feature extraction), or fine-tuning.

Pretext tasks

Pretext task Input Label made from the input Known from
Next-token prediction the first tt tokens token t+1t + 1 GPT language models
Masked tokens a sentence with about 15 % of tokens hidden the hidden tokens BERT
Masked patches an image with about 75 % of patches hidden the hidden pixels masked autoencoders (MAE)
Masked audio frames a waveform with spans hidden the hidden frames (as discrete units) wav2vec 2.0, HuBERT
Rotation prediction an image turned by 0, 90, 180 or 270 degrees the angle RotNet
Jigsaw an image cut into tiles and shuffled the permutation jigsaw puzzles
Colourisation a greyscale image its colours colourisation networks
Denoising a corrupted input the clean input denoising autoencoders
Two augmented views two random crops of one image "same image or not" SimCLR, MoCo (next lesson)

Masked modelling has become the dominant family because it scales: every position of every input is a training example, and filling in a gap forces the model to use context. If MM is the set of masked positions and x∖M\mathbf{x}_{\setminus M} the visible rest, a masked language model minimises the cross-entropy of the hidden tokens:

LMLM(θ)=− Ex∑i∈Mlog⁡pθ(xi∣x∖M)L_{\text{MLM}}(\theta) = -\,\mathbb{E}_{\mathbf{x}} \sum_{i \in M} \log p_\theta\big(x_i \mid \mathbf{x}_{\setminus M}\big)

A masked autoencoder for images replaces the cross-entropy with the squared error on the hidden patches only, 1∣M∣∑i∈M∥x^i−xi∥2\frac{1}{\lvert M \rvert} \sum_{i \in M} \lVert \hat{\mathbf{x}}_i - \mathbf{x}_i \rVert^2. In both, the loss counts only the hidden positions: predicting a visible token is trivial and teaches nothing. (Entropy, Cross-Entropy and KL and Language Modeling derive these losses.)

From scratch: masked words in NumPy

The smallest masked language model is a bag of words: average the embeddings of the visible words and predict the hidden one with a softmax over the vocabulary (word2vec's CBOW is exactly this). The corpus is generated: 4 topics with 40 words each, plus 20 filler words every topic uses. Each document has 8 words, 4 from its topic and 4 fillers. The pretrainer sees 4,000 documents without their topics. Afterwards, a logistic regression on the mean embedding of a document is trained with only 20 labelled documents and compared with the same classifier on word counts.

python · try it yourself
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

# A toy corpus: 4 topics with 40 words each, plus 20 filler words used by every topic.
# A document has 8 words: 4 from its topic, 4 fillers.
rng = np.random.default_rng(0)
K, per_topic, n_fill, L = 4, 40, 20, 8
V = K * per_topic + n_fill
def make_docs(n):
    topic = rng.integers(0, K, n)
    words = np.concatenate([topic[:, None] * per_topic + rng.integers(0, per_topic, (n, 4)),
                            K * per_topic + rng.integers(0, n_fill, (n, 4))], axis=1)
    return rng.permuted(words, axis=1), topic
unlab, _ = make_docs(4000)                 # unlabelled: the topics are thrown away
held, _ = make_docs(1000)                  # unlabelled too, to measure the pretext loss honestly
lab, y_lab = make_docs(20)                 # 20 labelled documents
test, y_test = make_docs(1000)

# Pretext: mask one word, predict it from the mean embedding of the other 7 (a bag-of-words "BERT")
D, lr = 16, 3.0
E = rng.normal(0, 0.1, (V, D))                     # word embeddings: what we keep
U = rng.normal(0, 0.1, (D, V)); c = np.zeros(V)    # prediction head: thrown away afterwards

def masked_batch(docs):
    rows = np.arange(len(docs))
    pos = rng.integers(0, L, len(docs))
    ctx = np.ones(docs.shape, bool); ctx[rows, pos] = False
    h = (E[docs] * ctx[:, :, None]).sum(1) / (L - 1)
    z = h @ U + c
    p = np.exp(z - z.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    return rows, docs[rows, pos], ctx, h, p

for epoch in range(1, 31):
    for start in range(0, len(unlab), 100):
        docs = unlab[start:start + 100]
        rows, target, ctx, h, p = masked_batch(docs)
        g = p.copy(); g[rows, target] -= 1; g /= len(docs)       # softmax cross-entropy gradient
        gh = g @ U.T / (L - 1)
        U -= lr * h.T @ g; c -= lr * g.sum(0)
        np.add.at(E, docs[ctx], -lr * np.repeat(gh, L - 1, axis=0))
    if epoch in (1, 10, 20, 30):
        rows, target, _, _, p = masked_batch(held)
        print(f"epoch {epoch:2d}: held-out masked-word loss {-np.log(p[rows, target]).mean():.3f}")
print(f"uniform guess {np.log(V):.3f}, best possible {0.5 * np.log(per_topic) + 0.5 * np.log(n_fill):.3f}")

def bag_of_words(docs):
    counts = np.zeros((len(docs), V))
    np.add.at(counts, (np.repeat(np.arange(len(docs)), L), docs.ravel()), 1)
    return counts
mean_embedding = lambda docs: E[docs].mean(1)
for name, f in (("bag of words", bag_of_words), ("pretrained embeddings", mean_embedding)):
    clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000)).fit(f(lab), y_lab)
    print(f"20 labels, {name:21s}: test accuracy {clf.score(f(test), y_test):.3f} on 1000 documents")
seen = np.isin(np.arange(K * per_topic), lab).sum()
print(f"topic words that occur in the 20 labelled documents: {seen} of {K * per_topic}")
En = E / np.linalg.norm(E, axis=1, keepdims=True)
for w in (0, 45):
    nearest = np.argsort(-(En @ En[w]))[1:6]
    print(f"nearest words to word {w} (topic {w // per_topic}): topics {(nearest // per_topic).tolist()}")
epoch  1: held-out masked-word loss 4.770
epoch 10: held-out masked-word loss 4.738
epoch 20: held-out masked-word loss 4.344
epoch 30: held-out masked-word loss 3.728
uniform guess 5.193, best possible 3.342
20 labels, bag of words         : test accuracy 0.772 on 1000 documents
20 labels, pretrained embeddings: test accuracy 1.000 on 1000 documents
topic words that occur in the 20 labelled documents: 60 of 160
nearest words to word 0 (topic 0): topics [0, 0, 0, 0, 0]
nearest words to word 45 (topic 1): topics [1, 1, 1, 1, 1]

Read the output from the bottom up. The 20 labelled documents contain only 60 of the 160 topic words, so a bag-of-words classifier has never seen most of the words in a test document and can only guess from the few it knows: 0.772. The masked-word pretrainer has seen all 4,000 unlabelled documents, and the only way to predict a hidden topic word is to recognise the topic from the visible ones. So words of the same topic end up with similar embeddings (the five nearest neighbours of words 0 and 45 are all from their own topic), and a document's mean embedding points to its topic even when every one of its words is new to the classifier: 1.000 on the 1,000 test documents.

The held-out loss also tells a story. It barely moves for the first 10 epochs (4.770, then 4.738), then falls to 3.728 by epoch 30 as the embeddings organise themselves. The best possible value is 12ln⁡40+12ln⁡20≈3.342\frac{1}{2}\ln 40 + \frac{1}{2}\ln 20 \approx 3.342: the context shows whether the hidden word is a topic word (when three topic words are visible) or a filler, but not which of the 40 or 20 it is. The toy corpus is far cleaner than real text, so the jump to a perfect score is larger than you would see in practice; the mechanism is the same one that makes BERT features useful.

A pretext task that does not help: rotation prediction

Rotation prediction is a classic image pretext task: rotate every image by 0, 1, 2 or 3 quarter turns and train a classifier to tell which. Here it is with scikit-learn's MLPClassifier on the 8 x 8 digits (1,257 training images, so 5,028 rotated ones), followed by a linear probe on its hidden layer with 50 labels.

python · try it yourself
import warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings("ignore", category=ConvergenceWarning)

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_pool, X_test, y_pool, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

def rotations(X):
    """Pretext data: every image in 4 orientations, label = number of quarter turns."""
    imgs = X.reshape(-1, 8, 8)
    Xr = np.concatenate([np.rot90(imgs, k, axes=(1, 2)).reshape(len(X), 64) for k in range(4)])
    return Xr, np.repeat(np.arange(4), len(X))

Xr, yr = rotations(X_pool)
Xr_test, yr_test = rotations(X_test)
pretext = MLPClassifier(hidden_layer_sizes=(64,), max_iter=60, random_state=0).fit(Xr, yr)
print(f"pretext task: rotation accuracy {pretext.score(Xr_test, yr_test):.3f} on {len(yr_test)} rotated test images")
for digit in (0, 1, 4, 8):
    m = np.tile(y_test, 4) == digit
    print(f"  digit {digit}: {pretext.score(Xr_test[m], yr_test[m]):.3f}")

W, b = pretext.coefs_[0], pretext.intercepts_[0]
phi = lambda X: np.maximum(0, X @ W + b)                # the pretrained hidden layer, frozen
rng = np.random.default_rng(0)
idx = rng.choice(len(y_pool), 50, replace=False)
for name, f in (("raw pixels", lambda X: X), ("rotation features", phi)):
    clf = LogisticRegression(max_iter=3000).fit(f(X_pool[idx]), y_pool[idx])
    print(f"linear probe with 50 labels, {name:17s}: test accuracy {clf.score(f(X_test), y_test):.3f}")
pretext task: rotation accuracy 0.962 on 2160 rotated test images
  digit 0: 0.889
  digit 1: 0.909
  digit 4: 0.991
  digit 8: 0.952
linear probe with 50 labels, raw pixels       : test accuracy 0.831
linear probe with 50 labels, rotation features: test accuracy 0.780

The network solves the pretext task well (0.962), and the per-digit numbers show the task is partly ambiguous: a 0 or a 1 turned half a turn looks much like the original, so those digits score lowest. But the features it learned are worse for recognising digits than the pixels themselves (0.780 against 0.831 with the same 50 labels). Telling "upright" from "sideways" on an 8 x 8 grid can be done with a few stroke-direction detectors; it does not need to know which digit it is looking at. On 64 clean pixels, there is also little left for pretraining to add: the pixels are already a good representation. The lesson generalises: a pretext task helps only if solving it requires the information the downstream task needs, and only if the raw input is a poor representation to begin with. Natural images at full resolution, raw audio and text are; small, clean, hand-engineered features are not.

Advantages and limits

Advantages Limits
Uses unlabelled data, which is cheap and plentiful Pretraining is the most compute-hungry step in this course; useful backbones take GPU-days or more
Builds a backbone for domains no public model covers The pretext task must match what the downstream task needs, and you only find out after pretraining
One pretrained encoder serves many downstream tasks Two hyperparameter searches: one for pretraining, one for adaptation
No label noise or annotator bias in the pretext labels Learns the biases of the unlabelled data (what was recorded, and what was not)

Pitfalls

  • Evaluating the pretext loss only. A lower pretext loss does not guarantee better features (the rotation network). Always measure downstream quality with a linear probe or a small fine-tune on a validation set.
  • Leaking the test set into pretraining. Self-supervised does not mean "anything goes": if the test examples are in the unlabelled pool, the encoder has seen them. Keep test data out of pretraining, or say clearly that the setting is transductive.
  • Shortcuts. Networks solve pretext tasks the easy way if they can: JPEG artefacts, black borders that reveal a rotation, chromatic aberration that reveals a patch's position. Each shortcut is a feature that does not transfer.
  • Masking too little. Masking 1 % of tokens makes prediction easy from neighbours. BERT masks about 15 % of text tokens; MAE masks 75 % of image patches, because images are redundant.
  • Comparing with a weak baseline. Compare against raw features, PCA (the linear autoencoder, itself the simplest self-supervised method) and a public pretrained model before concluding that your own pretraining pays off.

Practice

  1. Why does the masked-word loss count only the hidden position, not the 7 visible words?
  2. In the NumPy example, the best possible held-out loss is about 3.342, not ln⁡180≈5.193\ln 180 \approx 5.193. What does the model know that a uniform guess does not?
  3. You have 2 million unlabelled factory sensor traces and 300 labelled failures. Sketch a masked-modelling pretext task.
Answers
  1. The visible words are part of the input; predicting them would only teach the network to copy. The information is in the gap.
  2. Whether the hidden word is a topic word or a filler: every document has exactly 4 of each, so if three topic words are visible the hidden one is a topic word, and the visible topic words also say which topic. What remains is a uniform choice among 40 topic words or 20 fillers, 12ln⁡40+12ln⁡20\frac{1}{2}\ln 40 + \frac{1}{2}\ln 20.
  3. Cut each trace into fixed windows, hide random spans of time steps (or one sensor channel), and train the encoder to reconstruct the hidden values with the squared error on the hidden part only. Then train a small failure classifier on the encoder's features with the 300 labels, and compare with the same classifier on hand-made features.

Test yourself

What makes a task self-supervised?

  1. A human labels a small subset
  2. The labels are computed from the input itself, such as a hidden word or a rotation angle
  3. There is no loss function
  4. The model is trained without gradients

After pretraining with a masked-modelling task, what is usually kept?

  1. The pretext head only
  2. The encoder; the pretext head is discarded and a new task head is trained
  3. Nothing, only the loss curve
  4. The masked inputs

In the rotation example, the network reached 0.962 on the pretext task but its features gave 0.780 against 0.831 for raw pixels. Why?

  1. The network was not trained long enough
  2. Telling the angle of an 8 x 8 digit needs only stroke-direction features, not digit identity, and raw pixels are already a good representation here
  3. Logistic regression cannot use ReLU features
  4. The test set was too small

Why do masked autoencoders for images hide about 75 % of the patches, far more than BERT's 15 % of words?

  1. Images are smaller than texts
  2. Neighbouring patches are highly redundant, so a small mask can be filled in by simple interpolation
  3. To make training slower
  4. Because images have no labels