Latent representations and self-supervised learning
A representation is useful when it makes the tasks we care about easier. Relate PCA, dictionaries and embeddings to that idea, then study how self-supervised methods construct targets from the data themselves. Survey historical pretext tasks and modern methods, and set up linear-probe and k-NN evaluation used in the following lessons.
After this lesson you can
- Identify desirable properties of representations, including invariance, linear separability, sparsity and disentanglement, and ways to measure them.
- Formulate a pretext task as a supervised problem with labels derived from the data.
- Classify self-supervised methods as reconstructive, contrastive, non-contrastive, clustering-based or predictive in latent space.
- Train an encoder on a pretext task and evaluate it with linear probes and k-NN against PCA and pixel baselines.
- Reason about which invariances a pretext task or augmentation induces or destroys.
Before you start
- 12Principal component analysisLinear autoencoder and principal subspaceDictionary learningChance-adjusted external indices
- 15BackpropagationEpochs and shufflingMicro framework to PyTorch correspondence
- 11Softmax (multinomial logistic) regression
- 07Information bottleneck
- 16Multichannel convolutional layerLeNet-5
Motivation: labels are expensive, unlabeled data plentiful
A hospital holds millions of radiographs but only thousands have specialist-signed diagnoses. A company accumulates years of server telemetry but manually annotated only a few incident days. A language model trains on trillions of unlabeled words. In all three there is abundant and very few pairs .
So far this module addressed unlabeled data by asking what structure they have: clustering (k-means, mixtures, spectral), projection (, t-SNE, UMAP), anomaly detection. Each method ended in a result (groups, map, score) to inspect and use. This lesson changes the question: can unlabeled data construct a description of each observation that makes later tasks easy with few labels? That reusable description is a representation. This underlies GPT-style language-model pretraining by next-token prediction on unannotated text, and CLIP learning from image–text pairs already paired on the web (next lesson starts with contrastive-learning mathematics behind CLIP).
The lesson answers four questions in order: what makes a representation good and how to measure it; how data create their own supervision and what tasks have been used; what invariances each design introduces or destroys; and how to evaluate honestly, the protocol used in lessons 21–24.
What makes a representation good
Calling “good” only makes sense relative to a task, head family and label budget. The following result proves it, and is less trivial than it appears.
Proof
(a) If is a head on , is a head on and its risk is at least their infimum. (b) Given inverse and head on , head on satisfies almost surely, with equal risk. (c) A linear probe on is : an affine head on , so the infimum cannot decrease. Full-column-rank has left inverse , and any on can be written , .
∎Two consequences. First, pixels already contain all information, so a representation never creates information (data processing principle); it changes how easily a restricted head uses it and, with few labels, how many examples are required. Second, a linear representation (PCA, random projection, any linear pixel combination) cannot improve the best risk of a linear probe. With finite data it may improve by regularization (fewer coordinates and parameters to estimate from few labels). To expand what a linear probe can attain, a representation must be nonlinear: undo curvature the probe cannot undo alone.
Bengio, Courville and Vincent’s priors
What properties make tasks easy? Bengio, Courville and Vincent (2013) organized generic priors about the world a good representation should exploit: smoothness (nearby points have nearby outputs), multiple disentangleable explanatory factors, hierarchical factor organization, factors shared across tasks, data near low-dimensional manifolds, natural clustering, temporal and spatial coherence, sparsity (few factors active at once), and simple factor dependencies. Four measurable properties follow:
| Property | Requirement | Measurement (this lesson) |
|---|---|---|
| Linear separability | classes separated by hyperplanes | linear probe accuracy on |
| Invariance | for task-preserving transformations | relative displacement , with mean distance to other images |
| Sparsity | few active coordinates per datum | Hoyer sparsity |
| Dimension usage | data not collapsed into few directions | effective rank with (centered matrix singular values; Roy and Vetterli, 2007) |
Disentanglement (each coordinate controls one variation factor) is deliberately absent. Locatello et al. (2019) proved unsupervised disentangled representation learning impossible without model and data inductive biases, and across 12 000+ models could not identify well-disentangled ones without supervision. Measuring it also requires true factors, rarely available. Downstream tasks are available, making the probe the coming lessons’ gold standard.
The next cell measures all four properties on load_digits (1797 8×8 images, 1347 training, 450 evaluation). Five representations learned without labels on training: pixels, 16-component PCA, 16-atom NMF, random 16-dimensional projection, and a 64-center k-means dictionary with Coates, Lee and Ng’s (2011) triangular activation , where is mean center distance. It is nonlinear and sparse: only nearest centers activate.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import NMF, PCA
digits = load_digits()
X, y = digits.data, digits.target
orden = np.random.default_rng(0).permutation(len(X))
X, y = X[orden], y[orden]
ntr = 1347
Xtr, Xte, ytr, yte = X[:ntr], X[ntr:], y[:ntr], y[ntr:]
# cinco representaciones aprendidas SIN etiquetas con el entrenamiento
pca = PCA(16, random_state=0).fit(Xtr)
nmf = NMF(16, init="nndsvda", max_iter=500, random_state=0).fit(Xtr)
Wg = np.random.default_rng(1).normal(size=(64, 16)) / 4
km = KMeans(64, n_init=1, random_state=0).fit(Xtr)
def triangular(Z):
D = km.transform(Z)
return np.maximum(0, D.mean(1, keepdims=True) - D)
codificadores = {"píxeles (64)": lambda Z: Z, "PCA (16)": pca.transform, "NMF (16)": nmf.transform,
"proyección aleatoria (16)": lambda Z: Z @ Wg, "k-means triangular (64)": triangular}
def sonda_ridge(Ztr, ytr_, Zte, yte_, lam=1.0):
"""Sonda lineal de mínimos cuadrados regularizados sobre características estandarizadas (forma cerrada)."""
mu, sd = Ztr.mean(0), Ztr.std(0) + 1e-9
A = np.c_[(Ztr - mu) / sd, np.ones(len(Ztr))]
W = np.linalg.solve(A.T @ A + lam * np.eye(A.shape[1]), A.T @ np.eye(10)[ytr_])
return ((np.c_[(Zte - mu) / sd, np.ones(len(Zte))] @ W).argmax(1) == yte_).mean()
def hoyer(Z):
"""Dispersión de Hoyer de cada fila (0 = todas las coordenadas iguales, 1 = una sola distinta de cero), promediada."""
d = Z.shape[1]
l1, l2 = np.abs(Z).sum(1), np.sqrt((Z ** 2).sum(1)) + 1e-12
return float(np.mean((np.sqrt(d) - l1 / l2) / (np.sqrt(d) - 1)))
def rango_efectivo(Z):
"""Rango efectivo (Roy y Vetterli): exp de la entropía de los valores singulares normalizados de la matriz centrada."""
s = np.linalg.svd(Z - Z.mean(0), compute_uv=False)
p = s / s.sum()
return float(np.exp(-(p * np.log(p + 1e-12)).sum()))
def desplazar(Z, dx):
"""Traslación de dx columnas de las imágenes de 8x8 (ceros por la izquierda)."""
I = Z.reshape(-1, 8, 8)
out = np.zeros_like(I)
out[:, :, dx:] = I[:, :, :8 - dx]
return out.reshape(len(Z), 64)
def desplazamiento_relativo(f, Z, dx=1, n_ref=300):
"""|| z(T x) - z(x) || dividido por la distancia media de z(x) a las representaciones de n_ref imágenes distintas."""
z0, z1 = f(Z), f(desplazar(Z, dx))
ref = f(Z[-n_ref:])
d_ref = np.sqrt(((z0[:, None, :] - ref[None]) ** 2).sum(-1)).mean(1)
return float(np.mean(np.linalg.norm(z1 - z0, axis=1) / d_ref))
print(f"{'representación':26s} {'sonda':>6s} {'dispersión':>10s} {'rango ef.':>9s} {'desplaz. 1 px':>13s}")
for nombre, f in codificadores.items():
Ztr, Zte = f(Xtr), f(Xte)
print(f"{nombre:26s} {sonda_ridge(Ztr, ytr, Zte, yte):6.3f} {hoyer(Zte):10.3f} {rango_efectivo(Zte):9.1f} {desplazamiento_relativo(f, Xte):13.3f}")
# ¿por qué el rango efectivo de las representaciones de 64 dimensiones se queda lejos de 64?
for nombre in ("píxeles (64)", "k-means triangular (64)"):
Z = codificadores[nombre](Xte)
s2 = np.linalg.svd(Z - Z.mean(0), compute_uv=False) ** 2
print(f"{nombre}: las 16 primeras componentes explican el {100 * s2[:16].sum() / s2.sum():.0f} % de la varianza; "
f"coordenadas constantes: {(Z.std(0) < 1e-9).sum()}")Linear-probe ordering matches the theorem: pixels 0.940, 16-component PCA 0.931 (linear 64-to-16 projection gives the probe nothing new), NMF 0.904, random projection 0.789. Only nonlinear triangular k-means beats pixels (0.973). Other columns tell different stories. Hoyer sparsity separates NMF (0.529) and k-means (0.579) from pixels (0.422), PCA (0.333), projection (0.277). Read effective rank relative to dimension: PCA uses nearly all 16 coordinates (14.8), with uncorrelated comparable-variance components; projection (13.3) and especially NMF (11.5) concentrate variance in fewer directions; pixels (38.9) and k-means (37.0) use slightly over half of 64, since variance concentrates (first 16 principal components explain 86% of test-pixel and 92% of k-means variance; 7 border pixels are 0 for every test image). One-pixel-translation displacement is near 1 for all (pixels 1.048, PCA 0.961, projection 0.998, NMF 0.891), with k-means somewhat more stable (0.776): moving an 8×8 digit one column changes representation as much as replacing the digit. Reconstruction or clustering does not grant invariance for free: it must be requested, as discussed below.
How many labels does a representation save?
The table uses all 1347 labels. More interesting: few labels. The figure evaluates the same representations with a browser-trained linear probe using 13 labels (1%), 27, 67, 135, 404 and 1347 (100%); PCA and projection dimension can be changed.
load_digits digits (1347 training, 450 test). Five unlabeled-training representations: pixels, PCA, 16-atom NMF, random projection, 64-center triangular k-means. A linear probe (regularized least squares, regularization chosen by cross-validation using only budgeted labels) trains in browser on random training subsets (10 label samples at 13 and 27, 8 at 67, 6 at 135, 3 at 404, 1 at 1347) and is measured on test. Initially (135 labels, 10%, PCA and projection 16 dimensions): pixels 0.864, PCA 0.870, NMF 0.857, random projection 0.754, k-means 0.926; pixels need about 452 labels to match k-means, over three times more. Lower to 13 and raise to 404 to watch the gap close; change dimension: PCA at 64 compresses nothing. Previous-cell figures differ slightly due to another split and regularization.This shows the theorem in action. PCA and random projection are linear: with 64 components PCA (plus standardization) loses no information; with fewer it does and its curve is lower with many labels. At intermediate budget 16-component PCA can beat pixels by one point (0.870 versus 0.864 with 135 labels): theorem regularization, not new information, disappearing by 404 labels. NMF is nonlinear but 16 atoms compress too much and eventually trail pixels with enough labels. Triangular k-means activation instead nonlinearly groups similar digits: with few labels a linear boundary over 64 coordinates separates classes pixels do not. It is unsupervised: nobody specified what a 3 is.
Precedents: PCA, dictionaries and linear autoencoders
For decades representations were hand-designed: gradient histograms and SIFT for images, bags of words and TF-IDF for text, window statistics for signals. Each encodes designer prior knowledge (an edge, a word) and serves as baseline for learned representations. Early unlabeled learned representations are familiar: PCA is the maximum-variance linear representation; a linear-hidden-layer autoencoder with squared loss learns the same subspace, as the linear autoencoder lesson proves. Dictionaries and sparse coding add the nonlinearity just seen: a code solves an optimization with penalty, rather than projection. All share a limit: reconstructing pixels. Good reconstruction preserves what varies most (overall tone, stroke thickness, background), which may not be what a task needs (which digit or garment). Good image modeling and good classification representations are different objectives.
Naturally, is there a task without human labels whose solution forces preservation of what matters? This motivates self-supervision.
Self-supervised learning: supervision comes from data
Three examples share this template. Rotation: counts quarter-turns, rotates the image and . Denoising: is noise, and (the label is the datum itself). Next word: is position, the prefix and the following word. Labels are free in all cases: a controlled transformation produces them.
Why should it help? No general theorem guarantees it; each task bets that solving it requires structure useful downstream. Determining a shirt’s rotation requires recognizing it. Predicting the next word requires understanding a sentence. But the bet fails if a shortcut solves the task without structure or it requires preserving what later gets in the way. Both risks organize the rest of the lesson.
The cell builds rotation supervision from scratch on digits and trains a linear pixel classifier. Labels ( pairs) are free and perfectly balanced; accuracy depends on digit.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
digits = load_digits()
orden = np.random.default_rng(0).permutation(len(digits.data))
imagenes = digits.images[orden] # 1797 imágenes de 8 x 8
clase = digits.target[orden] # solo se usa para informar, nunca para entrenar
def tarea_rotacion(I):
"""Supervisión fabricada: las 4 rotaciones de cada imagen y el número de cuartos de vuelta como etiqueta."""
X = np.concatenate([np.rot90(I, k, axes=(1, 2)) for k in range(4)])
return X.reshape(len(X), 64), np.repeat(np.arange(4), len(I))
ntr = 1347
Xr_tr, yr_tr = tarea_rotacion(imagenes[:ntr])
Xr_te, yr_te = tarea_rotacion(imagenes[ntr:])
print("etiquetas gratis:", len(yr_tr), "pares de entrenamiento; reparto de etiquetas:", np.bincount(yr_tr))
clf = LogisticRegression(max_iter=300).fit(Xr_tr / 16, yr_tr)
acierto = clf.predict(Xr_te / 16) == yr_te
print(f"exactitud en la tarea pretexto (azar 0.25): {acierto.mean():.3f}")
# la exactitud por dígito: la etiqueta de la tarea no depende de qué dígito es, pero su dificultad sí
clase_te = np.tile(clase[ntr:], 4)
for c in range(10):
print(f"dígito {c}: {acierto[clase_te == c].mean():.3f}", end=" " if c % 5 != 4 else "\n")A linear pixel classifier without a single human label gets 82.0% of rotations (chance 25%). Per-digit accuracy varies greatly: 7 (0.972), 6 (0.957), 9 (0.938) are easy, 4 (0.679) hardest; 0, 1 and 8 around 0.78. This is not a task limit (a linear model on 64 pixels is very modest), but a reminder that pretext difficulty depends on the example, and high pretext accuracy says nothing yet about representation quality.
Historical pretext tasks
Between 2008 and 2018 many were tried, mostly on images. All create labels using the template above.
Context prediction (Doersch, Gupta and Efros, 2015). Sample a patch and one of its eight neighbors in a grid; the label is the neighbor’s relative position. Authors discovered an unexpected shortcut: chromatic aberration, because lenses focus wavelengths slightly differently and in some cameras one channel (often green) contracts toward center relative to others; the network inferred patch position without content. They prevented it with 48-pixel gaps (about half patch width), random shifts up to 7 pixels, and randomly dropping two of three color channels per patch.
Jigsaw (Noroozi and Favaro, 2016). Split an image into a tile grid (75×75 pixels, crop 64×64 with random offset, mean 11-pixel gap), shuffle using one of 1000 permutations chosen for large mean Hamming distance, and classify which was applied. Shortcuts include continuity across edges, intensity distributions and chromatic aberration; authors use random gaps, grayscale and color-channel variation. With possible permutations the chosen 1000 set chance to 0.1%.
Colorization (Zhang, Isola and Efros, 2016). Input is luminance and label chrominance , quantized for classification and reweighted by color rarity. It is reconstructive: the label is part of the datum.
Rotation (Gidaris, Singh and Komodakis, 2018). Simplest: four classes, rotations 0, 90, 180 and 270 degrees. An AlexNet pretrained this way achieved 54.4% mAP on PASCAL VOC 2007 detection, 2.4 points below the supervised counterpart, according to its abstract: then the best unsupervised result. You will use it in the lab.
Denoising and masking. Denoising autoencoders (Vincent, Larochelle, Bengio and Manzagol, 2008) corrupt inputs and reconstruct clean ones; masking hides regions to fill in (inpainting; MAE and BERT are modern forms). The label is the datum itself.
Now generate supervision yourself. Choose a Fashion-MNIST image and task; inspect the generated input–label pair and before switching tasks predict what it requires or forbids of the representation.
torch.rot90; chance 25%). Jigsaw: nine 8×8 tiles shuffled using one of 10 Hamming-distance-selected permutations (chance 10%); remove gaps to see the separation preventing edge-continuity shortcuts disappear. Context: center tile and one of eight neighbors (chance 12.5%). Mask: 4×4 blocks hidden; initially 50% (25 of 49 blocks, 400 pixels). Noise: copying input has expected MSE (0.16 at initial ); the reading gives the displayed pair's error. Each task asks what it requires or prevents in the representation; answer before advancing (answered items are marked).Across the five answers: rotation and jigsaw labels describe the transformation, requiring sensitivity to it. Denoising labels are transformation-independent, pushing toward approximate invariance (the augmentations figure measures how much). Masking and context require spatial detail. All admit shortcuts.
Augmentation-induced invariance
So far transformations defined labels. The second use, dominant in modern self-supervision, reverses this: a transformation that does not change what matters and should be invisible to the representation.
Invariance is inherited and incompatible with predicting the transformation.
Proof
(a) by invariance, with no assumption about . Part (b) is your proof exercise at the end; attempting it now is the best way to understand why invariance erases information.
∎Immediate practical reading: a pretext task predicting a transformation and invariance to that transformation are incompatible. Design determines what information is preserved.
This is also a design tool: invariance comes not from architecture but from chosen augmentations. In the lab you train identical same-seed encoders on rotation prediction, except one first gets up to 3-pixel translation and Gaussian noise with deviation 0.2 on the subsequently rotated image. Rotation label is independent of translation and noise, so theory predicts the second becomes invariant to them while both remain rotation-sensitive. The figure measures this.
Three readings. Rotation: at 90°, pixels move 0.99 of typical image distance, PCA 0.96 and rotation-trained encoders 1.05 and 1.03: rotation moves them as much as replacing the image, necessarily because their label is rotation (invariance would force chance). Translation and noise: augmentation approaches but does not reach invariance. At 3 pixels mean displacement falls 0.51 to 0.42; at (noise seen in training), 1.01 to 0.49, same as pixels (0.50). Invariance is not quality: the random encoder is among most translation-stable (0.45 at 3 pixels) yet has worst -NN of five; PCA is most noise-stable (0.21 at ), without being the best representation. PCA’s explanation is exact: isotropic noise distributes energy across 784 directions, PCA retains 128, leaving norm , while image distance in high-variance directions barely changes; . The clean-only rotation encoder moves 1.01 at , twice pixels. A network trained on clean images can amplify noise, corrected by augmentation. A constant representation is invariant to everything: the goal is invariance to irrelevance while preserving relevance, measured by the probe.
Design moral: the augmentation set is prior knowledge about irrelevance. Whatever augmentation destroys, the representation ignores.
Modern taxonomy and coming lessons
Since 2018, excepting language models (simple pretext tasks at enormous scale), vision methods fall into five nonexclusive families. Published taxonomies vary: Balestriero et al.’s 2023 Cookbook groups view-joining into deep metric learning (SimCLR), self-distillation (BYOL, SimSiam, DINO) and canonical correlation analysis (VICReg, Barlow Twins, SwAV), treating masked image modeling separately. Here we partition by mechanism, as lessons 21–24 do.
| Family | What the network learns | What prevents trivial solution | Examples | Lesson |
|---|---|---|---|---|
| Reconstructive | recover input or part from corrupted version, using data as labels | bottleneck or corruption (otherwise copy input) | denoising autoencoders (2008), BERT (2019), MAE (2022) | vision and LLM modules |
| Contrastive | bring two views of one datum together and push others away | negatives | CPC (2018), MoCo (2020), SimCLR (2020), CLIP (2021) | 21 and 22 |
| Noncontrastive | bring same-datum views together without negatives | asymmetry (stop-gradient, moving average) or covariance regularization | BYOL (2020), SimSiam (2021), DINO (2021), Barlow Twins (2021), VICReg (2022) | 23 (DINO in vision module) |
| Clustering-based | predict one view’s cluster assignment computed from another | balanced assignment | DeepCluster (2018), SwAV (2020) | 23 |
| Latent-space predictive | predict the missing part’s representation, not pixels | target network as moving average of main network, latent-space loss | data2vec (2022), I-JEPA (2023) | 24 |
The third column matters most. Almost all these objectives except reconstruction require similar representations of two views of one datum. That alone has a perfect empty solution: constant . Each family prevents collapse differently, and lessons 21–24 follow that order: contrastive mathematics (NCE and InfoNCE), methods with negatives (lesson 22), those without and collapse (23), theory and frontier (24).
Evaluating a representation
How do you compare representations? The standard answer since Alain and Bengio (2016) is a probe. This parallels evaluating clusters with external validity indices: labels do not train the representation and only measure it, except here a small head trains on some labels.
Each protocol measures something different. Linear probe measures whether classes are linearly accessible; -NN whether local geometry respects class without training additional parameters; fine-tuning the representation’s value as initialization; and label efficiency (probe or fine-tuning with 1% and 10% of ImageNet labels, semi-supervised protocol shared by S4L, CPC v2 and SimCLR) how much work is already done. Alain and Bengio also observed supervised-network layer linear separability grows monotonically with depth: a probe per layer is a microscope of network processing.
Lab: rotation prediction and linear probe
The lab follows the full Fashion-MNIST protocol. Review pieces if needed: encoder is a small CNN (multichannel convolution, like LeNet), trained by minibatch backpropagation with epoch shuffling and standard PyTorch correspondence. Three cells: first trains two identical 512-feature convolutional encoders for 20 epochs on rotation, one unchanged and one translated/noised before rotation, saving weights at 7 epochs. Second defines evaluation (softmax probe with L-BFGS, weight decay chosen on validation from training labels, weighted cosine -NN) and compares pixels, 128-component PCA, random untrained same-architecture encoder, and both trained encoders. Third measures label efficiency (1%, 10%, 100%; three seeds for first two) and epoch evolution.
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
torch.backends.cudnn.deterministic = True # mismos resultados en cada ejecución
torch.backends.cudnn.benchmark = False
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
FashionMNIST.mirrors = ["https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/"]
root = Path.home() / ".cache" / "atlas-data"
tr, te = FashionMNIST(root, train=True, download=True), FashionMNIST(root, train=False, download=True)
Xtr, ytr = tr.data.float().div(255).unsqueeze(1).to(dev), tr.targets.to(dev) # 60000 x 1 x 28 x 28
Xte, yte = te.data.float().div(255).unsqueeze(1).to(dev), te.targets.to(dev) # 10000 x 1 x 28 x 28
EPOCHS, CHECKPOINTS = 20, (0, 1, 2, 4, 8, 12, 20)
def make_encoder(seed):
"""Codificador convolucional pequeño: 28x28 -> 512 características (128 canales en una rejilla 2x2)."""
torch.manual_seed(seed)
def block(i, o):
return nn.Sequential(nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU())
return nn.Sequential(block(1, 32), nn.MaxPool2d(2), block(32, 64), nn.MaxPool2d(2),
block(64, 128), nn.AdaptiveAvgPool2d(2), nn.Flatten()).to(dev)
def augment(x, shift=3, sigma=0.2):
"""Traslación entera aleatoria de hasta `shift` píxeles (con ceros en el borde) y ruido gaussiano de desviación `sigma`."""
d = torch.randint(-shift, shift + 1, (len(x), 2), device=x.device).float()
theta = torch.zeros(len(x), 2, 3, device=x.device)
theta[:, 0, 0] = theta[:, 1, 1] = 1.0
theta[:, :, 2] = -2 * d / x.shape[-1]
grid = F.affine_grid(theta, list(x.shape), align_corners=False)
return F.grid_sample(x, grid, mode="nearest", padding_mode="zeros", align_corners=False) + sigma * torch.randn_like(x)
def rotation_task(x):
"""La tarea pretexto: las cuatro rotaciones de cada imagen, y como etiqueta cuántos cuartos de vuelta se giró."""
xs = torch.cat([torch.rot90(x, k, dims=(2, 3)) for k in range(4)])
return xs, torch.arange(4, device=x.device).repeat_interleave(len(x))
@torch.no_grad()
def features(enc, X, bs=5000):
enc.eval()
return torch.cat([enc(X[i:i + bs]) for i in range(0, len(X), bs)])
def pretrain(seed, aug, epochs=EPOCHS, bs=128, lr=1e-3):
"""Entrena el codificador a predecir la rotación. Devuelve los pesos en cada época de CHECKPOINTS y la exactitud en la tarea."""
enc = make_encoder(seed)
head = nn.Linear(512, 4).to(dev)
opt = torch.optim.Adam([*enc.parameters(), *head.parameters()], lr=lr)
g = torch.Generator(device=dev).manual_seed(seed)
snaps = {0: {k: v.clone() for k, v in enc.state_dict().items()}}
pretext_acc = {}
for ep in range(1, epochs + 1):
enc.train()
for idx in torch.randperm(len(Xtr), device=dev, generator=g).split(bs):
x = augment(Xtr[idx]) if aug else Xtr[idx]
xs, ys = rotation_task(x)
loss = F.cross_entropy(head(enc(xs)), ys)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
if ep in CHECKPOINTS:
snaps[ep] = {k: v.clone() for k, v in enc.state_dict().items()}
xs, ys = rotation_task(Xte)
with torch.no_grad():
pretext_acc[ep] = (head(features(enc, xs)).argmax(1) == ys).float().mean().item()
return snaps, pretext_acc
t0 = time.time()
snaps_rot, acc_rot = pretrain(seed=0, aug=False)
snaps_aug, acc_aug = pretrain(seed=0, aug=True)
print(f"Preentrenamiento: {time.time() - t0:.0f} s para dos codificadores de {EPOCHS} épocas")
print("Exactitud en la tarea pretexto (test, 4 rotaciones, azar = 0.25):")
for ep in CHECKPOINTS[1:]:
print(f" época {ep:2d}: sin aumentos {acc_rot[ep]:.3f} con aumentos {acc_aug[ep]:.3f}")npm run lab and open the connection link.def standardize(Ztr, Zte):
mu, sd = Ztr.mean(0), Ztr.std(0) + 1e-6
return (Ztr - mu) / sd, (Zte - mu) / sd
def fit_logreg(Z, y, wd, iters=100):
"""Regresión softmax con decaimiento de pesos, ajustada con L-BFGS. Entrena (d + 1) * K parámetros."""
W = torch.zeros(Z.shape[1], 10, device=dev, requires_grad=True)
b = torch.zeros(10, device=dev, requires_grad=True)
opt = torch.optim.LBFGS([W, b], lr=1.0, max_iter=iters, line_search_fn="strong_wolfe")
def closure():
opt.zero_grad()
loss = F.cross_entropy(Z @ W + b, y) + wd * (W ** 2).sum()
loss.backward()
return loss
opt.step(closure)
return W.detach(), b.detach()
def accuracy(Z, y, W, b):
return ((Z @ W + b).argmax(1) == y).float().mean().item()
def linear_probe(Ztr, ytr_, Zte, yte_, wds=(1e-4, 1e-3, 1e-2, 1e-1), seed=0):
"""Sonda lineal: el decaimiento se elige con una validación sacada de las etiquetas de entrenamiento; el test solo se mira al final."""
Ztr, Zte = standardize(Ztr, Zte)
perm = torch.randperm(len(Ztr), generator=torch.Generator().manual_seed(seed)).to(dev)
nv = max(len(Ztr) // 5, 1)
va, fi = perm[:nv], perm[nv:]
val = {wd: accuracy(Ztr[va], ytr_[va], *fit_logreg(Ztr[fi], ytr_[fi], wd)) for wd in wds}
best = max(val, key=val.get)
return accuracy(Zte, yte_, *fit_logreg(Ztr, ytr_, best))
def knn_eval(train_z, train_y, test_z, k=20, tau=0.07):
"""k-NN con similitud coseno (tras centrar) y votos ponderados por exp(s / tau)."""
mu = train_z.mean(0)
A = F.normalize(train_z - mu, dim=1)
B = F.normalize(test_z - mu, dim=1)
preds = []
for i in range(0, len(B), 2000):
s, idx = (B[i:i + 2000] @ A.T).topk(k, dim=1)
votes = torch.zeros(len(s), 10, device=dev).scatter_add_(1, train_y[idx], (s / tau).exp())
preds.append(votes.argmax(1))
return torch.cat(preds)
def pca_features(Ztr, Zte, dim=128):
mu = Ztr.mean(0)
evals, evecs = torch.linalg.eigh(((Ztr - mu).T @ (Ztr - mu)) / len(Ztr))
P = evecs[:, -dim:]
return (Ztr - mu) @ P, (Zte - mu) @ P
enc_rand = make_encoder(seed=1) # mismo diseño y sin entrenar, con otra semilla
enc_rot, enc_aug = make_encoder(0), make_encoder(0)
enc_rot.load_state_dict(snaps_rot[EPOCHS])
enc_aug.load_state_dict(snaps_aug[EPOCHS])
pix_tr, pix_te = Xtr.flatten(1), Xte.flatten(1)
reps = {"píxeles (784)": (pix_tr, pix_te), "PCA (128)": pca_features(pix_tr, pix_te),
"codificador aleatorio (512)": (features(enc_rand, Xtr), features(enc_rand, Xte)),
"rotación (512)": (features(enc_rot, Xtr), features(enc_rot, Xte)),
"rotación + aumentos (512)": (features(enc_aug, Xtr), features(enc_aug, Xte))}
print(f"{'representación':30s} {'sonda lineal':>12s} {'k-NN (k=20)':>12s}")
for name, (Ztr, Zte) in reps.items():
sonda = linear_probe(Ztr, ytr, Zte, yte)
knn = (knn_eval(Ztr, ytr, Zte) == yte).float().mean().item()
print(f"{name:30s} {sonda:12.4f} {knn:12.4f}")npm run lab and open the connection link.def label_budget(Ztr, Zte, frac, seeds):
accs = []
for s in seeds:
idx = torch.randperm(len(Ztr), generator=torch.Generator().manual_seed(100 + s))[: int(frac * len(Ztr))].to(dev)
accs.append(linear_probe(Ztr[idx], ytr[idx], Zte, yte, seed=s))
return float(np.mean(accs)), float(np.std(accs))
print(f"{'representación':30s} " + " ".join(f"{f'{int(100 * f)} % etiquetas':>17s}" for f in (0.01, 0.1, 1.0)))
for name, (Ztr, Zte) in reps.items():
cells = []
for frac, seeds in ((0.01, range(3)), (0.1, range(3)), (1.0, range(1))):
m, sd = label_budget(Ztr, Zte, frac, seeds)
cells.append(f"{m:.3f} ± {sd:.3f}" if len(seeds) > 1 else f"{m:.3f}")
print(f"{name:30s} " + " ".join(f"{c:>17s}" for c in cells))
print("\nSegún la época de preentrenamiento (sonda lineal y k-NN con todas las etiquetas):")
print("época sin aumentos (sonda, k-NN) con aumentos (sonda, k-NN)")
curve = {}
for ep in CHECKPOINTS:
row = []
for snaps in (snaps_rot, snaps_aug):
e = make_encoder(0)
e.load_state_dict(snaps[ep])
Ftr, Fte = features(e, Xtr), features(e, Xte)
row.append((linear_probe(Ftr, ytr, Fte, yte), (knn_eval(Ftr, ytr, Fte) == yte).float().mean().item()))
curve[ep] = row
print(f"{ep:5d} {row[0][0]:12.4f} {row[0][1]:8.4f} {row[1][0]:12.4f} {row[1][1]:8.4f}")npm run lab and open the connection link.Lab measurements with 20 epochs and seed 0 (fixed for repeatability). These are one local GPU run, not published results.
- Pretext is almost solved (test accuracy 0.990 without augmentations, 0.975 with, chance 0.25), still saying nothing by itself about representation.
- Linear probe (10 classes, all labels): pixels 0.846, 128-component PCA 0.839 (as theorem predicts, linear projection adds nothing to the probe), random encoder 0.882, rotation encoder 0.895 and augmented 0.895. Pretraining adds 4.9 points over pixels but only 1.3 over a same-architecture random encoder: most pixel gain comes from convolutional architecture, not pretraining. Without that baseline you would attribute it to the task.
- -NN (, ): pixels 0.861, PCA 0.866, random 0.818, rotation 0.880, augmented rotation 0.869. Here pretraining matters substantially: +6.2 points versus random. Probe and -NN rank representations differently: poor local geometry can hide behind a good linear probe.
- Label efficiency (mean and deviation of three label samples at 1% and 10%): at 1% (600 labels), rotation encoder 0.815 ± 0.007, random 0.773 ± 0.008, pixels 0.774 ± 0.010; at 10%, 0.866, 0.846, 0.829; at 100%, 0.894 (0.895 in the previous table using another validation split), 0.881, 0.846. Pretraining gains over random are 4.2, 2.0 and 1.3 points: fewer labels mean more benefit. PCA trails pixels at 1% (0.731).
- By epoch: probe goes 0.877 (epoch 0, random) to 0.889 at epoch 1 and 0.895 at 20; -NN 0.828 to 0.861 and 0.880. Most gain comes early; later refinement is small.
- Augmentations: translation and noise improve encoder stability (previous figure) but not probe (0.895 both), and slightly hurt -NN (0.869 versus 0.880). Induced invariance is not free: what is ignored must be irrelevant downstream, and garment classification here does not benefit from ignoring three-pixel translation.
Caution: there is one pretraining seed. Table deviations measure changing which labels are used, not repeated pretraining. There is a seed-scale hint: the lab’s two untrained encoders (table “random,” seed 1, and rotation epoch 0, seed 0) give probe 0.882 and 0.877, -NN 0.818 and 0.828: half- and one-point gaps. Against this scale, the probe’s 1.3-point gain and no augmentation effect need several seeds to confirm; -NN’s six points and 1%-label four points exceed it substantially.
This is self-supervision’s geometric footprint: as rotation prediction improves, difficult-pair classes separate along probe direction. But it is not magic or enormous: easy pairs (sandal/sneaker, dress/trousers) are nearly separated by all representations, and for the hardest pair the untrained encoder already helps (shirt/T-shirt: pixels 84.3%, untrained 85.0%, trained 87.7%). The right curve summarizes: early epochs give most improvement and -NN shows it most.
Do not overread the plot. Horizontal axis is exactly what the probe sees and accuracy uses all 2000 pair images, not 240 displayed points; vertical axis is only chosen for height. It is one pair: the lab’s 10-class accuracy summarizes the dataset.
Lab: an honest evaluation protocol (Pyodide)
The second lab implements from scratch in NumPy the protocol serious comparison needs: nested cross-validation for a linear probe (decay chosen in an inner fold seeing training only) and cosine -NN with votes weighted by . It reuses the first cell’s five digit representations. To show cheating’s harm, the table includes accuracy obtained by choosing regularization on the evaluation fold itself.
def estandarizar(Ztr, Zte):
mu, sd = Ztr.mean(0), Ztr.std(0) + 1e-9
return (Ztr - mu) / sd, (Zte - mu) / sd
def ajustar(A, y, lam):
"""Pesos de la sonda de mínimos cuadrados regularizados: una columna por clase y el sesgo en la última fila."""
A1 = np.c_[A, np.ones(len(A))]
return np.linalg.solve(A1.T @ A1 + lam * np.eye(A1.shape[1]), A1.T @ np.eye(10)[y])
def predecir(W, A):
return (np.c_[A, np.ones(len(A))] @ W).argmax(1)
def pliegues(n, k, seed):
return np.array_split(np.random.default_rng(seed).permutation(n), k)
def elegir_lambda(A, y, lams, k=3, seed=0):
"""Validación cruzada interna: solo ve las etiquetas de A."""
folds = pliegues(len(A), k, seed)
punt = [np.mean([(predecir(ajustar(A[np.setdiff1d(np.arange(len(A)), f)], y[np.setdiff1d(np.arange(len(A)), f)], lam), A[f]) == y[f]).mean()
for f in folds]) for lam in lams]
return lams[int(np.argmax(punt))]
def sonda_anidada(Z, y, lams=(0.01, 0.1, 1, 10, 100), externos=5, seed=0):
"""Exactitud de la sonda en cada pliegue exterior: con la regularización elegida solo con el entrenamiento (correcto)
y con la elegida mirando el propio pliegue de evaluación (trampa)."""
bien, trampa = [], []
for i, f in enumerate(pliegues(len(Z), externos, seed)):
tr = np.setdiff1d(np.arange(len(Z)), f)
A, B = estandarizar(Z[tr], Z[f])
bien.append((predecir(ajustar(A, y[tr], elegir_lambda(A, y[tr], lams, seed=i)), B) == y[f]).mean())
trampa.append(max((predecir(ajustar(A, y[tr], lam), B) == y[f]).mean() for lam in lams))
return np.array(bien), np.array(trampa)
def knn_eval(train_z, train_y, test_z, k=10, tau=0.07, n_clases=10):
"""k-NN con similitud coseno (tras centrar con la media del entrenamiento) y votos ponderados por exp(s / tau)."""
mu = train_z.mean(0)
A = train_z - mu
B = test_z - mu
A = A / (np.linalg.norm(A, axis=1, keepdims=True) + 1e-12)
B = B / (np.linalg.norm(B, axis=1, keepdims=True) + 1e-12)
S = B @ A.T
idx = np.argpartition(-S, k - 1, axis=1)[:, :k]
w = np.exp(np.take_along_axis(S, idx, 1) / tau)
votos = np.zeros((len(B), n_clases))
np.add.at(votos, (np.arange(len(B))[:, None], train_y[idx]), w)
return votos.argmax(1)
print(f"{'representación':26s} {'anidada':>13s} {'con trampa':>11s} {'test':>6s} {'k-NN':>6s} {'k-NN uniforme':>14s}")
for nombre, f in codificadores.items():
Ztr, Zte = f(Xtr), f(Xte)
bien, trampa = sonda_anidada(Ztr, ytr)
A, B = estandarizar(Ztr, Zte)
test = (predecir(ajustar(A, ytr, elegir_lambda(A, ytr, (0.01, 0.1, 1, 10, 100))), B) == yte).mean()
knn = (knn_eval(Ztr, ytr, Zte) == yte).mean()
unif = (knn_eval(Ztr, ytr, Zte, tau=1e6) == yte).mean()
print(f"{nombre:26s} {bien.mean():.3f} ± {bien.std():.3f} {trampa.mean():11.3f} {test:6.3f} {knn:6.3f} {unif:14.3f}")Three readings. Probe and -NN rank differently: nested probe favors triangular k-means (0.972) over pixels (0.935), but -NN favors pixels (0.989) over k-means (0.971): digit pixel local geometry is already excellent; linear separability is lacking. Temperature helps modestly: weighted versus uniform votes give pixels 0.989 versus 0.982, NMF 0.916 versus 0.902, random projection 0.922 versus 0.907; PCA ties at 0.982, and uniform wins k-means by 0.002 (0.973 versus 0.971). Tuning on evaluation barely shows here (at most 0.003): five regularization values and 270 images per fold produce small bias. The next cell shows when it grows.
# la trampa crece con el número de configuraciones probadas y con lo pequeño que es el conjunto de evaluación
lams_finos = tuple(10.0 ** np.linspace(-3, 3, 13))
for n_eval in (50, 450):
gan = []
for s in range(20):
g = np.random.default_rng(100 + s)
idx = g.permutation(len(Xtr))[:100] # solo 100 etiquetas de entrenamiento
ev = g.permutation(len(Xte))[:n_eval]
A, B = estandarizar(Xtr[idx], Xte[ev])
honesta = (predecir(ajustar(A, ytr[idx], elegir_lambda(A, ytr[idx], lams_finos, seed=s)), B) == yte[ev]).mean()
trampa = max((predecir(ajustar(A, ytr[idx], lam), B) == yte[ev]).mean() for lam in lams_finos)
gan.append(trampa - honesta)
print(f"test de {n_eval:3d} imágenes: la trampa añade {np.mean(gan):+.3f} de exactitud (media de 20 repeticiones)")With only 100 training labels, 13 regularization values and 50 evaluation images, choosing the best by evaluation adds mean 0.033 accuracy (20 repetitions); with 450 evaluation images, 0.011. Bias grows with configurations and small decision sets, common when comparing dozens of variants. Every decision (epoch, layer, , augmentation) counts as another configuration.
Protocol rules
Thus compare self-supervised methods as follows:
- Do not use test for model decisions. Neither probe hyperparameters, epoch, layer nor . Choose using training-label validation or a separate set.
- Same frozen encoder and probe. Different architectures, epochs or data amounts are not directly comparable: Kolesnikov, Zhai and Beyer (2019) found common CNN design practices do not always transfer to self-supervision, making architecture an experimental factor. If sizes differ, compare equal budgets (parameters or training FLOPs, epochs, data) and report both.
- Always include baselines. Pixels, PCA and especially the random encoder with identical architecture: in the lab an untrained encoder already beats pixels by 3.6 probe points (0.882 versus 0.846); without it pretraining gain is overstated.
- Multiple seeds and label budgets. Few-label results vary strongly with label sample.
- Pretext accuracy is not representation quality. Lab rotation accuracy reaches 97.5–99% but 10-class probes improve only 1.3 points over random.
Connections: bottlenecks and LLM pretraining
Two connections will be revisited later in the course. The first is module 7’s information bottleneck. If we call the quantity the pretext task asks the model to predict, the bottleneck seeks a code that minimizes : it compresses the original data while retaining what predicts the label. This provides a formal account of the central bet in this lesson. The learned representation preserves what the pretext task needs to solve its problem and forgets the rest. It will be useful downstream to the extent that the information needed by the pretext task resembles the information needed by the final task. That is why the design of the pretext task and its augmentations is central to the whole problem.
The second connection is language-model pretraining. Predicting the next token has exactly the structure of a pretext task: specifies the position, is the prefix, and is the token that follows. No human needs to supply a separate label for each example. It requires no hand-engineered invariance because solving the prediction task itself pushes the model to capture syntax, facts and style. What images lack—a natural task whose solution requires semantics—is already present in text. The same broad idea of generating supervision through masking appears in BERT and in masked image autoencoders.
Common mistakes
Exercises
Step 1 of 4. For (a), which argument is correct?
knn_eval(train_z, train_y, test_z, k, tau): for each test_z row select the k nearest train_z neighbors by cosine similarity (without centering) and return the class with largest weight sum . Classes are integers . Tests check hidden-data accuracy against reference and that one very similar neighbor outweighs two mediocre ones when is small, but not when very large.import numpy as np
def knn_eval(train_z, train_y, test_z, k, tau):
"""Devuelve la clase predicha para cada fila de test_z."""
return np.zeros(len(test_z), dtype=int)Summary
- Representation. plus restricted head. Data processing: and equality if is injective; usefulness matters with simple heads and few labels. Measurable properties: separability (probe), invariance, sparsity and effective rank. Disentanglement is not identifiable without inductive biases (Locatello et al., 2019).
- Self-supervision. . Historical pretexts: context and jigsaw (shortcut countermeasures), colorization, rotation (Gidaris, 2018), denoising and masking.
- Invariance. If is invariant to , any inherits it; predicting the applied element above chance is impossible. Augmentations decide what information is discarded and invariance is learned from them.
- Taxonomy. Reconstructive, contrastive, noncontrastive, clustering-based and latent-space predictive; each distinguishes similarity loss and anticollapse mechanism.
- Evaluation. Linear probe ( parameters), weighted cosine -NN with , label efficiency and fine-tuning. Hyperparameters only on training validation, same budget, multiple seeds and baselines (pixels, PCA, random encoder).