Module contents
Lesson 23 of 24Advanced 110 min

Non-contrastive methods and representation collapse

Without safeguards, learning without negatives can collapse all representations to a constant. Explore complete and dimensional collapse and how predictors, stop-gradient and moving averages help BYOL and SimSiam. Study Barlow Twins and VICReg for redundancy reduction, DeepCluster and SwAV for clustering, and effective rank as a label-free diagnostic.

After this lesson you can

  • Distinguish complete from dimensional collapse and detect each in the representation spectrum.
  • Explain predictors, stop-gradient and exponential moving averages in BYOL and SimSiam.
  • Derive the Barlow Twins and VICReg losses and identify the failure mode each term addresses.
  • Implement Sinkhorn–Knopp for balanced assignments as in SwAV.
  • Compute effective rank with RankMe and use it to select models without labels.

Before you start

Motivation: negatives are expensive and biased

In the previous lesson you learned multi-view contrastive learning: two augmented views of the same image should end up close, while views of different images should be far apart. The decomposition into alignment and uniformity clarified what each half of the loss does: alignment brings positive pairs together and uniformity, driven by negatives, prevents everything from gathering at one point. Negatives have three costs:

  • Compute and memory. The InfoNCE mutual-information bound saturates at log⁡N\log N, requiring many candidates per anchor: huge batches or a momentum-encoder queue.
  • Bias. Negatives come from the unlabeled dataset itself, and some share the anchor’s class: they are false negatives pushed away by the loss even though they should be close. With 10 balanced classes around 10% of negatives are false, and that fraction does not decrease when NN increases.
  • Fine-tuning temperature and batch size, which interact with the previous two points.

This lesson asks whether we can discard the repulsive half and keep only alignment. Phrased this way, the answer is no: alignment loss is minimized by a constant representation. But between 2020 and 2021 four families of methods appeared that learn without negatives and without collapse, each with a different mechanism:

FamilyExamplesWhat prevents collapse
AsymmetricBYOL, SimSiama predictor on one branch and stop-gradient on the other
Redundancy reductionBarlow Twins, VICRegan explicit term on representation covariance
ClusteringDeepCluster, SwAVprototype assignments required to distribute equally
Self-distillationDINOcentering and sharpening outputs of a moving-average teacher

The cost of negatives is visible in batch size. Without negatives, SimSiam gives ImageNet linear accuracy of 66.1% with batches of 64, 68.1% with 256, and 64.0% with 4096 (100 epochs; Chen and He, 2021, table 2): it works equally well with small batches. BYOL describes similar robustness: performance remains stable between 256 and 4096, while SimCLR degrades quickly as batch size decreases (Grill et al., 2020, figure 3a). Self-distillation is developed in the vision module (DINO); here we study the first three families and a tool common to all: measuring collapse without labels.

Complete and dimensional collapse

Let fθ:X→Rdf_\theta: \mathcal{X} \to \R^d be an encoder and z=fθ(x)\vb{z} = f_\theta(\vb{x}) the representation of data point x\vb{x} drawn from the data distribution. Everything that follows centers on its covariance matrix

Σz=Cov⁡(fθ(x))∈Rd×d,λ1≥λ2≥⋯≥λd≥0 sus autovalores.\mat{\Sigma}_z = \Cov\big(f_\theta(\vb{x})\big) \in \R^{d \times d}, \qquad \lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d \ge 0 \text{ sus autovalores}.

Complete collapse is the failure motivating negatives. If you only require the two views to match,

Linv(θ)=Ex, t1, t2∥fθ(t1(x))−fθ(t2(x))∥2  ≥  0,\Loss_{\text{inv}}(\theta) = \E_{\vb{x},\, t_1,\, t_2}\big\|f_\theta(t_1(\vb{x})) - f_\theta(t_2(\vb{x}))\big\|^2 \;\ge\; 0,

and any constant fθf_\theta attains the global minimum 00. This is an available solution: in a network with biases, setting the last-layer weights to zero suffices. Existence of that minimum does not imply every optimization reaches it. Cosine similarity behaves similarly: for nonzero outputs, loss −cos⁡(z1,z2)≥−1-\cos(\vb{z}_1, \vb{z}_2) \ge -1 reaches −1-1 as soon as all outputs point in the same direction.

Dimensional collapse is subtler and much more common. The representation is not constant, loss can look reasonable, and linear probing exceeds chance, but part of the space is dead: several components repeat the same feature or a few directions concentrate all variance. This is the typical failure of methods that do avoid complete collapse.

Spectral diagnosis

Both failures are visible in the spectrum of Σz\mat{\Sigma}_z, estimated using a few thousand unlabeled representations:

  1. Calculate Z∈Rn×d\mat{Z} \in \R^{n \times d} from nn data representations, center columns, and find singular values σk\sigma_k (or covariance eigenvalues λk=σk2/(n−1)\lambda_k = \sigma_k^2/(n-1)).
  2. Plot log⁡λk\log \lambda_k against kk, sorted descending. Complete collapse gives all λk\lambda_k close to zero on an absolute scale; dimensional collapse gives a step after which the curve falls several orders of magnitude.

This is the same reading as PCA’s explained variance, applied to network output. Jing et al. (2022) used it to show dimensional collapse is not exclusive to methods without negatives: in SimCLR with a two-layer projector and 128-dimensional output, trained 100 epochs on ImageNet, several embedding covariance singular values fall to zero. They identify two mechanisms in linear models. One is strong augmentation: in directions where augmentation variance exceeds data variance, weight-matrix singular values vanish. The other is implicit regularization of deep linear networks: layers align and small singular values grow more slowly than large ones, even with mild augmentation. Their proposal, DirectCLR, removes the projector and applies InfoNCE directly to the first d0d_0 representation components: on ImageNet (ResNet-50, 100 epochs), it obtains 62.7% linear accuracy versus 61.1% for SimCLR with a linear projector, 51.5% without a projector, and 66.5% with the usual two-layer projector.

SimSiam proposes an even cheaper complete-collapse diagnostic: the standard deviation of each component of z/∥z∥\vb{z}/\norm{\vb{z}}. If components were independent zero-mean Gaussians, each would have standard deviation near 1/d1/\sqrt{d}; if all outputs point the same way, it falls to zero. This diagnostic misses dimensional collapse; the spectrum does not.

Asymmetric methods: BYOL and SimSiam

BYOL: pursuing a slowly moving target

The update of ξ\xi is the exponential-moving-average weights update used to stabilize generative models, and the idea of averaging iterates comes from iterate averaging in optimization. In BYOL, however, the average is not used for evaluation: it is the target pursued by the online network. With ResNet-50, BYOL reaches 74.3% ImageNet linear accuracy, and 79.6% with a wider ResNet.

The paper’s ablations (table 5a, 300 epochs, τbase=0.99\tau_{\text{base}} = 0.99 as reference) isolate the target’s role:

Target networkLinear accuracy
Fixed and random (τ=1\tau = 1)18.8 %
Moving average, τbase=0.999\tau_{\text{base}} = 0.99969.8 %
Moving average, τbase=0.99\tau_{\text{base}} = 0.9972.5 %
Moving average, τbase=0.9\tau_{\text{base}} = 0.968.4 %
Instantaneous copy of the online network (τ=0\tau = 0)0.3 %

Two observations. Pursuing a fixed random network already teaches something (18.8%, when a random encoder gives 1.4% according to the paper): random-network representations contain information, and predicting them from another view forces its extraction. And if the target moves too quickly (τ=0\tau = 0), training collapses in that configuration.

SimSiam: without a moving average

SimSiam’s ablations (ImageNet, 100 epochs, linear accuracy; reference 67.7%) are the central experiment of this family:

  • Without stop-gradient: 0.1%, chance on ImageNet. Loss reaches its minimum −1-1 immediately and normalized-output standard deviation falls to zero: complete collapse.
  • Without predictor: 0.1%. Complete collapse again.
  • Fixed random predictor: 1.5%. There is no collapse here: loss stays high and training does not converge.
  • Predictor with constant learning rate (without the rest’s decay): 68.1%, slightly better than reference.

With 800 epochs and batches of 256, SimSiam reaches 71.3%; the same table’s BYOL reimplementation, with batches of 4096 and moving average, reaches 74.3%. The authors conclude the momentum encoder can improve accuracy but is not necessary to avoid collapse. Their paper’s note on BYOL version 3 confirms this from the other side: BYOL without moving average reaches 66.9% in 300 epochs if the predictor learning rate is multiplied by 10. Why that rate matters so much has a precise explanation in the next section’s model.

Why does stop-gradient work? Chen and He propose reading SimSiam as an EM-like algorithm. Consider loss with an auxiliary variable ηx\eta_{\vb{x}} per image,

L(θ,η)=Ex,t∥fθ(t(x))−ηx∥2,\Loss(\theta, \eta) = \E_{\vb{x}, t}\big\|f_\theta(t(\vb{x})) - \eta_{\vb{x}}\big\|^2,

and minimize by blocks: with η\eta fixed, take a step in θ\theta (so no gradient flows to the target); with θ\theta fixed, the optimum is ηx=Et[fθ(t(x))]\eta_{\vb{x}} = \E_t[f_\theta(t(\vb{x}))], the mean representation over augmentations. SimSiam approximates that expectation with a single augmentation ηx≈fθ(t′(x))\eta_{\vb{x}} \approx f_\theta(t'(\vb{x})), and predictor hh partially compensates for that approximation: it learns to predict the expectation from one view. The hypothesis explains both pieces’ roles, though it does not prove why iteration avoids the constant solution. That requires analyzing dynamics.

Dynamics without negative pairs in a linear model

Tian, Chen and Ganguli (2021) study the simplest possible version and obtain closed-form dynamics. Data x∈Rn\vb{x} \in \R^n with E[xx⊤]=X\E[\vb{x}\vb{x}\T] = \mat{X}; two views x1=x+e1\vb{x}_1 = \vb{x} + \vb{e}_1, x2=x+e2\vb{x}_2 = \vb{x} + \vb{e}_2 with independent augmentation noise E[ee⊤]=X′\E[\vb{e}\vb{e}\T] = \mat{X}'. Linear online network W∈Rd×n\mat{W} \in \R^{d \times n}, linear predictor Wp∈Rd×d\mat{W}_p \in \R^{d \times d}, and target network Wa\mat{W}_a. The loss, with stop-gradient on the target branch, is

J(W,Wp)=12 E∥WpWx1−sg⁡(Wax2)∥2.J(\mat{W}, \mat{W}_p) = \tfrac12\,\E\big\|\mat{W}_p \mat{W}\vb{x}_1 - \operatorname{sg}(\mat{W}_a \vb{x}_2)\big\|^2.

Its expected gradients follow in a few lines:

r=WpWx1−Wax2\vb{r} = \mat{W}_p\mat{W}\vb{x}_1 - \mat{W}_a\vb{x}_2
Prediction residual.
1/11

This is Tian et al.’s lemma 1. With these equations, the two collapsing ablations can be proved in a few lines.

Proof

(1) Without stop-gradient, loss is a function of W\mat{W} through both branches: J=12E∥pWx1−Wx2∥2J = \tfrac12\E\|p\mat{W}\vb{x}_1 - \mat{W}\vb{x}_2\|^2. Write pWx1−Wx2=(p−1)Wx+pWe1−We2p\mat{W}\vb{x}_1 - \mat{W}\vb{x}_2 = (p-1)\mat{W}\vb{x} + p\mat{W}\vb{e}_1 - \mat{W}\vb{e}_2; the three terms are uncorrelated, so

J=12[(p−1)2tr⁡(WXW⊤)+σ2(1+p2)tr⁡(WW⊤)],∇WJ=W[(p−1)2X+σ2(1+p2)I].J = \tfrac12\Big[(p-1)^2\tr(\mat{W}\mat{X}\mat{W}\T) + \sigma^2(1 + p^2)\tr(\mat{W}\mat{W}\T)\Big], \qquad \grad_{\mat{W}} J = \mat{W}\big[(p-1)^2\mat{X} + \sigma^2(1+p^2)\mat{I}\big].

With W˙=−∇WJ−ηW\dot{\mat{W}} = -\grad_{\mat{W}}J - \eta\mat{W},  ⁣d ⁣dt∥W∥F2=2tr⁡(W⊤W˙)=−2(p−1)2tr⁡(WXW⊤)−2[σ2(1+p2)+η]∥W∥F2≤−2σ2∥W∥F2\frac{\dd}{\dd t}\norm{\mat{W}}_F^2 = 2\tr(\mat{W}\T\dot{\mat{W}}) = -2(p-1)^2\tr(\mat{W}\mat{X}\mat{W}\T) - 2[\sigma^2(1+p^2) + \eta]\norm{\mat{W}}_F^2 \le -2\sigma^2\norm{\mat{W}}_F^2, because tr⁡(WXW⊤)≥0\tr(\mat{W}\mat{X}\mat{W}\T) \ge 0 and 1+p2≥11 + p^2 \ge 1. By Grönwall, ∥W(t)∥F≤e−σ2t∥W(0)∥F\norm{\mat{W}(t)}_F \le e^{-\sigma^2 t}\norm{\mat{W}(0)}_F.

(2) With Wp=I\mat{W}_p = \mat{I} and Wa=τW\mat{W}_a = \tau\mat{W}, the equation for W˙\dot{\mat{W}} in the derivation gives W˙=−W[(1−τ)X+(σ2+η)I]\dot{\mat{W}} = -\mat{W}\big[(1 - \tau)\mat{X} + (\sigma^2 + \eta)\mat{I}\big], and the same calculation gives  ⁣d ⁣dt∥W∥F2=−2(1−τ)tr⁡(WXW⊤)−2(σ2+η)∥W∥F2≤−2σ2∥W∥F2\frac{\dd}{\dd t}\norm{\mat{W}}_F^2 = -2(1-\tau)\tr(\mat{W}\mat{X}\mat{W}\T) - 2(\sigma^2 + \eta)\norm{\mat{W}}_F^2 \le -2\sigma^2\norm{\mat{W}}_F^2.

∎

The first part is the simplest case of Tian et al.’s theorem 2, which extends it to general predictors under a condition on their eigenvalues. In this model, without stop-gradient the target-branch gradient contributes to dynamics leading to the trivial solution; without a predictor, the online network pursues a copy of itself with added noise and a constant output minimizes loss. These observations do not prove every nonlinear network collapses under every optimizer.

The predictor saves the representation, direction by direction

With a predictor, the analysis requires more structure. Tian et al. assume X=I\mat{X} = \mat{I}, X′=σ2I\mat{X}' = \sigma^2\mat{I}, Wa=τW\mat{W}_a = \tau\mat{W}, and symmetric Wp\mat{W}_p commuting with F=WW⊤\mat{F} = \mat{W}\mat{W}\T. Then both matrices are diagonalized in the same basis and the system separates into scalar equations for eigenvalues pjp_j of Wp\mat{W}_p and sjs_j of F\mat{F}:

p˙j=αp sj[τ−(1+σ2)pj]−η pj,s˙j=2pj sj[τ−(1+σ2)pj]−2η sj.\dot p_j = \alpha_p\,s_j\big[\tau - (1+\sigma^2)p_j\big] - \eta\,p_j, \qquad \dot s_j = 2p_j\,s_j\big[\tau - (1+\sigma^2)p_j\big] - 2\eta\,s_j.

To see dimensional collapse, let each direction have its own variance. If X=diag⁡(x1,…,xn)\mat{X} = \diag(x_1, \dots, x_n) and W\mat{W}, Wp\mat{W}_p are diagonal in that basis (with d=nd = n), the derivation above gives, for each direction with variance xx, weight ww, and predictor eigenvalue pp:

p˙=αp w2[τx−(x+σ2)p]−η p,w˙=w(p[τx−(x+σ2)p]−η).\dot p = \alpha_p\,w^2\big[\tau x - (x + \sigma^2)p\big] - \eta\,p, \qquad \dot w = w\Big(p\big[\tau x - (x + \sigma^2)p\big] - \eta\Big).

With x=1x = 1 and s=w2s = w^2 these are Tian et al.’s equations. Three consequences, checked below on the full model without assuming anything diagonal:

A conservation law. Combining the two equations,  ⁣d ⁣dt(p2−αpw2)=−2η(p2−αpw2)\frac{\dd}{\dd t}\big(p^2 - \alpha_p w^2\big) = -2\eta\big(p^2 - \alpha_p w^2\big). With weight decay, the difference is forgotten exponentially and dynamics end on curve w2=p2/αpw^2 = p^2/\alpha_p; without weight decay, the initial condition is never forgotten. On that curve, p˙=p(p[τx−(x+σ2)p]−η)\dot p = p\big(p[\tau x - (x+\sigma^2)p] - \eta\big).

A weight-decay threshold. Function p [τx−(x+σ2)p]p\,[\tau x - (x+\sigma^2)p] reaches its maximum τ2x2/(4(x+σ2))\tau^2x^2/(4(x+\sigma^2)) at p=τx/(2(x+σ2))p = \tau x/(2(x+\sigma^2)). If

η>η∗(x)=τ2x24(x+σ2),\eta > \eta^*(x) = \frac{\tau^2 x^2}{4(x + \sigma^2)},

then p˙<0\dot p < 0 for every p>0p > 0 and the direction turns off. If η<η∗\eta < \eta^*, there are two nonzero fixed points, roots p−<p+p_- < p_+ of (x+σ2)p2−τx p+η=0(x+\sigma^2)p^2 - \tau x\,p + \eta = 0: p+p_+ is stable, p−p_- unstable and separates the collapse basin (p<p−p < p_-, ending at p=0p = 0) from the useful solution’s basin. With x=1x = 1 this is Tian et al.’s condition η≤τ2/(4(1+σ2))\eta \le \tau^2/(4(1+\sigma^2)). Directions with little signal relative to augmentation (small ratio x/(x+σ2)x/(x+\sigma^2)) have low thresholds and large collapse basins: they die first. This is how dimensional collapse appears.

The predictor sets amplitude. At the fixed point, representation standard deviation in that direction is x ∣w∣=x p+/αp\sqrt{x}\,\abs{w} = \sqrt{x}\,p_+/\sqrt{\alpha_p}. A faster predictor (larger αp\alpha_p) shrinks the collapse basin but also the amplitude. And when η→0\eta \to 0 and τ=1\tau = 1, p+→x/(x+σ2)p_+ \to x/(x+\sigma^2): the predictor learns to attenuate each direction according to its signal-to-noise ratio, like a Wiener filter.

What about the moving average? At steady state Wa=W\mat{W}_a = \mat{W} and τ=1\tau = 1, so it does not change fixed points. Tian et al. describe it as an automatic curriculum: initially τ\tau is small and target pjp_j is too, and τ\tau grows as the network learns; without it, with a symmetric predictor, they found stable training only with αp>1\alpha_p > 1. In real SimSiam the predictor is neither symmetric nor linear and its rate tuning serves as that curriculum.

InteractiveCollapse lab
Standard deviation of the representation in each direction, λj(WXW⊤)\sqrt{\lambda_j(\mat{W}\mat{X}\mat{W}^\top)}
  • dir. 1 (var. 2.0)
  • dir. 2 (var. 1.5)
  • dir. 3 (var. 1.0)
  • dir. 4 (var. 0.70)
  • dir. 5 (var. 0.45)
  • dir. 6 (var. 0.30)
Loss 12 E∥WpWx1−Wax2∥2\tfrac12\,\E\|\mat{W}_p\mat{W}\vb{x}_1 - \mat{W}_a\vb{x}_2\|^2
Recipe
0.010
1.00
0.50
Complete collapse: every direction vanishes and the representation is constant.
Final min. / max. standard deviation0.000 / 0.000
Largest standard deviation0.0001
Effective rank (from those standard deviations)unreliable
Final / maximum loss0.0000 / 0.105
Target without gradientsmoving average
The loss fell to nearly zero. Judging by loss alone, this training run would look perfect.
Linear Siamese network with six directions of variances 2, 1.5, 1, 0.7, 0.45, and 0.3 and isotropic augmentation variance σ², trained for 4000 gradient-descent steps with exact expected gradients. Start without a predictor: loss drops almost to zero as all six standard deviations sink. Activate the predictor (SimSiam or BYOL recipe) and see how many directions survive. Then raise weight decay to 0.1 and 0.2, and try α_p = 10. This is the same model and initialization as the next cell.

Lab: dynamics in NumPy

The first cell implements the full model without assuming diagonal structure: matrices 6×66 \times 6, exact expected gradients, step 0.050.05, 4000 steps, moving average Wa←0.99 Wa+0.01 W\mat{W}_a \leftarrow 0.99\,\mat{W}_a + 0.01\,\mat{W}, and deterministic pseudorandom initialization (the same as the interactive). Try all five recipes: BYOL, SimSiam, and three ablations.

[ ]Collapse dynamics in the linear modelBrowser
import numpy as np

XV = np.array([2.0, 1.5, 1.0, 0.7, 0.45, 0.3])   # varianzas de los datos en su base propia: X = diag(XV)
n = d = len(XV)

def hash_init(r, c, off, amp=0.25):
    """Inicialización pseudoaleatoria determinista (la misma que usa el interactivo)."""
    i, j = np.meshgrid(np.arange(1, r + 1), np.arange(1, c + 1), indexing="ij")
    v = np.sin(12.9898 * i + 78.233 * j + off) * 43758.5453
    return amp * (v - np.floor(v) - 0.5)

def run(pred=True, sg=True, ema=True, eta=0.01, ap=1.0, s2=0.5, steps=4000, lr=0.05, m=0.99):
    """Descenso por gradiente sobre J = 1/2 E||Wp W x1 - Wa x2||^2 con los gradientes esperados exactos.
    Devuelve las desviaciones típicas de la representación en sus direcciones principales, la pérdida y W."""
    X, XX = np.diag(XV), np.diag(XV + s2)          # E[x2 x1^T] = X,  E[x1 x1^T] = X + sigma^2 I
    W = hash_init(d, n, 0.0)
    Wp = hash_init(d, d, 3.7) if pred else np.eye(d)
    Wa = W.copy()
    for t in range(steps):
        tgt = Wa if ema else W
        R = Wp @ W @ XX - tgt @ X                  # E[r x1^T]
        gW = Wp.T @ R
        if not sg and not ema:                     # el gradiente también fluye por la rama objetivo
            gW -= Wp @ W @ X - W @ XX
        gWp = R @ W.T
        W = W - lr * (gW + eta * W)
        if pred:
            Wp = Wp - lr * (ap * gWp + eta * Wp)
        if ema:
            Wa = m * Wa + (1 - m) * W
    tgt = Wa if ema else W
    WpW = Wp @ W
    loss = 0.5 * np.trace(WpW @ XX @ WpW.T - 2 * tgt @ X @ WpW.T + tgt @ XX @ tgt.T)
    sd = np.sqrt(np.clip(np.linalg.eigvalsh(W @ X @ W.T)[::-1], 0, None))
    return sd, loss, W

recetas = {
    "BYOL (predictor y EMA)":      dict(),
    "SimSiam (predictor sin EMA)": dict(ema=False),
    "BYOL sin predictor":          dict(pred=False),
    "SimSiam sin predictor":       dict(pred=False, ema=False),
    "SimSiam sin stop-gradient":   dict(ema=False, sg=False),
}
print("desviaciones típicas finales de la representación y pérdida final")
for nombre, kw in recetas.items():
    sd, loss, _ = run(**kw)
    print(f"{nombre:28s} {np.array2string(sd, precision=4, suppress_small=True)}  pérdida {loss:.4f}")

The two predictor recipes end practically at the same place (standard deviations 1.1244 and 1.1245 in the first direction): in this model the moving average does not change the destination. All three ablations collapse completely, all with loss 0.00000.0000, while working recipes end with loss near 0.9: lower loss corresponds to the worst representation. Also notice the sixth direction, variance 0.3: it dies even with a predictor. The second cell explains why by comparing the simulation with theoretical fixed points.

[ ]Weight-decay threshold and predictor rateBrowser
s2 = 0.5
umbral = XV**2 / (4 * (XV + s2))                   # eta* de cada dirección, con tau = 1
print("umbral de weight decay eta* por dirección:", np.array2string(umbral, precision=4))

def teoria(eta, ap):
    """Desviación típica en el punto fijo estable, sqrt(x) p+ / sqrt(alpha_p), o 0 si eta > eta*."""
    disc = XV**2 - 4 * eta * (XV + s2)
    p = np.where(disc >= 0, (XV + np.sqrt(np.clip(disc, 0, None))) / (2 * (XV + s2)), 0.0)
    return np.sqrt(XV) * p / np.sqrt(ap)

print("\nweight decay (alpha_p = 1): direcciones vivas, simulación y punto fijo teórico")
for eta in [0.0, 0.01, 0.05, 0.1, 0.2]:
    sd = run(eta=eta)[0]
    print(f"  eta = {eta:4.2f}: {int((sd > 1e-2).sum())} vivas  sim {np.array2string(sd, precision=3, suppress_small=True)}"
          f"  teoría {np.array2string(teoria(eta, 1.0), precision=3)}")

print("\ntasa relativa del predictor (eta = 0.01)")
for ap in [0.3, 3.0, 10.0]:
    sd = run(ap=ap)[0]
    print(f"  alpha_p = {ap:4.1f}: {int((sd > 1e-2).sum())} vivas  sim {np.array2string(sd, precision=3, suppress_small=True)}"
          f"  teoría {np.array2string(teoria(0.01, ap), precision=3)}")

Theory matches each surviving direction to a thousandth: with η=0.01\eta = 0.01 it predicts 1.124, 0.91, 0.657, and 0.476 for the first four, while simulation gives 1.124, 0.911, 0.656, and 0.476, although matrix W\mat{W} began without any diagonal structure. What fixed-point theory does not decide is which destination each direction reaches; the collapse basin governs that:

  • The sixth direction (x=0.3x = 0.3, η∗=0.0281\eta^* = 0.0281) has a stable fixed point with η=0.01\eta = 0.01, but initialization leaves it in the collapse basin and it dies. With αp=10\alpha_p = 10 the basin shrinks and it survives, with amplitude 0.061 predicted by theory (0.059). In exchange, all amplitudes are divided by 10\sqrt{10}.
  • With η=0.05\eta = 0.05 the fifth direction dies, which has η∗=0.0533\eta^* = 0.0533: it is below threshold but so close that its collapse basin is huge. With η=0.1\eta = 0.1 the fourth also dies, whose threshold (0.1021) barely exceeds η\eta.
  • With η=0.2\eta = 0.2 theory still has two directions with stable fixed points (η∗=0.4\eta^* = 0.4 and 0.28120.2812), but simulation collapses entirely: weight decay enlarges collapse basins and both lie inside. The threshold is necessary, not sufficient.

This is SimSiam’s predictor ablation and the BYOL v3 note in miniature: predictor rate and weight decay jointly decide how many dimensions survive.

Redundancy reduction: Barlow Twins

Asymmetric methods avoid collapse through training dynamics; no loss forbids it. The second family forbids it in the objective itself. The idea comes from neuroscientist Horace Barlow (1961): a good sensory code should reduce redundancy, transforming highly correlated signals into independent components.

The invariance term asks each component to have the same value in the two views after standardization; redundancy asks distinct components to be uncorrelated. With λ>0\lambda > 0, loss is exactly zero when C=I\mat{C} = \mat{I}: the two views give the same standardized representation and its components are decorrelated, meaning the representation is whitened in the sense of Gaussian whitening. That equality requires nonconstant columns and, since they are centered in a batch of BB samples, at least B≥d+1B \ge d + 1; it is not always attainable. An exercise asks you to prove equivalence when correlations are defined.

Why does this prevent collapse? Complete collapse is excluded because CijC_{ij} divides by standard deviations: a constant component has undefined correlation and in practice (with ε\varepsilon in the denominator) gives Cii≈0C_{ii} \approx 0 and pays the entire invariance penalty. Dimensional collapse, however, is compatible with the invariance term: if every component copies the same invariant feature, all CiiC_{ii} are near 1. The redundancy term prevents it because those copies have Cij≈±1C_{ij} \approx \pm 1.

The paper’s numbers: a three-layer projector of 8192 units, λ=5⋅10−3\lambda = 5 \cdot 10^{-3}, batches of 2048, and 1000 epochs give 73.2% ImageNet linear accuracy (91.0% top-5). Ablations (table 5, 300-epoch reference at 71.4%) separate the two terms:

VariantLinear accuracy
Full Barlow Twins71.4 %
Invariance only (diagonal)57.3 %
Redundancy only (off diagonal)0.1 %
Normalize across features instead of the batch69.8 %

Without the redundancy term, accuracy remains 57.3%, above chance, but that number alone does not determine representation rank; repeated features illustrate possible dimensional collapse. Without the invariance term, accuracy is chance in this ablation. The paper also notes it works with batches as small as 256, without predictor, stop-gradient, or moving average, and unlike SimCLR and BYOL continues improving as projector dimension increases under the studied conditions.

InteractiveThe cross-correlation matrix
Cross-correlation C\mat{C} between views (step 400)
0.930.04−0.020.020.000.970.000.000.02−0.010.950.02−0.070.00−0.020.97B1A1B2A2B3A3B4A4
Correlation spectrum of view A, 1BZ^A⊤Z^A\tfrac1B\hat{\mat{Z}}_A^\top\hat{\mat{Z}}_A. The dashed line marks 1.
1.01λ11.01λ21.00λ30.98λ4
The two loss terms during training (log scale)
  • invariance
  • redundancy
Redundancy weight λ\lambda
Output dimension dd
step 400
Invariance ∑i(1−Cii)2\sum_i (1 - C_{ii})^20.009
Redundancy ∑i≠jCij2\sum_{i \neq j} C_{ij}^20.008
Diagonal CiiC_{ii}: minimum / maximum0.93 / 0.97
Largest off-diagonal ∣Cij∣|C_{ij}|0.07
Effective rank of one view4.00 of 4
Linear encoder from R^10 to R^d trained with Barlow Twins on toy data with exactly 4 invariant directions between views (content), 4 view-specific directions (style), and isotropic noise. With λ = 0.05 and d = 4, the diagonal rises nearly to 1 and the rest fades. Set λ = 0: the diagonal remains high, but all components correlate and one eigenvalue dominates a view’s spectrum. Then choose d = 6: there are not six invariant directions, and with large λ two components end with low diagonal values.

The interactive shows something the summary “the diagonal tends to 1” hides: the diagonal can approach 1 in only as many components as the data have invariant directions. With d=6d = 6 and four invariant directions, loss must choose between repeating content (paying redundancy) and using each view’s style (paying invariance), with λ\lambda deciding the tradeoff. The diagonal ceiling is not exactly 1 either: isotropic data noise makes even content directions differ somewhat between views.

VICReg: variance, invariance, and covariance

Barlow Twins combines invariance and decorrelation in one matrix and couples them through normalization. Bardes, Ponce and LeCun (2022) separate the three requirements into three terms.

Each term has a unique role:

  • Invariance ss: both views must give the same representation. Alone, it collapses.
  • Variance vv: a hinge requiring standard deviation at least γ\gamma in every component. It excludes complete collapse but allows all components to be identical.
  • Covariance cc: drives covariances between distinct components to zero. It excludes dimensional collapse by repetition.

The hinge acts on standard deviation, not variance, for a gradient reason. For column zj∈Rn\vb{z}^j \in \R^n, ∇Var⁡(zj)=2(zj−zˉj1)/(n−1)\grad \Var(\vb{z}^j) = 2(\vb{z}^j - \bar z^j\vb{1})/(n-1), whose norm 2sd⁡(zj)/n−12\operatorname{sd}(\vb{z}^j)/\sqrt{n-1} vanishes exactly when the component collapses; in contrast, ∇sd⁡(zj)=(zj−zˉj1)/((n−1)sd⁡(zj))\grad \operatorname{sd}(\vb{z}^j) = (\vb{z}^j - \bar z^j\vb{1})/\big((n-1)\operatorname{sd}(\vb{z}^j)\big) has norm 1/n−11/\sqrt{n-1} at any scale. As the authors note, with variance in the hinge, gradient dies precisely as the component approaches its mean and representations collapse; with standard deviation, the hinge keeps pushing equally hard even when the component is nearly dead. ε\varepsilon avoids division by zero at exact collapse, at the cost of weakening the push when standard deviation drops below ε=0.01\sqrt\varepsilon = 0.01.

VICReg reaches 73.2% ImageNet linear accuracy (91.1% top-5), matching Barlow Twins, without normalizing representations or sharing branch architecture. Without the variance term it collapses in the paper’s ablation. Table 4 adds the variance term to asymmetric methods: BYOL rises from 69.3% to 70.2%, SimSiam from 67.9% to 68.1%. SimSiam without BatchNorm, retaining predictor and stop-gradient, obtains 35.1% without additional regularization; the table distinguishes that configuration from others that collapse.

InteractiveEach VICReg term prevents a failure
Linear encoder from R^10 to R^4 trained for 600 Adam steps with VICReg on toy data (five groups in 4 content directions, plus view-specific style). In this four-dimensional toy covariance needs a larger weight than the paper’s ν = 1: start at λ = μ = ν = 25. Turn off variance: complete collapse. Re-enable it and disable covariance: each component has standard deviation 1, but all repeat the same direction. Disable invariance: rank is full, but view pairs remain far apart and groups mix. Finally, return to ν = 1 with all enabled.

The caption’s final step merits explanation. The paper’s weights are tuned for 8192-dimensional outputs and deep encoders. In a four-dimensional toy, with ν=1\nu = 1 invariance weighs so heavily that loss benefits from repeating directions and paying some covariance, and effective rank falls below 4: partial dimensional collapse with all terms active. VICReg weights are not universal; their relation to dimension and augmentation strength is tuned, and effective rank at the lesson’s end enables doing so without labels.

Clustering methods: DeepCluster and SwAV

The third family changes the question. Instead of directly comparing representations of two views, it assigns each representation to a group and asks both views to fall in the same group.

DeepCluster (Caron et al., 2018) alternates two steps each epoch: cluster features of the entire dataset using the k-means objective (after reducing to 256 dimensions by PCA, whitening, and normalization), and train the network to classify images by those pseudo-labels. The best number of ImageNet groups was k=10 000k = 10\,000, not the 1000 classes. The paper identifies two trivial solutions and remedies them:

  • Empty groups. If a group has no points, replace its centroid with a nonempty group’s centroid plus a small perturbation, and split that group’s points between them.
  • Trivial parameterization. If almost all images fall into few groups, the network can always predict the same thing. The remedy is to sample images uniformly over pseudo-labels, equivalent to weighting each image’s loss inversely by group size.

With AlexNet, DeepCluster achieved 36.1% linear accuracy on ImageNet’s conv5 layer, versus 32.8% for the best previous method. Its limitation is needing full passes over the dataset for k-means.

SwAV (Caron et al., 2020) clusters online within each batch. It maintains KK learnable prototypes c1,…,cK\vb{c}_1, \dots, \vb{c}_K (unit vectors, columns of C\mat{C}) and, for each view with normalized representation z\vb{z}, calculates a code q\vb{q}, a distribution over prototypes. Loss is swapped prediction: view tt predicts the code of view ss and vice versa,

L(zt,zs)=ℓ(zt,qs)+ℓ(zs,qt),ℓ(zt,qs)=−∑kqs(k)log⁡exp⁡(zt⊤ck/τ)∑k′exp⁡(zt⊤ck′/τ).L(\vb{z}_t, \vb{z}_s) = \ell(\vb{z}_t, \vb{q}_s) + \ell(\vb{z}_s, \vb{q}_t), \qquad \ell(\vb{z}_t, \vb{q}_s) = -\sum_k q_s^{(k)} \log \frac{\exp(\vb{z}_t\T\vb{c}_k/\tau)}{\sum_{k'}\exp(\vb{z}_t\T\vb{c}_{k'}/\tau)}.

Codes receive no gradient (another stop-gradient). If calculated with per-image softmax, the trivial solution would send everything to one prototype. SwAV calculates them for the whole batch by solving an optimal transport problem with an equipartition constraint: with Z∈Rd×B\mat{Z} \in \R^{d \times B} the batch representations in columns,

max⁡Q∈Q  tr⁡(Q⊤C⊤Z)+ε H(Q),Q={Q∈R+K×B:Q1B=1K1K,  Q⊤1K=1B1B},\max_{\mat{Q} \in \mathcal{Q}}\; \tr\big(\mat{Q}\T\mat{C}\T\mat{Z}\big) + \varepsilon\,H(\mat{Q}), \qquad \mathcal{Q} = \Big\{\mat{Q} \in \R_+^{K \times B} : \mat{Q}\vb{1}_B = \tfrac1K\vb{1}_K,\; \mat{Q}\T\vb{1}_K = \tfrac1B\vb{1}_B\Big\},

with H(Q)=−∑kbQkblog⁡QkbH(\mat{Q}) = -\sum_{kb} Q_{kb}\log Q_{kb}. Each prototype receives exactly 1/K1/K of batch mass. The paper’s values are K=3000K = 3000, τ=0.1\tau = 0.1, ε=0.05\varepsilon = 0.05, and three Sinkhorn iterations; continuous codes are used (rounding to the dominant prototype worked worse) and, for small batches, a queue of about 3840 recent representations supplies enough samples per prototype. With multi-crop (two 224-pixel views and six 96-pixel views), it reaches 75.3% ImageNet linear accuracy with ResNet-50. In the 400-epoch ablation configuration, multi-crop raises SwAV from 70.1% to 74.1%, and an improved DeepCluster version (DeepCluster-v2) performs similarly: 70.2% and 74.3%.

Equipartition with Sinkhorn–Knopp

The code problem has a closed-form solution apart from two vectors. With multipliers αk\alpha_k for rows and βb\beta_b for columns, the Lagrangian stationarity condition at Qkb>0Q_{kb} > 0 is

Skb−ε (log⁡Qkb+1)−αk−βb=0⟹Qkb=uk eSkb/ε vb,S_{kb} - \varepsilon\,(\log Q_{kb} + 1) - \alpha_k - \beta_b = 0 \quad\Longrightarrow\quad Q_{kb} = u_k\, e^{S_{kb}/\varepsilon}\, v_b,

with S=C⊤Z\mat{S} = \mat{C}\T\mat{Z}, uk=e−αk/ε−1/2u_k = e^{-\alpha_k/\varepsilon - 1/2}, and vb=e−βb/ε−1/2v_b = e^{-\beta_b/\varepsilon - 1/2}. The objective is strictly concave (because of entropy) on a compact convex set, so the optimum is unique, and positive because the derivative of −Qlog⁡Q-Q\log Q diverges at 00. Finding u\vb{u} and v\vb{v} means rescaling rows and columns of positive matrix eS/εe^{\mat{S}/\varepsilon} until it has the required marginals. The Sinkhorn–Knopp algorithm alternates the two rescalings:

Q←diag⁡(1K / Q1B) Q,Q←Q diag⁡(1B / Q⊤1K).\mat{Q} \leftarrow \diag\big(\tfrac{1}{K}\,/\,\mat{Q}\vb{1}_B\big)\,\mat{Q}, \qquad \mat{Q} \leftarrow \mat{Q}\,\diag\big(\tfrac1B\,/\,\mat{Q}\T\vb{1}_K\big).

Sinkhorn proved (1964 for doubly stochastic matrices, 1967 for arbitrary marginals) that every positive-entry matrix admits diagonal scaling to the required marginals, unique up to a factor, and alternation converges to it; Cuturi (2013) made it a standard tool for regularized optimal transport, since each iteration is two matrix-vector products. Convergence slows as ε\varepsilon decreases, and in double precision eS/εe^{S/\varepsilon} overflows if S/εS/\varepsilon exceeds about 709; robust implementations therefore work with log⁡Q\log\mat{Q} and log-sum-exp.

What does equipartition achieve against collapse? If all batch representations were equal, all columns of S\mat{S} would be equal and balanced codes uniform: q=1K1\vb{q} = \frac1K\vb{1}. Cross-entropy ℓ\ell would be at least log⁡K\log K. If model and data permit splitting the batch into groups with nearly deterministic codes predictable across views, such a solution can have lower loss. Equipartition rules out assigning all mass to one prototype, but does not itself eliminate the collapsed uniform-code solution or guarantee optimization avoids it.

InteractiveSinkhorn distributes prototypes
Batch and prototypes (color marks the dominant prototype in the code)
c1c2c3c4
Mass of each prototype (outline at step 0)
equilibrio3.21c10.37c20.00c30.41c4
Codes qb\vb{q}_b (columns of BQB\mat{Q}), with samples sorted by angle
c1c2c3c4
Marginal error at each step (log scale)
  • prototype c1
  • prototype c2
  • prototype c3
  • prototype c4
step 0: softmax per sample
±54°
0.050
Step0
Largest normalized mass (1 = balanced)3.21
Samples per prototype (largest code entry)19 2 0 3
Largest deviation from target marginals2.2138
Mean / maximum entropy (nats)0.114 / 1.386
Without equal allocation, prototype 1 takes 80% of the mass. Training to predict these codes pushes the whole batch toward one prototype.
Twenty-four unit representations concentrated around prototype c1, and four prototypes. At step 0 (per-sample softmax, no equipartition), almost all mass falls on c1; dashed bar outlines retain that state. Play iterations: odd steps rescale rows (each prototype to mass 1/K), even steps columns (each sample to 1/B). Observe which samples move to c3, the opposite prototype. Then lower ε to 0.01 and raise it to 1: compare code sharpness and how many steps error takes to fall.

Notice the final assignment with a concentrated batch: Sinkhorn sends to c3 (at 180°) the samples closest to it, even though they are within 60° of c1. The assignment does not respect local geometry; it respects the constraint. That tension is the training signal: to lower loss, the network must separate representations so balanced assignment is natural too.

Lab: Sinkhorn in NumPy

The cell implements Sinkhorn–Knopp in the log domain on a nearly collapsed batch (256 unit representations in R16\R^{16} around one direction, 10 random prototypes), checks marginals, solution form diag⁡(u) eS/εdiag⁡(v)\diag(\vb{u})\,e^{\mat{S}/\varepsilon}\diag(\vb{v}), and the effect of ε\varepsilon, and shows why the direct version fails with small ε\varepsilon.

[ ]Sinkhorn–Knopp, equipartition, and stabilityBrowser
import numpy as np

def logsumexp(A, axis):
    m = A.max(axis=axis, keepdims=True)
    return m + np.log(np.exp(A - m).sum(axis=axis, keepdims=True))

def sinkhorn_log(S, eps, n_iter):
    """S: puntuaciones K x B. Devuelve Q (K x B) con filas que suman 1/K y columnas 1/B, en el dominio logarítmico."""
    K, B = S.shape
    L = S / eps
    for _ in range(n_iter):
        L = L - logsumexp(L, axis=1) - np.log(K)    # cada prototipo recibe masa 1/K
        L = L - logsumexp(L, axis=0) - np.log(B)    # cada muestra reparte masa 1/B
    return np.exp(L)

def sinkhorn_directo(S, eps, n_iter):
    """La versión directa: exp(S/eps) y reescalados. Desborda si S/eps es grande."""
    K, B = S.shape
    Q = np.exp(S / eps)
    Q /= Q.sum()
    for _ in range(n_iter):
        Q /= Q.sum(axis=1, keepdims=True) * K
        Q /= Q.sum(axis=0, keepdims=True) * B
    return Q

# un lote casi colapsado: 256 representaciones unitarias alrededor de una misma dirección, 10 prototipos
rng = np.random.default_rng(0)
B, K, dim = 256, 10, 16
mu = rng.normal(size=dim)
Z = mu / np.linalg.norm(mu) + 0.1 * rng.normal(size=(B, dim))
Z /= np.linalg.norm(Z, axis=1, keepdims=True)
C = rng.normal(size=(dim, K))
C /= np.linalg.norm(C, axis=0, keepdims=True)
S = C.T @ Z.T                                       # K x B, cosenos

eps = 0.05
P = np.exp(S / eps - logsumexp(S / eps, axis=0))     # softmax por muestra: sin equipartición
print("sin Sinkhorn, muestras por prototipo (máximo del código):", np.bincount(P.argmax(0), minlength=K))
for it in [1, 3, 10, 100]:
    Q = sinkhorn_log(S, eps, it)
    err_f = np.abs(Q.sum(1) * K - 1).max()
    err_c = np.abs(Q.sum(0) * B - 1).max()
    print(f"{it:3d} iteraciones: {np.bincount(Q.argmax(0), minlength=K)}  error filas {err_f:.1e}  columnas {err_c:.1e}")

# la solución tiene la forma diag(u) exp(S/eps) diag(v): log Q - S/eps = a_k + b_b, de rango <= 2 una vez centrada
R = np.log(sinkhorn_log(S, eps, 100)) - S / eps
print("valores singulares de log Q - S/eps (centrado):", np.array2string(np.linalg.svd(R - R.mean(), compute_uv=False)[:3], precision=3))

for e in [0.02, 0.05, 0.2, 1.0]:
    Q = sinkhorn_log(S, e, 3) * B                      # columnas: códigos que suman 1
    H = -(Q * np.log(Q + 1e-300)).sum(0).mean()
    print(f"eps = {e:4.2f}: entropía media del código {H:.3f} nats (máx {np.log(K):.3f}),"
          f" error de filas tras 3 iteraciones {np.abs(Q.sum(1) / B * K - 1).max():.1e}")

with np.errstate(over="ignore", invalid="ignore"):
    Qd = sinkhorn_directo(S, 1e-4, 3)
print("eps = 1e-4: ¿NaN en la versión directa?", bool(np.isnan(Qd).any()),
      "| ¿en el dominio logarítmico?", bool(np.isnan(sinkhorn_log(S, 1e-4, 3)).any()))

Without equipartition, four prototypes take 255 of 256 samples (88, 115, 24, and 28) and the other six share one. One iteration already redistributes; after three, row error is 1.4⋅10−21.4 \cdot 10^{-2}, and after 100 it is at rounding level. Residual log⁡Q−S/ε\log\mat{Q} - \mat{S}/\varepsilon has exactly two nonzero singular values, as form ukeSkb/εvbu_k e^{S_{kb}/\varepsilon} v_b requires. The ε\varepsilon table shows the tradeoff: with ε=0.02\varepsilon = 0.02 codes are sharp (0.670 nats) but three iterations leave error 0.27; with ε=1\varepsilon = 1 allocation is exact immediately, but codes are nearly uniform (2.299 of 2.303 nats) and teach nothing. SwAV’s ε=0.05\varepsilon = 0.05 lies in the useful region. With ε=10−4\varepsilon = 10^{-4}, the direct version gives NaN and the log version does not.

DINO self-distillation solves the same problem without optimal transport: the teacher (a moving average of the student, as in BYOL) centers its outputs by subtracting a moving average, preventing one dimension from dominating, and sharpens them with low temperature, preventing uniform output. The effects balance; details are in the DINO lesson.

Effective rank and RankMe

So far you have diagnosed collapse by looking at entire spectra. To compare dozens of runs, one number is useful, and algebraic rank does not suffice: with numerical noise, a representation matrix almost always has full rank.

Its properties follow from those of entropy:

  • 1≤erank⁡(Z)≤rank⁡(Z)1 \le \operatorname{erank}(\mat{Z}) \le \rank(\mat{Z}): entropy of a distribution over rr atoms lies between 00 and log⁡r\log r. The upper bound holds if and only if the rr nonzero singular values are equal; the lower if and only if rank⁡Z=1\rank \mat{Z} = 1.
  • It is scale-invariant: erank⁡(cZ)=erank⁡(Z)\operatorname{erank}(c\mat{Z}) = \operatorname{erank}(\mat{Z}) for c≠0c \neq 0.
  • It is continuous in Z≠0\mat{Z} \neq \mat{0}, unlike rank: a singular value of 10−910^{-9} barely changes pp and barely changes effective rank, while numerical rank counts it fully or not depending on an arbitrary threshold. At the zero matrix, normalization by the singular-value sum is undefined.
InteractiveEffective rank
Singular values σ1,…,σ6\sigma_1, \dots, \sigma_6 of the representation matrix
1.00σ1p = 0.610.55σ2p = 0.340.06σ3p = 0.040.03σ4p = 0.020.00σ5p = 0.000.00σ6p = 0.00
Starting spectrum
Effective rank eH(p)e^{H(p)}2.369
Entropy H(p)H(p)0.862 nats
Numerical rank (σk>10−6σmax⁡\sigma_k > 10^{-6}\sigma_{\max})4
Components for 90% of ∑σk2\sum\sigma_k^22
Six draggable singular values. Start with two dominant values and a small tail: numerical rank is 4 and effective rank just over 2. Enable rounding noise (nothing below 10⁻⁴): numerical rank jumps to 6 and effective rank barely moves. Equalize several bars and check when it matches rank; lower all but one.

Garrido et al. (2023) propose embedding effective rank as a label-free model-selection criterion called RankMe: RankMe⁡(Z)=exp⁡(−∑kpklog⁡pk)\operatorname{RankMe}(\mat{Z}) = \exp(-\sum_k p_k \log p_k) with pk=σk(Z)/∥σ(Z)∥1+εp_k = \sigma_k(\mat{Z})/\norm{\sigma(\mat{Z})}_1 + \varepsilon. Their main results:

ε\varepsilon in this formula stabilizes the logarithm: with that literal addition the pkp_k do not sum to exactly one. Exact entropy identity and the bounds above refer to normalized proportions without that shift; with small ε\varepsilon the score approximates them. An exactly zero matrix must be handled separately.

  • In the studied runs (VICReg and variants, SimCLR, DINO), the authors observe low rank accompanying low performance on the tasks considered. This is an empirical regularity in those experiments, not a proven necessity for every task. High rank does not guarantee good performance either.
  • Choosing hyperparameters (SimCLR temperature, VICReg weights, learning rate, weight decay) by maximum RankMe is on average within half a point of an oracle choosing with ImageNet labels.
  • They compute RankMe on embeddings (projector output) from the source dataset with 25,600 samples; with 10,000 they already have over 95% of final rank in VICReg and SimCLR. They use it to predict representation quality (encoder output) on other tasks.
  • They warn to compare only runs of the same method: rank is not the sole factor and is not comparable across methods. There are exceptions within a method (on StanfordCars, the best VICReg does not have the highest rank).

The next cell applies RankMe to representations from the linear model and shows two subtleties. RankMe uses singular values of Z\mat{Z} without centering: if all representations are the same constant c\vb{c}, Z=1c⊤\mat{Z} = \vb{1}\vb{c}\T plus noise has a dominant singular value and RankMe is 1; centering first would leave only isotropic noise, giving maximum rank. And because it is scale-invariant, RankMe cannot see collapse toward zero: also inspect norm.

[ ]RankMe on the linear modelBrowser
def rankme(Z, eps=1e-7):
    """RankMe: exp de la entropía de p_k = sigma_k / sum_j sigma_j (+ eps), con los valores singulares de Z sin centrar."""
    s = np.linalg.svd(Z, compute_uv=False)
    p = s / s.sum() + eps
    return float(np.exp(-(p * np.log(p)).sum()))

rng = np.random.default_rng(1)
x = rng.normal(size=(2000, n)) * np.sqrt(XV)        # 2000 datos con covarianza diag(XV)
for nombre, kw in [("alpha_p = 10 (6 vivas)", dict(ap=10.0)), ("BYOL, eta = 0.01 (5 vivas)", dict()),
                   ("BYOL, eta = 0.1 (3 vivas)", dict(eta=0.1)), ("sin predictor (colapso)", dict(pred=False))]:
    Z = x @ run(**kw)[2].T                          # representaciones z = W x
    print(f"{nombre:28s} RankMe {rankme(Z):.3f}   norma media de z {np.linalg.norm(Z, axis=1).mean():.2e}")

c = rng.normal(size=d)
Zc = c + 1e-6 * rng.normal(size=(2000, d))           # colapso a una constante, con ruido de redondeo
print(f"\nconstante + ruido 1e-6: RankMe sin centrar {rankme(Zc):.3f}, centrando {rankme(Zc - Zc.mean(0)):.3f}")

RankMe orders the three living representations like their surviving directions: 5.172, 4.517, and 2.889 for 6, 5, and 3 directions. It does not reach the direction count because amplitudes differ, which is what it should measure. The collapsed representation without predictor gives 1.490, low but not 1: its mean norm is 5.85⋅10−55.85 \cdot 10^{-5} and what remains still has shape. A serious diagnostic panel shows RankMe alongside representation scale (or normalized-output standard deviation). And the noisy constant gives 1.000 uncentered and 5.997 centered, the maximum possible with d=6d = 6: centering would turn the worst collapse into the best score.

Lab: miniature BYOL, SimSiam, and VICReg

This standalone lab repeats the previous lesson’s encoder, augmentations, NT-Xent, and probe protocol. It downloads Fashion-MNIST the first time and uses CUDA if available. Full runs below train 30 epochs per configuration and can take a long time on CPU. To check the flow first, set environment variable ORYON_SHORT_RUN=1 before starting the local process: only 2048 training images, 256 test images, and one epoch are used. This is a functional check, not a performance comparison. Test data are reserved for each configuration’s final evaluation, and the probe selects regularization using a training split. RankMe is calculated on uncentered projector outputs alongside their norm: high rank alone does not certify absence of collapse.

[ ]Data, encoder, and probe from the previous lessonLocal GPU
import math
import time
import os
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
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
SHORT_RUN = os.environ.get('ORYON_SHORT_RUN') == '1'
if SHORT_RUN:
    Xtr, ytr, Xte, yte = Xtr[:2048], ytr[:2048], Xte[:256], yte[:256]
    print('Prueba corta: 2048 imágenes de entrenamiento, 256 de test, una época')


def make_encoder(seed):
    """Codificador convolucional pequeño: 28x28 -> 512 características."""
    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 make_head(d_out=128):
    """Cabeza de proyección: MLP de una capa oculta, 512 -> 512 -> d_out."""
    return nn.Sequential(nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, d_out)).to(dev)


def augment(x, crop=True, flip=True, jitter=True, scale=(0.3, 1.0)):
    """Una vista aleatoria de cada imagen del lote: recorte con cambio de tamaño y volteo (geométricos) y
    contraste, gamma y brillo (fotométricos). Todo en la GPU y con parámetros distintos por imagen."""
    n = len(x)
    u = lambda lo, hi: torch.empty(n, device=x.device).uniform_(lo, hi)
    if crop or flip:
        area = u(*scale) if crop else torch.ones(n, device=x.device)
        ratio = torch.exp(u(math.log(3 / 4), math.log(4 / 3))) if crop else torch.ones(n, device=x.device)
        sx, sy = (area * ratio).sqrt().clamp(max=1), (area / ratio).sqrt().clamp(max=1)
        sign = torch.where(torch.rand(n, device=x.device) < 0.5, -1.0, 1.0) if flip else torch.ones(n, device=x.device)
        theta = torch.zeros(n, 2, 3, device=x.device)
        theta[:, 0, 0], theta[:, 1, 1] = sx * sign, sy
        theta[:, 0, 2], theta[:, 1, 2] = (2 * torch.rand(n, device=x.device) - 1) * (1 - sx), (2 * torch.rand(n, device=x.device) - 1) * (1 - sy)
        x = F.grid_sample(x, F.affine_grid(theta, list(x.shape), align_corners=False), mode="bilinear", padding_mode="zeros", align_corners=False)
    if jitter:
        a, g, b = u(0.5, 1.5), torch.exp(u(math.log(0.6), math.log(1.6))), u(-0.15, 0.15)
        x = (a.view(-1, 1, 1, 1) * x.clamp(min=0) ** g.view(-1, 1, 1, 1) + b.view(-1, 1, 1, 1)).clamp(0, 1)
    return x


def nt_xent(z, tau):
    """NT-Xent de SimCLR. z: (2N, d); z[i] y z[i + N] son las dos vistas del ejemplo i."""
    z = F.normalize(z, dim=1)
    n2 = z.shape[0]
    sim = z @ z.T / tau
    sim = sim.masked_fill(torch.eye(n2, dtype=torch.bool, device=z.device), float("-inf"))   # fuera la autosimilitud
    target = torch.cat([torch.arange(n2 // 2, n2), torch.arange(0, n2 // 2)]).to(z.device)   # el positivo de i es i +- N
    return F.cross_entropy(sim, target)


def nt_xent_naive(z, tau):
    """La definición con dos bucles, en float64, para comprobar la versión vectorizada."""
    z = F.normalize(z.double(), dim=1)
    n2, total = len(z), 0.0
    for i in range(n2):
        j = (i + n2 // 2) % n2
        den = sum(math.exp(float(z[i] @ z[k]) / tau) for k in range(n2) if k != i)
        total += -math.log(math.exp(float(z[i] @ z[j]) / tau) / den)
    return total / n2


zt = torch.randn(12, 16, device=dev)
print(f"vectorizada {nt_xent(zt, 0.3).item():.6f}   bucles {nt_xent_naive(zt, 0.3):.6f}")


@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 train_simclr(seed=0, epochs=30, bs=512, tau=0.2, lr=2e-3, proj=True, aug=None, loss_fn=nt_xent, log_every=0):
    """Preentrena un SimCLR en miniatura. Devuelve el codificador, la cabeza (o None) y la pérdida media por época."""
    aug = aug or {}
    enc, head = make_encoder(seed), (make_head() if proj else nn.Identity().to(dev))
    params = [*enc.parameters(), *head.parameters()]
    opt = torch.optim.Adam(params, lr=lr, weight_decay=1e-6)
    steps = epochs * (len(Xtr) // bs)
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=steps, pct_start=0.1)
    g = torch.Generator(device=dev).manual_seed(seed)
    hist = []
    for ep in range(1, epochs + 1):
        enc.train(); head.train()
        tot = 0.0
        for idx in torch.randperm(len(Xtr), device=dev, generator=g).split(bs)[: len(Xtr) // bs]:
            x = Xtr[idx]
            z = head(enc(torch.cat([augment(x, **aug), augment(x, **aug)])))
            loss = loss_fn(z, tau)
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step(); sched.step()
            tot += loss.item()
        hist.append(tot / (len(Xtr) // bs))
        if log_every and ep % log_every == 0:
            print(f"  época {ep:3d}  pérdida {hist[-1]:.4f}")
    return enc, head, hist

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."""
    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 del entrenamiento; el test se mira al final."""
    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:]
    Zfit, Zval = standardize(Ztr[fi], Ztr[va])
    val = {wd: accuracy(Zval, ytr_[va], *fit_logreg(Zfit, ytr_[fi], wd)) for wd in wds}
    best = max(val, key=val.get)
    Ztr, Zte = standardize(Ztr, Zte)
    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 coseno con votos ponderados por exp(s / tau), como en la lección anterior."""
    mu = train_z.mean(0)
    A, B = F.normalize(train_z - mu, dim=1), 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) == yte).float().mean().item()


@torch.no_grad()
def align_uniform(f, n=5000, t=2.0, seed=0):
    """Alineamiento y uniformidad de Wang e Isola. f lleva un lote de imágenes a vectores (se normalizan aquí)."""
    torch.manual_seed(seed)
    x = Xte[:n]
    a, b = F.normalize(f(augment(x)), dim=1), F.normalize(f(augment(x)), dim=1)
    align = (a - b).pow(2).sum(1).mean().item()                               # E ||f(x) - f(y)||^2 sobre pares positivos
    uniform = torch.log(torch.exp(-t * torch.pdist(a).pow(2)).mean()).item()  # log E exp(-t ||f(x) - f(y)||^2) sobre pares distintos
    return align, uniform


def evaluate(enc, head=None, full=True, wds=(1e-4, 1e-3, 1e-2, 1e-1)):
    """Sonda y k-NN sobre h (salida del codificador) y, con cabeza, sobre z = g(h); alineamiento y uniformidad de h y de z."""
    out = {}
    Htr, Hte = features(enc, Xtr), features(enc, Xte)
    out["probe_h"] = linear_probe(Htr, ytr, Hte, yte, wds=wds)
    out["knn_h"] = knn_eval(Htr, ytr, Hte)
    enc.eval()
    out["au_h"] = align_uniform(lambda x: enc(x))
    if head is not None and not isinstance(head, nn.Identity):
        head.eval()
        with torch.no_grad():
            Ztr, Zte = head(Htr), head(Hte)
        if full:
            out["probe_z"] = linear_probe(Ztr, ytr, Zte, yte, wds=wds)
        out["knn_z"] = knn_eval(Ztr, ytr, Zte)
        out["au_z"] = align_uniform(lambda x: head(enc(x)))
    return out
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Each method receives two independent augmentations per image. BYOL uses a target copy updated by moving average; SimSiam shares the encoder and stops target gradients; VICReg uses explicit invariance, variance, and covariance terms. The no-stop-gradient ablation is symmetric and shows whether collapse appears with this architecture and budget. Decay and learning rate for each configuration remain explicit; one run does not prove a general law.

[ ]BYOL, SimSiam, and VICReg: implementations and ablationsLocal GPU
import copy

def cosine_loss(p, z):
    return 2 - 2 * (F.normalize(p, dim=1) * F.normalize(z, dim=1)).sum(dim=1).mean()

def vicreg_loss(a, b, inv_weight=25.0, var_weight=25.0, cov_weight=1.0):
    n, d = a.shape
    inv = (a - b).square().sum(dim=1).mean()
    def penalties(z):
        z = z - z.mean(dim=0)
        std = torch.sqrt(z.var(dim=0, unbiased=True) + 1e-4)
        variance = F.relu(1 - std).mean()
        cov = z.T @ z / (n - 1)
        off = cov - torch.diag_embed(torch.diagonal(cov))
        return variance, off.square().sum() / d
    va, ca = penalties(a)
    vb, cb = penalties(b)
    return inv_weight * inv + var_weight * (va + vb) + cov_weight * (ca + cb)

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

def train_no_neg(method, seed=0, epochs=30, bs=512, lr=2e-3,
                 momentum=0.99, predictor=True, stop=True):
    torch.manual_seed(seed)
    enc, head = make_encoder(seed), make_head()
    pred = nn.Sequential(
        nn.Linear(128, 512), nn.ReLU(), nn.Linear(512, 128)).to(dev)
    if method == "vicreg" or not predictor:
        pred = nn.Identity().to(dev)
    target_enc = copy.deepcopy(enc) if method == "byol" else None
    target_head = copy.deepcopy(head) if method == "byol" else None
    if target_enc is not None:
        for p in list(target_enc.parameters()) + list(target_head.parameters()):
            p.requires_grad_(False)
    params = list(enc.parameters()) + list(head.parameters()) + list(pred.parameters())
    opt = torch.optim.Adam(params, lr=lr, weight_decay=1e-6)
    steps_epoch = len(Xtr) // bs
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=epochs * steps_epoch, pct_start=0.1)
    gen = torch.Generator(device=dev).manual_seed(seed)
    history = []
    for ep in range(epochs):
        enc.train(); head.train(); pred.train()
        total = 0.0
        for idx in torch.randperm(len(Xtr), device=dev, generator=gen)[:steps_epoch * bs].split(bs):
            x = Xtr[idx]
            v1, v2 = augment(x), augment(x)
            z1, z2 = head(enc(v1)), head(enc(v2))
            if method == "vicreg":
                loss = vicreg_loss(z1, z2)
            else:
                p1, p2 = pred(z1), pred(z2)
                if method == "byol":
                    target_enc.train(); target_head.train()
                    with torch.no_grad():
                        t1, t2 = target_head(target_enc(v1)), target_head(target_enc(v2))
                else:
                    t1, t2 = (z1.detach(), z2.detach()) if stop else (z1, z2)
                loss = (cosine_loss(p1, t2) + cosine_loss(p2, t1)) / 2
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step(); sched.step()
            if target_enc is not None:
                with torch.no_grad():
                    online = list(enc.parameters()) + list(head.parameters())
                    target = list(target_enc.parameters()) + list(target_head.parameters())
                    for a, b in zip(target, online):
                        a.mul_(momentum).add_(b, alpha=1 - momentum)
            total += loss.item()
        head.eval(); enc.eval()
        with torch.no_grad():
            Z = head(features(enc, Xtr[:2048], bs=512))
            history.append((total / steps_epoch, effective_rank(Z),
                            Z.norm(dim=1).mean().item()))
        print(f"{method}, época {ep + 1}: pérdida {history[-1][0]:.4f}, RankMe {history[-1][1]:.2f}, norma {history[-1][2]:.4f}")
    return enc, head, history

print("Comprobación de VICReg: una representación constante incumple el término de varianza.")
z = torch.ones(8, 128, device=dev)
print("pérdida con todas las salidas iguales:", float(vicreg_loss(z, z)))

configs = [
    ("BYOL", "byol", {}),
    ("BYOL sin predictor", "byol", {"predictor": False}),
    ("BYOL sin media móvil", "byol", {"momentum": 0.0}),
    ("SimSiam", "simsiam", {}),
    ("SimSiam sin stop-gradient", "simsiam", {"stop": False}),
    ("SimSiam sin predictor", "simsiam", {"predictor": False}),
    ("VICReg", "vicreg", {}),
]
resultados = {}
for name, method, kwargs in configs:
    encoder, projector, history = train_no_neg(method, epochs=1 if SHORT_RUN else 30, **kwargs)
    metric = evaluate(encoder, projector, full=False)
    resultados[name] = (metric["probe_h"], history[-1])
    print(name, "sonda lineal de h", round(metric["probe_h"], 4),
          "pérdida, RankMe y norma final", history[-1])

enc_sc, head_sc, hist_sc = train_simclr(seed=0, epochs=1 if SHORT_RUN else 30, bs=512, tau=0.2)
metric_sc = evaluate(enc_sc, head_sc, full=False)
with torch.no_grad():
    head_sc.eval()
    z_sc = head_sc(features(enc_sc, Xtr[:2048], bs=512))
resultados["SimCLR"] = (metric_sc["probe_h"],
                        (hist_sc[-1], effective_rank(z_sc), z_sc.norm(dim=1).mean().item()))
for name, (probe, stats) in resultados.items():
    print(f"{name:28s} sonda {probe:.4f} pérdida {stats[0]:.4f} RankMe {stats[1]:.2f} norma {stats[2]:.4f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Interpret ablations alongside their spectrum and norm, not loss alone. BYOL’s target uses batch statistics in training, so this single-GPU comparison is a teaching implementation, not a reproduction of the papers’ distributed protocol. To compare another architecture or seed, retrain all rows and retain the same evaluation set.

Comparison and practical recipes

MethodWhat prevents complete collapseWhat prevents dimensional collapseSensitive hyperparametersImageNet, ResNet-50, linear
SimCLR (with negatives)InfoNCE uniformityuniformity, partlytemperature, batch size(lesson 22 reference)
BYOLpredictor + stop-gradient (dynamics)nothing explicit: predictor rate, weight decayτbase\tau_{\text{base}}, predictor rate74.3 %
SimSiampredictor + stop-gradient (dynamics)nothing explicitpredictor rate (without decay)71.3 % (800 epochs)
Barlow Twinsbatch normalization + invarianceredundancy termλ\lambda, projector dimension73.2 %
VICRegvariance termcovariance termλ,μ,ν\lambda, \mu, \nu73.2 %
SwAVequipartition and swapped prediction, without a general guaranteedistributed use of KK prototypes, without a full-rank guaranteeε\varepsilon, KK, queue for small batches75.3 % (multi-crop)

The last column’s numbers come from the cited papers with different budgets (epochs, batch size, multi-crop), so they do not rank methods: they show that when well tuned, all reach roughly the same level. Practical recipes from the lesson:

  1. Monitor collapse without labels from the first experiment: embedding RankMe, standard deviation of z/∥z∥\vb{z}/\norm{\vb{z}}, and mean norm every epoch. Falling loss proves nothing.
  2. In asymmetric methods, the predictor matters. If collapse occurs, try raising its learning rate or not decaying it, and lowering weight decay; the linear model shows both determine how many dimensions survive.
  3. In methods with an explicit regularizer, tune weights with RankMe within the same method. Published weights assume particular dimension and architecture.
  4. The projector is part of the method. Barlow Twins improves with very wide projectors and DirectCLR shows the projector protects representations from dimensional collapse; always evaluate the representation before the projector.
  5. Adding VICReg’s variance term to another method is a cheap safety net against complete collapse.

Common mistakes

Exercises

QuizThe moving-average target
What role does the moving-average target network play in BYOL, and what happens in SimSiam, which lacks it?
QuizThe variance axis
You implement the VICReg hinge as F.relu(1 - torch.sqrt(z.var(dim=1) + 1e-4)).mean(), with z of shape (n, d) (one row per image). What happens?
QuizA perfect variance
In a small experiment, the projector ends in a BatchNorm1d without affine parameters. Each embedding component has standard deviation 1 in every epoch and loss falls. What can you conclude?
QuizA faster predictor
In the linear model with predictor, moving average, and η=0.01\eta = 0.01, you raise relative predictor rate from αp=1\alpha_p = 1 to αp=10\alpha_p = 10. Based on the lesson, what do you expect?
QuizLowering regularization
In SwAV you lower ε\varepsilon from 0.05 to 0.005 and keep three Sinkhorn iterations. What happens?
QuizWhat RankMe does and does not say
Which statements about RankMe are correct? (There may be several.)

More than one answer may be correct.

NumericEffective rank of a truncated spectrum
A representation matrix has singular values (3,1,0,0)(3, 1, 0, 0). What is its effective rank exp⁡(H(p))\exp(H(p)), with pk=σk/∑jσjp_k = \sigma_k / \sum_j \sigma_j and natural logarithm?
NumericThreshold for a direction
In the linear model with predictor, τ=1\tau = 1 and augmentation variance σ2=0.3\sigma^2 = 0.3, one data direction has variance x=0.8x = 0.8. What is the critical weight decay η\eta above which nonzero fixed points in that direction disappear?
NumericAmplitude left by the predictor
Same setting with x=2x = 2, σ2=0.5\sigma^2 = 0.5, τ=1\tau = 1, η=0.04\eta = 0.04 and αp=4\alpha_p = 4. If the direction reaches the stable fixed point, what is representation standard deviation there, x ∣w∣\sqrt{x}\,\abs{w}?
ProofInvariance alone collapses; variance prevents it
Prove: (a) Every constant encoder globally minimizes Linv(θ)=E∥fθ(t1(x))−fθ(t2(x))∥2\Loss_{\text{inv}}(\theta) = \E\|f_\theta(t_1(\vb{x})) - f_\theta(t_2(\vb{x}))\|^2. (b) In VICReg with μ>0\mu > 0 and γ>ε\gamma > \sqrt{\varepsilon}, a constant encoder has loss 2μ(γ−ε)>02\mu(\gamma - \sqrt\varepsilon) > 0 on any batch, whereas an invariant encoder with standard deviation at least γ\gamma in every component and zero covariances has loss 0. If one exists, no constant encoder is a global minimum.
0
Let fθ≡cf_\theta \equiv \vb{c} in (a) and (b). In (b), Z\mat{Z} and Z′\mat{Z}' are representations of the two views of a batch of n≥2n \ge 2 images.

Step 1 of 4. What is Linv\Loss_{\text{inv}} for fθ≡cf_\theta \equiv \vb{c}, and why is it a global minimum?

ProofWhen Barlow Twins loss is zero
Prove: Let ZA,ZB∈RB×d\mat{Z}^A, \mat{Z}^B \in \R^{B \times d} be column-centered with every column nonzero, and λ>0\lambda > 0. Then LBT=0\Loss_{\text{BT}} = 0 if and only if Z^A=Z^B\hat{\mat{Z}}^A = \hat{\mat{Z}}^B and 1B(Z^A)⊤Z^A=I\tfrac1B(\hat{\mat{Z}}^A)\T\hat{\mat{Z}}^A = \mat{I}, where Z^\hat{\mat{Z}} is Z\mat{Z} with each column divided by its standard deviation.
0
Write z^iA,z^jB∈RB\hat{\vb{z}}^A_i, \hat{\vb{z}}^B_j \in \R^B for standardized columns with norm B\sqrt B. Then Cij=1B⟨z^iA,z^jB⟩C_{ij} = \tfrac1B\inner{\hat{\vb{z}}^A_i}{\hat{\vb{z}}^B_j}.

Step 1 of 4. If LBT=0\Loss_{\text{BT}} = 0, what follows about C\mat{C}?

CodeStable Sinkhorn for SwAV
Implement sinkhorn(scores, eps, n_iter). scores is a matrix (B, K) of scores (one row per sample, one column per prototype). Return P of shape (B, K), proportional to exp⁡(scores/ε)\exp(\text{scores}/\varepsilon) up to row and column rescaling, so each row sums to 1 (each sample’s code) and, after enough iterations, each column sums to B/KB/K (all prototypes receive equal mass). Each iteration rescales columns first to B/KB/K and rows next to 1, so rows are exact. Work in the log domain: tests use scores around 1000 with ε=0.01\varepsilon = 0.01.
import numpy as np

def sinkhorn(scores, eps, n_iter):
  """Asignaciones (B, K): filas que suman 1 y columnas que suman B/K."""
  P = np.exp(scores / eps)
  return P / P.sum(axis=1, keepdims=True)   # solo normaliza las filas
Shift+Enter to run

Summary

Key idea
Without negatives, invariance alone is minimized by a constant representation. Negative-free methods avoid this in three ways: asymmetry (predictor and stop-gradient) whose dynamics leave directions with sufficient signal alive, an explicit term on representation covariance (Barlow Twins, VICReg), or prototype assignments forced to spread (SwAV). None completely prevents dimensional collapse, which loss misses but effective rank reveals.
  • Complete and dimensional collapse. The former gives Σz=0\mat{\Sigma}_z = \mat{0}; the latter a spectrum with a step. Both are diagnosed from representation spectra, and loss falls in both.
  • BYOL and SimSiam. In the studied linear model and its assumptions, removing stop-gradient or the predictor leads to collapse. With a predictor, each direction has weight-decay threshold τ2x2/(4(x+σ2))\tau^2x^2/(4(x+\sigma^2)) and a collapse basin that predictor rate can shrink. SimSiam empirically shows moving average is unnecessary in its configuration.
  • Barlow Twins drives cross-view correlation to identity: invariance on the diagonal and decorrelation off it. VICReg separates variance (a hinge on standard deviation across the batch), invariance, and covariance; each term prevents a failure.
  • DeepCluster and SwAV learn to predict group assignments. Equipartition, solved with Sinkhorn–Knopp in the log domain, makes collapse a high-loss solution.
  • RankMe, effective rank eH(p)e^{H(p)} of uncentered embeddings, selects hyperparameters without labels within one method; it is scale-invariant, so accompany it with representation norm.