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
- 12Multi-view contrastive learningAlignment and uniformityk-means objective (inertia)Explained variance and number of components
- 15Batch normalizationEpochs and shuffling
- 00Canonical training and evaluation loop
- 19Exponential moving average of weights
- 06Iterate averagingGradient descent dynamics on quadratics
- 07Shannon entropy
- 04Whitening
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 , 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 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:
| Family | Examples | What prevents collapse |
|---|---|---|
| Asymmetric | BYOL, SimSiam | a predictor on one branch and stop-gradient on the other |
| Redundancy reduction | Barlow Twins, VICReg | an explicit term on representation covariance |
| Clustering | DeepCluster, SwAV | prototype assignments required to distribute equally |
| Self-distillation | DINO | centering 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 be an encoder and the representation of data point drawn from the data distribution. Everything that follows centers on its covariance matrix
Complete collapse is the failure motivating negatives. If you only require the two views to match,
and any constant attains the global minimum . 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 reaches 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 , estimated using a few thousand unlabeled representations:
- Calculate from data representations, center columns, and find singular values (or covariance eigenvalues ).
- Plot against , sorted descending. Complete collapse gives all 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 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 . If components were independent zero-mean Gaussians, each would have standard deviation near ; 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 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, as reference) isolate the target’s role:
| Target network | Linear accuracy |
|---|---|
| Fixed and random () | 18.8 % |
| Moving average, | 69.8 % |
| Moving average, | 72.5 % |
| Moving average, | 68.4 % |
| Instantaneous copy of the online network () | 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 (), 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 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 per image,
and minimize by blocks: with fixed, take a step in (so no gradient flows to the target); with fixed, the optimum is , the mean representation over augmentations. SimSiam approximates that expectation with a single augmentation , and predictor 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 with ; two views , with independent augmentation noise . Linear online network , linear predictor , and target network . The loss, with stop-gradient on the target branch, is
Its expected gradients follow in a few lines:
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 through both branches: . Write ; the three terms are uncorrelated, so
With , , because and . By Grönwall, .
(2) With and , the equation for in the derivation gives , and the same calculation gives .
∎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 , , , and symmetric commuting with . Then both matrices are diagonalized in the same basis and the system separates into scalar equations for eigenvalues of and of :
To see dimensional collapse, let each direction have its own variance. If and , are diagonal in that basis (with ), the derivation above gives, for each direction with variance , weight , and predictor eigenvalue :
With and 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, . With weight decay, the difference is forgotten exponentially and dynamics end on curve ; without weight decay, the initial condition is never forgotten. On that curve, .
A weight-decay threshold. Function reaches its maximum at . If
then for every and the direction turns off. If , there are two nonzero fixed points, roots of : is stable, unstable and separates the collapse basin (, ending at ) from the useful solution’s basin. With this is Tian et al.’s condition . Directions with little signal relative to augmentation (small ratio ) 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 . A faster predictor (larger ) shrinks the collapse basin but also the amplitude. And when and , : 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 and , so it does not change fixed points. Tian et al. describe it as an automatic curriculum: initially is small and target is too, and grows as the network learns; without it, with a symmetric predictor, they found stable training only with . In real SimSiam the predictor is neither symmetric nor linear and its rate tuning serves as that curriculum.
Lab: dynamics in NumPy
The first cell implements the full model without assuming diagonal structure: matrices , exact expected gradients, step , 4000 steps, moving average , and deterministic pseudorandom initialization (the same as the interactive). Try all five recipes: BYOL, SimSiam, and three ablations.
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 , 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.
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 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 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 (, ) has a stable fixed point with , but initialization leaves it in the collapse basin and it dies. With the basin shrinks and it survives, with amplitude 0.061 predicted by theory (0.059). In exchange, all amplitudes are divided by .
- With the fifth direction dies, which has : it is below threshold but so close that its collapse basin is huge. With the fourth also dies, whose threshold (0.1021) barely exceeds .
- With theory still has two directions with stable fixed points ( and ), 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 , loss is exactly zero when : 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 samples, at least ; 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 divides by standard deviations: a constant component has undefined correlation and in practice (with in the denominator) gives and pays the entire invariance penalty. Dimensional collapse, however, is compatible with the invariance term: if every component copies the same invariant feature, all are near 1. The redundancy term prevents it because those copies have .
The paper’s numbers: a three-layer projector of 8192 units, , 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:
| Variant | Linear accuracy |
|---|---|
| Full Barlow Twins | 71.4 % |
| Invariance only (diagonal) | 57.3 % |
| Redundancy only (off diagonal) | 0.1 % |
| Normalize across features instead of the batch | 69.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.
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 and four invariant directions, loss must choose between repeating content (paying redundancy) and using each view’s style (paying invariance), with 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 : both views must give the same representation. Alone, it collapses.
- Variance : a hinge requiring standard deviation at least in every component. It excludes complete collapse but allows all components to be identical.
- Covariance : 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 , , whose norm vanishes exactly when the component collapses; in contrast, has norm 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. avoids division by zero at exact collapse, at the cost of weakening the push when standard deviation drops below .
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.
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 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 , 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 learnable prototypes (unit vectors, columns of ) and, for each view with normalized representation , calculates a code , a distribution over prototypes. Loss is swapped prediction: view predicts the code of view and vice versa,
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 the batch representations in columns,
with . Each prototype receives exactly of batch mass. The paper’s values are , , , 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 for rows and for columns, the Lagrangian stationarity condition at is
with , , and . The objective is strictly concave (because of entropy) on a compact convex set, so the optimum is unique, and positive because the derivative of diverges at . Finding and means rescaling rows and columns of positive matrix until it has the required marginals. The Sinkhorn–Knopp algorithm alternates the two rescalings:
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 decreases, and in double precision overflows if exceeds about 709; robust implementations therefore work with and log-sum-exp.
What does equipartition achieve against collapse? If all batch representations were equal, all columns of would be equal and balanced codes uniform: . Cross-entropy would be at least . 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.
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 around one direction, 10 random prototypes), checks marginals, solution form , and the effect of , and shows why the direct version fails with small .
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 , and after 100 it is at rounding level. Residual has exactly two nonzero singular values, as form requires. The table shows the tradeoff: with codes are sharp (0.670 nats) but three iterations leave error 0.27; with allocation is exact immediately, but codes are nearly uniform (2.299 of 2.303 nats) and teach nothing. SwAV’s lies in the useful region. With , 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:
- : entropy of a distribution over atoms lies between and . The upper bound holds if and only if the nonzero singular values are equal; the lower if and only if .
- It is scale-invariant: for .
- It is continuous in , unlike rank: a singular value of barely changes 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.
Garrido et al. (2023) propose embedding effective rank as a label-free model-selection criterion called RankMe: with . Their main results:
in this formula stabilizes the logarithm: with that literal addition the do not sum to exactly one. Exact entropy identity and the bounds above refer to normalized proportions without that shift; with small 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 without centering: if all representations are the same constant , 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.
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 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 : 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.
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
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.
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}")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
| Method | What prevents complete collapse | What prevents dimensional collapse | Sensitive hyperparameters | ImageNet, ResNet-50, linear |
|---|---|---|---|---|
| SimCLR (with negatives) | InfoNCE uniformity | uniformity, partly | temperature, batch size | (lesson 22 reference) |
| BYOL | predictor + stop-gradient (dynamics) | nothing explicit: predictor rate, weight decay | , predictor rate | 74.3 % |
| SimSiam | predictor + stop-gradient (dynamics) | nothing explicit | predictor rate (without decay) | 71.3 % (800 epochs) |
| Barlow Twins | batch normalization + invariance | redundancy term | , projector dimension | 73.2 % |
| VICReg | variance term | covariance term | 73.2 % | |
| SwAV | equipartition and swapped prediction, without a general guarantee | distributed use of prototypes, without a full-rank guarantee | , , queue for small batches | 75.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:
- Monitor collapse without labels from the first experiment: embedding RankMe, standard deviation of , and mean norm every epoch. Falling loss proves nothing.
- 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.
- In methods with an explicit regularizer, tune weights with RankMe within the same method. Published weights assume particular dimension and architecture.
- 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.
- Adding VICReg’s variance term to another method is a cheap safety net against complete collapse.
Common mistakes
Exercises
F.relu(1 - torch.sqrt(z.var(dim=1) + 1e-4)).mean(), with z of shape (n, d) (one row per image). What happens?BatchNorm1d without affine parameters. Each embedding component has standard deviation 1 in every epoch and loss falls. What can you conclude?More than one answer may be correct.
Step 1 of 4. What is for , and why is it a global minimum?
Step 1 of 4. If , what follows about ?
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 up to row and column rescaling, so each row sums to 1 (each sample’s code) and, after enough iterations, each column sums to (all prototypes receive equal mass). Each iteration rescales columns first to and rows next to 1, so rows are exact. Work in the log domain: tests use scores around 1000 with .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 filasSummary
- Complete and dimensional collapse. The former gives ; 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 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 of uncentered embeddings, selects hyperparameters without labels within one method; it is scale-invariant, so accompany it with representation norm.