Tongzhou Wang, Phillip Isola (MIT) — arXiv:2005.10242, ICML 2020

What Contrastive Loss Actually Optimizes

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.

Prerequisites: dot products + what softmax does + the idea of an expectation. Hyperspheres, potential energy, and the asymptotic proof are built from zero.
10
Chapters
7
Interactive Sims
2
Metrics
4
Lines of Code

Chapter 0: The Mystery

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?

The field had an answer, and the answer was wrong. The standard story in 2018–2020 was mutual information maximisation. The loss was introduced by van den Oord et al. as InfoNCE — the name literally encodes the claim — and it comes with a theorem: minimising it maximises a lower bound on the mutual information between the two views. Clean, principled, and, as an explanation of why the representations are good, it does not survive contact with two facts.

Failure 1: mutual information cannot tell good features from scrambled ones

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

I( g(A) ; B ) = I( A ; B )

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:

Mutual information
I(f′(x); y) = I(f(x); y) — identical, to the last bit
↓ same number …
Linear probe accuracy
Can drop from 70% to near chance — a cubed, rotated feature space is not linearly separable any more

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.

What downstream quality actually depends on. A linear probe cares about geometry: are the classes arranged so a hyperplane can cut between them? Mutual information is a property of the partition of probability mass and is completely indifferent to geometry. Any explanation of contrastive learning that is invariant to bijections is explaining the wrong thing. That is the gap Wang & Isola walk into.

Failure 2: the bound is loose, and tightening it makes things worse

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,

I(x;y)  ≥  log M − ℓInfoNCE

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 Mlog M (nats)Ceiling in bitsComment
256 (a typical SimCLR batch on one node)ln 256 = 5.5458.0 bits256 = 28, so the arithmetic is exact
4,096 (SimCLR's large-batch setting)ln 4096 = 8.31812.0 bitsDoubling the batch buys exactly one bit
65,536 (MoCo's memory queue)ln 65536 = 11.09016.0 bitsA 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.

Inline concept check — answer before reading on. Batch size clearly matters in practice: SimCLR gets better with M = 4096 than with M = 256. If the MI story is dead, why should M matter at all?  …  Because M is not buying you certified bits; it is buying you negatives. Every extra negative is one more constraint of the form "these two things must not be confused", which is a statement about the arrangement of points in space, not about a bit count. Chapter 4 turns that intuition into a theorem: as M grows, the loss converges to a specific geometric objective, and the convergence rate is O(M−1/2).

Where the log M ceiling comes from

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

P(j is the positive) = [ p(yj|x)/p(yj) ] / ∑k [ p(yk|x)/p(yk) ]

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

InfoNCE  ≥  log M − I(x; y)

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.

A convention warning, so Chapter 4 does not confuse you. The bound above counts M candidates, one of which is positive. Chapter 4 will count M negatives, giving M+1 terms in the denominator. The two differ by log(1 + 1/M), which vanishes as M grows and is 0.4% at M = 256 — irrelevant asymptotically, but worth knowing when you are reconciling two papers' arithmetic and they disagree in the fourth decimal place.

Three more explanations that do not survive

Before accepting the paper's answer, it is worth ruling out the other things people say in seminars, because each is almost right.

The explanationWhy it feels rightWhere it breaks
"It learns to be invariant to augmentations"True — positive pairs are augmentations of one image, so the encoder is pushed toward augmentation-invarianceOnly 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 apartThis 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 featuresThe 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 correctBijection-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.

The move: stop asking what quantity is bounded, ask what geometry is favoured

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.

Property 1 — Alignment
Features of positive pairs land in the same place. The encoder is invariant to whatever transformation generated the pair.
↓ and, in tension with it …
Property 2 — Uniformity
Across the whole dataset, features are spread out to cover the hypersphere as evenly as possible — preserving as much information as the geometry allows.
↓ and here is the claim …
The theorem
As the number of negatives M → ∞, the contrastive loss provably decomposes into exactly these two terms — one measuring alignment, one measuring uniformity.

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.

The bar this sets. An explanation of a loss function is a hypothesis. The way you test a hypothesis about "what a loss really wants" is to build the thing it supposedly wants and check whether it works as well. Most analysis papers stop at the plot. This one ships the falsification test: if alignment and uniformity are what InfoNCE is secretly optimising, then optimising them openly should work at least as well. It does — STL-10 linear probe goes from 80.46% to 81.15%, ImageNet-100 with MoCo goes from 72.80% to 74.60%. Small numbers, enormous epistemic weight.

What the two numbers actually are

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.

align(f; α) = E(x,y) ~ ppos [ ‖ f(x) − f(y) ‖2α ]

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.

uniform(f; t) = log Ex, y ~ pdata [ e−t ‖ f(x) − f(y) ‖22 ]

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.

Why "energy" is the right word and not a metaphor. The uniformity metric is, structurally, the same object that physicists compute for charged particles on a sphere: sum a repulsive potential over every pair, and ask which arrangement minimises the total. Swap the Gaussian potential e−t d² for the Coulomb potential 1/d and you get the Thomson problem, posed in 1904 and still open for most point counts. Contrastive learning is doing electrostatics on a sphere, with images as the charges. Chapter 3 makes this exact.

Where we are going

Chapters 1–3 — build the two metrics
Why the sphere is the right stage → alignment and the role of α → uniformity, the Gaussian kernel, and the proof that its unique minimiser is the uniform distribution
Chapters 4–5 — the theorem, and doing it by hand
Walk the M → ∞ decomposition honestly, including the two error terms → then compute both metrics on four points on a circle with visible arithmetic
Chapters 6–9 — use it, then interrogate it
Optimise the metrics directly → read models off the tradeoff plane → what the lens predicts (temperature, dimensional collapse) and what it cannot see → the papers it made possible
Why does the mutual-information story fail as an explanation of why contrastive features are good for a linear probe?

Chapter 1: Why the Sphere

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.

f(x)  =  h(x) / ‖ h(x) ‖2

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.

What the object is

The set of all unit-length vectors in Rm is the unit hypersphere, written Sm−1:

Sm−1 = { u ∈ Rm : ‖ u ‖2 = 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:

u · v = ‖u‖ ‖v‖ cosθ = cosθ

The dot product is the cosine of the angle between them, because both lengths are 1. And the squared distance:

‖ u − v ‖2 = (u−v)·(u−v) = ‖u‖2 + ‖v‖2 − 2 u·v = 2 − 2 u·v

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.0000.0000.000
30°0.8660.2680.518
60°0.5001.0001.000
90° (orthogonal)0.0002.0001.414
120°−0.5003.0001.732
180° (antipodal)−1.0004.0002.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.

Reason 1: without normalisation, the norm is a free temperature dial

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

ℓ = −log [ espos / ( espos + ∑i=1M esi ) ]

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
The loss fell by a factor of 108 and the representation did not change at all. Same angles, same relative arrangement, same everything a downstream classifier could ever use. The only difference is a scalar multiplying every vector. An unnormalised encoder can therefore drive its loss toward zero by inflating its outputs — gradient descent will happily discover this, because it is by far the cheapest direction. Scaling the norm by r is exactly equivalent to dividing the temperature by r2. The norm becomes a second, uncontrolled temperature, and the model spends its capacity turning that dial instead of arranging the geometry.

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.

The norm as a hidden temperature

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.

Radius r 1.00
Temperature τ 0.50
Positive angle 20°

Reason 2: a compact space is the only place "uniform" means anything

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."

The paper's framing choice, stated plainly. By committing to the hypersphere, Wang & Isola make "maximally spread out" a well-posed target with a unique answer, rather than a vibe. Every theorem in the paper — uniqueness of the minimiser, weak* convergence of finite point sets — depends on compactness. Take the normalisation away and there is no theory left, only heuristics. The one-line division in the training script is load-bearing for the mathematics, not just for the optimiser.

Reason 3: bounded similarities keep the exponential from exploding

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.

Reason 4: the sphere is a good place for a linear probe

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.

An uncomfortable fact about high-dimensional spheres

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

std( u · v ) = 1 / √m
Dimension mTypical random cosine 1/√mTypical random angleWhat it means
2 (a circle)0.707≈ 45° from orthogonalTwo random points are often quite similar; the circle is crowded
160.250≈ 75°Getting roomy
128 (the standard projection dim)0.088≈ 85°Almost everything is almost orthogonal to almost everything
20480.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.

Inline concept check. You move a model from a 128-dim projection head to a 512-dim one and keep τ = 0.07. What happens to the effective sharpness of the softmax?  …  The random-cosine spread halves, from 0.088 to 0.044, so every off-diagonal logit shrinks by 2× while the positive-pair logit (which is not a random cosine — it is trained to be near 1) barely changes. The softmax becomes more peaked on the positive, which sounds good but reduces the gradient flowing to the negatives — and negatives are the entire source of uniformity. In practice you would want a somewhat larger τ at higher dimension. This is the kind of prediction the alignment-uniformity lens makes cheap; Chapter 8 collects more of them.

How much room is there, actually?

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:

P( u · v ≥ ε )  ≤  e−dε2/2

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 εAngleFraction of S127 inside the capReading
0.184.3°e−0.64 = 0.527Half the sphere — a cosine of 0.1 means nothing at all
0.372.5°e−5.76 = 0.0032Three parts in a thousand
0.560.0°e−16 = 1.1 × 10−7One ten-millionth of the surface
0.836.9°e−41 = 1.6 × 10−18Vanishing. Reaching cosine 0.8 by accident is impossible
The capacity argument in one line. If a cap at cosine 0.5 holds one ten-millionth of the sphere, then a uniform distribution over S127 can support on the order of 107 mutually distinguishable regions at that resolution — regions in which no two representatives are within 60° of each other. ImageNet has 1.28 million images. So a 128-dimensional sphere is, to within an order of magnitude, exactly big enough to give every ImageNet image its own well-separated address. That is not a coincidence about ImageNet; it is why 128 became the standard projection dimension and why halving it starts to hurt.

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.

Normalise what, exactly?

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.

Summary before we build

The normalisation buysBecauseWhere it shows up later
The loss depends only on geometryNorm inflation, an equivalent free temperature, is removedChapter 4 — the theorem is about the distribution of points, so the points must be pinned to the surface
"Uniform" is well-defined and uniqueCompact + homogeneous ⇒ exactly one rotation-invariant probability measure σm−1Chapter 3 — every uniqueness proof
Distance and dot product are interchangeable‖u−v‖2 = 2 − 2u·v exactlyChapters 2 and 4 — converting the loss's first term into the alignment metric
Numerical safetys ∈ [−1,1] bounds the exponent by 1/τAny training run that does not produce NaN
A friendly space for linear probesA linear classifier becomes an angular threshold cutting spherical capsChapter 7 — why position on the tradeoff plane predicts probe accuracy
An engineer removes the L2 normalisation from a SimCLR implementation, keeps everything else identical, and reports that the training loss now converges to a much lower value. What has actually happened?

Chapter 2: Alignment

Alignment is the easy half, and it is worth doing slowly anyway, because the easy half contains the one parameter people misconfigure.

Where positive pairs come from

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.

Why symmetry matters in practice. Suppose your "augmentation" for the first view is identity and for the second view is a heavy crop. Then the marginals differ: view-1 features come from clean images, view-2 features from crops. The two views now live in different regions of the sphere, and a model can reduce the loss by exploiting the view identity rather than the content — a shortcut. Symmetric augmentation pipelines are not cosmetic; they are what makes "the feature distribution" a single well-defined object rather than two.

The metric, derived

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:

align(f; α) = E(x,y) ~ ppos [ ‖ f(x) − f(y) ‖2α ],    α > 0

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.

What α actually controls

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

∂(dα) / ∂d = α · dα−1

Evaluate that at both distances:

αGradient at d = 0.2 (good pair)Gradient at d = 1.2 (bad pair)Ratio bad : goodBehaviour
0.50.5 × 0.2−0.5 = 1.1180.5 × 1.2−0.5 = 0.4560.41×Inverted. Pushes hardest on pairs that are already close; nearly ignores the failures
1.01 × 0.20 = 1.0001 × 1.20 = 1.0001.00×Neutral. Every pair gets the same push regardless of how wrong it is
2.02 × 0.2 = 0.4002 × 1.2 = 2.4006.0×Hard-pair focused. The worst pair receives six times the pull
3.03 × 0.04 = 0.1203 × 1.44 = 4.32036×Aggressive; a single mislabelled positive pair can dominate the batch
Read the α = 0.5 row again. With a sub-linear exponent, the gradient at d → 0 diverges — the metric spends its effort perfecting pairs that are already essentially perfect, while a pair that has landed on the far side of the sphere barely registers. That is the opposite of what you want from a training signal. It is also exactly the shape of a robust loss (like a Huber or an L1) if what you feared was outliers — so the right choice of α depends on whether your "hard positives" are genuinely hard or are just mislabelled. Wang & Isola use α = 2 throughout and report that results are stable for α ∈ {1, 2}.
The α dial — which positive pairs get the push

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.

α 2.00
Pair A gap 0.21
Pair B gap 1.20

Alignment as invariance — and the trap inside it

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.

You choose the augmentations
Random crop, colour jitter, greyscale, blur — a claim about which changes preserve meaning
↓ defines ppos
Alignment enforces invariance to exactly those
align → 0 means f cannot distinguish an image from its augmentations
↓ consequence
Anything the augmentation destroys is destroyed in the features
Aggressive colour jitter ⇒ a colour-blind encoder. Fine for ImageNet objects. Fatal for bird species or medical stains.
The honest boundary of this paper. Alignment and uniformity describe what the loss does to a feature distribution given ppos. They say nothing about how to choose ppos — and the choice of augmentations is where nearly all of the domain knowledge in modern self-supervision lives. The theory explains the machine; the augmentations decide what the machine learns. Chapter 8 returns to this as the lens's main blind spot.

What the number looks like in practice

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

align = E[ 2 − 2 f(x)·f(y) ] = 2 − 0 = 2.000

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.

Inline concept check. Two teams report contrastive models on the same dataset. Team A: ℓalign = 0.18. Team B: ℓalign = 0.61. Which model is better?  …  Unanswerable, and the question is malformed. If Team A used a horizontal flip as its only augmentation, an encoder can achieve tight alignment while learning almost nothing, because flip-invariance is nearly free. Team B's 0.61 under crop-plus-jitter-plus-blur may represent far more learned invariance. Alignment measures how well the encoder met the demand you placed on it, and the two teams placed different demands. This is why the paper always reports both metrics together with a fixed protocol, and why the tradeoff plane needs its axes labelled with the setup that produced them.

Alignment is not intra-class compactness

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.

QuantityMeasured overOptimised by contrastive loss?
AlignmentPairs of augmentations of one imageYes — directly, it is half the objective
Intra-class compactnessPairs of different images with the same labelNo — and the uniformity term works against it
Inter-class separationPairs of images with different labelsOnly 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.

The identity that makes Chapter 4 work

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:

‖ f(x) − f(y) ‖2 = 2 − 2 f(x)·f(y)   ⇒   − f(x)·f(y) = ½ ‖ f(x) − f(y) ‖2 − 1

Take the expectation over positive pairs and divide by τ:

− (1/τ) Eppos[ f(x)·f(y) ]  =  (1/2τ) ℓalign(f; 2)  −  1/τ

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 isalign(f; 2), and that is why 2 is the canonical exponent.

Inline concept check. Someone proposes replacing ‖f(x)−f(y)‖2 with 1 − cos(f(x), f(y)) as the alignment metric, arguing that cosine is "more natural" for normalised vectors. What changes?  …  Nothing that matters. 1 − cos = 1 − f(x)·f(y) = ½‖f(x)−f(y)‖2, so it is the α = 2 alignment metric scaled by ½. The two formulations have identical minimisers and identical gradient directions; only the learning rate you would want differs. The reason the paper writes it as a distance to a power is that the distance form generalises to other α, while the cosine form is locked at α = 2.

What perfect alignment does to the sphere

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.

You are training a contrastive model on a dataset where about 3% of your "positive pairs" are actually mislabelled — two different images accidentally paired. You are using ℓalign with α = 3. What is the specific mechanism by which this hurts?

Chapter 3: Uniformity

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.

Attempt 1: maximise the average pairwise distance

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

Ex, y ~ pdata [ ‖ f(x) − f(y) ‖2 ]

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 circleMean vectorE‖u−v‖2 = 2 − 2‖E[u]‖2Verdict of this objective
Genuinely uniform σ102.000Optimal
Two antipodal atoms, half mass each½u0 + ½(−u0) = 02.000Also optimal — a perfect tie
All mass on one pointu0, norm 10.000Worst, 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 lesson generalises. Any "spread" objective that is linear in the dot product is a statement about the mean and nothing else. That includes maximising the average distance, minimising the average cosine, and every variant of "make the Gram matrix's off-diagonal small on average." All of them are satisfied by a two-point collapse. You need an objective that is sensitive to the full shape of the distribution, not just its first moment.

Attempt 2: maximise the entropy of the feature distribution

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.

The paper's answer: the pairwise Gaussian potential

Define the Gaussian potential kernel (also called the radial basis function or heat kernel) between two points on the sphere:

Gt(u, v) = e−t ‖u−v‖22,    t > 0

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:

uniform(f; t) = log Ex, y ~ pdata [ e−t ‖ f(x) − f(y) ‖22 ]

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 d2AngleG2 = e−2d2Contribution
0.001.000000Maximum penalty — two features have collapsed onto each other
0.2730°0.585137Still substantial
1.0060°0.135335Fading
2.0090°0.018316Nearly invisible
4.00180°0.000335Zero for all practical purposes
Why the logarithm, given that log is monotone and cannot change the minimiser. It is there for the gradients, and the reason is quantitative. In 128 dimensions with t = 2, a well-spread feature cloud has a mean potential around e−4 ≈ 0.0195. The derivative of log A with respect to any parameter is (1/A) ∂A, so the log form multiplies every gradient by 1/0.0195 ≈ 51× compared with optimising the raw mean. Without it, the uniformity term's gradient is drowned by the alignment term's at exactly the point where you most need it. The log also makes the metric's numeric range comparable across choices of t and dimension, which is what turns it into a reportable diagnostic rather than an internal quantity.

Why this kernel: the uniqueness result

Here is the theorem that justifies the whole construction. The paper states it as Proposition 1.

Proposition 1 (Wang & Isola 2020). For any t > 0, the normalised surface measure σm−1 — the uniform distribution on Sm−1 — is the unique minimiser of the pairwise Gaussian potential

    minμ ∫∫ Gt(u, v) dμ(u) dμ(v)

over all Borel probability measures μ on the sphere.

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μ:

E(μλ) = E(μ0) + 2λ ∫∫ Gt0 dν + λ2 ∫∫ 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. ∎

Why the Gaussian kernel is strictly positive definite, in one paragraph. Use the Chapter 1 identity to rewrite it as a function of the dot product: Gt(u,v) = e−t(2−2u·v) = e−2t e2t(u·v). Now expand the exponential as a power series: e2ts = ∑k (2t)ksk/k!, whose coefficients are all strictly positive. Each power (u·v)k, decomposed into spherical harmonics on the sphere, contributes non-negatively to every harmonic degree up to k. Summing over all k, every degree receives a strictly positive total. A kernel whose entire harmonic spectrum is positive is strictly positive definite — and that is the whole reason the uniqueness proof works.

The same lens explains why Attempt 1 failed

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.

Deriving the uniform reference value by hand

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:

I0(z) = ∑k=0 (z2/4)k / (k!)2

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.

The general-dimension version, for when you need it. On Sm−1 the same integral produces a ratio of Bessel functions of order (m−2)/2, which is tedious. In practice nobody evaluates it, because in high dimension there is a much friendlier approximation: the dot product between two independent uniform points is nearly Gaussian with variance 1/m, so E[e2t(u·v)] ≈ e2t2/m and

    ℓuniform ≈ −2t + 2t2/m

which at t = 2 and m = 128 gives −3.9375. That single formula is the reference value you will use for the rest of this lesson, and it is derived properly in Chapter 7. It fails badly below about m = 8, where the exact circle result −1.5750 is the honest answer.

The kernel spectrum, tabulated

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.

KernelHarmonic degrees with non-zero weightBlind toUnique minimiser is σ?
−u·v (linear)Degree 1 onlyEverything except the mean vectorNo — any mean-zero distribution ties, including two atoms
(u·v)2Degrees 0 and 2Odd structure; a two-atom cloud and its mirror are indistinguishableNo
e−t‖u−v‖2All degrees, all strictly positiveNothingYes, for every t > 0
‖u−v‖−s (Riesz)All degrees positive, but the energy integral diverges for s ≥ m−1Nothing, where it is finiteYes, 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.

SHOWCASE — the potential landscape, and which kernels get fooled

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.

Kernel width t 2.0
Preset:

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.

From distributions to batches: Proposition 2

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.

A finite-batch subtlety worth knowing. A batch of M points drawn i.i.d. from the true uniform distribution does not achieve the M-point optimal energy — random points clump. On the circle at t = 2, a single random pair has expected potential 0.207, so a random 4-point batch has an expected mean potential of 0.207 and hence ℓuniform ≈ −1.58, whereas the best possible 4-point configuration (a perfect square, Chapter 5) scores 0.0123 and −4.40. The metric on a batch therefore measures something slightly stronger than "looks uniformly distributed" — it measures "is well spread for its size." That is a feature, not a bug: it is what gives the gradient something to push on at every step.

What t does, at both extremes

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

log E[Gt] ≈ log(1 − t E[d2]) ≈ −t E[d2] = −2t + 2t ‖E[u]‖2

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.

tuniform, two atomsuniform, true uniformGap (nats)What the metric is really doing
0.1−0.1801−0.19000.010Almost blind — a two-point collapse costs a hundredth of a nat
2 (the default)−0.6928−1.57500.882Sharply discriminative across the whole sphere
10−0.6931−2.41041.717Dominated 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.

The Thomson connection, made exact. Replace e−td2 with the Coulomb potential 1/d and minimising the pairwise energy of M points on S2 is the Thomson problem (1904): where do M electrons sit on a sphere? For M = 4 the answer is a regular tetrahedron; for M = 8 it is emphatically not a cube. That family of Riesz potentials 1/ds also has σ as its minimising measure, but only for s in a dimension-dependent range, and the integrals diverge outside it. The Gaussian kernel is the well-behaved cousin: bounded, smooth, differentiable everywhere, and with σ as its unique minimiser for every t > 0. That robustness is why the paper picks it — and Chapter 4 will reveal a second, better reason: the Gaussian kernel is what falls out of the contrastive loss whether you asked for it or not.
A colleague proposes a simpler uniformity term: minimise the average cosine similarity between all pairs of features in the batch. Why does the Gaussian potential do something this cannot?

Chapter 4: The Asymptotic Theorem

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.

The loss we are analysing

Write the contrastive loss with an explicit number of negatives M:

contrastive(f; τ, M) = E [ −log ( ef(x)·f(y)/τ / ( ef(x)·f(y)/τ + ∑i=1M ef(xi)·f(x)/τ ) ) ]

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.

Step 1: split the log

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):

ℓ = − s+/τ  +  log ( es+ + ∑i esi )

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.

Step 2: normalise by log 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.

Step 3: let M go to infinity

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

AM = (1/M) ∑i esi  →  Ex ~ pdata [ ef(x)·f(x)/τ ]

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.

Theorem 1 (Wang & Isola 2020), asymptotics of the contrastive loss. For fixed τ > 0, as M → ∞,

  ℓcontrastive(f; τ, M) − log M  →  −(1/τ) E(x,y)~ppos[ f(x)·f(y) ]  +  Ex~pdata[ log Ex~pdata[ ef(x)·f(x)/τ ] ]

(1) The first term is minimised precisely by perfectly aligned encoders. (2) If perfectly uniform encoders exist for this data distribution, they are exactly the minimisers of the second term. (3) The absolute deviation from the limit decays as O(M−1/2).

Step 4: recognising the two terms

Term one is alignment. This is Chapter 2's identity, reused verbatim:

−(1/τ) E[ f(x)·f(y) ] = (1/2τ) E[ ‖f(x)−f(y)‖2 ] − 1/τ = (1/2τ) ℓalign(f; 2) − 1/τ

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:

log Ex[ ef(x)·f(x)/τ ] = 1/τ + log Ex[ Gt( f(x), f(x) ) ],    t = 1/(2τ)
The temperature IS the kernel width. t = 1/(2τ). Every choice of contrastive temperature is silently a choice of how far uniformity should reach. τ = 0.5 gives t = 1 — a broad, gentle repulsion. τ = 0.07, the SimCLR default, gives t ≈ 7.1 — a sharp, short-range repulsion that, by Chapter 3's t → ∞ analysis, behaves much more like a packing objective concentrated on nearest neighbours. The paper's default metric uses t = 2, corresponding to τ = 0.25; its ImageNet-100 experiments used t = 3, i.e. τ ≈ 0.167. Chapter 8 turns this single equation into a set of predictions about temperature that match what practitioners had already discovered empirically.

The one place to be honest about a gap

Compare the theorem's second term with the metric from Chapter 3, carefully:

ObjectWhere the log sits
The theorem's second termEx[ log Ex[ Gt ] ] — log inside, averaged over anchors
uniform, the metric we optimiselog 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.

Do not skip this and do not overclaim it. The honest statement is: ℓuniform is not literally a term in the asymptotic contrastive loss. It is a metric that (a) shares the same unique minimiser, (b) is derived from the same kernel that the loss produces, and (c) is better behaved as an optimisation target and a reported diagnostic. Papers that say "contrastive loss equals alignment plus uniformity" are compressing this. The equality is exact for the alignment half and is a same-minimiser correspondence for the uniformity half.

The convergence rate, and where the error actually comes from

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.

Doing it by hand at M = 3

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.
Look at how large those two terms are, and that they have opposite signs. At M = 3 the positive pair is 52% of the denominator, which inflates the loss by 0.73 nats. Simultaneously, three negatives at 90°, 180° and 270° badly underestimate the true partition function — none of them landed near the anchor, and the exponential is dominated by exactly those near-collisions — which deflates it by 0.47. The two errors partly cancel, which is why small-M contrastive learning is not as catastrophic as the raw error terms suggest, and also why the finite-M loss is a biased estimate of the asymptotic objective in a direction that depends on your data.
SHOWCASE — watching the loss converge to its decomposition

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.

Temperature τ 1.00
Positive angle 20°

The other extreme: what happens at M = 1

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 MGap to the limit −0.7038Regime
1+0.32981.034A different objective entirely — the positive is half the denominator
3−0.44360.260Two large errors of opposite sign, partly cancelling
16−0.5960.108Recognisably the right objective, noticeably biased
256−0.6920.011Practically 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.

Three assumptions the theorem makes that your training loop breaks

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.

ImplementationWhat it actually doesConsequence for the theorem
SimCLR — in-batch negativesThe negatives for anchor i are the other 2N−2 views in the same batch, which include the other view of every other imageNegatives 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 queueNegatives were encoded by an exponential-moving-average copy of the encoder, several thousand steps agoThe 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 datasetSome "negatives" are semantically identical to the anchor — two photos of the same species, two near-duplicate framesThe objective contains constraints that are false. Chapter 8's uniformity-tolerance dilemma is exactly the cost of this, and it gets worse as τ falls
Inline concept check. MoCo's queue holds 65,536 negatives, far more than SimCLR's 4,094. Does the theorem say MoCo is therefore 4× closer to the asymptotic objective?  …  It says the sampling noise term is √16 = 4× smaller, yes. It says nothing about the lag, which is a bias rather than a variance and does not shrink with M at all. A queue trades one error for another: less noise in the estimate of the repulsive field, but the field being estimated belongs to an older encoder. That trade is favourable in practice, which is a fact about optimisation dynamics that this theorem has nothing to say about.

What the theorem does not say

Three caveats, all of which the paper is upfront about and all of which get misquoted.

The theorem saysIt does not say
The loss functional converges to alignment plus a uniformity-flavoured termThat 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 termThat 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
In the asymptotic decomposition, which error source sets the O(M−1/2) convergence rate, and what does that imply for practice?

Chapter 5: Four Points, by Hand

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.

The setup

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:

dij2 = ‖ui − uj2 = 2 − 2 cos(θi − θ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.

Why six pairs and not sixteen. Four points give C(4,2) = 6 unordered distinct pairs. The population definition of ℓuniform draws x and y independently, which includes the case x = y and would give sixteen ordered pairs. For a continuous feature distribution the diagonal has probability zero, so the practical estimator drops it — and dropping it also removes a constant 1 from the average that would otherwise dominate at small batch sizes. Every number below uses the six-pair convention, exactly as the code does.

Configuration A: total collapse

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.

Configuration B: perfectly aligned, two atoms

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.

Configuration C: the perfect square

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.

Configuration D: the actual optimum

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δalignuniformTotal at λ = 1
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
The optimum is neither collapsed nor perfectly spread, and it never will be. With four points and two positive pairs, the objective wants the pairs tight (alignment) and the four points evenly spaced (uniformity), and those two wishes are literally incompatible — tightening a pair necessarily crowds two points together. What you get is a negotiated settlement whose location depends on λ and t. This is not an artefact of the toy. It is the permanent condition of contrastive learning, and Chapter 7 is about reading where a real model settled.
SHOWCASE — drag four points, watch both metrics move

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.

λ (uniformity weight) 1.00
Kernel width t 2.0
Preset:

Where the settlement sits: a bifurcation you can derive

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.

Collapse threshold:   λ t = 1   ⇒   at t = 2,   λ* = 0.5

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.

Now translate it back into contrastive language. Chapter 4 gave t = 1/(2τ). Substituting, the collapse condition λt > 1 becomes

    λ > 2τ

Lower temperature means a smaller uniformity weight suffices to prevent collapse — which is precisely the empirical folklore that low temperatures make contrastive learning robust against collapse, derived here from a four-point toy in six lines of algebra. Note also what happens as τ grows: you need an ever larger λ to keep the representation open, and at some point no reasonable weighting saves you. That is the same degeneracy Chapter 3 found at t → 0, arriving from a different direction.

Sweeping λ: the settlement moves, and it moves abruptly

The threshold calculation says something happens at λt = 1. Compute the actual optimum at several λ (holding t = 2) and you can watch it happen.

λλtOptimal δalignuniformTotal
0.250.500.0000−1.0979−0.2745
0.501.000.0000−1.0979−0.5490
0.551.10≈ 34°1.2508−3.5476−0.7004
1.002.00≈ 41°1.7217−4.2500−2.5284
2.004.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.

This is a subcritical bifurcation, and it has a training-loop consequence. Evaluate the total at λ = 0.502 and the collapsed solution still wins globally; at λ = 0.505 the split solution wins. The local stability of the collapsed solution ends at λt = 1, but the global optimum switches essentially at the same place and does so by jumping. The practical reading: gradient descent started from a nearly-collapsed initialisation can sit in the collapsed basin even when a much better split solution exists, because just above the threshold the barrier between them is real. If your run collapses and raising λ slightly does not rescue it, do not conclude that λ is not the problem — restart, or raise λ well past the threshold rather than creeping up to it.

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.

Extending to eight points, and why it barely changes

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.

A sanity check you should run on your own code

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 getAlmost certainly
uniform = −1.3500 instead of −4.3963 on the squareYou 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 squareYou forgot to square: .norm() without .pow(alpha), so you averaged distances (√2) rather than squared distances
uniform = −3.0898 on the squareYou applied t to the distance rather than the squared distance — a missing .pow(2) before .mul(-t)
uniform = 0.0123 on the squareYou forgot the final .log(). The values will look plausible and your gradients will be about 80× too small
Both metrics exactly right, but training collapsesNot a metric bug. Check λt > 1
Using t = 2 and λ = 1, the four-point square scores −2.3963 while the δ = 41° configuration scores −2.5284, even though the square has strictly better uniformity. What is the general lesson?

Chapter 6: Optimising the Two Metrics Directly

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.

The entire implementation

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.

ExpressionShapeWhy 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()scalarThe α 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()sameGt for each pair. Squared distance then scale by −t; reversing these gives a completely different kernel
.mean().log()scalarMean 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)) / 2scalarUniformity is a property of the marginal feature distribution, and both views are samples from it. Averaging the two estimates halves the variance for free
The cost is identical to InfoNCE's. 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.

The numerical trap

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.

SettingSmallest term e−4tfloat32 (min normal ≈ 1.2e−38)float16 (min normal ≈ 6.1e−5)
t = 2 (default)3.4e−4FineFine
t = 5 (the paper's BookCorpus setting)2.1e−9FineUnderflows to 0
t = 104.2e−18FineUnderflows to 0
t = 253.7e−44Underflows to 0Dead

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.

What the paper actually ran

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.

BenchmarkObjective usedOutput dimBatch
STL-100.98 · ℓalign(α=2) + 0.96 · ℓuniform(t=2)128768
NYU-Depth-V20.98 · ℓalign(α=2) + 0.96 · ℓuniform(t=2)128128
ImageNet-100 (MoCo)3 · ℓalign(α=2) + ℓuniform(t=3)128128
BookCorpus (Quick-Thought)0.9 · ℓalign(α=2) + 0.1 · ℓuniform(t=5)1200400

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.

The results

BenchmarkMetricContrastive lossalign + λℓuniform
STL-10Linear probe accuracy80.46%81.15%
STL-105-NN accuracy on fc776.33%76.78%
NYU-Depth-V2Depth MSE (lower is better)0.70240.7014
ImageNet-100MoCo linear probe, top-172.80%74.60%
ImageNetMoCo v2 linear probe, top-167.5% ± 0.1%67.69%
BookCorpusMR / CR sentence classification77.51% / 83.86%77.51% / 83.86%
Read these numbers for what they are. The gains are small — 0.7 points on STL-10, 0.19 on full ImageNet, dead even on BookCorpus. If this were a benchmark paper it would be unpublishable. It is not a benchmark paper. The hypothesis under test is "alignment and uniformity are what contrastive loss optimises", and the prediction is "therefore optimising them directly should be at least as good". A tie is a pass. A consistent small win across six benchmarks in two modalities is a strong pass. The one genuinely large result — ImageNet-100 MoCo going from 72.80% to 74.60% — is the batch-128 setting, where the finite-M error terms of Chapter 4 are largest and the explicit form has the most to gain.

Porting an existing InfoNCE run, step by step

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.

StepCalculationResult
1. Convert the temperaturet = 1/(2τ) = 1/(2 × 0.1)t = 5
2. Check the collapse thresholdNeed λ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 numericsSmallest term is e−4t = e−20 = 2.1e−9Fine 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 scaleAt t = 5 the four-point square gives ln((4e−10 + 2e−20)/6) = −10.41Confirms 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.

Inline concept check. Your port runs, and ℓuniform settles at −9.4 against a reference of −9.61. Is that healthy?  …  A 0.21-nat deficit at t = 5. Map it through −2t + 2t2/k: −10 + 50/k = −9.4 gives k ≈ 83, versus the full 128. So roughly a third of the dimensions are contributing little. Not an emergency, but worth checking the covariance spectrum, and a good illustration that the same 0.2-nat deficit means very different things at different t — the same reported deficit at t = 2 would mean −4 + 8/k = −3.73, so k ≈ 29 — a far worse collapse. Always convert the deficit into an effective dimension before reacting to it.

What you get in exchange, practically

Beyond the accuracy, the reformulation buys engineering leverage that a single entangled scalar cannot.

With InfoNCEWith ℓalign + λℓuniform
One knob, τ, which simultaneously sets the alignment/uniformity balance and the kernel widthThree independent knobs: λ (balance), t (kernel width), α (hard-positive weighting)
One loss number. A collapsing run and a badly-aligned run look similar for many epochsTwo 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 MBoth metrics are comparable across runs, models, and papers — which is why they became a standard reporting axis

A training checklist

StepDo thisThe decision that matters
1. NormaliseF.normalize(h, dim=1) on both views before the lossNon-negotiable. Chapter 1: without it, norm inflation is a free win and uniformity is ill-posed
2. Pair correctlyAssert that row i of x and row i of y are the same imageA shuffled pairing gives a loss that decreases and a representation that is worthless
3. Pick tStart at t = 2; use t = 1/(2τ) if you are porting from a tuned InfoNCE runChapter 4's identity makes the port exact rather than a guess
4. Pick λStart at λ = 1, and always check λt > 1Chapter 5's bifurcation. Below the threshold you are training a collapse
5. Pick αα = 2 unless your positive pairs are noisy, then try α = 1Chapter 2's gradient table — α decides whether outlier pairs dominate
6. Log bothPrint ℓalign and ℓuniform every epoch, not just the sumThe whole point of the reformulation. The sum hides which force is failing
7. Guard numericsUse the logsumexp form; keep pairwise distances in float32t ≥ 5 under AMP produces silent −inf
8. Sanity checkFeed the four-point square from Chapter 5 and assert −4.3963Five seconds to write, and it catches every one of the five classic bugs
The most valuable line of this whole chapter is line 6. Once you log the two numbers separately, a class of debugging that used to require intuition becomes mechanical. Loss is flat and ℓuniform is near 0? Collapse — raise λ or t. Loss is flat and ℓalign is near 2? Your positive pairs are not actually positive — check the augmentation pipeline and the row pairing. ℓalign good, ℓuniform good, downstream accuracy bad? Now you have a genuinely interesting problem, and Chapter 8 has a list of what it might be.
Why does the paper average lunif(x) and lunif(y) rather than concatenating both views into one batch of 2N features and calling lunif once?

Chapter 7: The Tradeoff Plane

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.

Orienting yourself

Both metrics are "lower is better", so down and to the left is good. Fix the ranges from what we already know.

AxisRangeWhat 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 = 20 = 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
Where −3.94 comes from, since you will want to know whether your number is good. For u and v drawn independently and uniformly from Sd−1 in high dimension, the dot product is approximately Gaussian with mean 0 and variance 1/d. Using the Gaussian moment generating function, E[e2t(u·v)] = e2t2/d, so

    ℓuniform = log( e−2t · e2t2/d ) = −2t + 2t2/d

At t = 2 and d = 128 that is −4 + 8/128 = −3.9375. Memorise it as "about −3.94 is the uniform reference at the standard settings." Anything materially above it is crowding; anything below it means your batch is better-packed than an i.i.d. uniform sample, which is normal for optimised finite configurations.

The four corners

Top-right — ℓalign high, ℓuniform near 0
Untrained. Features are neither invariant nor spread. This is where every run starts.
Bottom-right — ℓalign ≈ 0, ℓuniform ≈ 0
Collapsed. The constant encoder. Perfect alignment, zero information. The classic failure of alignment-only objectives, and exactly what happens below the λt = 1 threshold.
Top-left — ℓalign high, ℓuniform very low
Scattered. Features spread beautifully and positive pairs land nowhere near each other. A random projection of raw pixels sits here. Maximum information, zero invariance, useless downstream.
Bottom-left — both low
The target. Tight positive pairs, well-spread marginal. Every good self-supervised encoder lives in a narrow band here, and the paper's central empirical finding is that downstream accuracy tracks position in this band.

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.

SHOWCASE — the tradeoff plane

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.

λ 1.00
Kernel width t 2.0

The frontier is real, and it is not a line you can cross

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 changeEffect on ℓalignEffect on ℓuniformMechanism
Raise λ (or lower τ)Worse (up)Better (left)Directly reweights the negotiation — you slide along the frontier
Stronger augmentationsWorse (up)Roughly unchangedPositive pairs become genuinely harder to map together; the encoder is asked for more invariance than it can supply
Bigger batchRoughly unchangedBetter (left)Lower-variance estimate of the repulsive field — Chapter 4's √M
Higher output dimensionRoughly unchangedBetter (left), toward the −2t floor−2t + 2t2/d: more room means less crowding, but with diminishing returns
More capacity / longer trainingBetter (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).

Reading real models: the sentence-embedding case

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 familyAlignmentUniformityReading
Mean-pooled BERT, no tuningGoodPoor — the anisotropic coneEverything is close to everything; similarity scores are nearly uninformative
Post-hoc whitening or normalising flows on BERTDegradedMuch improvedThese 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 preservedSubstantially improvedThe 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)ImprovedImprovedBetter positive pairs improve both at once — again a frontier move, not a slide
Why this became the standard diagnostic. Before Wang & Isola, "my embeddings are anisotropic" was an observation with no obvious objective attached, and the fixes were post-hoc transformations justified by intuition. After, anisotropy is simply a high ℓuniform, it is one of the two things your training objective controls, and you can tell at a glance whether a proposed fix moved the frontier or just slid along it. That distinction — slide versus move — is the single most useful thing this plane gives you, and it is the reason the plot appears in dozens of papers that are not about hyperspheres at all.

A reading protocol

Log both metrics each epoch and the plane becomes a diagnostic instrument.

What you seeDiagnosisAction
uniform rises toward 0 over the first few hundred stepsCollapse in progressRaise λ or t; check λt > 1; check your positive pairs are not identical inputs
align stuck near 2 while ℓuniform is excellentThe encoder is behaving like a random projection — repelling everything and learning no invarianceLower λ; verify the row pairing between the two views; check the augmentations are not destroying the content entirely
Both metrics excellent, downstream accuracy mediocreThe augmentation set is wrong for the task — the encoder became invariant to something that matteredNothing in the loss will fix this. Change ppos. See Chapter 8
uniform improves when you enlarge the batch but accuracy does notYou were already past the point where uniformity noise was the bottleneckSpend 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-rankDimensional collapse, which uniformity detects only weaklyChapter 8 — measure the covariance spectrum directly; uniformity will not catch this for you
Inline concept check. Two runs finish at the same point on the plane, but one has a batch of 128 and the other a batch of 1024. Are their ℓuniform values comparable?  …  Not exactly. ℓuniform is estimated as the log of a mean over C(M,2) pairs, and log of a sample mean is a biased estimate of the log of the population mean, downward, with the bias shrinking as M grows. On top of that, a small batch can be arranged more perfectly than a large one, so the achievable minimum itself depends on M. The practical rule: compare metric values only across runs with the same batch size and the same t, or evaluate all runs on a fixed, large held-out batch. Papers that omit these two numbers alongside their alignment-uniformity plot are not reporting enough.
A post-hoc whitening transform applied to frozen BERT embeddings improves uniformity dramatically and degrades alignment slightly, while unsupervised SimCSE improves uniformity comparably with alignment roughly preserved. On the tradeoff plane, what is the essential difference?

Chapter 8: What It Predicts, and What It Cannot See

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.

Prediction 1: everything temperature does

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τ)RegimePredicted behaviourWhat practitioners report
1.00.5Approaching the t → 0 degeneracyUniformity becomes a weak, mean-zero-only constraint; two-atom collapse is nearly freeHigh temperatures give poor, low-rank representations
0.51.0Broad repulsionAll negatives contribute comparably; the model tolerates semantically similar negatives sitting closeBetter class-level tolerance, worse instance separation
0.15.0Sharp repulsionThe potential is dominated by the nearest neighbours, so the hardest negatives absorb almost all the gradientThe known "hardness-aware" property of low temperature
0.077.1SimCLR defaultClose to a packing objective; excellent instance discrimination, and semantically identical images are pushed apart as hard as anything elseStrong linear probes, but measurable damage to fine-grained class structure
0.0150Effectively the Tammes problemOnly the single closest pair matters per anchor; extremely high gradient varianceTraining becomes unstable and downstream quality falls
The uniformity-tolerance dilemma, derived. Low τ means large t means short-range repulsion means the gradient is dominated by whichever negative happens to be closest — and on real data the closest negative is very often another image of the same class. So the same knob that buys you uniformity buys you a loss that actively separates semantically identical inputs. Wang & Liu (2021) named this the uniformity-tolerance dilemma and studied it empirically. Wang & Isola's framework predicts it from t → ∞ behaving like best packing, one year earlier and without running the experiment.

Prediction 2: the returns to batch size scale as √M

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 termRelative std of AM at M = 256
0.500.1770.180.011
0.200.4420.470.029
0.071.2631.980.124
0.032.94676.74.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.

Prediction 3: what stronger augmentation costs

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.

Prediction 4: why the projection head gets thrown away

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.

Backbone output h(x), 2048-dim
Rich, keeps augmentation-sensitive information. Never directly optimised. This is what you use.
↓ the projection head g, whose job is to destroy nuisance
Head output f(x) = g(h(x))/‖·‖, 128-dim on the sphere
Aligned and uniform by construction. This is where every metric in this paper is computed. Thrown away at deployment.
The prediction, and it is testable. Measure ℓalign at both depths. The head's output should have substantially better alignment than the backbone's, because that is the entire function of the head — and the size of that gap is a direct measure of how much augmentation-sensitive information the head is deleting. If the gap is near zero, your head is not doing its job and you may as well remove it. If the gap is enormous, your augmentations are demanding invariance to something the backbone finds expensive to forget, which is a signal that the pipeline is too aggressive for the domain. Two numbers at two depths, and a whole class of architecture questions becomes measurable. This is not in the original paper; it is what the framework buys you.

Limit 1: uniformity is a weak detector of dimensional collapse

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 kuniform = −4 + 8/kDifference from k = 128Downstream impact
128 (healthy)−3.9375Baseline
64−3.87500.06 natsUsually negligible
32−3.75000.19 natsStarting to hurt
16−3.50000.44 natsClearly damaging
8−3.00000.94 natsSevere
A quarter of a nat is not a smoke alarm. Collapsing from 128 usable dimensions to 32 — a 4× loss of representational capacity — moves ℓuniform by 0.19, which is within the run-to-run variation you would see from changing the seed. The metric's sign is right and its uniqueness theorem is intact; the population minimiser really is the full-sphere uniform distribution. But as a practical detector, uniformity is nearly blind to collapse until it is already severe, because the Gaussian potential at t = 2 only notices crowding at short range and a 32-dimensional sub-sphere is still very roomy. If you care about rank, measure the covariance spectrum. Uniformity will not do it for you.
Dimensional collapse: what uniformity sees and what it misses

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.

Effective dim k 32
Kernel width t 2.0

Limit 2: uniformity is not necessary

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.

Limit 3: instance uniformity fights class structure

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.

So why does it work at all? Because real encoders never come close to the uniform optimum. Finite capacity, finite training, and a smooth architecture mean that the cheapest way to satisfy "push everything apart" is to push apart along the directions that already separate things — and those directions, for a convolutional network on natural images, are semantic. Uniformity supplies the pressure; the network's inductive bias supplies the direction. The paper's theory covers the pressure and is entirely silent on the direction. That is not a flaw in the theorem, but it is a large hole in any story that claims to explain why the features are semantic.

Limit 4: the theory is silent on augmentations, which is where the prior lives

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.

Limit 5: the analysis is over unconstrained encoders

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 explainsThe lens does not explain
Why collapse happens and how to prevent itWhy the non-collapsed solution is semantic
What temperature does, quantitativelyWhich augmentations to choose
Why batch size helps and how muchWhy BYOL works without negatives
Why anisotropy is bad and what fixes itHow to detect dimensional collapse
How to compare two encoders on two axesWhere the frontier itself comes from
Your contrastive model shows ℓalign = 0.31 and ℓuniform = −3.79 at t = 2 with a 128-dimensional head — both healthy — yet the linear probe underperforms a baseline by 6 points. Which diagnosis does this lesson support?

Chapter 9: Legacy & Cheat Sheet

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.

The complete cheat sheet

SymbolMeaningDefaultWhere it was built
Sm−1Unit hypersphere in Rm; where L2-normalised features livem = 128Ch 1
σm−1The uniform (normalised surface) measure — the unique rotation-invariant probability measure on the sphereCh 1, 3
pposDistribution over positive pairs; symmetric, with both marginals equal to pdataSet by your augmentationsCh 2
align(f; α)Eppos‖f(x)−f(y)‖α. Range [0, 2α]α = 2Ch 2
uniform(f; t)log Ex,y e−t‖f(x)−f(y)‖2. Range (−∞, 0]t = 2Ch 3
Gt(u,v)Gaussian potential e−t‖u−v‖2; strictly positive definite on the spheret = 2Ch 3
τContrastive temperature0.07–0.5Ch 1, 4
λWeight on the uniformity term when the metrics are optimised directly≈ 1 for visionCh 5, 6

The five equations worth memorising

#IdentityWhy it matters
1‖u−v‖2 = 2 − 2 u·vDistance 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
3eu·v/τ = e1/τ Gt(u,v),   t = 1/(2τ)Temperature is kernel width. The Gaussian potential was in the loss all along
4contrastive − 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
5uniform ≈ −2t + 2t2/d for uniform features in dimension dThe reference value — −3.94 at t = 2, d = 128 — and the effective-dimension readout

Six things people get wrong about this paper

The claim you will hearWhat 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

The papers this one made possible

WorkWhat it borrowedWhat it added
SimCSE (Gao, Yao, Chen 2021)The alignment-uniformity plane as its primary analytical toolShowed 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 readingNamed 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 storyDiagnosed 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, restatedReplaced 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 boundAn 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 assumptionIdentifiability: under a von Mises-Fisher latent model, contrastive learning recovers the true latents up to rotation. The strongest available answer to "why semantic?"
Why a coordinate system beats a technique. The direct-optimisation result in Chapter 6 is worth 0.7 accuracy points and almost nobody uses it. The plane is used by everyone, because it converts an unfalsifiable conversation ("my embeddings feel degenerate") into two numbers with known ranges, known references, and a known tradeoff structure. That is the highest-leverage thing an analysis paper can produce: not a better model, but a better argument format for everyone who comes next.

The five-sentence summary

1
Contrastive losses operate on L2-normalised features, so the object being shaped is a probability distribution on a hypersphere.
2
Two properties describe a good such distribution: positive pairs coincide (alignment) and the marginal covers the sphere evenly (uniformity).
3
As the number of negatives grows, the contrastive loss provably converges to exactly these two terms — alignment exactly, uniformity up to a same-minimiser correspondence — at rate O(M−1/2).
4
Both are four-line differentiable metrics, and optimising them directly matches or beats InfoNCE on six benchmarks across vision and language — which is the test that makes the explanation an explanation.
5
Plotted against each other they give a plane on which every encoder is a point, every hyperparameter is a direction, and the difference between "slid along the frontier" and "moved the frontier" becomes visible.

Build it yourself — the afternoon recipe

StepWhat to doThe decision that matters
1. Instrument firstAdd lalign and lunif to a training loop you already have, and just log them alongside your existing InfoNCEZero risk, immediate payoff. You will see the collapse story in your own curves before changing anything
2. Unit-test the metricsAssert the Chapter 5 four-point square gives ℓalign = 2.0000 and ℓuniform = −4.3963Catches all five classic bugs in five seconds
3. Port the temperatureSet t = 1/(2τ) from your tuned run, and start at λ = 1Equation 3 makes this exact rather than a search
4. Swap the lossReplace InfoNCE with ℓalign + λℓuniformCheck λt > 1 before you launch, or you are training a collapse
5. Plot the planeRun a small λ sweep and scatter the endpoints with downstream accuracy as colourFive runs is enough to see the frontier. This plot will outlive the project
6. Check the spectrumAlso log the covariance eigenvalues of your featuresChapter 8 — uniformity will not catch dimensional collapse for you

References

  1. Wang, T., Isola, P. "Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere," ICML 2020 — arXiv:2005.10242. The paper this lesson is built on. Code at github.com/SsnL/align_uniform.
  2. van den Oord, A., Li, Y., Vinyals, O. "Representation Learning with Contrastive Predictive Coding," 2018 — arXiv:1807.03748. Where InfoNCE and the log M bound come from.
  3. Tschannen, M., Djolonga, J., Rubenstein, P., Gelly, S., Lucic, M. "On Mutual Information Maximization in Representation Learning," ICLR 2020 — arXiv:1907.13625. The paper that broke the MI story empirically.
  4. Chen, T., Kornblith, S., Norouzi, M., Hinton, G. "A Simple Framework for Contrastive Learning of Visual Representations" (SimCLR), ICML 2020 — arXiv:2002.05709. The normalisation, the temperature, the batch size.
  5. He, K., Fan, H., Wu, Y., Xie, S., Girshick, R. "Momentum Contrast for Unsupervised Visual Representation Learning" (MoCo), CVPR 2020 — arXiv:1911.05722. The queue that makes M large.
  6. Gao, T., Yao, X., Chen, D. "SimCSE: Simple Contrastive Learning of Sentence Embeddings," EMNLP 2021 — arXiv:2104.08821. The alignment-uniformity plane as a standard NLP diagnostic.
  7. Wang, F., Liu, H. "Understanding the Behaviour of Contrastive Loss," CVPR 2021 — arXiv:2012.09740. Hardness-awareness and the uniformity-tolerance dilemma.
  8. Jing, L., Vincent, P., LeCun, Y., Tian, Y. "Understanding Dimensional Collapse in Contrastive Self-supervised Learning," ICLR 2022 — arXiv:2110.09348. The failure mode uniformity does not see.
  9. Zimmermann, R. S., Sharma, Y., Schneider, S., Bethge, M., Brendel, W. "Contrastive Learning Inverts the Data Generating Process," ICML 2021 — arXiv:2102.08850. Why the uniform-on-the-sphere solution turns out to be semantic.
  10. Borodachov, S., Hardin, D., Saff, E. Discrete Energy on Rectifiable Sets, Springer 2019. The potential-theory background for Propositions 1 and 2 — strictly positive definite kernels, minimal energy, and weak* convergence of optimal point configurations.
Cross-domain bridge
You have been doing electrostatics on a sphere this whole time
Swap the Gaussian potential for the Coulomb potential 1/d and the uniformity objective becomes the Thomson problem: where do M electrons arrange themselves on a sphere to minimise their mutual repulsion? Posed in 1904, solved exactly for only a handful of M, and the answers are the same shapes that show up when you visualise a well-trained contrastive encoder's two-dimensional projection. The alignment term is then a set of springs pulling paired charges together. Training is a relaxation of a physical system, gradient descent is damped dynamics, and collapse is what happens when the springs beat the charges — which is exactly the λt = 1 threshold Chapter 5 derived. If you want the same geometry with different labels, see our lessons on contrastive learning, similarity metrics, and vector embeddings; for the models this analysis was aimed at, see CLIP, CLAP, SimCSE, and DINO.
"What I cannot create, I do not understand."
Four lines of PyTorch, one four-point unit test, and a scatter plot with two axes. You can hold every part of this paper in your head at once — which is exactly why it changed how the field argues.
Exit gate — teach it back before you leave.

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.

Which sentence best captures why this paper mattered more than its 0.7-point accuracy gain suggests?