Lesson 3.4 — Self-supervised & Contrastive Learning
From labels to self-supervision
| Paradigm | Training Signal | Example |
|---|---|---|
| Supervised | External / human labels y | Defect classification |
| Unsupervised | Data structure, no human labels | PCA, clustering |
| Self-supervised | Targets or relations constructed from data itself | AE reconstruction, Masked Prediction, SimCLR |
Keep three distinct variables separate: h is the downstream representation,
z is the pretraining projection, and u = z / ||z||₂ is the
L2-normalized vector used for similarity.
Views & invariance
Suppose the downstream job is to distinguish vertical and horizontal defects, regardless of where they appear. During contrastive pretraining, two views derived from one image are designated as a positive pair. The training objective rewards their projected representations for remaining close.

Pair the original with the shifted view. Their pixel coordinates differ, but they still have the same orientation. Pulling their representations together rewards a property this classifier needs. Pair the original with the rotated view and the training signal now rewards similarity across the very distinction the classifier must recover.
The choice changes with the task. A position estimator needs to know that shifting the image shifts the predicted location. For that output, a predictable change under translation is desirable. Choose augmentations by tracing what each one does to the intended target.
Generate two views of the same defect with translation and noise
01 · Image Augmentation Playground (Two Positive Views)
L2 normalization & cosine similarity
02 · Embedding & Cosine Similarity
PyTorch L2 normalization
import torch
import torch.nn.functional as F
z = torch.tensor([[1.0, 0.0], [2.0, 2.0]])
u = F.normalize(z, p=2, dim=-1, eps=1e-12)
print(u @ u.T) # pairwise cosine similarities
Batch indexing & false negatives
Do not confuse interleaved indexing (i ^ 1) with concatenated indexing
[a0..aN-1, b0..bN-1] where the positive is (i + N) mod 2N. False
negatives occur when distinct instances of the same underlying class act as negatives.
03 · Positive / Negative Pair Inspector (Interleaved 2N)
04 · Batch Similarity Matrix (6 Views, Diagonal Masked)
InfoNCE / NT-Xent · temperature & symmetric gradients
Take one anchor view and hide its similarity with itself. Of the remaining views, exactly one is the other augmentation of the same source. This is the classification problem from Lesson 2.1 with a different target: identify that partner within the batch.
For an interleaved batch of normalized embeddings , the positive partner is . Let . The per-anchor loss is
Temperature controls how much a similarity advantage counts. Compare one positive and one competing negative in the same row. Their common denominator cancels:
If the positive leads, lowering temperature strengthens its advantage over that negative. If a negative leads, lowering temperature favors the negative. If they tie, their odds stay even. When all candidates tie, the loss is .
05 · InfoNCE & Temperature Explorer
A symmetric batch loss takes every view as an anchor. Its embedding influences both its own comparison row and the rows where it appears as a candidate. Backpropagation through L2 normalization projects the update onto the tangent space at the normalized embedding and scales it by the inverse original norm (for norms above the numerical floor).
06 · Contrastive Gradient Animation (6 2D Vectors)
Shared encoder, projection head & robot visual encoder lab
07 · Trace a SimCLR Batch
Frozen encoder & linear probe
08 · Frozen Encoder & Linear Probe (36 Validation Images)
In the default flattened-MLP experiment (3 labeled examples/class, 36 val images),
fixed holdout NT-Xent drops 3.379449 → 2.792237, yet frozen linear-probe validation
accuracy is Random 27.78%, Contrastive 25.00%, Supervised
27.78%. In this configuration, the training objective improved while the frozen
contrastive representation yielded one fewer correct prediction than the random encoder.
Complete reproducible experiment (ssl0304.py)
Complete PyTorch script (ssl0304.py)
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1)
D = torch.float64
def rng(seed):
x = seed & 0xffffffff
def draw():
nonlocal x
x = (1664525 * x + 1013904223) & 0xffffffff
return x / 4294967296
return draw
def data(n, seed):
r = rng(seed)
out = []
for i in range(n):
y = i % 3
a = 2 + int(4 * r())
b = 2 + int(4 * r())
x = []
for k in range(64):
h, w = divmod(k, 8)
v = w == b and abs(h - a) <= 1
u = h == a and abs(w - b) <= 1
x.append((0.85 if (v if y == 0 else u if y == 1 else v or u) else 0.15) + 0.06 * (2 * r() - 1))
out.append((x, y))
return out
def augment(x, r, shift, noise):
dy = int((2 * shift + 1) * r()) - shift
dx = int((2 * shift + 1) * r()) - shift
gain = 0.75 + 0.5 * r()
bias = 0.16 * (r() - 0.5)
out = []
for k in range(64):
h, w = divmod(k, 8)
h -= dy
w -= dx
v = x[h * 8 + w] if 0 <= h < 8 and 0 <= w < 8 else 0.15
out.append(max(0, min(1, gain * v + bias + noise * (2 * r() - 1))))
return out
def init(seed):
r = rng(seed + 2000)
return [[0.4 * (r() - 0.5) if i % 2 == 0 else 0.0 for _ in range(n)] for i, n in enumerate([512, 8, 24, 3, 24, 3])]
def param(a, shape):
return nn.Parameter(torch.tensor(a, dtype=D).reshape(shape))
def linear(x, w, b):
return x @ w.T + b
def nt_xent(z, tau):
u = F.normalize(z, dim=1, eps=1e-12)
logits = (u @ u.T) / tau
logits = logits.masked_fill(torch.eye(len(z), dtype=torch.bool), -torch.inf)
return F.cross_entropy(logits, torch.arange(len(z)) ^ 1)
def run(seed=3, tau=0.25, shift=1, noise=0.06, updates=100, nlabel=3):
base = init(seed)
pre = data(60, seed)
labeled = data(3 * nlabel, seed + 1000)
val = data(36, seed + 2000)
x = torch.tensor([a for a, _ in labeled], dtype=D)
y = torch.tensor([y for _, y in labeled])
vx = torch.tensor([a for a, _ in val], dtype=D)
vy = torch.tensor([y for _, y in val])
make_encoder = lambda: [param(base[0], (8, 64)), param(base[1], (8,))]
make_head = lambda i: [param(base[i], (3, 8)), param(base[i + 1], (3,))]
encode = lambda x_in, e: linear(x_in, *e).tanh()
eval_r = rng(seed + 5000)
eval_views = torch.tensor([augment(a, eval_r, shift, noise) for a, _ in data(12, seed + 3000) for _ in range(2)], dtype=D)
e = make_encoder()
p = make_head(2)
opt = torch.optim.Adam(e + p, lr=0.015)
r = rng(seed + 4000)
hist = []
for t in range(updates + 1):
batch = [pre[(t * 12 + i) % 60][0] for i in range(12)]
views = torch.tensor([augment(a, r, shift, noise) for a in batch for _ in range(2)], dtype=D)
z = linear(encode(views, e), *p)
loss = nt_xent(z, tau)
if t % 10 == 0 or t == updates:
hist.append(dict(t=t, loss=loss.item(), fixed=nt_xent(linear(encode(eval_views, e), *p), tau).item()))
if t == updates:
break
opt.zero_grad()
loss.backward()
opt.step()
sup = make_encoder()
sh = make_head(4)
opt = torch.optim.Adam(sup + sh, lr=0.02)
for _ in range(80):
opt.zero_grad()
F.cross_entropy(linear(encode(x, sup), *sh), y).backward()
opt.step()
results = []
for name, enc in [("Random", make_encoder()), ("Contrastive", e), ("Supervised", sup)]:
with torch.no_grad():
h, vh = encode(x, enc), encode(vx, enc)
head = make_head(4)
opt = torch.optim.Adam(head, lr=0.03)
for _ in range(80):
opt.zero_grad()
F.cross_entropy(linear(h, *head), y).backward()
opt.step()
with torch.no_grad():
logits = linear(vh, *head)
acc = (logits.argmax(1) == vy).double().mean().item()
results.append((name, acc))
return hist, results
if __name__ == "__main__":
hist, results = run()
print("Fixed holdout NT-Xent:", hist[0]["fixed"], "->", hist[-1]["fixed"])
print("Probe acc:", results)