Everyone knew InfoNCE worked. Nobody could say what it wanted. This paper answers with two numbers you can compute in four lines of PyTorch — and then throws the loss away and optimizes the two numbers instead.
It is 2020. You have trained a self-supervised encoder. The recipe is four lines long: take an image, make two random crops of it, push both through a ResNet, L2-normalise the outputs, and minimise a loss that says these two vectors should be closer to each other than either is to any other image in the batch. No labels anywhere.
Then you freeze the encoder, fit a single linear layer on top of its features using ImageNet labels, and it gets 70% top-1. A linear layer. On features that were never told what a dog is.
So here is the question this paper asks, and it is embarrassingly basic: what did that loss teach the encoder? Not "does it work" — we can see it works. What property of the representation is the loss actually pushing on?
This is the argument that ends the debate, so let us do it carefully and from zero.
Mutual information I(A;B) measures how many bits knowing A tells you about B. Its defining property — the one that makes it beautiful and, here, useless — is invariance under invertible transformations. If g is a bijection (a function you can undo exactly), then
Why? Because knowing g(A) and knowing A are the same knowledge. You can compute either from the other. No information is created or destroyed by relabelling.
Now take your trained encoder f, which produces 128-dimensional features, and build a second encoder f′ = g ∘ f, where g is some wild but invertible scrambling of R128 — say, a random orthogonal rotation composed with a coordinate-wise cube. Then:
Two encoders, the same mutual information, wildly different usefulness. Therefore mutual information cannot be the quantity that determines downstream quality. It is not that the story is imprecise; it is that the story is measuring something that is blind to the thing we care about.
The second failure is empirical and just as damaging. The InfoNCE bound has a hard ceiling. With M samples in the denominator, the bound states, roughly,
Since the loss cannot go below zero, the bound can never certify more than log M nats of information, no matter how good your encoder is. Put numbers on it.
| Batch / queue size M | log M (nats) | Ceiling in bits | Comment |
|---|---|---|---|
| 256 (a typical SimCLR batch on one node) | ln 256 = 5.545 | 8.0 bits | 256 = 28, so the arithmetic is exact |
| 4,096 (SimCLR's large-batch setting) | ln 4096 = 8.318 | 12.0 bits | Doubling the batch buys exactly one bit |
| 65,536 (MoCo's memory queue) | ln 65536 = 11.090 | 16.0 bits | A 256× bigger denominator buys 8 more bits |
Sixteen bits. That is two bytes. The true mutual information between two crops of the same photograph — sharing lighting, texture, object identity, scene layout — is enormously larger than two bytes. The bound is not slightly loose; at these batch sizes it is nearly vacuous, and yet the method works beautifully.
Worse: Tschannen et al. (2020) took the obvious next step and asked what happens if you use a tighter mutual-information estimator. If MI maximisation were the mechanism, tighter estimates should give better representations. They found the opposite — looser, "worse" estimators frequently produce better features. The correlation between the stated objective and the actual outcome is not merely weak. It sometimes runs backwards.
That ceiling is worth deriving rather than quoting, because the same log M will reappear as the natural normalisation in Chapter 4's theorem, and seeing it twice from two directions is what makes the theorem feel inevitable.
The InfoNCE bound comes from turning density-ratio estimation into a classification problem. Suppose you are handed M candidates, exactly one of which is the true partner y of an anchor x, and the other M−1 are drawn independently from the marginal. Your job is to say which. If your critic scores candidate yj with some function g(x, yj), the posterior probability that candidate j is the true one, under this generative story, is
So the optimal critic is the density ratio p(y|x)/p(y), whose log is exactly the pointwise mutual information. Plug the optimal critic into the cross-entropy loss of this M-way classification problem and rearrange, and you get
which is the same statement as I(x;y) ≥ log M − ℓ. Two facts follow immediately, and both are structural rather than incidental.
The bound saturates at log M. A cross-entropy loss is non-negative, so the right-hand side can never exceed log M. This is not a slack estimate you can tighten with a better encoder; it is the information content of the M-way classification task itself. You are asking a question whose answer contains log M nats, so no answer can certify more than log M nats.
M is the batch, and the batch is memory. That is why the field spent 2019 and 2020 building machinery — memory banks, momentum queues, 4096-way TPU batches — whose only purpose is to make one number in a bound larger. Whether that machinery was helping for the stated reason is precisely what the next two failures cast doubt on.
Before accepting the paper's answer, it is worth ruling out the other things people say in seminars, because each is almost right.
| The explanation | Why it feels right | Where it breaks |
|---|---|---|
| "It learns to be invariant to augmentations" | True — positive pairs are augmentations of one image, so the encoder is pushed toward augmentation-invariance | Only half the story. A constant encoder f(x) = c is perfectly augmentation-invariant and completely useless. Invariance alone predicts collapse, which does not happen |
| "It performs instance discrimination" | True by construction — the task is telling instances apart | This restates the loss rather than explaining it. Why should being able to tell 1.28M photos apart make a linear classifier over 1000 semantic classes work? |
| "It clusters semantically similar images" | Empirically it does — look at any t-SNE of the features | The loss never sees a class label. It explicitly pushes every other image away, including images of the same class. The clustering is an emergent side effect, not the objective |
| "It maximises mutual information" | The bound is real and the derivation is correct | Bijection-invariant, therefore blind to the geometry that decides linear-probe accuracy — and empirically anti-correlated when tightened |
Look down the "where it breaks" column and a shape appears. Every failed explanation captures exactly one force. Invariance captures the pull. Instance discrimination captures the push. Neither, alone, is a description of what the optimum looks like.
Wang & Isola change the question. Instead of "which information-theoretic functional does this loss estimate?", they ask: if I could optimise this loss perfectly, over an unrestricted encoder, what would the resulting distribution of features on the sphere look like?
That question has an answer, and it has exactly two parts.
And then the paper does the thing that makes it a great paper rather than a good one. It writes both properties down as explicit, differentiable, four-line metrics, throws InfoNCE away, optimises the two metrics directly, and shows that this matches or beats the original loss on vision and language benchmarks alike.
You will spend three chapters deriving these. Here they are up front, so you know where you are heading. Let f be the encoder, and assume its output is L2-normalised, so every feature is a point on the unit sphere.
Read it in English: take a positive pair, measure how far apart their features landed, raise that distance to a power α (default 2), and average over all positive pairs. Lower is better. Zero means every positive pair maps to exactly the same point.
Read it in English: take two independent samples from the dataset, measure the squared distance between their features, pass it through a decaying exponential — nearby points score high, far points score near zero — average, and take the log. Lower is better. It is the average pairwise potential energy of the feature cloud, and Chapter 3 proves that it is minimised, uniquely, by the uniform distribution on the sphere.
Two lines of maths. Four lines of PyTorch. That is the whole contribution, and the rest of this lesson is about earning it.
Every contrastive method in this literature does the same small thing right before computing the loss: it divides the feature vector by its own length.
Here h is the network — ResNet plus a projection MLP — and f is what actually enters the loss. One division. It looks like a numerical-stability nicety, the sort of line you would skim past. It is the reason the entire paper is possible, and this chapter is about why.
The set of all unit-length vectors in Rm is the unit hypersphere, written Sm−1:
The superscript is m−1, not m, because the surface has one dimension fewer than the space it sits in. In R3, the surface of a ball is S2 — two-dimensional, which is why a map of the Earth is a flat sheet. For a 128-dimensional projection head, features live on S127.
Two identities do all the work in this lesson, so derive them once and never again. For unit vectors u and v:
The dot product is the cosine of the angle between them, because both lengths are 1. And the squared distance:
Expand the bracket, use ‖u‖2 = ‖v‖2 = 1, and you are done. This tiny identity is the hinge on which Chapter 4's theorem turns: squared distance and dot product are the same quantity, affinely rescaled. Anything written with one can be rewritten with the other.
| Angle θ | u · v | ‖u − v‖2 = 2 − 2cosθ | ‖u − v‖ |
|---|---|---|---|
| 0° (identical) | 1.000 | 0.000 | 0.000 |
| 30° | 0.866 | 0.268 | 0.518 |
| 60° | 0.500 | 1.000 | 1.000 |
| 90° (orthogonal) | 0.000 | 2.000 | 1.414 |
| 120° | −0.500 | 3.000 | 1.732 |
| 180° (antipodal) | −1.000 | 4.000 | 2.000 |
Memorise the last row. The maximum possible squared distance on a unit sphere is 4. Every number in Chapters 3 and 5 lives in [0, 4], and knowing the ceiling makes the exponentials legible at a glance.
This is the argument that most people have not actually worked through, so let us do the arithmetic.
The contrastive loss for one anchor with one positive and M negatives is
where s is a similarity score and τ (tau) is the temperature, a positive scalar that sharpens the softmax as it shrinks. Suppose the network outputs unnormalised vectors and we use the raw dot product s = h(x) · h(z). Take a concrete arrangement: all vectors at radius r, the anchor at angle 0°, the positive at 20°, and three negatives at 80°, 150°, and 200°. Set τ = 0.5.
The raw dot product between two vectors of length r at angle θ is r2cosθ. So every logit scales with r2. At r = 1:
arithmetic — unit-length features, tau = 0.5cosines: pos cos(20) = 0.9397 neg1 cos(80) = 0.1736 neg2 cos(150) = -0.8660 neg3 cos(200) = -0.9397 logits = cos / 0.5 = [ 1.8794 , 0.3473 , -1.7321 , -1.8794 ] exps = [ 6.5495 , 1.4152 , 0.1769 , 0.1527 ] sum = 8.2943 loss = -ln(6.5495 / 8.2943) = -ln(0.789634) = 0.2362
Now scale every vector to r = 2 — without moving a single one of them angularly. Every logit is multiplied by r2 = 4:
arithmetic — same angles, radius 2logits = 4 * [ 1.8794 , 0.3473 , -1.7321 , -1.8794 ] = [ 7.5175 , 1.3892 , -6.9282 , -7.5175 ] exps = [ 1840.04 , 4.0116 , 0.00098 , 0.00054 ] sum = 1844.050 loss = -ln(1840.04 / 1844.050) = -ln(0.997824) = 0.0022
Normalisation closes that escape hatch. On the sphere, s = cosθ is bounded in [−1, 1] and depends on nothing but the angular arrangement. The only way to reduce the loss is to move points relative to each other — which is to say, to learn.
One anchor (warm), one positive (green), three negatives (grey), fixed at the angles above. Drag the radius slider and watch the loss plummet while the arrangement stays frozen. Then toggle normalisation on: the ring snaps to radius 1 and the loss becomes a pure function of angle. The temperature slider shows the equivalence — radius r behaves exactly like temperature τ/r2.
This reason is quieter and more fundamental. The paper's entire second metric is "the features should be uniformly distributed". Ask yourself what that would mean in R128.
It means nothing. There is no uniform probability distribution on an unbounded space. Try to build one: assign equal density everywhere, integrate over infinite volume, and the total is infinite, not 1. You cannot normalise it. Uniform on Rm does not exist.
On a sphere it does exist, and it is unique. The sphere is compact (closed and bounded — finite surface area) and homogeneous (every point looks like every other point; rotations move any point to any other). Those two facts together give you exactly one rotation-invariant probability measure, the normalised surface measure, written σm−1. It is the thing you get by picking a point "at random on the sphere."
A practical point, but a real one. The loss exponentiates s/τ. With τ = 0.07 — SimCLR's setting for some configurations — and unnormalised features whose dot products can reach 40, you are computing e571. That overflows a float32 (which tops out near e88) and you get inf, then nan, then a dead run.
Normalised, the extreme case is e1/0.07 = e14.29 ≈ 1.6 × 106. Comfortable. This is why models like CLAP and CLIP that learn the temperature also clamp it: the bounded similarity gives you a known worst case, and you keep it that way.
The last reason is about the downstream task, and it is the one the paper leans on when it argues that these properties should help, not just that they are what the loss does.
A linear probe fits w and asks whether w · f(x) separates the classes. On the sphere, w · f(x) = ‖w‖ cos(angle between w and the feature). Up to the constant ‖w‖, a linear classifier on the sphere is an angular threshold: it carves the sphere with a hyperplane through the origin, producing two caps. If a class occupies a compact cap, a linear probe finds it.
That is precisely the arrangement alignment produces: each semantic group compressed into a small region. And uniformity ensures those regions are pushed apart rather than piled on top of each other. The two properties are not arbitrary aesthetic preferences — they are exactly the conditions under which the linear probe you are going to run at evaluation time can succeed.
One more piece of geometry, because it explains temperature settings you have probably copied without understanding. Take two points drawn independently and uniformly from Sm−1. What is their dot product, typically?
By symmetry the mean is 0. The variance works out to exactly 1/m. So the typical magnitude of the cosine between two random features is
| Dimension m | Typical random cosine 1/√m | Typical random angle | What it means |
|---|---|---|---|
| 2 (a circle) | 0.707 | ≈ 45° from orthogonal | Two random points are often quite similar; the circle is crowded |
| 16 | 0.250 | ≈ 75° | Getting roomy |
| 128 (the standard projection dim) | 0.088 | ≈ 85° | Almost everything is almost orthogonal to almost everything |
| 2048 | 0.022 | ≈ 88.7° | Effectively an orthogonal basis's worth of room |
At m = 128, the spread of the "background" similarities is about 0.09. Now recall the loss divides by τ. If τ = 1, the logits from random negatives span roughly ±0.09 — the softmax over them is nearly flat, and the loss barely distinguishes anything. If τ = 0.07, that same spread becomes ±1.3 in logit space, which is a meaningful softmax. The temperature's job is to rescale the natural angular noise floor of the sphere into a usable dynamic range, and the noise floor is set by the dimension.
Uniformity is a claim that spreading features out preserves information. That claim is only interesting if the sphere has enough room to be worth spreading into, so let us measure the room.
The tool is a concentration inequality. For u and v drawn independently and uniformly from Sd−1, the probability that their cosine exceeds a threshold ε falls off exponentially in the dimension:
Read the right side as "the fraction of the sphere lying inside a cap of cosine radius ε around any fixed point." Evaluate it at d = 128:
| Cosine threshold ε | Angle | Fraction of S127 inside the cap | Reading |
|---|---|---|---|
| 0.1 | 84.3° | e−0.64 = 0.527 | Half the sphere — a cosine of 0.1 means nothing at all |
| 0.3 | 72.5° | e−5.76 = 0.0032 | Three parts in a thousand |
| 0.5 | 60.0° | e−16 = 1.1 × 10−7 | One ten-millionth of the surface |
| 0.8 | 36.9° | e−41 = 1.6 × 10−18 | Vanishing. Reaching cosine 0.8 by accident is impossible |
The same inequality explains a second thing you have certainly noticed: contrastive models trained in high dimension report very small cosine similarities between unrelated items — 0.05, 0.1 — and beginners read that as "the model thinks nothing is similar to anything." It does not. Those numbers are the background level of a high-dimensional sphere, and a cosine of 0.3 that would look unimpressive in two dimensions is, at d = 128, a one-in-three-hundred event. Always calibrate similarity scores against 1/√d, never against 1.
One implementation detail that trips people up. Modern contrastive models have two stages: a backbone h producing, say, 2048-dimensional features, and a small projection head g producing 128 dimensions. The normalisation goes on the output of g, and the loss operates there. But the representation you actually use downstream is the backbone output h, before the head.
So every property this paper analyses — alignment, uniformity, position on the plane — is a property of a space that gets thrown away at deployment. That sounds absurd and is one of the field's genuinely odd empirical facts: features before the projection head consistently give better linear probes than features after it. Chapter 8 revisits this with the alignment-uniformity lens, which gives it a satisfying explanation. For now, just be precise about which vector you are measuring, and report it, because the two spaces have very different metric values.
| The normalisation buys | Because | Where it shows up later |
|---|---|---|
| The loss depends only on geometry | Norm inflation, an equivalent free temperature, is removed | Chapter 4 — the theorem is about the distribution of points, so the points must be pinned to the surface |
| "Uniform" is well-defined and unique | Compact + homogeneous ⇒ exactly one rotation-invariant probability measure σm−1 | Chapter 3 — every uniqueness proof |
| Distance and dot product are interchangeable | ‖u−v‖2 = 2 − 2u·v exactly | Chapters 2 and 4 — converting the loss's first term into the alignment metric |
| Numerical safety | s ∈ [−1,1] bounds the exponent by 1/τ | Any training run that does not produce NaN |
| A friendly space for linear probes | A linear classifier becomes an angular threshold cutting spherical caps | Chapter 7 — why position on the tradeoff plane predicts probe accuracy |
Alignment is the easy half, and it is worth doing slowly anyway, because the easy half contains the one parameter people misconfigure.
Everything starts with a distribution the paper calls ppos: the distribution over pairs (x, y) that we have declared to be "the same thing." In vision, x and y are two random augmentations of one image — a crop, a colour jitter, a flip. In the sentence-embedding setting they might be two adjacent sentences. In CLIP-style models they are an image and its caption.
The paper requires one technical condition on ppos, and it is worth naming because it is easy to violate by accident: the two marginals must match. If you look only at x, you should see pdata; if you look only at y, you should also see pdata. Formally ppos is symmetric and both of its marginals equal pdata.
We want a number that is small when positive pairs land in the same place. The obvious candidate is the distance between them. Average it over the pair distribution and you are done:
Three observations, each of which you should be able to reconstruct.
It is bounded. On the sphere, distances live in [0, 2], so ℓalign ∈ [0, 2α]. For the default α = 2, the range is [0, 4]. A value of 0 means perfect alignment. A value of 4 means every positive pair is antipodal, which would take active malice to achieve.
Its minimum is exactly "perfectly aligned." The metric is zero if and only if f(x) = f(y) almost surely for positive pairs — the paper's definition of a perfectly aligned encoder. Since a distance is non-negative and its average is zero only when it is zero almost everywhere, there is no slack in this statement.
It says nothing about anything else. The constant encoder f(x) = u0 achieves ℓalign = 0. So does an encoder that maps every cat and every truck to the same point. Alignment is a purely local property of the pair distribution and is completely blind to whether the representation retains information. Hold that thought; it is why Chapter 3 exists.
Now the part people get wrong. α is not a "strength" knob — that is what λ is for when you combine the two losses. α changes which positive pairs the gradient cares about.
Take two positive pairs in a batch. Pair A landed 0.2 apart (already well aligned). Pair B landed 1.2 apart (badly aligned — roughly 70°). Compute the loss under three settings of α:
arithmetic — two positive pairs at distances 0.2 and 1.2alpha = 0.5: (0.2^0.5 + 1.2^0.5)/2 = (0.4472 + 1.0954)/2 = 0.7713 alpha = 1.0: (0.2 + 1.2 )/2 = (0.2000 + 1.2000)/2 = 0.7000 alpha = 2.0: (0.2^2 + 1.2^2 )/2 = (0.0400 + 1.4400)/2 = 0.7400
The loss values are almost the same. That is not the interesting part. The interesting part is the derivative, because the derivative is what gradient descent uses. For a single pair at distance d, the contribution is dα, so
Evaluate that at both distances:
| α | Gradient at d = 0.2 (good pair) | Gradient at d = 1.2 (bad pair) | Ratio bad : good | Behaviour |
|---|---|---|---|---|
| 0.5 | 0.5 × 0.2−0.5 = 1.118 | 0.5 × 1.2−0.5 = 0.456 | 0.41× | Inverted. Pushes hardest on pairs that are already close; nearly ignores the failures |
| 1.0 | 1 × 0.20 = 1.000 | 1 × 1.20 = 1.000 | 1.00× | Neutral. Every pair gets the same push regardless of how wrong it is |
| 2.0 | 2 × 0.2 = 0.400 | 2 × 1.2 = 2.400 | 6.0× | Hard-pair focused. The worst pair receives six times the pull |
| 3.0 | 3 × 0.04 = 0.120 | 3 × 1.44 = 4.320 | 36× | Aggressive; a single mislabelled positive pair can dominate the batch |
Left: two positive pairs on the circle, their separations set by the sliders. Right: the curve dα with both pairs marked, and the gradient arrow at each — arrow length is the pull that pair contributes. Sweep α and watch the pull transfer between the easy pair and the hard one. At α < 1 the arrows invert; at α = 1 they are equal; at α = 2 the hard pair dominates.
There is a second, more conceptual way to read this metric. Because ppos is generated by augmentation, saying "positive pairs map to the same point" is the same as saying the encoder is invariant to the augmentation distribution. Whatever the augmentation destroys, the encoder is being told to ignore.
This is where the semantics secretly enter. The loss has no idea what a dog is. But the crop-and-jitter pipeline says: colour is not identity, position is not identity, scale is not identity, but texture and shape are. Alignment then forces the encoder to build features that survive exactly those nuisances. The augmentation set is the entire prior, smuggled in through ppos.
A metric with no reference values is useless, so fix the scale before you ever log one.
The no-information reference is 2.0. If the encoder's output were statistically independent of its input — a random projection of noise — then f(x) and f(y) are two independent uniform points on the sphere, so E[f(x)·f(y)] = 0 and
That is the same 2.0 as the "untrained" corner of Chapter 7's plane, and it holds at any dimension. A freshly initialised network usually sits a little below it, because random convolutional features of two crops of the same photo are weakly correlated, but 2 is the ceiling you should think of.
The perfect-invariance reference is 0.0, achievable and undesirable on its own.
Trained models land between roughly 0.2 and 0.8, and where exactly depends almost entirely on how aggressive your augmentations are, not on how good your model is. That is the single most important thing to internalise about this metric: ℓalign is not a quality score. A model trained with weak augmentations will have better alignment and worse features. Only compare alignment values across runs that share an augmentation pipeline.
A frequent confusion, and clearing it up sharpens what the objective actually is.
Alignment is defined over positive pairs, which in self-supervised learning means augmentations of the same instance. It says nothing about whether two different photographs of golden retrievers land near each other. As far as ℓalign is concerned, those two photos are unrelated inputs, and Chapter 3's uniformity term will actively push them apart.
| Quantity | Measured over | Optimised by contrastive loss? |
|---|---|---|
| Alignment | Pairs of augmentations of one image | Yes — directly, it is half the objective |
| Intra-class compactness | Pairs of different images with the same label | No — and the uniformity term works against it |
| Inter-class separation | Pairs of images with different labels | Only incidentally, as a special case of pushing all instances apart |
That the resulting features are nonetheless class-compact is an emergent phenomenon, driven by the fact that a finite-capacity network cannot separate two golden retrievers as cheaply as it can separate a retriever from a fire truck. The objective supplies a uniform push; the architecture decides where the push is easy. Chapter 8 returns to this as the framework's central unexplained step, and it is the reason a supervised contrastive loss — which redefines ppos to include same-label pairs — is a genuinely different objective rather than a tweak.
One last piece of bookkeeping, and it is the reason α = 2 is the natural default rather than an arbitrary one. Use the identity from Chapter 1:
Take the expectation over positive pairs and divide by τ:
Read the left side: it is "minimise the negative cosine of positive pairs", which is exactly the numerator of the contrastive loss in disguise. Read the right side: it is the alignment metric with α = 2, multiplied by a positive constant, minus a constant that does not depend on f.
These are the same objective. Not similar — identical, up to an affine transformation that cannot change which encoder is optimal. When Chapter 4 splits the contrastive loss in two, the first half is not "something like alignment". It is ℓalign(f; 2), and that is why 2 is the canonical exponent.
Picture the endgame. If ℓalign = 0 exactly, then every positive pair sits on the same point. Positive-pairing induces an equivalence relation on the data — "x ~ y if they are augmentations of the same underlying image" — and a perfectly aligned encoder is constant on each equivalence class. So the feature cloud is not really a cloud at all; it is a finite set of atoms, one per image in the dataset.
That is worth sitting with. A perfectly aligned encoder on a dataset of N images produces at most N distinct points on the sphere, no matter how rich the network. The continuous-looking feature distribution you see in a t-SNE plot is a consequence of imperfect alignment, not of the objective. And the question of where those N atoms should go — that is precisely the question uniformity answers, and precisely the question that classical physicists have been asking about electrons on a sphere for a century.
Alignment took one paragraph to motivate and one line to write. Uniformity takes a chapter, because "spread the points out" is a phrase with dozens of plausible formalisations and almost all of them are broken. Watching two of them break is the fastest way to understand why the paper's choice is the right one.
The most natural idea. If you want points spread out, push apart every pair. So define a loss that minimises the negative average squared distance, i.e. maximises
where x and y are drawn independently. Expand using Chapter 1's identity, and remember that for independent draws the expectation of a product is the product of expectations:
derivation — average pairwise squared distance on the sphereE[ ||u - v||^2 ] = E[ 2 - 2 u.v ] = 2 - 2 E[u . v] = 2 - 2 E[u] . E[v] # u, v independent = 2 - 2 ||E[u]||^2 # same distribution, so E[u] = E[v]
Stop and read that last line, because it is devastating. The average pairwise distance depends on the feature distribution only through its mean vector. Every other detail — shape, spread, number of modes, dimension actually used — is invisible to it. Maximising the average distance is exactly and only the instruction "make the mean zero."
Here is the counterexample that kills it. Put half your probability mass on a single point u0 and the other half on −u0. Total collapse to two atoms — the representation retains exactly one bit about the input.
| Distribution on the circle | Mean vector | E‖u−v‖2 = 2 − 2‖E[u]‖2 | Verdict of this objective |
|---|---|---|---|
| Genuinely uniform σ1 | 0 | 2.000 | Optimal |
| Two antipodal atoms, half mass each | ½u0 + ½(−u0) = 0 | 2.000 | Also optimal — a perfect tie |
| All mass on one point | u0, norm 1 | 0.000 | Worst, correctly |
Verify the two-atom row by hand rather than trusting the formula. Draw two points independently: with probability ½ they land on the same atom (distance2 = 0) and with probability ½ on opposite atoms (distance2 = 4). Average: ½(0) + ½(4) = 2. Identical to the uniform distribution's score. The objective cannot tell them apart.
The theoretically correct thing to want. The uniform distribution on a compact space is precisely the maximum-entropy distribution, so "maximise differential entropy" has exactly the right answer.
It is also unusable, for three reasons that any practitioner will recognise. Estimating differential entropy in 128 dimensions from a batch of 256 samples is statistically hopeless — nearest-neighbour estimators have variance that swamps the signal at these sample sizes. The estimators that do exist are not smoothly differentiable, so backpropagating through them is painful. And entropy on a manifold requires care about the reference measure, which invites subtle bugs.
We want something with entropy's minimiser and a sample mean's tractability. That is what a pairwise potential gives you.
Define the Gaussian potential kernel (also called the radial basis function or heat kernel) between two points on the sphere:
Think of it as a proximity score with a tunable reach. Two points on top of each other score G = 1. Points at maximum separation (squared distance 4) score e−4t, which at t = 2 is 0.000335 — effectively zero. In between it falls off smoothly.
Now average this over all pairs of independently drawn data points and take the logarithm:
This is the total pairwise potential energy of the feature cloud, log-scaled. Every pair of points that sits close together contributes energy; pairs that are far apart contribute nothing. Minimising it means arranging the points so that no two of them are crowded.
| Squared distance d2 | Angle | G2 = e−2d2 | Contribution |
|---|---|---|---|
| 0.00 | 0° | 1.000000 | Maximum penalty — two features have collapsed onto each other |
| 0.27 | 30° | 0.585137 | Still substantial |
| 1.00 | 60° | 0.135335 | Fading |
| 2.00 | 90° | 0.018316 | Nearly invisible |
| 4.00 | 180° | 0.000335 | Zero for all practical purposes |
Here is the theorem that justifies the whole construction. The paper states it as Proposition 1.
Unique is a strong word and it is meant literally: not "one of the minimisers", not "a minimiser up to rotation" — there is exactly one distribution that achieves the minimum, and it is the one you wanted. Let us see why, in two moves.
Move 1: the energy is strictly convex. A kernel K is called strictly positive definite if, for every signed measure ν that is not zero but has total mass zero, the double integral ∫∫ K dν dν is strictly positive. The Gaussian kernel has this property on the sphere. Now take two different distributions μ0 and μ1, and interpolate: μλ = (1−λ)μ0 + λμ1. Write ν = μ1 − μ0, which has total mass 1 − 1 = 0. Expanding the energy E(μ) = ∫∫Gt dμ dμ:
The coefficient of λ2 is strictly positive by strict positive definiteness. So E, viewed along any straight line between two distinct distributions, is a strictly convex parabola. A strictly convex function on a convex set has at most one minimiser. That is the uniqueness, and it came entirely from one property of the kernel.
Move 2: symmetry forces the minimiser to be uniform. Gt(u,v) depends only on the distance between u and v, so rotating both points leaves it unchanged. Therefore if you rotate the whole distribution, its energy is unchanged: E(R#μ) = E(μ) for every rotation R. Suppose μ* is the unique minimiser. Then R#μ* is also a minimiser, so by uniqueness R#μ* = μ*, for every rotation. A probability measure on the sphere invariant under all rotations is the surface measure, and nothing else. Hence μ* = σm−1. ∎
This is the satisfying part. The linear "spread" objective −E[u·v] is a kernel too, and its harmonic spectrum has exactly one non-zero entry: degree 1. It sees the mean and is blind to every other degree, which is why a two-atom distribution slips past it undetected. The Gaussian kernel's spectrum is positive at every degree, so no distribution can hide from it.
Run the numbers side by side, on the circle, with t = 2. The uniform distribution's Gaussian energy on S1 has a closed form — Eσ[Gt] = e−2t I0(2t), where I0 is the modified Bessel function of the first kind:
arithmetic — uniform vs. two-atom collapse, t = 2# Two antipodal atoms, half mass each. # Independent draws: P(same atom) = 1/2 -> d^2 = 0 ; P(opposite) = 1/2 -> d^2 = 4 E[G_2] = 0.5 * exp(0) + 0.5 * exp(-8) = 0.5 * 1.000000 + 0.5 * 0.000335 = 0.500168 l_uniform = ln(0.500168) = -0.6928 # Genuinely uniform on the circle. E[G_2] = exp(-2t) * I_0(2t) = exp(-4) * I_0(4) = 0.0183156 * 11.301922 = 0.207001 l_uniform = ln(0.207001) = -1.5750 # Gap = 0.882 nats. The Gaussian kernel is not fooled. # Under the LINEAR objective both score exactly 2.000. Tie.
The number −1.5751 in that code block deserves to be earned rather than quoted, because it is the reference against which every other configuration is judged, and the derivation is a nice piece of undergraduate calculus.
On the circle, parametrise a point by its angle. Two independent uniform draws differ by an angle θ that is itself uniform on [0, 2π). Their squared distance is 2 − 2cosθ, so
derivation — the uniform distribution's Gaussian energy on the circleE[G_t] = (1/2pi) INTEGRAL_0^{2pi} exp( -t (2 - 2 cos(theta)) ) d(theta)
= exp(-2t) * (1/2pi) INTEGRAL_0^{2pi} exp( 2t cos(theta) ) d(theta)
\____________ this is the integral definition of I_0(2t) ____________/
= exp(-2t) * I_0(2t)
The modified Bessel function I0 is defined by that integral, which is the sort of coincidence that stops being a coincidence once you notice that exponentials of cosines are how rotationally symmetric things on circles always end up. Its power series lets us evaluate it by hand:
At t = 2 we need I0(4), so z2/4 = 4. Each term is 4k/(k!)2:
arithmetic — I_0(4) from its series, nine termsk=0: 1 / (0!)^2 = 1 / 1 = 1.000000 k=1: 4 / (1!)^2 = 4 / 1 = 4.000000 k=2: 16 / (2!)^2 = 16 / 4 = 4.000000 k=3: 64 / (3!)^2 = 64 / 36 = 1.777778 k=4: 256 / (4!)^2 = 256 / 576 = 0.444444 k=5: 1024 / (5!)^2 = 1024 / 14400 = 0.071111 k=6: 4096 / (6!)^2 = 4096 / 518400 = 0.007901 k=7: 16384 / (7!)^2 = 16384 / 25401600 = 0.000645 k=8: 65536 / (8!)^2 = 65536 / 1.6257e9 = 0.000040 sum = 11.301922 E[G_2] = exp(-4) * 11.301922 = 0.0183156 * 11.301922 = 0.207001 l_uniform = ln(0.207001) = -1.5750
Notice how fast it converges: nine terms give six correct digits. Notice also the shape of the terms — they rise, peak around k = 2, then collapse. That peak sits near k ≈ z/2, which is the same "the exponential is dominated by a narrow band" behaviour that will explain the sampling-noise problem in Chapter 4.
One table to make the "strictly positive definite" idea concrete. Every rotation-invariant kernel on the sphere decomposes into spherical-harmonic degrees, and what determines whether it can be fooled is which degrees it gives weight to.
| Kernel | Harmonic degrees with non-zero weight | Blind to | Unique minimiser is σ? |
|---|---|---|---|
| −u·v (linear) | Degree 1 only | Everything except the mean vector | No — any mean-zero distribution ties, including two atoms |
| (u·v)2 | Degrees 0 and 2 | Odd structure; a two-atom cloud and its mirror are indistinguishable | No |
| e−t‖u−v‖2 | All degrees, all strictly positive | Nothing | Yes, for every t > 0 |
| ‖u−v‖−s (Riesz) | All degrees positive, but the energy integral diverges for s ≥ m−1 | Nothing, where it is finite | Yes, but only for 0 < s < m−1 |
Read the last two rows together and the paper's choice looks obvious rather than arbitrary. The Riesz family works, but its valid range of exponents depends on the dimension you happen to be in, and outside that range the objective is literally infinite for the distribution you want. The Gaussian kernel is bounded above by 1, bounded below by e−4t, smooth, differentiable, and correct for every t and every m. It is the boring choice, which in numerical work is the highest compliment available.
Points live on the circle — drag any of them. The ring around the outside is the potential field: bright means a new point placed there would pay a high energy cost, dark means there is room. Watch the field carve out the gaps as you move points. The panel underneath scores the same configuration under three kernels; load the two-atom preset and see the linear kernel award it a perfect tie with uniform while the Gaussian does not.
Press Minimise from the two-atom preset and watch the points fan out into an even ring. That animation is the entire content of Proposition 1, run numerically: descent on the Gaussian energy has one destination.
Proposition 1 is about probability measures, and a training batch is a finite set of M points. The bridge is the paper's Proposition 2: if you take the M-point configuration that minimises the average pairwise Gaussian potential, and let M grow, the empirical distribution of those points converges weak* to σm−1.
"Weak* convergence" means: for every continuous test function g, the average of g over your M optimal points converges to the integral of g against the uniform measure. Informally, the point cloud becomes indistinguishable from a uniform sample under any smooth measurement you could make.
That is what licenses the practical estimator. In code you compute the mean potential over the C(M,2) distinct pairs in the batch, which is a consistent estimate of the population double integral (the diagonal, where x = y, has probability zero under a continuous feature distribution). Minimising the batch quantity drives you toward the population minimiser.
The width t is not a nuisance parameter. It selects which classical problem you are solving, and both limits are worth deriving because Chapter 8 uses them to explain temperature.
As t → 0, uniformity degenerates into Attempt 1. For small t, e−td2 ≈ 1 − td2, so
Minimising that is minimising ‖E[u]‖2 — the mean-zero condition, with the two-atom degeneracy fully restored. The theory survives at any t > 0, but the discriminative power of the metric vanishes as t → 0.
As t → ∞, uniformity becomes best packing. With a huge t, the sum ∑ e−td2 is completely dominated by the single smallest distance, so log of the mean ≈ −t · mini≠j dij2 plus a constant. Minimising that means maximising the minimum pairwise distance — the Tammes problem of packing spherical caps, posed by a botanist in 1930 while counting pollen-grain pores.
| t | ℓuniform, two atoms | ℓuniform, true uniform | Gap (nats) | What the metric is really doing |
|---|---|---|---|---|
| 0.1 | −0.1801 | −0.1900 | 0.010 | Almost blind — a two-point collapse costs a hundredth of a nat |
| 2 (the default) | −0.6928 | −1.5750 | 0.882 | Sharply discriminative across the whole sphere |
| 10 | −0.6931 | −2.4104 | 1.717 | Dominated by nearest neighbours — drifting toward pure packing |
Every number in that table is computed from the two closed forms above; the Kernel width t slider in the simulation reproduces them live. The moral: t = 2 is not magic, but it does sit in the useful middle, and both extremes fail in ways you can now name.
We have two metrics that we invented because they seemed like the right things to want. Now comes the claim that makes this a paper about contrastive learning rather than a paper about sphere geometry: the contrastive loss, in the limit of many negatives, is exactly these two metrics added together.
The derivation is four lines of algebra plus one appeal to the law of large numbers. We are going to walk every step, including the parts that are usually waved through, because the error terms are where the practical lessons live.
Write the contrastive loss with an explicit number of negatives M:
The outer expectation is over a positive pair (x, y) drawn from ppos and M independent negatives xi− drawn from pdata. This is InfoNCE, NT-Xent, and the MoCo loss, all of which are the same object with different sampling schemes for the negatives.
The only trick in the whole derivation is that −log(a/b) = −log a + log b. Abbreviate the positive similarity as s+ = f(x)·f(y) and the i-th negative similarity as si = f(xi−)·f(x):
Already something is visible. The first term wants the positive pair's similarity to be large — that is alignment, and Chapter 2 proved it is exactly the α = 2 alignment metric up to an affine map. The second term wants the total exponentiated similarity to everything to be small. That is a repulsion. But it is not yet in a form we recognise, because the sum grows with M.
Pull a factor of M out of the sum so that what remains is an average rather than a total:
derivation — the whole theorem, in four linesl = -s+/tau + log( exp(s+/tau) + SUM_i exp(s_i/tau) )
= -s+/tau + log( M * [ (1/M) SUM_i exp(s_i/tau) + exp(s+/tau)/M ] )
= -s+/tau + log M + log( (1/M) SUM_i exp(s_i/tau) + exp(s+/tau)/M )
\_________ A_M _________/ \__ B_M __/
l - log M = -s+/tau + log( A_M + B_M )
The subtraction of log M is not a cosmetic normalisation. It has a physical meaning: log M is, to leading order, the loss a completely uninformative encoder achieves. If every similarity were identical, the softmax would be uniform over the M+1 candidates and the loss would be exactly log(M+1) — which differs from log M by log(1 + 1/M), a quantity that is 0.004 at M = 256 and vanishes in the limit. So ℓ − log M reads as "how much better than guessing", and it is the only version of the loss that can converge to anything finite as M grows. It is also, satisfyingly, the same log M that capped the mutual-information bound in Chapter 0 — the two appearances are the same quantity seen from opposite ends.
Look at the two pieces inside the log.
AM is a sample average. The M negatives are i.i.d. draws from pdata, and esi/τ is a bounded function of each one — bounded because si ∈ [−1, 1] on the sphere, so the summand lives in [e−1/τ, e1/τ]. Bounded random variables satisfy the law of large numbers, so
This is the step where the sphere earns its keep for the third time. Without normalisation, si is unbounded, esi/τ may have infinite mean, and the law of large numbers may simply fail to apply.
BM vanishes. BM = es+/τ/M ≤ e1/τ/M → 0. The positive pair, which occupies a full slot in the denominator, becomes negligible once there are enough negatives. Note the rate: this term is O(1/M).
Putting them together and taking the outer expectation gives the paper's Theorem 1.
Term one is alignment. This is Chapter 2's identity, reused verbatim:
A positive multiple of the alignment metric, minus a constant. Minimising one is minimising the other. There is no approximation here at all.
Term two is uniformity. Substitute u·v = 1 − ½‖u−v‖2 into the exponent:
derivation — the Gaussian kernel appears uninvitedexp( u.v / tau ) = exp( (1 - 0.5*||u-v||^2) / tau )
= exp(1/tau) * exp( -||u-v||^2 / (2 tau) )
= exp(1/tau) * G_t(u, v) with t = 1/(2 tau)
Read that. Nobody chose a Gaussian kernel. The contrastive loss exponentiates a dot product; a dot product on the sphere is an affine function of squared distance; therefore the exponential of a dot product is a Gaussian potential. The kernel Chapter 3 justified on abstract grounds is the one the loss was already using.
Take logs and the constant slides out:
Compare the theorem's second term with the metric from Chapter 3, carefully:
| Object | Where the log sits |
|---|---|
| The theorem's second term | Ex[ log Ex−[ Gt ] ] — log inside, averaged over anchors |
| ℓuniform, the metric we optimise | log Ex, x−[ Gt ] — a single log outside both expectations |
These are not the same number. By Jensen's inequality, since log is concave, E[log Z] ≤ log E[Z], so the theorem's term is always less than or equal to ℓuniform. The two coincide exactly when the inner quantity Ex−[Gt(f(x), f(x−))] is the same for every anchor x — that is, when every point on the sphere experiences the same total potential from the rest of the cloud.
Which is exactly what the uniform distribution does. By rotational symmetry, a uniform cloud looks identical from every one of its points, so the Jensen gap closes precisely at the target. That is why both quantities are minimised by the same perfectly uniform encoder, and why the paper is comfortable optimising the outer-log version: it is a cleaner, single-scalar, lower-variance object whose minimiser is the one the theorem points at.
Statement (3) of the theorem says the deviation decays as O(M−1/2). We already have both error sources in hand, so let us see which one is responsible.
Source B (the positive in the denominator): BM = es+/τ/M, which is O(1/M).
Source A (sampling noise in the partition function): AM is a mean of M i.i.d. bounded variables, so by the central limit theorem AM − A∞ = Op(M−1/2). Passing through the log with a first-order expansion, log AM − log A∞ ≈ (AM − A∞)/A∞, still O(M−1/2).
M−1/2 is slower than M−1, so sampling noise in the partition function is what sets the rate. This has a direct practical reading: the reason large batches help is not primarily that they remove the positive from the denominator. It is that they reduce the variance of the estimate of the repulsive field. Doubling the batch reduces that noise by a factor of √2, which is exactly the disappointing scaling everyone has observed.
Time to put digits on all of this. Toy setup: features live on a circle. The anchor sits at 0°. Its positive sits at 20°. Negatives are drawn uniformly from the circle; our unlucky draw gives three at 90°, 180°, and 270°. Set τ = 1, so t = 1/(2τ) = 0.5.
arithmetic — the finite-M losss+ = cos(20) = 0.9397 exp(s+/tau) = exp(0.9397) = 2.559195 s1 = cos(90) = 0.0000 exp(s1/tau) = 1.000000 s2 = cos(180) = -1.0000 exp(s2/tau) = 0.367879 s3 = cos(270) = 0.0000 exp(s3/tau) = 1.000000 denominator = 2.559195 + 1.000000 + 0.367879 + 1.000000 = 4.927074 l = -ln( 2.559195 / 4.927074 ) = -ln(0.519385) = 0.6551 # reference: an uninformative encoder scores ln(M+1) = ln 4 = 1.3863 l - ln M = 0.6551 - 1.0986 = -0.4436
Now the limit. Because the negatives are uniform on the circle, the population partition function has a closed form — the average of ecosθ/τ over a uniform angle is the modified Bessel function I0(1/τ):
arithmetic — the M -> infinity limitA_inf = E_theta[ exp(cos(theta)/tau) ] = I_0(1/1) = I_0(1) = 1.266066 limit = -s+/tau + ln(A_inf) = -0.9397 + ln(1.266066) = -0.9397 + 0.235915 = -0.7038
So at M = 3 we are at −0.4436 and the limit is −0.7038: a gap of 0.2602 nats. Decompose it into the two sources we identified, using A3 = (1.000000 + 0.367879 + 1.000000)/3 = 0.789293 and B3 = 2.559195/3 = 0.853065:
arithmetic — where the 0.2603 came froml - ln M = -s+/tau + ln( A_3 + B_3 ) = -0.9397 + ln( 0.789293 + 0.853065 ) = -0.9397 + ln( 1.642358 ) = -0.9397 + 0.496133 = -0.4436 # checks out # Source B: the positive occupying a slot in the denominator. ln(A_3 + B_3) - ln(A_3) = 0.496133 - (-0.236617) = +0.7328 # Source A: three unlucky negatives underestimate the partition function. ln(A_3) - ln(A_inf) = -0.236617 - 0.235915 = -0.4725 # Total: +0.7328 - 0.4725 = +0.2602. Matches the gap.
The horizontal line is the asymptotic limit computed exactly. The warm curve is ℓcontrastive − log M, Monte-Carlo estimated at each batch size on the same toy. The teal band is the O(M−1/2) envelope. The two dashed traces underneath split the residual into its two sources: the positive-in-denominator term (falling like 1/M) and the partition-function sampling noise (falling like M−1/2). Drop the temperature and watch the noise term explode — that is the small-τ large-batch requirement, derived rather than folklore.
Small-M behaviour is where the asymptotic story is least applicable and most instructive, so run the same toy with a single negative at 90°.
arithmetic — one positive, one negative, tau = 1denominator = exp(0.9397) + exp(0.0) = 2.559195 + 1.000000 = 3.559195 l = -ln( 2.559195 / 3.559195 ) = -ln(0.719038) = 0.3298 l - ln(1) = 0.3298 - 0 = 0.3298 # log M = 0, so no normalisation at all limit = -0.7038 gap = 1.0336 nats
The gap is now larger than the limit itself, and it has a structural cause rather than a statistical one. At M = 1 the positive occupies half the denominator, so the loss can never fall below log 2 × something — and since a cross-entropy is non-negative while the asymptotic objective is comfortably negative, the two are not even in the same range. At M = 1 you are not approximating the asymptotic objective badly; you are optimising a different function.
This is the quantitative content of the folklore that contrastive learning "needs many negatives". Tabulate the gap across the whole range on this toy:
| M | ℓ − log M | Gap to the limit −0.7038 | Regime |
|---|---|---|---|
| 1 | +0.3298 | 1.034 | A different objective entirely — the positive is half the denominator |
| 3 | −0.4436 | 0.260 | Two large errors of opposite sign, partly cancelling |
| 16 | −0.596 | 0.108 | Recognisably the right objective, noticeably biased |
| 256 | −0.692 | 0.011 | Practically the limit, for this toy |
The values for M = 16 and M = 256 are Monte-Carlo estimates that the simulation below reproduces exactly; the first two rows are the hand computations above. Note how quickly it converges here and remember Chapter 8's warning: this toy uses τ = 1 on a circle. At τ = 0.07 in 128 dimensions the constant in front of M−1/2 is enormously larger, and M = 256 is nowhere near enough.
The derivation assumed the M negatives are independent draws from pdata, encoded by the current f. Every popular implementation violates this, and it is worth knowing how.
| Implementation | What it actually does | Consequence for the theorem |
|---|---|---|
| SimCLR — in-batch negatives | The negatives for anchor i are the other 2N−2 views in the same batch, which include the other view of every other image | Negatives are not independent of each other, and each image contributes twice. The law of large numbers still applies (the dependence is weak) but the effective sample size is smaller than the nominal count |
| MoCo — a momentum queue | Negatives were encoded by an exponential-moving-average copy of the encoder, several thousand steps ago | The repulsion is against a lagged feature distribution, not the current one. Early in training, when f moves fast, the model is being made uniform with respect to a distribution that no longer exists |
| Any real dataset | Some "negatives" are semantically identical to the anchor — two photos of the same species, two near-duplicate frames | The objective contains constraints that are false. Chapter 8's uniformity-tolerance dilemma is exactly the cost of this, and it gets worse as τ falls |
Three caveats, all of which the paper is upfront about and all of which get misquoted.
| The theorem says | It does not say |
|---|---|
| The loss functional converges to alignment plus a uniformity-flavoured term | That your ResNet-50 can reach the minimiser. The analysis is over unrestricted encoders; a real network has finite capacity and is trained by SGD from a particular initialisation |
| Perfectly uniform encoders, if they exist, minimise the second term | That they exist. With finitely many images and perfect alignment, features are a finite point set, which cannot literally be the uniform measure. There is always a residual tension — Chapter 7 is about reading it |
| The deviation decays as O(M−1/2) | That M = 256 is close to the limit. The constant hidden in the O depends on τ and on the feature distribution, and Chapter 8 shows it grows sharply as τ shrinks |
Two metrics, one theorem, zero intuition for what the numbers feel like. This chapter fixes that with the smallest possible non-trivial example: four features on a circle, worked entirely by hand, with every exponential written out.
Take a dataset of two images. Each is augmented twice, giving four views and therefore four features. Positive pairs are {1, 2} and {3, 4}. The encoder maps to S1, the unit circle, so every feature is an angle. Use the paper's defaults: α = 2 and t = 2.
We need two formulas and nothing else. From Chapter 1, for points at angles θi and θj:
Alignment averages d2 over the two positive pairs. Uniformity takes e−2d2 over all six distinct pairs (that is what torch.pdist gives you), averages, and logs.
Everything at 0°. All six pairwise distances are zero.
arithmetic — all four points at 0 degreesalignment: d(1,2)^2 = 0 , d(3,4)^2 = 0 l_align = (0 + 0)/2 = 0.0000 # perfect uniformity: all six pairs have d^2 = 0, so G = exp(0) = 1 mean = 6/6 = 1.0000 l_uniform = ln(1.0000) = 0.0000 # the worst possible value total (lambda = 1) = 0.0000 + 0.0000 = 0.0000
Note the ceiling: because G ≤ 1 for every pair, the mean is at most 1 and ℓuniform is at most 0. Zero is the collapse signature. If you ever log a uniformity value at or near 0.00, your encoder has died — no further diagnosis needed.
Points 1 and 2 both at 0°; points 3 and 4 both at 180°. Alignment is still perfect, but the representation now carries one bit.
arithmetic — pairs collapsed onto antipodal atomsalignment: d(1,2)^2 = 2 - 2cos(0) = 0 ; d(3,4)^2 = 0 l_align = 0.0000 uniformity: (1,2): d^2 = 0 -> G = 1.000000 (3,4): d^2 = 0 -> G = 1.000000 (1,3): d^2 = 4 -> G = exp(-8) = 0.000335 (1,4): d^2 = 4 -> G = 0.000335 (2,3): d^2 = 4 -> G = 0.000335 (2,4): d^2 = 4 -> G = 0.000335 mean = (1 + 1 + 4*0.000335)/6 = 2.001342/6 = 0.333557 l_uniform = ln(0.333557) = -1.0979 total (lambda = 1) = 0.0000 - 1.0979 = -1.0979
Better. The two forces are already visible: alignment is indifferent between A and B, and uniformity is the only thing that prefers B.
Points at −45°, +45°, 135°, 225°. This is the most uniform arrangement four points on a circle can achieve, and it destroys alignment: each positive pair is now 90° apart.
arithmetic — the four-point squarealignment: d(1,2)^2 = 2 - 2cos(90) = 2 ; d(3,4)^2 = 2 l_align = (2 + 2)/2 = 2.0000 uniformity: four pairs at 90 deg -> d^2 = 2 -> G = exp(-4) = 0.018316 two pairs at 180 deg -> d^2 = 4 -> G = exp(-8) = 0.000335 mean = (4*0.018316 + 2*0.000335)/6 = 0.073933/6 = 0.012322 l_uniform = ln(0.012322) = -4.3963 total (lambda = 1) = 2.0000 - 4.3963 = -2.3963
Better still, on the sum — and this should surprise you. The square has the worst possible alignment for a configuration of this shape, and it still beats the perfectly-aligned Configuration B by 1.30 nats. At λ = 1 and t = 2, uniformity is the dominant force.
Neither extreme is best. Parametrise the family: put the two positive pairs symmetrically around 0° and 180°, each pair separated by 2δ. Configuration B is δ = 0; Configuration C is δ = 45°. Sweep δ and compute:
| δ | Positive-pair gap 2δ | ℓalign | ℓuniform | Total at λ = 1 |
|---|---|---|---|---|
| 0° | 0° | 0.0000 | −1.0979 | −1.0979 |
| 15° | 30° | 0.2679 | −1.6330 | −1.3651 |
| 30° | 60° | 1.0000 | −3.0780 | −2.0780 |
| 41° | 82° | 1.7217 | −4.2500 | −2.5284 |
| 45° (square) | 90° | 2.0000 | −4.3963 | −2.3963 |
Work the winning row so you trust it. At δ = 41° the points sit at −41°, 41°, 139°, 221°:
arithmetic — delta = 41 degrees, the optimum at lambda = 1within-pair gap = 82 deg d^2 = 2 - 2cos(82) = 2 - 2(0.139173) = 1.721654 l_align = 1.7217 six pairs: (1,2) 82 deg -> d^2 = 1.721654 -> G = exp(-3.443307) = 0.031959 (3,4) 82 deg -> d^2 = 1.721654 -> G = 0.031959 (1,3) 180 deg -> d^2 = 4.000000 -> G = exp(-8.000000) = 0.000335 (2,4) 180 deg -> d^2 = 4.000000 -> G = 0.000335 (1,4) 98 deg -> d^2 = 2.278346 -> G = exp(-4.556693) = 0.010497 (2,3) 98 deg -> d^2 = 2.278346 -> G = 0.010497 mean = (0.031959 + 0.031959 + 0.000335 + 0.000335 + 0.010497 + 0.010497)/6 = 0.085582/6 = 0.014264 l_uniform = ln(0.014264) = -4.2500 total = 1.7217 - 4.2500 = -2.5284 # beats the square by 0.13 nats
Drag any point around the circle. Warm chords link the two positive pairs; the faint grey web is every pair contributing to uniformity, with line brightness proportional to its Gaussian potential — crowded pairs glow. The panel shows all six potentials, the two metrics, and the total, recomputed live. The preset buttons reproduce every row of the table above, digit for digit. Minimise runs gradient descent on the total and shows you where the negotiation lands.
Slide λ down in the simulation and something abrupt happens: below a certain value the optimum snaps to δ = 0, and the two positive pairs collapse onto single points. That threshold is computable in a few lines, and the answer is clean enough to be worth memorising.
Let φ = 2δ be the within-pair gap, and expand both metrics for small φ. Using cosφ ≈ 1 − φ2/2:
derivation — when does the collapsed solution stop being optimal?alignment: l_align = 2 - 2cos(phi) ~= phi^2
uniformity: two within-pair distances d^2 ~= phi^2
two antipodal d^2 = 4
two cross d^2 ~= 4 - phi^2
mean G = [ 2 exp(-t phi^2) + 2 exp(-4t) + 2 exp(-4t) exp(t phi^2) ] / 6
for large t the exp(-4t) terms are negligible:
mean G ~= (1/3) exp(-t phi^2) -> l_uniform ~= -ln 3 - t phi^2
total J(phi) = phi^2 + lambda * ( -ln 3 - t phi^2 )
= const + phi^2 * ( 1 - lambda * t )
The sign of (1 − λt) decides everything. If λt < 1, the coefficient is positive, so φ = 0 is a minimum and the pairs collapse. If λt > 1, the coefficient is negative, φ = 0 becomes a maximum, and the configuration splits open.
Keeping the antipodal e−4t terms shifts this to λ* = 0.5005, so the approximation is good to one part in a thousand. Try it in the simulation: set t = 2, put λ at 0.45, press Minimise, and the points fuse into two atoms. Nudge λ to 0.55 and they split.
The threshold calculation says something happens at λt = 1. Compute the actual optimum at several λ (holding t = 2) and you can watch it happen.
| λ | λt | Optimal δ | ℓalign | ℓuniform | Total |
|---|---|---|---|---|---|
| 0.25 | 0.50 | 0° | 0.0000 | −1.0979 | −0.2745 |
| 0.50 | 1.00 | 0° | 0.0000 | −1.0979 | −0.5490 |
| 0.55 | 1.10 | ≈ 34° | 1.2508 | −3.5476 | −0.7004 |
| 1.00 | 2.00 | ≈ 41° | 1.7217 | −4.2500 | −2.5284 |
| 2.00 | 4.00 | ≈ 43° | 1.8605 | −4.3583 | −6.8560 |
Look at the jump between λ = 0.50 and λ = 0.55. The optimum does not slide out from 0° gradually; it leaps to 34°. Above the threshold, the configuration snaps open almost all the way, and further increases in λ buy only a few more degrees.
The same calculation also explains the shape of the tradeoff frontier you will meet in Chapter 7. Between λ = 0.55 and λ = 2, alignment worsens from 1.25 to 1.86 while uniformity improves from −3.55 to −4.36. Every extra unit of uniformity is bought with alignment, and the exchange rate gets steadily worse. That is what a frontier looks like when you plot it.
Four points on a circle is a toy; the reason to trust it is that nothing qualitative changes when you scale it up. Take eight points with four positive pairs on S1. Two reference configurations:
arithmetic — 8 points, 4 positive pairs, t = 2, 28 distinct pairs# Config P: pairs fully collapsed onto 4 atoms, atoms 90 degrees apart 4 pairs at d^2 = 0 -> G = 1 16 pairs at d^2 = 2 -> G = exp(-4) = 0.018316 8 pairs at d^2 = 4 -> G = exp(-8) = 0.000335 mean = (4 + 0.293056 + 0.002684)/28 = 4.295740/28 = 0.153419 l_align = 0.0000 l_uniform = ln(0.153419) = -1.8746 # Config Q: all eight evenly spaced, 45 degrees apart 8 pairs at 45 deg -> d^2 = 0.585786 -> G = 0.309867 8 pairs at 90 deg -> d^2 = 2.000000 -> G = 0.018316 8 pairs at 135 deg -> d^2 = 3.414214 -> G = 0.001081 4 pairs at 180 deg -> d^2 = 4.000000 -> G = 0.000335 mean = (2.478936 + 0.146528 + 0.008648 + 0.001342)/28 = 0.094123 l_align = 2 - 2cos(45) = 0.585786 l_uniform = ln(0.094123) = -2.3629 # At lambda = 1: Config P total = -1.8746 ; Config Q total = -1.7771 # Now P wins -- because with four classes instead of two, collapsing # the pairs still leaves the atoms well spread.
The flip is instructive. With eight points and four pair-classes, the collapsed-pairs configuration is already reasonably uniform — four atoms 90° apart is not crowded — so at λ = 1 it beats the fully-spread configuration, where with four points it lost. (Neither is the true optimum: running gradient descent at λ = 1 lands at ℓalign ≈ 0.25, ℓuniform ≈ −2.20, total ≈ −1.95 — an interior compromise that beats both, exactly as Chapter 7's frontier will show.) The general principle: the more distinct positive-pair classes your data has, the less the two forces conflict, because a finite point set with many points approximates the uniform measure better. On a real dataset with a million instances, the tension that dominates this toy is faint, and both metrics can be driven low simultaneously. The toy exaggerates the conflict precisely because it is small.
You can watch both configurations in the eight-point simulation of Chapter 7, which optimises exactly this setup at a range of λ and plots where each one lands.
These hand numbers are a unit test. Any implementation of the two metrics must reproduce them, and getting a mismatch localises the bug immediately.
| You get | Almost certainly |
|---|---|
| ℓuniform = −1.3500 instead of −4.3963 on the square | You included the self-pairs — 16 ordered pairs, four of them at distance 0 contributing G = 1 each — instead of the 6 distinct pairs. Use pdist, not cdist. The four ones dominate the mean, which is exactly why the diagonal must go |
| ℓalign = 1.4142 instead of 2.0000 on the square | You forgot to square: .norm() without .pow(alpha), so you averaged distances (√2) rather than squared distances |
| ℓuniform = −3.0898 on the square | You applied t to the distance rather than the squared distance — a missing .pow(2) before .mul(-t) |
| ℓuniform = 0.0123 on the square | You forgot the final .log(). The values will look plausible and your gradients will be about 80× too small |
| Both metrics exactly right, but training collapses | Not a metric bug. Check λt > 1 |
Here is the moment the paper stops being an analysis and becomes an experiment. If alignment and uniformity are genuinely what InfoNCE is optimising, then writing them down and optimising them openly should work at least as well. If it does not, the analysis was a story.
python — the paper's reference implementation, verbatim in substanceimport torch def lalign(x, y, alpha=2): # x, y: (N, d) L2-normalised features of the two views. Row i of x # and row i of y are a positive pair. return (x - y).norm(dim=1).pow(alpha).mean() def lunif(x, t=2): # pdist gives the N(N-1)/2 DISTINCT pairwise distances -- no self-pairs. sq_pdist = torch.pdist(x, p=2).pow(2) return sq_pdist.mul(-t).exp().mean().log() loss = lalign(x, y) + lam * (lunif(x) + lunif(y)) / 2
Four lines. Walk them once with shapes, because every one of them is a decision.
| Expression | Shape | Why it is written this way |
|---|---|---|
(x - y) | (N, d) | Row-wise difference. Row i of x and row i of y must be the two views of the same image — getting this pairing wrong is the single most common bug and produces a loss that trains to a plausible-looking plateau |
.norm(dim=1) | (N,) | Euclidean distance per pair. dim=1 reduces the feature axis, not the batch axis |
.pow(alpha).mean() | scalar | The α from Chapter 2. Note the order: norm first, then power. .pow(2) after .norm() is the squared distance; .norm().mean().pow(2) would be a different and wrong quantity |
torch.pdist(x, p=2) | (N(N−1)/2,) | The condensed distance vector — every distinct unordered pair, exactly once, with the diagonal excluded. This is Chapter 5's six-pair convention |
.pow(2).mul(-t).exp() | same | Gt for each pair. Squared distance then scale by −t; reversing these gives a completely different kernel |
.mean().log() | scalar | Mean first, log second. Log of the mean, never mean of the logs — the latter would be a different functional whose minimiser is not the uniform distribution |
(lunif(x) + lunif(y)) / 2 | scalar | Uniformity is a property of the marginal feature distribution, and both views are samples from it. Averaging the two estimates halves the variance for free |
pdist on an (N, d) batch is O(N2d) — precisely the cost of the N×N similarity matrix that InfoNCE already builds. You are not paying for the reformulation. What you get in exchange is that the two forces are now separate tensors you can log, weight, and debug independently, instead of two entangled halves of one scalar.There is exactly one way this code bites you, and it is worth pre-empting. The uniformity term computes e−t d2 and then takes a log of the mean. If every pair is far apart and t is large, every term underflows to zero, the mean is zero, and the log is −∞. Your loss becomes -inf, then nan.
| Setting | Smallest term e−4t | float32 (min normal ≈ 1.2e−38) | float16 (min normal ≈ 6.1e−5) |
|---|---|---|---|
| t = 2 (default) | 3.4e−4 | Fine | Fine |
| t = 5 (the paper's BookCorpus setting) | 2.1e−9 | Fine | Underflows to 0 |
| t = 10 | 4.2e−18 | Fine | Underflows to 0 |
| t = 25 | 3.7e−44 | Underflows to 0 | Dead |
The fix is the standard one: never exponentiate before you have to. Fold the mean and the log into a single log-sum-exp, which subtracts the maximum internally and is exact in the region where the naive form dies.
python — the numerically safe form (use this under AMP)def lunif_stable(x, t=2): sq_pdist = torch.pdist(x, p=2).pow(2) # (N(N-1)/2,) # log( mean_k exp(-t d_k^2) ) = logsumexp_k(-t d_k^2) - log(K) return torch.logsumexp(-t * sq_pdist, dim=0) - torch.log( torch.tensor(float(sq_pdist.numel()), device=x.device))
Mathematically identical, numerically bulletproof. Cast the pairwise distances to float32 even under mixed precision; the cost is negligible next to the encoder forward pass.
The experiments cover vision and language, and the hyperparameters are worth tabulating because they show that λ and t are genuinely dataset-dependent rather than universal constants.
| Benchmark | Objective used | Output dim | Batch |
|---|---|---|---|
| STL-10 | 0.98 · ℓalign(α=2) + 0.96 · ℓuniform(t=2) | 128 | 768 |
| NYU-Depth-V2 | 0.98 · ℓalign(α=2) + 0.96 · ℓuniform(t=2) | 128 | 128 |
| ImageNet-100 (MoCo) | 3 · ℓalign(α=2) + ℓuniform(t=3) | 128 | 128 |
| BookCorpus (Quick-Thought) | 0.9 · ℓalign(α=2) + 0.1 · ℓuniform(t=5) | 1200 | 400 |
Two things jump out. The vision settings sit near λ ≈ 1 with t = 2 or 3, which by Chapter 5's threshold λt > 1 puts them comfortably on the non-collapsed side. The sentence-embedding setting is very different — λ = 0.1 with t = 5, so λt = 0.5, i.e. below the toy's threshold. That is not a mistake; text positive pairs (adjacent sentences) are far noisier than augmented crops, so the useful regime is much more alignment-dominated. The same lens, different settlement.
| Benchmark | Metric | Contrastive loss | ℓalign + λℓuniform |
|---|---|---|---|
| STL-10 | Linear probe accuracy | 80.46% | 81.15% |
| STL-10 | 5-NN accuracy on fc7 | 76.33% | 76.78% |
| NYU-Depth-V2 | Depth MSE (lower is better) | 0.7024 | 0.7014 |
| ImageNet-100 | MoCo linear probe, top-1 | 72.80% | 74.60% |
| ImageNet | MoCo v2 linear probe, top-1 | 67.5% ± 0.1% | 67.69% |
| BookCorpus | MR / CR sentence classification | 77.51% / 83.86% | 77.51% / 83.86% |
Suppose you already have a tuned SimCLR-style run: τ = 0.1, batch 512, 128-dimensional head. You want the two-metric form without re-tuning from scratch. Chapter 4's identities make this a calculation rather than a search.
| Step | Calculation | Result |
|---|---|---|
| 1. Convert the temperature | t = 1/(2τ) = 1/(2 × 0.1) | t = 5 |
| 2. Check the collapse threshold | Need λt > 1, so λ > 1/5 | λ > 0.2; start at 1.0 for margin |
| 3. Compute the uniform reference at this t | −2t + 2t2/d = −10 + 50/128 | −9.61 — not −3.94, because t changed |
| 4. Check numerics | Smallest term is e−4t = e−20 = 2.1e−9 | Fine in float32, underflows in float16 — use the logsumexp form |
| 5. Set α | Equation 2 says the loss's first term is exactly α = 2 | α = 2, no choice to make |
| 6. Sanity-check the scale | At t = 5 the four-point square gives ln((4e−10 + 2e−20)/6) = −10.41 | Confirms your implementation tracks t correctly |
Two of those rows catch bugs that are otherwise invisible. Step 3 matters because people memorise −3.94 as "the good value" and then panic when a t = 5 run reports −9.5; the reference moves with t, and comparing metric values across different t is meaningless. Step 4 matters because the failure is silent: under automatic mixed precision the uniformity term simply becomes a constant −∞ that contributes no gradient, and your run collapses while the loss looks superficially fine.
Beyond the accuracy, the reformulation buys engineering leverage that a single entangled scalar cannot.
| With InfoNCE | With ℓalign + λℓuniform |
|---|---|
| One knob, τ, which simultaneously sets the alignment/uniformity balance and the kernel width | Three independent knobs: λ (balance), t (kernel width), α (hard-positive weighting) |
| One loss number. A collapsing run and a badly-aligned run look similar for many epochs | Two numbers you can plot separately. Collapse is unmistakable — ℓuniform heads to 0 within a few hundred steps |
| Negatives are the batch, so the balance shifts silently when you change the batch size | λ is explicit and batch-size-independent; only the variance of the uniformity estimate depends on the batch |
| Comparing two runs means comparing loss values that are not comparable across τ or M | Both metrics are comparable across runs, models, and papers — which is why they became a standard reporting axis |
| Step | Do this | The decision that matters |
|---|---|---|
| 1. Normalise | F.normalize(h, dim=1) on both views before the loss | Non-negotiable. Chapter 1: without it, norm inflation is a free win and uniformity is ill-posed |
| 2. Pair correctly | Assert that row i of x and row i of y are the same image | A shuffled pairing gives a loss that decreases and a representation that is worthless |
| 3. Pick t | Start at t = 2; use t = 1/(2τ) if you are porting from a tuned InfoNCE run | Chapter 4's identity makes the port exact rather than a guess |
| 4. Pick λ | Start at λ = 1, and always check λt > 1 | Chapter 5's bifurcation. Below the threshold you are training a collapse |
| 5. Pick α | α = 2 unless your positive pairs are noisy, then try α = 1 | Chapter 2's gradient table — α decides whether outlier pairs dominate |
| 6. Log both | Print ℓalign and ℓuniform every epoch, not just the sum | The whole point of the reformulation. The sum hides which force is failing |
| 7. Guard numerics | Use the logsumexp form; keep pairwise distances in float32 | t ≥ 5 under AMP produces silent −inf |
| 8. Sanity check | Feed the four-point square from Chapter 5 and assert −4.3963 | Five seconds to write, and it catches every one of the five classic bugs |
lunif(x) and lunif(y) rather than concatenating both views into one batch of 2N features and calling lunif once?Two numbers per encoder means every encoder is a point. Put ℓuniform on the horizontal axis and ℓalign on the vertical, and you have a map of the entire design space of contrastive representation learning. This chapter is about learning to read it, because once you can, a plot that took a week to produce answers questions that used to take a month of ablations.
Both metrics are "lower is better", so down and to the left is good. Fix the ranges from what we already know.
| Axis | Range | What the ends mean |
|---|---|---|
| ℓalign (vertical) | [0, 4] at α = 2, in practice [0, 2] | 0 = positive pairs land on top of each other. 2 = they are 90° apart on average, which is what an untrained network gives you |
| ℓuniform (horizontal) | (−∞, 0], in practice [−4, 0] at t = 2 | 0 = total collapse. −3.94 = genuinely uniform on S127. Lower than that means the batch is spread better than random, which finite point sets can be |
The paper's headline plot is exactly this: hundreds of encoders trained with varying losses and hyperparameters, each plotted at its (ℓuniform, ℓalign) coordinates and coloured by downstream accuracy. The colouring is not noise. Accuracy varies smoothly across the plane, and the best models occupy a compact region, which is the empirical content of the claim that these two numbers are what matters.
A simulated family of encoders, each a real four-to-twelve-point configuration optimised on the sphere under a different (λ, t), plotted at its two metric values. The shading is a downstream-quality proxy; the warm marker is the configuration currently selected by the sliders, and the inset shows its actual point cloud. Sweep λ to walk the frontier from the collapsed corner to the scattered one, and watch the proxy peak somewhere in the middle. Positions of the named real models are schematic — they indicate direction, not measured coordinates.
Chapter 5 proved it in miniature: with finitely many positive-pair classes, perfect alignment and perfect uniformity cannot both hold. Perfect alignment collapses each class to a single point, and a finite set of points is not the uniform measure. So the reachable region of the plane has a boundary — a Pareto frontier — and every training run is a trajectory that eventually parks somewhere along it.
How far the frontier extends depends on things you control:
| What you change | Effect on ℓalign | Effect on ℓuniform | Mechanism |
|---|---|---|---|
| Raise λ (or lower τ) | Worse (up) | Better (left) | Directly reweights the negotiation — you slide along the frontier |
| Stronger augmentations | Worse (up) | Roughly unchanged | Positive pairs become genuinely harder to map together; the encoder is asked for more invariance than it can supply |
| Bigger batch | Roughly unchanged | Better (left) | Lower-variance estimate of the repulsive field — Chapter 4's √M |
| Higher output dimension | Roughly unchanged | Better (left), toward the −2t floor | −2t + 2t2/d: more room means less crowding, but with diminishing returns |
| More capacity / longer training | Better (down) | Better (left) | Pushes the whole frontier outward — this is the only move that is not a tradeoff |
| Larger t at fixed λ | Worse (up) | Better (left) | Sharper repulsion, and λt rises past the collapse threshold |
Read the last two rows together. Everything except capacity is a slide along the frontier; capacity and training time are what move the frontier itself. That is a useful triage rule when a run underperforms: first ask whether you are at a bad point on a good frontier (retune λ, t, batch) or on a bad frontier (bigger model, longer schedule, better augmentations).
The clearest published use of this plane is in the sentence-embedding literature, where the two pathologies are unusually well separated. Mean-pooled BERT embeddings are famously anisotropic — they occupy a narrow cone, so almost any two sentences have cosine similarity above 0.6 regardless of meaning. In alignment-uniformity language, that is good alignment, terrible uniformity: the top-left of the useful band, near the collapsed corner on the uniformity axis.
| Model family | Alignment | Uniformity | Reading |
|---|---|---|---|
| Mean-pooled BERT, no tuning | Good | Poor — the anisotropic cone | Everything is close to everything; similarity scores are nearly uninformative |
| Post-hoc whitening or normalising flows on BERT | Degraded | Much improved | These methods fix uniformity by construction and pay for it in alignment — a pure slide left-and-up along the frontier |
| Unsupervised SimCSE (dropout as the augmentation) | Roughly preserved | Substantially improved | The frontier itself moved. This is the result SimCSE's analysis section is built around, and the alignment-uniformity plot is how it is argued |
| Supervised SimCSE (NLI pairs) | Improved | Improved | Better positive pairs improve both at once — again a frontier move, not a slide |
Log both metrics each epoch and the plane becomes a diagnostic instrument.
| What you see | Diagnosis | Action |
|---|---|---|
| ℓuniform rises toward 0 over the first few hundred steps | Collapse in progress | Raise λ or t; check λt > 1; check your positive pairs are not identical inputs |
| ℓalign stuck near 2 while ℓuniform is excellent | The encoder is behaving like a random projection — repelling everything and learning no invariance | Lower λ; verify the row pairing between the two views; check the augmentations are not destroying the content entirely |
| Both metrics excellent, downstream accuracy mediocre | The augmentation set is wrong for the task — the encoder became invariant to something that mattered | Nothing in the loss will fix this. Change ppos. See Chapter 8 |
| ℓuniform improves when you enlarge the batch but accuracy does not | You were already past the point where uniformity noise was the bottleneck | Spend the compute on capacity or schedule instead — you are on the wrong frontier, not the wrong point |
| Metrics look fine at t = 2 but downstream is poor and features are low-rank | Dimensional collapse, which uniformity detects only weakly | Chapter 8 — measure the covariance spectrum directly; uniformity will not catch this for you |
A good explanation earns its keep by predicting things nobody fed into it. This chapter collects the predictions the alignment-uniformity lens makes for free, and then — because a lesson that only lists a theory's wins is advertising — the places where it is silent or wrong.
We have the identity t = 1/(2τ) from Chapter 4 and the two limiting behaviours of t from Chapter 3. Combine them and every empirical fact about temperature in contrastive learning falls out.
| τ | t = 1/(2τ) | Regime | Predicted behaviour | What practitioners report |
|---|---|---|---|---|
| 1.0 | 0.5 | Approaching the t → 0 degeneracy | Uniformity becomes a weak, mean-zero-only constraint; two-atom collapse is nearly free | High temperatures give poor, low-rank representations |
| 0.5 | 1.0 | Broad repulsion | All negatives contribute comparably; the model tolerates semantically similar negatives sitting close | Better class-level tolerance, worse instance separation |
| 0.1 | 5.0 | Sharp repulsion | The potential is dominated by the nearest neighbours, so the hardest negatives absorb almost all the gradient | The known "hardness-aware" property of low temperature |
| 0.07 | 7.1 | SimCLR default | Close to a packing objective; excellent instance discrimination, and semantically identical images are pushed apart as hard as anything else | Strong linear probes, but measurable damage to fine-grained class structure |
| 0.01 | 50 | Effectively the Tammes problem | Only the single closest pair matters per anchor; extremely high gradient variance | Training becomes unstable and downstream quality falls |
Chapter 4 established that the convergence bottleneck is sampling noise in the partition function, decaying as O(M−1/2). Two consequences that people usually discover the expensive way:
Doubling the batch buys a factor of √2, not 2. The famous diminishing returns of large-batch contrastive learning are not mysterious; they are the central limit theorem.
The constant in front of M−1/2 grows as τ shrinks. The variance of es/τ across negatives explodes when 1/τ is large, because the expectation is dominated by rare near-collisions. Put numbers on it: in d = 128, similarities between random features are roughly Gaussian with standard deviation 1/√128 = 0.088, so s/τ has standard deviation 0.088/τ. The relative standard deviation of a single term es/τ is then √(e(0.088/τ)2 − 1):
| τ | Spread of s/τ | Relative std of one term | Relative std of AM at M = 256 |
|---|---|---|---|
| 0.50 | 0.177 | 0.18 | 0.011 |
| 0.20 | 0.442 | 0.47 | 0.029 |
| 0.07 | 1.263 | 1.98 | 0.124 |
| 0.03 | 2.946 | 76.7 | 4.80 |
Read the last row: at τ = 0.03, a 256-sample estimate of the repulsive field carries a relative error approaching 500%. Low temperature and small batches are mathematically incompatible, and the alignment-uniformity framing tells you why rather than just that.
Augmentations define ppos, which appears only in the alignment term. Predicted effect of turning up the augmentation strength: ℓalign worsens, ℓuniform is essentially untouched, and downstream accuracy follows an inverted U — too weak and the encoder has learned no invariance worth having, too strong and it is being asked for invariance to things that carry the signal. The plane makes the diagnosis mechanical: if accuracy is falling and only the vertical coordinate moved, augmentation is your culprit.
Chapter 1 flagged the oddity: the loss shapes the post-projection space, but everyone uses the pre-projection backbone features downstream, and they work better. The alignment-uniformity lens gives this a clean account.
The loss is applied at the head's output, so it is that space that gets driven toward the negotiated settlement — tight positive pairs, uniform marginal. In particular, the head is rewarded for discarding any information that distinguishes two views of the same image, because keeping it costs alignment. Colour statistics, crop position, blur level: all of it is nuisance under the augmentation pipeline, and all of it should be destroyed by the time you reach the loss.
But some of that information is useful for some downstream task. Colour is nuisance for "is this a dog" and essential for "is this a ripe tomato". The backbone, sitting one nonlinearity earlier, has not yet been forced to throw it away — the head does the discarding, and discarding is what the head is for.
Here is where the lens has a genuine blind spot, and it is worth quantifying rather than gesturing at.
Dimensional collapse is the failure where features remain spread out but occupy only a low-dimensional subspace of the sphere — the covariance eigenvalue spectrum has a handful of large values and a long tail of near-zeros. Jing et al. (2022) documented it in trained contrastive models. Does uniformity catch it?
Use the formula from Chapter 7. Features uniformly spread over a k-dimensional sub-sphere score ℓuniform = −2t + 2t2/k. At t = 2:
| Effective dimension k | ℓuniform = −4 + 8/k | Difference from k = 128 | Downstream impact |
|---|---|---|---|
| 128 (healthy) | −3.9375 | — | Baseline |
| 64 | −3.8750 | 0.06 nats | Usually negligible |
| 32 | −3.7500 | 0.19 nats | Starting to hurt |
| 16 | −3.5000 | 0.44 nats | Clearly damaging |
| 8 | −3.0000 | 0.94 nats | Severe |
Left: the eigenvalue spectrum of the feature covariance for a synthetic 64-dimensional embedding whose energy is confined to k directions. Right: the resulting ℓuniform, plotted against the analytic curve −2t + 2t2/k, with the healthy reference marked. Slide k down and watch the spectrum fall off a cliff while the uniformity readout barely twitches — then raise t and watch the metric become more sensitive, at the cost of the packing pathologies of Chapter 3.
The most direct challenge to the framework arrived within a year of it. BYOL and SimSiam train self-supervised encoders with no negatives at all. There is no repulsive term, nothing that could be called a uniformity objective, and by every naive argument they should collapse instantly. They do not, and they match or beat contrastive methods.
What prevents collapse there is architectural — a predictor head, a stop-gradient, an exponential-moving-average target network — rather than a term in the loss. The honest conclusion: alignment and uniformity describe what the contrastive family of losses optimises, not what self-supervised learning in general requires. Uniformity is one way to avoid collapse. It is not the only way, and the paper does not claim otherwise.
The related methods are worth naming because they show the two forces recurring under different names. Barlow Twins and VICReg replace the repulsive term with explicit variance and decorrelation penalties on the feature dimensions. Read structurally, those are anti-collapse mechanisms operating on the covariance spectrum rather than on pairwise distances — a different answer to the same question that alignment-uniformity poses, and one that, per Limit 1, targets exactly the failure uniformity is bad at seeing.
A subtle one, and arguably the deepest. ℓuniform is computed over the marginal distribution of instances. It is minimised when every image is as far as possible from every other image, including two photographs of the same breed of dog.
But the representation we want for a linear probe is the opposite: images of the same class should be clustered. A perfect classifier's feature distribution is not uniform at all; it is a small number of tight blobs. The perfectly uniform encoder is, from the classifier's point of view, a hash function.
Alignment is defined relative to ppos, and ppos is whatever you decided it should be. Change the augmentation pipeline and you change what "the same thing" means, which changes the entire semantics of the learned space — while every equation in the paper stays word-for-word identical.
Concretely: strip colour jitter from SimCLR's pipeline and it learns colour-histogram features, because colour becomes a legitimate cue for instance identity. Add heavy colour jitter and colour is destroyed, which is right for ImageNet objects and catastrophic for bird species or histopathology stains. Neither case changes ℓalign or ℓuniform's definition by one symbol. The framework explains the mechanism; the augmentations decide what the mechanism is applied to, and nearly all of the domain knowledge in self-supervised learning lives there.
Every theorem in the paper is a statement about functionals over all measurable f. Real encoders are a ResNet trained by SGD from a specific initialisation, and that constraint set is not a technicality — it is, per Limit 3, doing much of the work. The paper is careful to say "if perfectly uniform encoders exist"; the practical answer is usually that they do not, and what you get instead is the network's biased approximation to them, which is precisely why the representation is useful.
| The lens explains | The lens does not explain |
|---|---|
| Why collapse happens and how to prevent it | Why the non-collapsed solution is semantic |
| What temperature does, quantitatively | Which augmentations to choose |
| Why batch size helps and how much | Why BYOL works without negatives |
| Why anisotropy is bad and what fixes it | How to detect dimensional collapse |
| How to compare two encoders on two axes | Where the frontier itself comes from |
Some papers are remembered for a model. This one is remembered for a plot. Six years on, if you open a paper about contrastive learning, sentence embeddings, or representation collapse, there is a good chance you will find a two-axis scatter with alignment on one axis and uniformity on the other. That is the legacy: not a technique, a coordinate system.
| Symbol | Meaning | Default | Where it was built |
|---|---|---|---|
| Sm−1 | Unit hypersphere in Rm; where L2-normalised features live | m = 128 | Ch 1 |
| σm−1 | The uniform (normalised surface) measure — the unique rotation-invariant probability measure on the sphere | — | Ch 1, 3 |
| ppos | Distribution over positive pairs; symmetric, with both marginals equal to pdata | Set by your augmentations | Ch 2 |
| ℓalign(f; α) | Eppos‖f(x)−f(y)‖α. Range [0, 2α] | α = 2 | Ch 2 |
| ℓuniform(f; t) | log Ex,y e−t‖f(x)−f(y)‖2. Range (−∞, 0] | t = 2 | Ch 3 |
| Gt(u,v) | Gaussian potential e−t‖u−v‖2; strictly positive definite on the sphere | t = 2 | Ch 3 |
| τ | Contrastive temperature | 0.07–0.5 | Ch 1, 4 |
| λ | Weight on the uniformity term when the metrics are optimised directly | ≈ 1 for vision | Ch 5, 6 |
| # | Identity | Why it matters |
|---|---|---|
| 1 | ‖u−v‖2 = 2 − 2 u·v | Distance and dot product are the same thing on the sphere. Everything else follows |
| 2 | −(1/τ)E[f(x)·f(y)] = (1/2τ)ℓalign(f;2) − 1/τ | The loss's first term is the alignment metric, exactly |
| 3 | eu·v/τ = e1/τ Gt(u,v), t = 1/(2τ) | Temperature is kernel width. The Gaussian potential was in the loss all along |
| 4 | ℓcontrastive − log M → alignment term + uniformity term, error O(M−1/2) | The theorem. log M is the uninformative baseline; √M is why big batches only half-help |
| 5 | ℓuniform ≈ −2t + 2t2/d for uniform features in dimension d | The reference value — −3.94 at t = 2, d = 128 — and the effective-dimension readout |
| The claim you will hear | What is actually true |
|---|---|
| "Contrastive loss equals alignment plus uniformity." | The first term equals ℓalign(α=2) exactly, up to a positive scale and a constant. The second is a same-minimiser correspondence, not an equality — the theorem's term has Ex inside the log and ℓuniform has it outside. Chapter 4 spells out the Jensen gap and why it closes at the uniform optimum |
| "Lower ℓalign means a better model." | Only within a fixed augmentation pipeline. Weaken your augmentations and alignment improves while the representation gets worse. Neither metric is a quality score on its own; the pair is |
| "Uniformity prevents collapse, so a good uniformity value means no collapse." | It prevents the trivial constant-encoder collapse. It is nearly blind to dimensional collapse — a 4× loss of effective rank moves the number by 0.19 nats at t = 2. Measure the covariance spectrum separately |
| "Self-supervised learning works by making features uniform." | BYOL and SimSiam have no repulsive term at all and do not collapse. Uniformity is one anti-collapse mechanism among several, and the paper is scoped to the contrastive family |
| "The metrics are comparable across papers." | Only at matched t, matched batch size, matched output dimension, and matched depth in the network. The reference value alone moves from −3.94 (t = 2, d = 128) to −9.61 (t = 5, d = 128). Always report the settings alongside the number |
| "The paper shows you should stop using InfoNCE." | It shows the direct form works at least as well, which is evidence for the analysis. The accuracy gains are fractions of a point. The enduring contribution is the diagnostic, not the replacement loss |
| Work | What it borrowed | What it added |
|---|---|---|
| SimCSE (Gao, Yao, Chen 2021) | The alignment-uniformity plane as its primary analytical tool | Showed that mean-pooled BERT's anisotropy is a uniformity failure, and that dropout-as-augmentation fixes it without paying in alignment. This is the paper that made the plot standard in NLP |
| Understanding the Behaviour of Contrastive Loss (Wang & Liu 2021) | The temperature-as-kernel-width reading | Named and measured the uniformity-tolerance dilemma; showed the loss is hardness-aware and that low τ separates semantically identical inputs |
| Understanding Dimensional Collapse (Jing, Vincent, LeCun, Tian 2022) | The observation that uniformity alone is not the whole anti-collapse story | Diagnosed collapse in the covariance spectrum — precisely the failure mode Chapter 8 showed uniformity is weak at detecting — and proposed DirectCLR |
| Barlow Twins / VICReg (Zbontar et al. 2021; Bardes, Ponce, LeCun 2022) | The two-force decomposition, restated | Replaced pairwise repulsion with explicit variance and decorrelation terms on feature dimensions — a different anti-collapse mechanism aimed at exactly the spectrum uniformity cannot see |
| Provable Guarantees / Spectral Contrastive Loss (HaoChen et al. 2021) | The framing that the loss shapes a distribution rather than estimating a bound | An augmentation-graph view with downstream error guarantees — a complementary answer to the "why is it semantic?" question Chapter 8 left open |
| Contrastive Learning Inverts the Data Generating Process (Zimmermann et al. 2021) | The hypersphere setting and the uniform-marginal assumption | Identifiability: under a von Mises-Fisher latent model, contrastive learning recovers the true latents up to rotation. The strongest available answer to "why semantic?" |
| Step | What to do | The decision that matters |
|---|---|---|
| 1. Instrument first | Add lalign and lunif to a training loop you already have, and just log them alongside your existing InfoNCE | Zero risk, immediate payoff. You will see the collapse story in your own curves before changing anything |
| 2. Unit-test the metrics | Assert the Chapter 5 four-point square gives ℓalign = 2.0000 and ℓuniform = −4.3963 | Catches all five classic bugs in five seconds |
| 3. Port the temperature | Set t = 1/(2τ) from your tuned run, and start at λ = 1 | Equation 3 makes this exact rather than a search |
| 4. Swap the loss | Replace InfoNCE with ℓalign + λℓuniform | Check λt > 1 before you launch, or you are training a collapse |
| 5. Plot the plane | Run a small λ sweep and scatter the endpoints with downstream accuracy as colour | Five runs is enough to see the frontier. This plot will outlive the project |
| 6. Check the spectrum | Also log the covariance eigenvalues of your features | Chapter 8 — uniformity will not catch dimensional collapse for you |
Without scrolling up: (1) state why mutual information cannot explain downstream quality, in one sentence about bijections; (2) write both metrics from memory, including where the log sits in each; (3) derive t = 1/(2τ) from the sphere identity; (4) explain why the linear "spread the features out" objective is fooled by a two-atom collapse and the Gaussian potential is not; (5) compute ℓuniform for four points at 0°, 90°, 180°, 270° at t = 2 and check you get −4.3963; (6) state the collapse threshold in terms of λ and t, and translate it into τ. If any of the six stalls, its chapter is one tap away.