Non-contrastive methods and collapse
A non-contrastive method learns image features by asking two views of the same photograph to agree, and it asks nothing else. It uses no negatives, the other images that a contrastive method pushes away. That makes it cheaper and simpler, but it opens a trap. A network that outputs the same vector for every photograph makes every pair of views agree perfectly. Its loss is the best possible, and it has learned nothing. This failure is called collapse. This section explains how methods without negatives avoid collapse, and how you can tell when a training run has fallen into it.
Here is the setting, recalled from §28.2. Take one unlabeled photo and make two views of it. Each view is a random crop of the photo with a random color distortion. An encoder network turns each view into a vector. A contrastive loss pulls the two vectors of one photo together. It also pushes them away from the vectors of every other photo in the batch. Those other photos are the negatives, and they are what stops the encoder from mapping everything to one point. They are also expensive. SimCLR used batches of 4,096 images spread over 128 TPU cores, and MoCo kept a queue of 65,536 stored vectors.
Delete the negatives and only the pull is left. A loss that only pulls is minimized by a constant output. The book has shown this twice. In §1.10, a linear encoder trained only to match two views shrank to the zero map. In §7.2, a retrieval encoder trained only to pull pairs together retrieved no better than a blind guess.
And yet methods with no negatives work, and some beat SimCLR. The yardstick is the linear-probe accuracy of §28.1. You freeze the trained encoder, fit one linear classifier on its features with the ImageNet labels, and report that classifier's accuracy. With a ResNet-50, SimCLR reached 69.3 percent. BYOL, which has no negatives, reached 74.3 (Grill et al. 2020). SimSiam, simpler still, reached 67.7 percent after 100 epochs with an ordinary batch and plain SGD (Chen and He 2021). Remove one line of SimSiam's code, a stop-gradient defined below, and it scores 0.1 percent, which is chance on 1,000 classes. Nothing in either loss forbids the constant solution. So what keeps these networks away from it?
There are two kinds of answer. Either the loss makes the constant expensive, or training is arranged so that it never gets there. Methods of the first kind add a term to the loss. The term keeps every output dimension spread out, or decorrelates the dimensions, or forces each batch to use many clusters. Methods of the second kind make the two branches of the network different. One branch gets a stop-gradient, the other gets an extra small network, or the target changes slowly.
This section builds both kinds. We first make collapse precise and measurable. Then we take apart BYOL and SimSiam, which are of the second kind. In a linear network small enough to solve by hand, we prove that the stop-gradient is what saves them. Then we derive three methods of the first kind, Barlow Twins, VICReg, and SwAV. We end with dimensional collapse, a quieter failure that strikes even methods with negatives.
The symbols are those of the whole chapter, and here they are in one place.
- is an unlabeled image. and are two random augmentations drawn from the augmentation policy of §28.2, so the two views are and .
- The encoder is a ResNet-50, or a ViT followed by pooling. It produces the representation , the vector every evaluation reads. For a ResNet-50, .
- The projection head is a small MLP. It maps the representation to the embedding , the vector the loss sees. §28.2 showed why the head is thrown away after training.
- holds the trainable parameters. A batch holds images, so views.
- is the unit vector along .
- In this section always means weight decay. Other weights get subscripts, such as .
What collapse looks like, and how to measure it
You cannot read collapse off the loss, because a collapsed network usually has an excellent loss. SimSiam without its stop-gradient quickly reaches , the lowest value its loss can take. You have to look at the embeddings themselves. There are three ways for them to fail.
Complete collapse is easy to see once you look. Dimensional collapse is the dangerous one. The network still tells inputs apart, but only along a few directions, so the loss and even a quick probe can look fine. Three measurements catch these failures, and we build them one at a time.
Measure one, the spread of each coordinate
Normalize every embedding to unit length. Take the standard deviation of each coordinate over a batch, and average over the coordinates. A completely collapsed network scores 0, because every unit vector is the same. A healthy network, whose unit vectors point evenly in every direction, scores , up to the sampling noise of the batch. For that is . SimSiam's authors used this reference value. Their Figure 2 shows two curves, one sitting near 0.0221 with the stop-gradient and one falling to 0 without it.
∂ Proof by symmetry
Flipping the sign of coordinate is an orthogonal map, so and have the same distribution, and . Swapping coordinates and is orthogonal too, so for all . These equal second moments add up to , so each is . The standard deviation is then . ∎
This test has a blind spot, which the cell below shows. Embeddings confined to an 8-dimensional subspace of score almost as well as healthy ones. Their unit vectors still point in many different directions, so every coordinate still varies. To see dimensional collapse you need the spectrum.
Measure two, the spectrum
Stack the embeddings of a batch into the matrix , subtract the mean of each column, and compute the singular values (§0.10). Each nonzero singular value stands for one direction along which the embeddings vary, and its size says how much they vary along it. A completely collapsed batch has every singular value equal to zero. A batch confined to directions has nonzero singular values and the rest at zero. A healthy batch has singular values of similar size.
Measure three, the effective rank
A spectrum is a list of numbers. When you compare a hundred runs, you want one number per run. The effective rank counts how many directions share the spread. Three tiny cases show what it should do. Singular values mean two equal directions, so the count should be 2. Singular values should count 4. Singular values should count a little more than 1, because one direction holds almost everything. The exponential of an entropy does exactly this.
∂ Proof of the bounds
Without , the form a probability distribution on outcomes. The entropy of such a distribution lies between 0, reached only by a point mass, and , reached only by the uniform distribution (§0.5). Exponentiating gives . ∎
In plain words, the effective rank counts the directions that carry the embeddings' spread, each weighted by its share. Check it on the third tiny case. With the shares are , the entropy is , and the effective rank is .
The effective rank is a cousin of the stable rank of §0.10. The stable rank divides the squared Frobenius norm by the largest squared singular value, so it compares the spectrum with its top value only. The effective rank depends on the shape of the whole spectrum.
Two details change the number in practice. RankMe uses the singular values themselves, not their squares (the eigenvalues of ). And RankMe's formula does not center, so a nonzero mean adds a direction. When you compare runs, use one convention and say which.
Now a small simulation. The cell runs all three measurements on three sets of 1,024 embeddings of width 128. One set is completely collapsed. One is confined to a rank-8 subspace. One is isotropic, meaning spread evenly in every direction.
The collapsed set has standard deviation 0, centered singular values that are zero up to rounding, and effective rank 1. The isotropic set sits at the reference, 0.0883 against , with effective rank 125.9 of 128. The rank-8 set is the lesson. Its standard deviation, 0.0857, is within 3 percent of healthy. Its effective rank, 7.94, exposes it at once.
Diagnose collapse
Write collapse_report(Z, eps=1e-7). It takes a batch of embeddings Z of shape (n, d_z) with no zero rows, and it returns a dict with the three measurements above plus one more.
"std"is the per-coordinate spread. Normalize each row to unit length, take the standard deviation of each coordinate over the rows (ddof=0), and average over the coordinates."sv"holds allmin(n, d_z)singular values of the column-centered matrixZ - Z.mean(0), in descending order."erank"is RankMe of the uncenteredZ, with and natural logarithms."k99"is the smallest such that the top squared centered singular values hold at least 99 percent of their total. Return 0 if the centered matrix has no spread, meaning that total is at most times the sum of the squared entries ofZ.
BYOL, a network that predicts a slowly moving copy of itself
BYOL, short for Bootstrap Your Own Latent, trains a network to predict its own output for a different view of the same image. The "own output" comes from a slowly updated copy of the network. The method starts from an experiment that sounds too simple to work. Freeze a randomly initialized network and call it the target. Train a second network to predict the target's embedding of one view from the other view. The constant solution is impossible here, because the target is fixed and does not output a constant.
The trained network reached 18.8 percent linear-probe accuracy on ImageNet, while the random target itself scored 1.4 (Grill et al. 2020, Table 5). Predicting a poor representation produced a better one. Now make the improved network the new target, and repeat. BYOL runs that bootstrap continuously, at every training step.
Three pieces make it work, and each needs a name.
- The online network is the one trained by gradient descent.
- The target network has the same architecture but never receives gradients. After every step, its weights move a small fraction of the way toward the online weights. This update is an exponential moving average (EMA), the same one §28.2 built for MoCo's key encoder.
- The predictor is a small MLP that sits only on the online side, after the projection head. It turns the online embedding into a guess of the target's embedding.
The equality in the loss is the identity for unit vectors. §28.2 derived what the moving average does. It averages the online weights over a window of about steps, and it lags behind them by steps on average. At the target trails by steps. The cosine schedule gives halfway through and at the end. So the target changes ever more slowly as the online network settles.
Notice what is missing. Nothing pushes two different images apart. Why, then, does the online network not drift to a constant, which the target, a moving average of it, would eventually copy?
The BYOL paper gives an argument. It is worth stating carefully, because it is often overstated. Suppose the predictor is always the best possible one for the current online and target networks. Then an online network that carries any information about the image predicts the target at least as well as a collapsed one. So collapsing gains nothing. The derivation below makes this exact.
The argument is about equilibria under two assumptions, an optimal predictor and a fixed target. It is not a proof that training reaches a good place, and the BYOL authors say so. Collapsed equilibria still exist. The authors report only that training never converged to one.
∂ BYOL's argument from an optimal predictor
For squared error, the best predictor of the target embedding from the online embedding is the conditional mean, (§0.4). The loss it achieves is . By the law of total variance, , so
The right side is what a constant online output achieves, since conditioning on a constant tells you nothing. More generally, replacing by any function of it can only discard information, so it never lowers . With an optimal predictor, the online network gains nothing by collapsing. ∎
The last line is the clue that the rest of this section develops. A slow target and a fast predictor are two ways of doing one job, which is keeping the predictor ahead of the network it predicts. In an interview, the expected answer to "what does BYOL need?" is the predictor and the asymmetry between the branches. The moving average is a stabilizer on top.
SimSiam, the stop-gradient alone
If the predictor matters more than the moving average, how much of BYOL can you delete? Chen and He (2021) deleted the target network entirely. Both branches use the same network with the same weights, an arrangement called a Siamese network. The only asymmetry left is a stop-gradient. A stop-gradient treats a value as a constant during backpropagation. The forward pass uses the value, but no gradient flows back through it. In PyTorch it is .detach().
In terms of architecture, SimSiam is BYOL with , the setting that gave BYOL 0.3 percent. So why does one recipe fail and the other work? BYOL's own appendix gives part of the answer. With no target network and a predictor learning rate raised tenfold, BYOL reached 66.6 percent. The two recipes also differ in weight decay, with LARS in BYOL's ablation and with SGD in SimSiam. Weight decay and the predictor's speed are exactly the quantities the linear theory below singles out. The balance is fragile, and in practice you tune those two first.
The predictor is essential, and SimSiam's paper has an exact argument for why.
Proof. The first term sends gradient only through , namely . The second sends gradient only through , namely . Because is symmetric in its two arguments, . So the two pieces add up to exactly half the full gradient of , which flows through both arguments. ∎
In plain words, without a predictor the stop-gradient changes only the step size. The network then minimizes directly, and the constant solution wins. The PyTorch block near the end checks this identity with autograd.
A hypothesis is not a mechanism. To see a mechanism, we need a model small enough to solve.
A linear Siamese network you can solve
Tian, Chen and Ganguli (2021) found such a model. Strip the network down to one number per part, and the training dynamics can be solved by hand. The solution shows exactly what the stop-gradient, the predictor, and the weight decay each do.
Here is the model. The data are . Each view adds independent augmentation noise of variance , so and , with . The online network is one weight . The predictor is one weight (a number, not a probability). The target is the online weight itself, as in SimSiam. The loss is the squared error between the predicted online output and the target output,
Two expectations do all the work. The first is , since and are independent with mean 0. The second is , since every other term contains an independent zero-mean factor. Expanding the square gives .
With the stop-gradient, the target is held constant while we differentiate. So only the online copy of receives gradient,
Without the stop-gradient, receives gradient through both branches, and
The same point gets two opposite verdicts. With the stop-gradient the online weight grows. Without it the weight shrinks. To see where each run ends, follow the gradients over time.
Gradient flow is the small-learning-rate limit of gradient descent (§0.6). It is written , where the dot is the derivative in training time. Three additions bring the model closer to practice.
- The predictor gets a learning rate times that of the online weight.
- Both weights get weight decay .
- The target becomes instead of . The value is SimSiam. A below 1 models a moving-average target, which lags behind a growing online weight. Tian et al. call this ratio , a letter this book keeps for temperatures.
Finally, write for the squared online weight. It measures how much signal the online output carries, which is what a probe can use. Collapse is .
∂ Proof of the three items
The flow equations are the gradients above with in place of the target weight 1, since . For , use and .
For item 1, . The data terms are and , which cancel. The decay terms are . With the derivative is 0. Since , the factor must vanish at a fixed point, which gives . And has the sign of , so moves toward without overshooting.
For item 2, solve the linear equation . On the parabola, substitute into to get . Its nonzero roots solve the stated quadratic, and they are real exactly when its discriminant is nonnegative. The bracket is negative for , positive between the roots, and negative above . So for the flow pushes away from and toward or 0, which gives the stability claims. Above the threshold, use , the maximum of a downward parabola. Then , a negative multiple of , so decays exponentially from every start.
For item 3, the bracket is a quadratic in with positive leading coefficient . Its minimum is at , where it equals , positive for . So . A quantity whose rate of decrease is at least times itself decays at least as fast as (Grönwall's inequality), which gives the bound. ∎
In plain words, the loss on its own rewards shrinking. The stop-gradient changes the dynamics so that they preserve a quantity, and that quantity is a wall between the run and the collapsed axis . At a non-collapsed fixed point, the predictor has learned how much an augmentation shrinks the shared signal. Its value is the regression coefficient of one view on the other. Without the stop-gradient, the noise makes the two views disagree by an amount proportional to , and the cheapest fix is . For the weight decays at an exponential rate of at least .
Now each of the three hyperparameters has a meaning, and each is a setting you will tune in a real run.
- A faster predictor (larger ) flattens the parabola, so more starting points lie above it. BYOL and SimSiam both found fast predictors helpful. But conservation gives . So a very fast predictor does all the learning while barely grows. That fits a finding of Tian et al. on STL-10, a benchmark of 96-pixel images in 10 classes. Plugging in the optimal linear predictor at every step gave about 40 percent, against 74 to 75 for a predictor trained by gradient descent.
- Weight decay makes the run forget its starting point and ties to . Then the size of the online weight reflects the augmentation strength. Too much decay collapses everything.
- A lagging target ( below 1) sets a modest goal early and raises it as approaches 1. Tian et al. describe this as an automatic curriculum for the predictor.
The cell draws the flow for in three regimes. The gray arrows show the direction of the flow at each point, the dashed curve is the parabola (with ), and the green line marks . The red path is one run from .
The left run keeps at its starting value, , up to the error of the Euler steps. It ends at , exactly , with . The middle run, with weight decay 0.05, is pulled down onto the parabola. It ends at and . That is essentially the larger root , with . The right run, without the stop-gradient, slides to while wanders. That is collapse.
SimSiam in one dimension, with and without the stop-gradient
Simulate the scalar model with , the one the theorem above solves. Implement simulate_siamese(w0, p0, sigma2, alpha_p=1.0, wd=0.0, stop_grad=True, dt=0.01, steps=2000). Integrate the gradient flow with explicit Euler steps of size dt. Update and together, both computed from their current values,
with = wd. When stop_grad is true, treats the target as a constant. Otherwise it differentiates through the target too. Return two arrays w and p of length steps + 1, with the starting values at index 0.
Sixteen directions at once, and which ones survive
Real data are not the same in every direction. Some directions carry a lot of variation from image to image, and some carry little. The theorem has a sharper form that says which directions a non-contrastive method keeps. Repeat the scalar algebra for one input direction along which the data have variance instead of 1. Keep the augmentation noise at in every direction. Then and . With the stop-gradient and the flow is
The proof of item 2 of the theorem goes through word for word, with replaced by and by .
In plain words, with weight decay a non-contrastive network keeps exactly the directions whose signal is strong compared with the augmentation noise. It lets the rest collapse. A tiny example makes the threshold concrete. With and , the bar is . A direction with scores and survives easily. A direction with scores and dies.
This puts a number on an idea that runs through the whole chapter, from the augmentation graph of §28.1 onward. What the augmentations destroy, the representation learns to ignore. In practice, stronger augmentation or more weight decay means fewer surviving directions.
The cell checks the theorem in a small simulation with real matrices. It trains a 16 by 16 linear online network and a 16 by 16 linear predictor, three ways. The data have variances , the augmentation noise is , and the weight decay is 0.01. The cell uses the exact expected gradients, the large-batch limit, which keeps the run deterministic and fast. The threshold predicts that the first 8 directions survive. Along a surviving direction, the embedding's scale should be when .
The prediction holds to within 0.002 for the first seven directions. The theory gives 1.124, 0.863, 0.645, 0.467, 0.324, 0.214, and 0.131. Training gives 1.125, 0.863, 0.646, 0.466, 0.326, 0.216, and 0.130. The network started from a random matrix that was not aligned with the data, and it was never told which directions exist. The eighth direction sits right at the threshold, against 0.04, and is still settling. The ninth and beyond are dying, as predicted. The moving-average target lands in the same place. Without the stop-gradient, the whole network shrinks to a scale of . What little shape is left comes from the slowest-dying directions, so its effective rank of 1.77 describes almost nothing.
Setting the predictor directly
The theory says what a trained linear predictor converges to. So why train it at all? Tian et al. proposed to compute it directly, a method they call DirectPred. Here is the idea in plain words. Measure how the predictor's inputs are spread, find their main directions, and build a predictor that keeps those directions and scales each one by the square root of its strength.
In symbols, let be the online network's output, which is the predictor's input. Its correlation matrix is , uncentered. The matrix theory in the box above says the predictor's eigenvectors align with those of . On the parabola, each eigenvalue of is tied to the predictor's eigenvalue by , so . DirectPred estimates with a moving average over batches, , where sets how slowly the average moves. It decomposes and sets
The small lifts weak directions so that they can still grow. The test was on STL-10 with a ResNet-18 trained for 100 epochs with a moving-average target. DirectPred reached 76.77 percent, against 74.51 for a linear predictor trained by gradient descent. The term added about another point, 77.86 at its best setting. That is small-scale evidence, but it is evidence that the linear theory captured something real. An interviewer who asks "what does the predictor learn?" will be pleased by this answer, a map aligned with the main directions of its inputs.
DirectPred on a linear Siamese network
Train a linear BYOL with a moving-average target, and set its predictor by DirectPred at every step. Work in the expected-gradient (large-batch) setting of the cell above. Implement train_linear_byol(W0, nu, sigma2, predictor="directpred", steps=600, lr=0.1, m=0.99, rho=0.3, eps=0.0) and return the final online weights W. Use and . Start with W = Wa = W0 and . Then take steps steps, each doing three things in this order.
- Set the predictor. If
predictor == "directpred", update , take its eigendecomposition withnp.linalg.eigh, clip negative eigenvalues to 0, and set by the formula above. Ifpredictor == "none", set . - Take a gradient step of size
lron with respect to only, holding the target fixed, with no weight decay. - Update the target, .
The tests compare your weights with a reference. Then they check that DirectPred keeps many directions alive while the network without a predictor keeps shrinking.
Is BatchNorm a hidden source of negatives?
BatchNorm (§0.7) normalizes each feature with the mean and variance of the whole batch. So the gradient of one image's loss flows into every other image in the batch. A widely read 2020 analysis of BYOL suggested that this coupling acts as a hidden contrastive term. In small experiments, a ResNet-18 on STL-10 trained with SGD, it reported that BYOL did no better than chance without BatchNorm in its projector and predictor.
Richemond et al. (2020) tested the idea at full scale. They replaced BatchNorm everywhere with two layers that use no batch statistics at all. Group normalization normalizes groups of channels within one image, and weight standardization normalizes each filter's weights. BYOL trained this way reached 73.9 percent, against 74.3 with BatchNorm. Removing BatchNorm with nothing in its place gave 0.1 percent. Three changes together brought that back to 65.7, with still no batch statistics. They were a better weight initialization, keeping BatchNorm's learned scale and shift as plain parameters, and a longer warmup. So batch statistics are not what prevents collapse, although they help optimization. The linear theory above has no BatchNorm either, which supports the same conclusion. This is a favorite interview question, and the answer is the experiment, not the hypothesis.
Barlow Twins, make the cross-correlation the identity
The asymmetric methods avoid collapse through their training dynamics, and it took a theorem to see why. Barlow Twins takes the other road. It writes a loss whose minimum is not a collapsed network in the first place (Zbontar et al. 2021). The name honors the neuroscientist Horace Barlow, who argued that the brain recodes its sensory input so that no two units of the code carry the same information. That is redundancy reduction. Barlow Twins adds a second demand, that each unit ignore the augmentation.
In plain words, the loss asks two things of every output unit . Unit for the first view should be perfectly correlated with unit for the second view, so the unit ignores the augmentation. And unit for one view should be uncorrelated with every other unit for the other view, so no two units duplicate each other. One matrix holds all those correlations at once, and the loss pushes it toward the identity.
Each is the correlation over the batch between dimension of the first view and dimension of the second. It lies in when , by the Cauchy-Schwarz inequality (an inner product is at most the product of the two lengths). A positive only shrinks it. Here is a tiny batch worked through by hand.
The general statement says exactly where the loss is zero, and what collapse costs.
∂ Proof
The loss is a sum of squares with positive weights, so it is nonnegative and vanishes exactly when every square does, and . With , each standardized column has . So is equality in Cauchy-Schwarz between two vectors of the same length, which forces . Substituting into gives for , and together with the diagonal this is . The converse is the same computation backwards. For a constant network, , so , , and the loss is . ∎
In plain words, the invariance term says every output unit must report the same thing for both views. The redundancy term says no two units may report the same thing. Collapse breaks the first rule in every unit, so it costs instead of 0. The standardization does the work that negatives did in §28.2, because a unit with no spread cannot correlate with anything.
There is a catch that the formula hides. Centering removes one dimension, so the centered batch has rank at most , and so does . It cannot equal the identity unless . With the paper's and , the minimum 0 is out of reach. The loss is always a compromise between its two terms. Even so, Barlow Twins kept improving across every projector width its authors tried, while SimCLR and BYOL saturate early. In an interview, this rank argument is the expected answer to "can Barlow Twins reach zero loss?".
To train with this loss you need its gradient, which passes through the batch standardization.
∂ The gradient of the Barlow Twins loss
Write and , which has diagonal entries and off-diagonal entries . Since is linear in , a small change changes the loss by
using the cyclic property of the trace. So , the same shape as (§0.2).
Next comes the standardization. It is BatchNorm without the learned scale and shift, whose backward pass §0.7 derived. For one column with upstream gradient and standardized values ,
where is the batch mean of and the batch mean of the elementwise product. The two subtracted terms remove the parts of that a shift or a rescaling of the column would absorb, so every column of the result sums to zero. Here is in fact 0, because is a combination of the centered columns of , but the general formula costs nothing. The second view's gradient is the same with the roles swapped, .
Barlow Twins, no loops
Implement barlow_twins(Z1, Z2, lam=5e-3, eps=1e-5) for two batches of embeddings of shape (B, d_z). Standardize each dimension of each view over the batch (axis 0), with that view's own mean and population variance and inside the square root. Form by dividing by . Return (loss, C, dZ1), where dZ1 is the gradient of the loss with respect to Z1. Use no Python loops over the batch or the dimensions.
VICReg, three terms with three jobs
Barlow Twins ties invariance and decorrelation together in one cross-correlation matrix. It also hides the scale of the embeddings behind a standardization. VICReg separates the jobs into three terms, each computed on its own branch where possible (Bardes, Ponce and LeCun 2022). In plain words, it asks for three things. The two views of an image should be close. Every dimension should keep a minimum spread over the batch. And no two dimensions should be correlated. The name lists the terms, variance, invariance, and covariance.
The variance term is the hinge of §1.10. There it charged one minus each dimension's standard deviation whenever that standard deviation fell below 1, and it stopped a linear encoder from shrinking to zero. Here it gains a small and an average over the dimensions.
Each term has one job. Invariance pulls the views together. Variance forbids complete collapse. Covariance forbids dimensional collapse by decorrelating the dimensions. The variance term cannot do that alone, since every dimension could carry the same signal with unit spread.
Why hinge the standard deviation and not the variance? The paper remarks that a hinge on the variance has a vanishing gradient near collapse. Computing the gradient makes the remark exact.
∂ Proof
Write . The variance is , and . So , because the centered entries sum to zero. The chain rule through the square root multiplies by , which gives the first formula. Its norm is with , which simplifies to the stated value. The norm of is .
For the covariance term, gives with , which is symmetric. With ,
so . Centering multiplies by on the left, and , so it changes nothing. ∎
In plain words, the standard-deviation hinge pushes a shrinking dimension apart with a nearly constant force, about . A variance hinge pushes with a force proportional to . So the closer a dimension gets to collapse, the less a variance hinge resists, which is exactly backward.
Put numbers on it with , so . A dimension that has shrunk to gets a push of from the standard-deviation hinge. A variance hinge would give it , five times less, and the gap widens as falls. The standard-deviation hinge keeps most of its force down to , where it is still of its full size.
The is there because the derivative of is undefined at . With it, the force falls off linearly once drops well below . Even there it is times the variance hinge's force. An interviewer asking "why the square root?" wants this argument.
Compared with Barlow Twins, VICReg makes three different choices, and it shares one limit.
| Barlow Twins | VICReg | |
|---|---|---|
| Scale of the embeddings | removed by standardization, so rescaling a dimension changes nothing | visible to the loss, so the variance term must hold it up |
| What is decorrelated | the two branches against each other, through one cross-correlation | each branch on its own, so the branches need not share weights, architectures, or even input modalities |
| Invariance | a correlation of 1 per dimension | a plain squared distance |
| Reachable minimum when exceeds | no | no |
The last row holds for VICReg for a rank reason. A covariance with every diagonal entry at least 1 and zeros off the diagonal is full rank. The covariance of samples has rank at most . So with and , the variance and covariance terms cannot both be zero.
The second row is VICReg's practical advantage. Because each branch is regularized on its own, the paper pairs images with text and evaluates retrieval on MS-COCO, a dataset of photos with captions. Whitening methods take the hard version of the same idea. W-MSE (Ermolov et al. 2021) whitens each batch of embeddings exactly, with the matrices of §0.10, so that their covariance is the identity. Only then does it apply a mean-squared-error loss between the views, so collapse is impossible by construction.
The cell computes the Barlow Twins and VICReg terms on a healthy batch of 512 pairs in and on four damaged versions. It shows which term answers which kind of damage.
Read the table one row at a time. Four dead dimensions cost Barlow Twins almost exactly 4 in its invariance term, because each dead dimension has . They cost VICReg through its variance term, 12.9. Eight copies of one dimension light up the redundancy and covariance terms. Noisy views raise both invariance terms. Shrinking the whole batch tenfold changes nothing for Barlow Twins, whose standardization removes scale. VICReg's variance term jumps to 44.9, because it alone watches the scale.
The widget below lets you damage a batch yourself and watch each term respond. Predict before you slide. Choose Barlow Twins and correlated dims, and push the correlation between dimensions to 0.9. Which term grows, and roughly by how much, given that there are off-diagonal entries weighted by 0.005? Then choose VICReg and spread, set the spread per dimension to 0.1, and predict the variance term before you look.
Each kind of damage shows up in the term built to catch it, the division of labor the cell above printed. The paper's coefficient study, which drops terms from the loss at ImageNet scale, tells the same story.
VICReg loss and its gradient
Implement vicreg(Z1, Z2, lam_inv=25.0, lam_var=25.0, lam_cov=1.0, eps=1e-4) for two batches of shape (B, d_z), exactly as the definition box writes it. Five details matter. Use the unbiased variance and covariance. Hinge , not the variance. Keep the factors. Average the invariance over the batch. Regularize each branch separately. Return (loss, dZ1, dZ2), the loss and its gradients with respect to both inputs. Use no loops.
Clustering, and codes that must be balanced
A third family prevents collapse by counting. Give the network a set of clusters, assign every image to one of them, and train the network to predict an image's assignment from another view of it. Collapse would put every image in one cluster. So add a rule that the clusters must be used equally, and the constant solution can no longer score well.
SwAV, short for swapping assignments between views (Caron et al. 2020), does the balancing inside each batch. So the method runs online, one batch at a time, with no pass over the whole dataset.
SwAV's clusters are prototypes, learned unit vectors in the embedding space, one per cluster. An image's code is a soft assignment, a probability distribution over the prototypes. The codes of a batch are chosen to agree with the embeddings as much as possible, under one rule. Every prototype must receive an equal share of the batch, a rule called equipartition. Then each view is trained to predict the other view's code.
Choosing the codes is an optimal transport problem. Think of each image as holding an equal share of mass, , that it must ship to the prototypes. Shipping mass from image to prototype earns the score , the cosine similarity between them, per unit of mass. The plan must earn as much as possible, and every prototype must receive the same total, . Here is a tiny case. With 4 images and 2 prototypes, each prototype must receive half the mass, two images' worth, even if all 4 images prefer the first prototype.
The entropy term keeps the codes soft, and sets how soft. The constrained problem has a closed-form solution up to two scaling vectors, and the algorithm that finds them takes a few lines.
∂ Deriving the form of the transport plan
The objective is strictly concave in (a linear term plus times the strictly concave entropy), and the constraint set is convex and compact, so the maximizer exists and is unique. Attach a multiplier to each image's constraint and to each prototype's,
Setting gives
Every entry is positive, so the constraint is inactive, and the stationary point is the maximizer. The column constraint reads , so for fixed the right is . The row constraint gives . Sinkhorn-Knopp alternates these two updates. That is the same as alternately dividing each column of the current matrix by its sum and multiplying by , then each row by its sum and multiplying by . One global constant multiplying cancels in every rescaling, which is why subtracting the largest score before exponentiating is safe.
The same entropic balanced assignment appears in §13.3, which derives it for routing tokens to experts, with tokens in place of images and experts in place of prototypes. There its job is to keep every expert busy. Here its job is to make the constant solution expensive, and the next result says exactly how expensive.
Proof. Swapping two images leaves the problem unchanged, so by uniqueness the solution has identical rows. The column constraint then forces every entry to be , so every code is uniform. The loss of each image is a cross-entropy against the uniform distribution, which is at least that distribution's entropy, (§0.5). ∎
For SwAV's 3,000 prototypes, a collapsed encoder pays at least per image. An encoder whose predictions match confident, balanced codes can bring the loss down toward the codes' own entropy, which is near 0 when is small. Equipartition turns the constant solution into a bad one.
The same reasoning explains SwAV's three warnings, and each is a setting you must get right in practice.
- A large weights the entropy so heavily that the codes are nearly uniform whatever the embeddings. Then the target carries no information, and the authors observed that training collapses.
- A small gives sharp codes, but becomes extreme, and three iterations may not finish balancing them. The cell below shows this.
- A small batch breaks the balance. The batch must be large compared with , or there is no meaningful balanced assignment. With batch 256 and 3,000 prototypes, SwAV keeps a queue of the last 3,840 embeddings and computes codes over it. That is a far shorter queue than MoCo's 65,536.
The cell balances 6 images over 3 prototypes, a small example you can follow entry by entry.
Four of the six images prefer prototype 1, so assigning each image to its best prototype gives totals . At , three iterations barely move them, to . The scores differ by up to 0.9, and dwarfs everything else. Fifty iterations reach the equipartition , and they split image 4 evenly between the first two prototypes. At , three iterations already balance the batch, but image 4's code is soft, . A small buys sharp targets at the cost of slow balancing. With thousands of images per batch, SwAV's authors found three iterations enough in practice. The collapsed batch gets uniform codes and a loss of exactly .
Sinkhorn-Knopp for balanced codes
Implement sinkhorn(scores, eps=0.05, n_iters=3) for scores of shape (B, K_p), following SwAV's released order exactly.
- Form of shape
(K_p, B), subtracting the single largest entry ofscores / epsbefore exponentiating, and divide by its total. - Repeat
n_iterstimes. Rescale every row (prototype) to sum to , then every column (image) to sum to . - Rescale every column to sum to 1, and return the transpose, codes of shape
(B, K_p)whose rows sum to 1.
Use one global constant for the shift in step 1. A per-image shift would change the result after a finite number of iterations. The released code skips the shift, which changes nothing mathematically but can overflow.
Dimensional collapse, even with negatives
Negatives prevent complete collapse. They do not prevent dimensional collapse. Jing, Vincent, LeCun and Tian (2022) trained a standard SimCLR for 100 epochs on ImageNet with 128-dimensional embeddings. A sizable part of the embedding covariance spectrum had fallen to essentially zero. They proved two mechanisms that cause it, each for linear networks.
Strong augmentation. Take a one-layer linear encoder trained with InfoNCE, the contrastive loss of §7.2. Its gradient flow is for a symmetric matrix . That matrix is a weighted covariance of the data minus a weighted covariance of the augmentation noise. Along a direction where the augmentation varies more than the data, has a negative eigenvalue. Treating as fixed, as their Theorem 1 does, the weight along that direction then shrinks to zero. In plain words, pushing negatives apart along such a direction does not pay, because pulling the positive pair together along it costs more.
Implicit regularization. Now take two linear layers, . During training, the singular vectors of adjacent layers align. Each aligned pair of singular values then grows at a rate proportional to its own size. So small directions stay small, and the product drifts toward low rank, even without strong augmentation (their Theorems 2 and 3).
The cell tests the first mechanism in a small simulation. It trains a linear encoder on 16-dimensional data of unit variance with InfoNCE over a batch of 64. The similarity is , as in their analysis. It runs once with mild augmentation and once with augmentation of variance 8 on dimensions 8 to 15.
With mild augmentation, all 16 singular values of stay alive. The noisy half sits at 0.33 to 0.68, against 1.3 to 1.9 for the clean half. With strong augmentation, the noisy half falls to between 0.001 and 0.09, while the clean half grows past 1.6. That is a gap of at least 18 times, and up to three orders of magnitude. The encoder still has negatives, and it has still discarded half of its dimensions.
Here the discarded directions are pure nuisance, which is the point of augmentation. In a real image the line between nuisance and content is not so clean. Jing et al. argue that the lost dimensions are capacity a downstream task could have used, and the projector results below support them.
This also explains the projection head. A trainable projector between the representation and the loss can absorb the collapse, so that the representation keeps more dimensions than the embedding . Jing et al. confirmed it at 100 epochs with a ResNet-50.
- SimCLR with a two-layer nonlinear projector reached 66.5 percent.
- With a linear projector it reached 61.1, and with no projector 51.5. Without a projector, the representation's own spectrum collapsed.
- Their DirectCLR applies InfoNCE directly to a fixed sub-vector of the representation, its first coordinates, with no trainable projector. It reached 62.7, beating the linear projector.
Garrido et al. (2023) later turned the same observation into a tool. The effective rank of the embeddings tracks downstream accuracy well enough to select hyperparameters without labels, which §28.6 takes up. An interviewer who asks why we throw the projection head away expects this answer, as well as the one from §28.2.
In PyTorch
Here are four of the losses in production form, BYOL, SimSiam, Barlow Twins, and VICReg. The stop-gradient is .detach(), and the moving-average update runs under torch.no_grad(). The block also checks two exact results against autograd. One is SimSiam's identity, that without a predictor the stop-gradient loss has half the gradient of the plain loss. The other is the VICReg covariance gradient from the theorem.
All the joint-embedding methods side by side
Every method in this chapter so far is a joint-embedding method. It embeds two views with encoders and compares the embeddings. The table puts the methods of §28.2 and this section together, at real scale.
Each family pays a different cost for avoiding collapse. Contrastive methods pay for many negatives. The redundancy-reduction methods, Barlow Twins and VICReg, pay in memory, not compute.
The asymmetric methods, BYOL and SimSiam, pay in sensitivity to hyperparameters instead. Their success depends on the target momentum, the predictor's learning rate, and the weight decay. Those are exactly the three quantities the linear theory singles out.
Where it breaks. The mechanisms are understood for linear networks. For deep networks, the linear theorems predict the ablations, but nobody has proved that BYOL or SimSiam avoid collapse. Both also have failure modes the theory does not cover. A frozen predictor fails to converge, and BatchNorm on the predictor's output makes the loss oscillate. Barlow Twins and VICReg cannot reach their minimum when exceeds the batch, so the balance of their terms depends on . Clustering methods need a batch or a queue that is large compared with the number of prototypes. And every method here compares whole-image embeddings. None of them is trained to keep the spatial detail that segmentation needs. That gap is what §28.4 and §28.5 address.
The same tools reach beyond whole images. A stop-gradient and a moving-average target keep joint-embedding predictive architectures from collapsing, models that predict the embeddings of hidden image regions from the visible ones. LeCun's 2022 proposal for such architectures, A Path Towards Autonomous Machine Intelligence, suggested variance and covariance terms like VICReg's for the same purpose.
Read more
- Grill et al. (2020). Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning. BYOL, its ablations on the target and the predictor (Table 5), and the optimal-predictor argument (Section 3.2 and Appendix H).
- Chen and He (2021). Exploring Simple Siamese Representation Learning. SimSiam, the stop-gradient experiment, the predictor ablation with its exact gradient argument, and the expectation-maximization hypothesis.
- Tian, Chen and Ganguli (2021). Understanding Self-Supervised Learning Dynamics without Contrastive Pairs. The linear theory of this section, eigenspace alignment, and DirectPred.
- Zbontar, Jing, Misra, LeCun and Deny (2021). Barlow Twins: Self-Supervised Learning via Redundancy Reduction. The cross-correlation loss and its connection to the information bottleneck.
- Bardes, Ponce and LeCun (2022). VICReg: Variance-Invariance-Covariance Regularization for Self-Supervised Learning. The three-term loss, the coefficient study, and the comparison with every other family in its appendix.
- Caron et al. (2020). Unsupervised Learning of Visual Features by Contrasting Cluster Assignments. SwAV, online codes by Sinkhorn-Knopp, and multi-crop.
- Jing, Vincent, LeCun and Tian (2022). Understanding Dimensional Collapse in Contrastive Self-supervised Learning. Dimensional collapse in SimCLR, its two linear mechanisms, and DirectCLR.
- Garrido, Balestriero, Najman and LeCun (2023). RankMe: Assessing the Downstream Performance of Pretrained Self-Supervised Representations by Their Rank. The effective rank as a label-free measure of representation quality.