Module contents
Lesson 24 of 24Research 115 min

Theory and frontier of self-supervised learning

Why does self-supervised learning work, and what can it guarantee? This lesson examines latent-class bounds, spectral contrastive loss, spectral embeddings and identifiability, then explores JEPA and convergence of representations.

After this lesson you can

  • State the framework of Arora et al. and discuss which assumptions fail in practice.
  • Prove that spectral contrastive loss is a low-rank factorization of the normalized adjacency matrix of the augmentation graph.
  • Explain why nonlinear ICA is not identifiable without assumptions and how auxiliary information or augmentations can make it identifiable.
  • Reproduce recovery of content factors by contrastive learning on synthetic data.
  • Compare reconstruction and latent-space prediction objectives (JEPA) and critically read a recent paper in the field.

Before you start

What a theory should explain

Two views of an image have something in common, but the loss does not know which downstream task will matter to you. If the augmentation removes color, a color classifier will have a problem; if two crops contain different objects, treating them as positives may impose the wrong invariance. A useful theory identifies the assumptions connecting pretraining to a downstream task and indicates when they stop holding.

In this lesson we follow three connections. First, latent classes relate contrastive learning and classification. Next, the augmentation graph turns a loss into a spectral factorization. Finally, a generative model allows us to ask which factors are identifiable. None of these connections claims that every network trained with InfoNCE automatically recovers human concepts.

Latent classes and collisions

If there are CC equiprobable classes, τc=1/C\tau_c = 1/C. A collision is a different image of the same latent class treated as a negative; it need not be an error for every task. What “false” means depends on which distinction you want to preserve.

Arora et al. (2019) relate population contrastive risk to the average risk of classification tasks over those classes. For the specific loss and assumptions of their theorem 4.1, if f^\hat f minimizes empirical risk over MM triplets and representations are bounded, with probability at least 1−δ1-\delta one obtains a bound for the mean classifier of the form

Lsupμ(f^)≤Lun(f)−τc1−τc+GenM1−τc.L_{\mathrm{sup}}^{\mu}(\hat f) \leq \frac{L_{\mathrm{un}}(f)-\tau_c}{1-\tau_c} + \frac{\mathrm{Gen}_M}{1-\tau_c}.

The generalization term depends on the Rademacher complexity of the representation family and the sample size. This is not a bound for any arbitrary metric or loss: the statement uses their task distribution, loss and a specific classifier. As τc\tau_c approaches one, the factor 1/(1−τc)1/(1-\tau_c) reveals a weak guarantee.

Conditional independence fails for two augmentations of the same photograph: in addition to their class they share identity, background and other details. Classes may also overlap and augmentation may change the relevant label. The theory does not apply merely because the code uses a contrastive loss; one must check the sampling mechanism and which task is included in the average.

The mean classifier uses the mean representation of examples for each class. This matters: the bound concerns a specific linear rule and tasks drawn from the same family of classes, not the best downstream network on any distribution. If some classes are frequent, collision depends on the sum of squares of their probabilities, not simply on the number of classes. For example, a distribution (0.9,0.1)(0.9,0.1) has collision probability 0.92+0.12=0.820.9^2+0.1^2=0.82, despite there being two classes. The bound can worsen even when the function represents a particular task well, because it controls an average under a task distribution and loses strength with collisions.

The complexity term also points to a trade-off: a more expressive family may reduce training loss and make it harder to control the gap to the population. The generalization bound does not claim that training finds the global minimum or that a finite sample contains every possible augmentation. In an experiment it is useful to record both out-of-sample performance and stability when positives and negatives change.

The augmentation graph and spectral loss

Imagine that nodes are all possible views and two nodes receive weight if they can occur as views of the same observation. Increasing the probability of crossing classes erases structure that a probe could use. The figure uses a symmetric four-block graph: with probability 1−ε1-\varepsilon the next node is chosen within the class and with ε\varepsilon it is chosen uniformly from all nodes, including its own class. Thus the effective crossing probability is 3ε/43\varepsilon/4 and its spectrum is known exactly. Small points include fixed measurement noise; the nearest-centroid linear probe is fitted on 40 and evaluated on another 40. That noise is part of this example, not the theorem.

InteractiveThe augmentation graph
Two spectral coordinates and noisy measurements
Probability of moving between classes
Three nodes per class. Diagonal: 0.89. Off-diagonal: 0.04.
  • class 1
  • class 2
  • class 3
  • class 4
0.15
Probability of switching classes 3ε/43\varepsilon/40.11
Class eigenvalue 1−ε1-\varepsilon0.85
Gap to the remaining eigenvalues0.85
Linear probe test errors0 / 40 (0.0 %)
Move the mixture between classes. The three class directions have eigenvalue 1−ε1-\varepsilon; as it approaches zero their separation from the rest decreases and noisy measurements become confounded. Large points are spectral centers and small ones are perturbed observations.

The first term attracts positives. The second is a quadratic penalty on independent pairs and prevents all outputs from growing without bound. This is a different loss from NT-Xent, although both use positive and negative pairs. HaoChen et al. (2021) study this graph without requiring positives to be independent given the label.

Proof

The positive term is −2∑ijwijfi⊤fj=−2tr⁡(F⊤AˉF)-2\sum_{ij}w_{ij}f_i\T f_j=-2\tr(\mat F\T\bar{\mat A}\mat F). By independence of negatives, the quadratic term is ∑ijpipj(fi⊤fj)2=∥FF⊤∥F2\sum_{ij}p_ip_j(f_i\T f_j)^2=\|\mat F\mat F\T\|_F^2. Expanding the Frobenius square gives exactly their sum plus ∥Aˉ∥F2\|\bar{\mat A}\|_F^2. Matrix W\mat W is an expectation of outer products and is therefore positive semidefinite; congruence by D−1/2\mat D^{-1/2} preserves that property. The spectral theorem and low-rank approximation give the solution, up to rotations of the columns and ambiguity in tied eigenvalues.

∎

The trivial eigenvector associated with eigenvalue 1 describes stationary mass, not necessarily a class. Group information lies in other directions. A small gap makes the subspace unstable under perturbations; a large gap is not enough if graph groups do not match the task you will evaluate. Connect this interpretation to spectral clustering and Laplacian eigenmaps.

[ ]Factorizing an augmentation graphBrowser
import numpy as np

def graph(eps=0.2, groups=4, per_group=3):
    n = groups * per_group
    block = np.kron(np.eye(groups), np.ones((per_group, per_group)) / per_group)
    return (1 - eps) * block + eps * np.ones((n, n)) / n

A = graph()
n, d = len(A), 4
eigenvalues, eigenvectors = np.linalg.eigh(A)
order = np.argsort(eigenvalues)[::-1]
eigenvalues, eigenvectors = eigenvalues[order], eigenvectors[:, order]
rng = np.random.default_rng(24)
F = rng.normal(scale=0.1, size=(n, d))
for _ in range(1500):
    grad = 4 * (F @ F.T - A) @ F
    F -= 0.05 * grad
U = np.linalg.svd(F, full_matrices=False)[0][:, :d]
projector_error = np.linalg.norm(U @ U.T - eigenvectors[:, :d] @ eigenvectors[:, :d].T)
print('autovalores mayores:', np.round(eigenvalues[:6], 4))
print('brecha entre cuarto y quinto:', round(eigenvalues[3] - eigenvalues[4], 4))
print('diferencia entre proyectores:', round(projector_error, 6))
print('error de factorización:', round(np.linalg.norm(A - F @ F.T), 6))

Compare projectors, not individual columns: multiplying F\mat F by any orthogonal matrix leaves FF⊤\mat F\mat F\T unchanged. The three class directions have the same eigenvalue and may rotate among themselves without changing the solution. In this example ε=0.2\varepsilon=0.2; changing it changes the gap. Do not extrapolate perfect classification on a graph built with labels to real images.

To see the role of the gap, take a graph disconnected by class. Each block admits a constant vector and combinations of those vectors describe its connected components. An augmentation edge between classes couples blocks and changes their spectrum; not every isolated edge destroys the information, but enough connections can make class directions indistinguishable from others. If there is a tie at the boundary between retained and discarded dimensions, small perturbations may choose a different basis. In the simulation, taking ε\varepsilon to 1 makes the class gap disappear: views connect without distinguishing blocks.

The example matrix was chosen using labels so that its spectrum could be known. In a real application the graph is induced by an augmentation distribution and is unknown at population scale. A practical guarantee needs assumptions of within-class connectivity, few harmful cross-class connections and an estimation analysis. HaoChen et al. formulate conditions of that kind and relate them to linear classification; our algebraic identity alone does not guarantee a good probe.

A spectral bridge, not a universal identity

Balestriero and LeCun (2022) relate contrastive and non-contrastive objectives to spectral embedding methods, including global and local methods. In the regimes they analyze, the relation between views becomes an affinity structure, and the solution depends on that structure and on the constraints. Conceptual similarity does not mean that every practical implementation has exactly the same minima: normalization, parametrization, batch size and optimization matter. A neighbor relation misaligned with the task may be harmful even when the objective is minimized.

In a local interpretation, an affinity graph indicates which pairs should remain close, as in Laplacian eigenmaps. A global interpretation also compares geometry over a broader set, as in multidimensional scaling. Regularizers and scale constraints determine which constant or degenerate solutions are excluded. This comparison helps formulate questions: does your augmentation affinity respect downstream labels? What happens if you change its strength? Does the spectrum change because the task is harder or because the batch estimates the graph poorly? Seeing a loss decrease is not enough.

Why nonlinear ICA needs additional information

In linear ICA, independence and non-Gaussianity assumptions constrain the mixture. In arbitrary nonlinear ICA, independence alone does not identify the factors. For example, take U,VU,V independent uniform variables on the torus [0,1)2[0,1)^2 and define U′=UU'=U, V′=(U+V) mod 1V'=(U+V)\bmod 1. The transformation is invertible almost everywhere, U′,V′U',V' remain independent uniform variables and yet V′V' mixes the two factors. The same observable data admit two different independent explanations. The discontinuity of the modular representation does not turn this example into a theorem about all smooth function classes; it suffices to see why independence alone does not solve the problem without fixing the admissible family.

The mechanism extends to a broad family of continuous distributions. For a pair (S1,S2)(S_1,S_2) whose marginal and conditional distributions have continuous, strictly increasing cumulative distribution functions on their supports, define U=F1(S1)U=F_1(S_1) and V=F2∣1(S2∣S1)V=F_{2\mid1}(S_2\mid S_1). The probability integral transform makes UU uniform and VV uniform conditional on S1S_1; therefore they are independent. The inverses of the two functions recover the original pair almost surely. Then Va=(V+aU) mod 1V_a=(V+aU)\bmod1 for any aa preserves that independence and is inverted by subtracting aUaU. Infinitely many independent mixtures are compatible with the same observation. The construction uses regularity and treatment of endpoints; it does not claim that the same formula applies to distributions with atoms.

There is even a smooth ambiguity with Gaussian sources. Let z∼N(0,I2)\vb z\sim\Normal(\vb 0,\mat I_2) and rotate each point by an angle depending smoothly on ∥z∥2\norm{\vb z}^2. The rotation preserves the radius, and in polar coordinates changes the angle by a radius-dependent translation. The isotropic Gaussian distribution is unchanged, so the transformed coordinates remain independent Gaussians. Since the radius is preserved, the transformation is inverted by the opposite rotation; if the angle depends on radius, the mixture is nonlinear. This example does not contradict the assumptions of non-Gaussian linear ICA: the sources in this construction are Gaussian and the transformation is nonlinear.

Auxiliary information can break this ambiguity. Temporal contrastive learning exploits distribution changes between segments; in iVAE latent distributions conditioned on an auxiliary variable satisfy diversity and form conditions. Hyvärinen and Morioka (2016) and Khemakhem et al. (2020) give results under specific assumptions. Check what is identified and up to which transformation before calling a recovered coordinate “causal.”

Content and style under augmentations

In the contrastive identifiability model of von Kügelgen et al. (2021), an observation is generated from content and style; augmentations preserve content and perturb style. Under conditions on the generator, augmentations and objective, the content block is identified up to an invertible transformation. This preserves information about the block, but does not necessarily identify each coordinate or its semantic meaning. Zimmermann et al. (2021) prove another form of inversion under a specific probabilistic model and family of losses; these are not assumption-free guarantees for arbitrary networks.

The figure constructs 600 examples with two content and two style factors, applies an orthogonal rotation followed by tanh⁡\tanh component-wise, and trains an encoder with NT-Xent in the browser. The transformation is invertible on its image. The encoder is pretrained without labels on all 600; the neighbor probe is fitted on 400 and evaluated on the other 200. Thus those 200 are held out for the probe but not for pretraining. A high R2R^2 demonstrates predictive recovery in this experiment, not exact identifiability.

InteractiveContent versus style
Content plane cc: both views of each example
Style plane ss: both views of each example
How much of each factor the embedding retains (nearest-neighbor regression, held-out data)
0100020003000−0.4−0.200.20.40.60.81training steps
  • content cc
  • style ss
  • view 1 (filled) and view 2 (hollow)
0.10
1.00
Training steps0
Content retained (R2R^2)0.00
Style retained (R2R^2)0.00
The readouts depend on training and augmentation. Compare both factors on held-out data.
Perturb style and observe the out-of-sample content R2R^2. Then perturb content or both factors and restart. What information becomes unreliable across views?

Laboratory: an invertible generator and out-of-sample recovery

The following experiment runs InfoNCE on a known generator. Each observation is mixed using an orthogonal matrix and a tanh⁡\tanh nonlinearity, invertible on its image. An augmentation adds noise separately to content and style before mixing. Three encoders are trained from the same initialization and neighbor regressors are fitted on training examples, with evaluation on held-out examples. The printed numbers come from your run, not von Kügelgen et al.; repeating with different seeds shows the variation.

[ ]InfoNCE and content identifiability in a known generatorLocal GPU
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import r2_score

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
rng = np.random.default_rng(24)
latent = rng.uniform(-1, 1, size=(4000, 4)).astype('float32')
Q, _ = np.linalg.qr(rng.normal(size=(4, 4)))
Q = torch.tensor(Q, dtype=torch.float32, device=device)
L = torch.tensor(latent, device=device)

def observe(z):
    return torch.tanh(z @ Q)

def contrastive(z, temperature=0.3):
    z = F.normalize(z, dim=1)
    n2 = len(z)
    logits = z @ z.T / temperature
    logits = logits.masked_fill(torch.eye(n2, dtype=torch.bool, device=z.device), float('-inf'))
    targets = (torch.arange(n2, device=z.device) + n2 // 2) % n2
    return F.cross_entropy(logits, targets)

def train_views(sc, ss, seed=0, steps=2500, batch=128):
    torch.manual_seed(seed)
    net = nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 3)).to(device)
    opt = torch.optim.Adam(net.parameters(), lr=1e-3)
    scale = torch.tensor([sc, sc, ss, ss], device=device)
    for _ in range(steps):
        idx = torch.randint(0, 3000, (batch,), device=device)
        z = L[idx]
        a, b = observe(z + torch.randn_like(z) * scale), observe(z + torch.randn_like(z) * scale)
        loss = contrastive(net(torch.cat([a, b])))
        opt.zero_grad(set_to_none=True)
        loss.backward()
        opt.step()
    with torch.no_grad():
        embedding = F.normalize(net(observe(L)), dim=1).cpu().numpy()
    scores = []
    for target in (latent[:, :2], latent[:, 2:]):
        probe = KNeighborsRegressor(n_neighbors=10, weights='distance').fit(embedding[:3000], target[:3000])
        scores.append(r2_score(target[3000:], probe.predict(embedding[3000:])))
    return float(loss.item()), scores

for name, sc, ss in [('estilo perturbado', 0.0, 1.0), ('contenido perturbado', 1.0, 0.0), ('ambos perturbados', 1.0, 1.0)]:
    outcomes = np.array([train_views(sc, ss, seed=seed)[1] for seed in (0, 1, 2)])
    print(f'{name:24s} R2 contenido {outcomes[:, 0].mean():.3f} ± {outcomes[:, 0].std():.3f}'
          f' R2 estilo {outcomes[:, 1].mean():.3f} ± {outcomes[:, 1].std():.3f}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The experiment provides a positive control because we know the true factors. The two outputs are not enough to conclude that a transformation is invertible: a flexible probe on a finite set may fail or succeed for reasons of capacity and sample size. If σc>0\sigma_c>0, the assumption of exactly invariant content no longer holds.

In a run of the three seeds with the cell parameters, style augmentation gave content R2R^2 0.992±0.0010.992\pm0.001 and style −0.089±0.009-0.089\pm0.009; when content was perturbed, the values were −0.074±0.014-0.074\pm0.014 and 0.991±0.0010.991\pm0.001. With both perturbed they were 0.492±0.1160.492\pm0.116 and 0.429±0.1220.429\pm0.122. The deviations are across three training runs, not confidence intervals. These are results for this model and this probe, not the paper or a guarantee for other augmentations.

To interpret a negative R2R^2, recall that the regressor performs worse than predicting the held-out set mean; it does not mean “negative information.” Recovery depends on the probe model and embedding distance. A stronger probe may read a nonlinear transformation that a linear one misses, but can also overfit. Repeat fitting across seeds, examine both coordinates and separate hyperparameter selection from final evaluation.

Reconstruction and prediction in latent space

A joint embedding predictive architecture learns to predict representations of a target part from context, rather than requiring every pixel. I-JEPA uses a target encoder updated by a moving average and predicts target blocks from a context block. The choice of masks and the way degenerate solutions are avoided are part of the method. The paper does not prove that latent objectives automatically discard every irrelevant detail.

The following model separates two independent Gaussian variables: content of variance 1 and texture of variance σ2\sigma^2. A rank-one linear autoencoder reconstructing both chooses the direction of greatest variance. The second procedure receives the content itself, chosen in advance, as its latent target. Its perfect result is built into the design: this is not I-JEPA training or an empirical comparison between methods. Equal variances give a family of optimal solutions.

InteractiveReconstruct pixels or predict representations
ReconstructionLatent target01
  • linear autoencoder
  • fixed latent target
Here, the latent target is the content chosen in advance. This illustrates the trade-off. A real JEPA would require separate evidence that it discovers this content automatically.
0.6
Texture differential entropy (nats)0.91
Reconstruction: content R2R^21.00
Prediction of fixed content: R2R^21.00
Increase the texture standard deviation. What does the autoencoder preserve when its budget is one dimension? In the predictive model the content target was fixed in advance: consider what additional information that choice introduces.

LeJEPA (2025) proposes regularization toward an isotropic Gaussian distribution for a family of predictive objectives. Its claims of stability and guarantees should be read with the paper’s assumptions, not as a guarantee that every useful task has a single optimal representation.

Optional challenge: a mini JEPA and a reconstruction

This educational laboratory uses 7×77\times7 maps from Fashion-MNIST. In each image a block of 2×22\times2 positions is hidden: one network predicts the target representations of those positions, computed by a moving-average encoder; another predicts average pixels of the same patches. Both encoders share the same architecture and receive the same type of mask, but their objectives differ in scale and difficulty. The protocol does not reproduce I-JEPA or a benchmark from the paper. It records uncentered effective rank and a linear probe of the frozen representations. The first run downloads Fashion-MNIST.

[ ]Mini JEPA versus pixel-patch predictionLocal GPU
import copy
from pathlib import Path
from torchvision.datasets import FashionMNIST
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
root = Path.home() / '.cache' / 'atlas-data'
train_data = FashionMNIST(root, train=True, download=True)
test_data = FashionMNIST(root, train=False, download=True)
X_train = train_data.data.float().div(255).unsqueeze(1)
X_test = test_data.data.float().div(255).unsqueeze(1)
y_train, y_test = train_data.targets.numpy(), test_data.targets.numpy()

def encoder():
    return nn.Sequential(nn.Conv2d(1, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                         nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2)).to(device)

def mask_block(batch, generator):
    mask = torch.zeros(batch, 1, 7, 7, device=device)
    rows = torch.randint(0, 6, (batch,), generator=generator, device=device)
    cols = torch.randint(0, 6, (batch,), generator=generator, device=device)
    for dr in (0, 1):
        for dc in (0, 1):
            mask[torch.arange(batch, device=device), 0, rows + dr, cols + dc] = 1
    return mask

def rankme(z):
    singular = torch.linalg.svdvals(z)
    if singular.sum().item() == 0:
        return 0.0
    p = singular / singular.sum()
    p = p[p > 0]
    return torch.exp(-(p * p.log()).sum()).item()

def train_masked(kind, seed=0, epochs=20, batch=256, m=0.99):
    torch.manual_seed(seed)
    net = encoder()
    head = nn.Conv2d(64, 64 if kind == 'latent' else 1, 1).to(device)
    target = copy.deepcopy(net) if kind == 'latent' else None
    if target is not None:
        for param in target.parameters():
            param.requires_grad_(False)
    opt = torch.optim.Adam(list(net.parameters()) + list(head.parameters()), lr=1e-3)
    generator = torch.Generator(device=device).manual_seed(seed)
    for epoch in range(epochs):
        order = torch.randperm(len(X_train), generator=generator, device=device)
        running, batches = 0.0, 0
        for idx in order.split(batch):
            x = X_train[idx.cpu()].to(device)
            mask = mask_block(len(x), generator)
            context = x * (1 - F.interpolate(mask, size=(28, 28), mode='nearest'))
            pred = head(net(context))
            with torch.no_grad():
                target_value = target(x) if target is not None else F.avg_pool2d(x, 4)
            loss = ((pred - target_value).square() * mask).sum() / (mask.sum() * pred.shape[1])
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step()
            if target is not None:
                with torch.no_grad():
                    for t, s in zip(target.parameters(), net.parameters()):
                        t.mul_(m).add_(s, alpha=1 - m)
            running += loss.item(); batches += 1
        with torch.no_grad():
            z = net(X_train[:1024].to(device)).mean(dim=(2, 3))
            print(f'{kind}, época {epoch + 1}: pérdida {running / batches:.4f}, RankMe {rankme(z):.2f}, norma {z.norm(dim=1).mean().item():.3f}')
    return net

@torch.no_grad()
def encode_images(net, x, batch=512):
    net.eval()
    return torch.cat([net(part.to(device)).mean(dim=(2, 3)).cpu() for part in x.split(batch)]).numpy()

for kind in ('latent', 'pixels'):
    net = train_masked(kind)
    z_train = encode_images(net, X_train[:12000])
    z_test = encode_images(net, X_test)
    probe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500, random_state=0))
    probe.fit(z_train, y_train[:12000])
    print(f'{kind}: sonda lineal de test {probe.score(z_test, y_test):.4f}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

A small latent loss can coexist with collapse. If the norm or spectrum fades, report that result and try another seed or explicit regularization; do not turn absence of collapse into a guarantee. To quantitatively compare real methods, data, compute and protocol must be matched and the experiment repeated.

In one complete run of 20 epochs with seed 0 and a probe fitted on 12,000 examples, test accuracy was 0.8053 for the latent objective and 0.7993 for the pixel objective. These are two measurements from a toy example with one seed, different loss scales and the same test sample: they do not establish general superiority. Runs can vary with hardware and implementation. The result shows what this code produces; it does not claim to reproduce published I-JEPA performance.

The platonic hypothesis and examining a paper

Huh et al. (2024) observe increased alignment between representation neighborhoods of large models in several experiments and propose the hypothesis of convergence toward a shared representation. This is an explanatory hypothesis, not proof of a universal geometry. Their equation 11 compares, for each example, the number of neighbors shared by two representations divided by kk. It depends on the sample, distance, kk and tie-breaking protocol; two representations may share neighbors yet differ in information important for another task.

The following control compares three distinct representations of the same digit images: PCA, NMF and a learned dictionary. They are fitted and evaluated on the same 200 images to illustrate the metric, not to measure generalization. The seed and small iteration count make this a diagnostic experiment, not a replication of the paper’s multimodal models.

[ ]Shared neighbors across three representationsBrowser
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA, NMF, MiniBatchDictionaryLearning
import numpy as np

X_digits = load_digits().data[:200] / 16.0
reps = {
    'PCA': PCA(n_components=8, random_state=0).fit_transform(X_digits),
    'NMF': NMF(n_components=8, init='nndsvda', max_iter=50, random_state=0).fit_transform(X_digits),
    'diccionario': MiniBatchDictionaryLearning(n_components=8, batch_size=64, max_iter=8, random_state=0).fit_transform(X_digits),
}

def mutual_knn_alignment(z1, z2, k):
    def neighbors(z):
        distances = ((z[:, None, :] - z[None, :, :]) ** 2).sum(axis=2)
        np.fill_diagonal(distances, np.inf)
        return np.argsort(distances, axis=1, kind='stable')[:, :k]
    a, b = neighbors(z1), neighbors(z2)
    return np.mean([len(set(x) & set(y)) / k for x, y in zip(a, b)])

for k in (5, 10, 20):
    print('k =', k, {f'{a} / {b}': round(mutual_knn_alignment(reps[a], reps[b], k), 3)
                       for a, b in [('PCA', 'NMF'), ('PCA', 'diccionario'), ('NMF', 'diccionario')]})

To read a recent result, separate the hypothesis from the design: which data entered pretraining, which set and seeds were held out, which architecture and budget were used, what intervention isolated the mechanism and what is the uncertainty interval? Repeat the metric with several kk, seeds and budgets before attributing an improvement to the objective.

Exercises

Quiz
Which assumption of the latent-class model often fails for two crops of the same image?
Quiz
What changes when predicting a target representation instead of pixels?
CodeNeighborhood alignment
Implement mutual_knn_alignment(Z1, Z2, k), with 1 ≤ k < n. Each row represents the same example in both spaces. Exclude the example itself, use Euclidean distance and, for each row, divide the number of shared neighbors by k. Return the average. Break ties by index.
import numpy as np
def mutual_knn_alignment(Z1, Z2, k):
  pass
Shift+Enter to run
Proof
Prove: Spectral loss is equivalent to a factorization of normalized adjacency, up to a constant.
0
Let each row of F be the representation of a view multiplied by the square root of its probability.

Step 1 of 2. What term is produced by the product of F and its transpose?

Proof
Prove: Latent independence is insufficient to identify an arbitrary nonlinear mixture.
0
A marginal and conditional probability integral transform maps a regular continuous pair to independent uniform U and V on the unit interval.

Step 1 of 3. Why is V independent of U?

Summary

Key idea
Self-supervised guarantees depend on how views are generated and on the task. The augmentation graph explains a family of losses as spectral factorization; identifiability requires additional assumptions; latent prediction needs a target and controls that prevent degenerate solutions.