Skip to content

MLDay 42 of 50Deep Learning

Self-Supervised Learning and Foundation Models

You have 4,136 text messages, and a colleague had time to label 20 of them as spam or not.

9 min read

You have 4,136 text messages, and a colleague had time to label 20 of them as spam or not. Labels cost hours; raw text costs nothing. Self-supervised learning puts the unlabelled 4,116 to work.

The idea

Self-supervised learning trains a model on labels it makes from the raw data itself. It sets a pretext task: a puzzle whose answer is already hidden in the data. Three common ones:

  • Masked word: hide a word in a sentence and predict it from its neighbours.
  • Next word: predict the word that comes next.
  • Matching pairs: tell whether two crops come from the same photo, or whether a caption belongs to an image.

Nobody cares about the puzzle itself. What matters is what the model must learn to solve it. To guess the gap in "you have won a ___", it has to learn that "prize", "cash" and "guaranteed" show up in the same places. Their word vectors (the embeddings of D40) end up closer together than those of unrelated words.

This first stage is pretraining. Then the learned layers go to work on a real task. Freeze them and train only a small classifier on top: a linear probe, as with the frozen image network in D38. Or keep training the whole network on the labelled data: fine-tuning.

A foundation model is one large network pretrained this way on a huge amount of text or images, then adapted to many tasks. Large language models start as next-word predictors, with the self-attention of D41 in place of the simple average used below.

A tiny example

One message, "see you at the station", becomes five training examples. Hide each word in turn; the two words on each side are the input.

Input (the context) Label (the hidden word)
___ you at see
see ___ at the you
see you ___ the station at
you at ___ station the
at the ___ station

Five words gave five labelled examples, and nobody labelled anything. The 4,136 training messages give 59,704 (counting only words seen 3+ times).

The formula

The predictor gives every word in its vocabulary a score, and softmax turns the scores into probabilities (D33). The loss is the usual cross-entropy, with the hidden word as the true class:

L=−ln⁡p(hidden word)L = -\ln p(\text{hidden word})
Symbol Meaning
LL the loss for one gap; 0 means the model was sure and right
p(hidden word)p(\text{hidden word}) the probability the model gave the word that was really there
ln⁡\ln the natural log

Worked: p=0.5p = 0.5 gives L=0.69L = 0.69; p=0.9p = 0.9 gives L=0.11L = 0.11. A model that guesses evenly among the 2,295 words of its vocabulary gives each p=12,295p = \frac{1}{2{,}295}, so L=ln⁡2,295=7.74L = \ln 2{,}295 = 7.74.

Try it

Fill the gap: call me when you ___ home

Move the scores. Softmax turns them into probabilities: each is e to the score, divided by the sum of them all, so the bars always add up to 1. The right answer is "get".

most likely free, p = 0.609cross-entropy −ln p(get) = 3.495

The hidden word is "get", but the model starts out betting on "free" (p = 0.609), and the cross-entropy is 3.495. Raise the get score to 2.5: its probability passes 0.5 and the loss falls to 0.675. Push it to 4.7 and the loss reaches 0.102. Notice that "are" fits the gap too, so a real model can't be sure, and its loss never reaches 0.

In code

Pretext data. The dedupe and split from Day 22, then masked-word examples from the training texts only. The labels are never read here.

# script_id: day_042_self_supervised_learning/masked_words
import os
import re
from collections import Counter
from pathlib import Path

import numpy as np
import pandas as pd
import torch
from torch import nn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "sms_spam" / "SMSSpamCollection", sep="\t", header=None,
                 names=["label", "text"], quoting=3).drop_duplicates("text")
y = (df["label"] == "spam").astype(int)
X_train, X_test, y_train, y_test = train_test_split(
    df["text"], y, test_size=0.2, stratify=y, random_state=42)


def tokens(text: str) -> list[str]:
    return re.findall(r"[a-z0-9]+", text.lower())


counts = Counter(w for text in X_train for w in tokens(text))
vocab = ["<pad>"] + [w for w, c in counts.items() if c >= 3]          # words seen 3+ times
idx = {w: i for i, w in enumerate(vocab)}
ctx, tgt = [], []
for text in X_train:
    ids = [idx[w] for w in tokens(text) if w in idx]
    for i, word in enumerate(ids):                     # hide word i; the 2 words each side are the input
        c = ids[max(0, i - 2):i] + ids[i + 1:i + 3]
        if c:
            ctx.append(c + [0] * (4 - len(c)))         # pad to 4 with <pad>, which the average skips
            tgt.append(word)
ctx, tgt = torch.tensor(ctx), torch.tensor(tgt)
print(f"{len(X_train):,} messages -> {len(tgt):,} masked-word examples; {len(vocab):,} words")
4,136 messages -> 59,704 masked-word examples; 2,295 words

Pretrain. nn.EmbeddingBag averages the context words' vectors (D40), and a linear layer scores every word in the vocabulary.

# script_id: day_042_self_supervised_learning/masked_words
torch.manual_seed(42)
model = nn.Sequential(nn.EmbeddingBag(len(vocab), 32, padding_idx=0),   # average the context vectors
                      nn.Linear(32, len(vocab)))                       # one score per word
opt = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()
g = torch.Generator().manual_seed(42)
for epoch in range(5):
    for batch in torch.randperm(len(tgt), generator=g).split(256):
        loss = loss_fn(model(ctx[batch]), tgt[batch])
        opt.zero_grad()
        loss.backward()
        opt.step()
model.eval()
with torch.no_grad():
    print(f"mean loss {loss_fn(model(ctx), tgt):.2f}; guessing gives ln {len(vocab):,} = {np.log(len(vocab)):.2f}")
    p = model(torch.tensor([[idx["when"], idx["you"], idx["home"], 0]])).softmax(dim=1)[0]
    top = p.topk(3)
    print("call me when you ___ home:", ", ".join(f"{vocab[i]} {v:.3f}" for v, i in zip(top.values, top.indices)))
mean loss 4.23; guessing gives ln 2,295 = 7.74
call me when you ___ home: are 0.098, get 0.077, re 0.056

The mean loss on its training gaps is 4.23, far below guessing's 7.74, and the top guesses for the gap are sensible words.

Probe. Each message becomes the average of its word vectors, frozen. A logistic regression trains on a few labelled messages. The same probe on untrained, random vectors of the same size is the control, and TF-IDF + logistic regression from D20 is the yardstick. The score is PR-AUC on all 1,035 test messages (a model that ranks at random scores about 0.13, the spam share).

# script_id: day_042_self_supervised_learning/masked_words
def features(emb: nn.EmbeddingBag, texts: pd.Series) -> np.ndarray:
    rows = [[idx[w] for w in tokens(t) if w in idx] for t in texts]
    width = max(map(len, rows))
    with torch.no_grad():                               # frozen: no gradients, no updates
        return emb(torch.tensor([r + [0] * (width - len(r)) for r in rows])).numpy()


torch.manual_seed(0)
encoders = {"random": nn.EmbeddingBag(len(vocab), 32, padding_idx=0), "pretrained": model[0]}
feats = {name: (features(e, X_train), features(e, X_test)) for name, e in encoders.items()}
print("labelled   random  pretrained  tf-idf   (test PR-AUC, mean of 5 draws)")
for n in [20, 50, 200, 1000]:
    ap = {"random": [], "pretrained": [], "tf-idf": []}
    for seed in range(5):
        few = train_test_split(np.arange(len(y_train)), train_size=n, stratify=y_train, random_state=seed)[0]
        for name, (f_train, f_test) in feats.items():
            probe = make_pipeline(StandardScaler(), LogisticRegression()).fit(f_train[few], y_train.iloc[few])
            ap[name].append(average_precision_score(y_test, probe.predict_proba(f_test)[:, 1]))
        tfidf = make_pipeline(TfidfVectorizer(), LogisticRegression()).fit(X_train.iloc[few], y_train.iloc[few])
        ap["tf-idf"].append(average_precision_score(y_test, tfidf.predict_proba(X_test)[:, 1]))
    print(f"{n:8,} " + "".join(f"{np.mean(v):9.2f}" for v in ap.values()))
labelled   random  pretrained  tf-idf   (test PR-AUC, mean of 5 draws)
      20      0.19     0.82     0.52
      50      0.20     0.86     0.73
     200      0.30     0.89     0.89
   1,000      0.33     0.90     0.93

With 20 labels, the pretrained vectors score 0.82 against 0.19 for random ones. The network's shape is the same, so the gap is what the masked-word puzzle taught. They also beat TF-IDF, which has to learn every spam word from just 3 spam examples. By 200 labels TF-IDF catches up, and at 1,000 it wins: averaging 32-number word vectors blurs detail that TF-IDF's one weight per word keeps. Pretraining pays most when labels are scarce.

Quick check

Quick check

1. Where do the masked-word predictor's labels come from?

2. The model gives the hidden word p = 0.9. What is the loss?

3. You have 100,000 unlabelled support tickets and 30 labelled ones. What is the best first plan?

Next

D43: Reinforcement Learning Basics drops labels altogether: an agent learns from rewards that arrive after a series of choices.

Data: SMS Spam Collection v.1 (UCI Machine Learning Repository, dataset 228), CC BY 4.0; cite Almeida, T. A., Gómez Hidalgo, J. M. and Yamakami, A. (2011), "Contributions to the Study of SMS Spam Filtering: New Collection and Results", Proceedings of the 2011 ACM Symposium on Document Engineering.

Next · Day 43 · 8 minReinforcement Learning Basics← Previous: Day 41 · Self-Attention from Scratch
Not tapped yet