Contrastive Learning for Retrieval: InfoNCE, Temperature, and Negative Sampling
How a dual encoder is taught to place a query near its answer and far from everything else — one loss read three ways: a mutual-information lower bound, a tug-of-war between alignment and uniformity on the hypersphere, and a temperature-sharpened gradient that the hardest negative dominates
Overview & motivation
Two topics have brought us to the edge of dense retrieval without saying the one thing that makes it work. The retrieval problem defined relevance as ranking by a similarity functional and showed that on the unit sphere the cosine, dot-product, and Euclidean rankings all coincide. Hypersphere geometry then told us that L2-normalized embeddings live on that sphere, and that a topical cluster is a von Mises–Fisher distribution whose concentration we can measure. What neither topic said is where those embeddings come from. They are not handed down. They are trained — and the loss that trains them is the subject of this topic and the foundation of everything in neural retrieval that follows.
The setup is the one every dense retriever shares. We want an encoder that maps a query and its relevant document to nearby points and maps the query far from everything else. Contrastive learning makes that goal a loss directly: show the model a query, its true positive, and a batch of negatives, and ask it to pick the positive out of the lineup. The loss that scores how well it does — InfoNCE — is, underneath, the same softmax cross-entropy that trains any classifier, with the candidates playing the role of classes. The interest is not in the formula but in what it secretly optimizes, and we will read it three ways: as a bound on mutual information, as a competition between two geometric forces on the sphere, and as a gradient whose sharpness one number controls.
Each negative repels the query with a force equal to its softmax weight pᵢ = esᵢ/τ / Σ. As τ → 0 the mass collapses onto the single hardest negative — the one nearest the query — and the weight entropy falls toward 0; as τ grows the push spreads to all negatives and the entropy rises toward log N = 2.08. The gradient structure is exact; which τ is right is empirical.
The first panel is the gradient itself — the query, its positive, and a spread of negatives on the unit circle, each negative pushed away with a force equal to its softmax weight, which the temperature slider sharpens onto the hardest one. The second is the information bound: the mutual information InfoNCE certifies against the ceiling that caps it, climbing and then saturating as the negatives grow. The third is the geometry — a random initialization and the single configuration that both minimizing InfoNCE and minimizing alignment-plus-uniformity converge to, with temperature tuning where on the sphere the trained cloud settles.
The contrastive setup and notation
Fix a query with a single relevant document, the positive , and a set of irrelevant documents, the negatives . An encoder maps each to a vector, and because dense retrievers L2-normalize, every vector is a unit vector — we are working on the sphere of the previous topic from the start. The score of a candidate is the temperature-scaled cosine similarity
where is the angle between query and document and is the temperature, a positive scale we will return to. The score is exactly the similarity functional the retrieval problem took as given; the difference now is that it is something we train, and the temperature is the dial that controls how harshly differences in similarity are amplified before the softmax sees them.
Definition 1 (The contrastive setup and the InfoNCE loss).
Given a query , its positive , and negatives , all encoded to unit vectors, the InfoNCE loss is the negative log-probability that an -way softmax assigns to the positive:
This is the cross-entropy of a classifier whose “classes” are the candidates and whose label is “the positive.” In practice the negatives are taken in-batch: for a batch of paired queries and positives, every other pair’s positive serves as a negative, so a batch of size supplies negatives at no extra encoding cost.
Three properties anchor the formula before we read it more deeply, and the notebook asserts each. Adding a constant to every score leaves the loss unchanged — only differences of scores matter, the usual softmax invariance. As the scores wash out and the loss approaches the value of a uniform guess, ; for the lab’s eight candidates that ceiling is . And when the positive sits far above every negative, the loss falls to zero — the classifier is certain and correct. With the object in hand, we ask what minimizing it accomplishes.
Movement 1 — InfoNCE is a mutual-information lower bound
The first reading is the one that named the loss. van den Oord, Li, and Vinyals introduced InfoNCE as an estimator for mutual information: the claim is that pushing the loss down pushes up a guaranteed lower bound on , the number of nats the query and its positive share.
Theorem 1 (The CPC mutual-information bound).
Let the positive pair be drawn from the joint and the negatives independently from the marginal . Then
Equivalently, minimizing InfoNCE maximizes a lower bound on the mutual information — but a bound that can never exceed , no matter how good the encoder.
Proof (Proof sketch).
The loss is minimized when the critic inside the softmax is proportional to the density ratio — the optimal -way classifier scores each candidate by how much more likely it is under the query than under the marginal. Substitute that optimal critic, writing for the positive’s ratio and for the negatives’. The loss becomes . Each negative is drawn from , so it has expectation , and by the law of large numbers the sum of of them concentrates on its mean — exactly so as . Replacing the sum by and then dropping the additive positive term gives the chain , and since by definition of the mutual information, taking expectations yields . Counting the positive among the candidates sharpens this to the form of the statement; rearranging gives the bound. The slack enters at the law-of-large-numbers step and the dropped term, and closes only as .
∎The ceiling is the honest part of the story, and the notebook makes it visible by estimating the bound on a problem where the truth is known. Take and jointly Gaussian with correlation ; then the mutual information is exactly , and choosing so that nats, we can watch the bound chase it. Using the Bayes-optimal critic — so we measure the bound itself, not some encoder’s approximation of it — the certified information climbs from nats with a single negative ( candidates), to at eight candidates, to at , approaching the true but never arriving. At the smallest batch the ceiling is itself below the truth: with two candidates the bound cannot certify two nats of shared information no matter how perfect the encoder. This is not a slack to be tuned away — it is structural. More negatives raise the ceiling, which is the precise, unromantic reason large batches improve contrastive retrieval, and the reason the mutual-information story saturates exactly in the small-batch regime practitioners live in.
Movement 2 — alignment and uniformity on the sphere
The information reading explains why negatives help but says little about the geometry the loss produces. The second reading, due to Wang and Isola, is geometric, and it lands precisely on the sphere of the previous topic. As the number of negatives grows, the loss separates into two interpretable forces.
Theorem 2 (The alignment–uniformity decomposition).
On the unit sphere, as the number of negatives , minimizing InfoNCE is equivalent to minimizing the sum of two terms:
Alignment pulls positive pairs together; uniformity — a Gaussian potential over independent pairs — pushes all embeddings apart. The uniformity term is minimized by the uniform distribution on : the very von Mises–Fisher law, the maximum-entropy distribution on the sphere, that the hypersphere topic singled out.
The connection to the prior topic is exact, not analogical. There we learned that a tight cluster is a high- vMF and that the uniform sphere is its limit, with mean resultant length zero. Here, uniformity is defined as the spread that drives the configuration toward that same uniform law, and temperature plays the role of an inverse concentration, : low temperature trains tight, high- clusters of positives, high temperature loose ones. The cluster tightness the previous topic taught us to measure is the quantity this loss optimizes.
The notebook makes the decomposition executable by optimizing a small cloud of paired points on the sphere two ways and comparing where they land. From a random initialization — alignment , uniformity , mean resultant length — minimizing alignment-plus-uniformity directly drives the configuration to alignment and uniformity with mean resultant ; minimizing the in-batch InfoNCE loss instead reaches alignment and uniformity with mean resultant . The two endpoints coincide: InfoNCE collapses the positive pairs and spreads the cloud to the uniform sphere, reaching the same place the explicit two-term objective does. That the mean resultant length falls essentially to zero is the previous topic’s signature of uniformity — the cloud has become the vMF — recovered as the fixed point of a loss that never mentions it.
Movement 3 — temperature and the hard-negative gradient
The third reading is the most operational, and the cleanest to prove. It explains what the temperature actually does to the learning signal, and why one negative usually matters far more than the rest.
Theorem 3 (The InfoNCE gradient is a softmax-weighted repulsion).
Write for the bare cosine logit of candidate — here, unlike Definition 1’s temperature-scaled , we differentiate with respect to the pre-temperature score — and for its softmax weight. The gradient of the single-positive loss with respect to these cosine logits is
Each negative is pushed away with force proportional to its own softmax weight , so the hardest negative — the one with the highest similarity to the query — dominates the gradient. The temperature controls how sharply: as the weight collapses onto the single nearest negative, and as it spreads uniformly across all of them.
Proof (Proof).
The loss is where . Differentiating the log-softmax is standard: , since the comes from the chain rule through and the from the numerator. For the positive this is ; for a negative it is . The gradient with respect to the query embedding then inherits these weights, , so a hard negative with large literally contributes more to the update direction.
∎The temperature panel of the lab puts numbers on the sharpening. Over a fixed spread of eight negatives, the single largest gradient weight falls from at — almost the entire push on one negative — to at to at , near the uniform . Read the same motion as entropy: the weight distribution’s Shannon entropy rises from nats at to at to at , climbing toward the uniform ceiling . Low temperature is a hardness-aware loss that spends almost all its gradient on the toughest distractor; high temperature treats all negatives alike. The gradient structure is exact and proved. Which temperature is right is not: a temperature low enough to focus on hard negatives is also low enough to punish a genuinely relevant document that merely looks like a negative, the uniformity-versus-tolerance trade-off that makes a tuned hyperparameter rather than a derived one.
Proposition 1 (What the laboratory measures).
The three panels run on a deterministic synthetic setup, not a trained encoder: the negatives in Panel A are a fixed spread of cosine similarities, the bound in Panel B is a Monte-Carlo estimate on the Gaussian joint with the Bayes-optimal critic, and the configurations in Panel C are gradient-descent optima on a small sphere. Every measured number — the bound curve, the alignment and uniformity values, the finance hard-negative share — is owned by the companion notebook and mirrored here to the decimal; the laboratory recomputes only the closed forms (the softmax weights, the ceiling , and ).
Finance case study
Honest accounting
InfoNCE is the objective; the machinery that optimizes it is where the neural-retrieval track goes next. The architecture is a dense dual encoder — separate query and document towers trained with exactly this loss — and the engineering that makes it work is negative sampling: in-batch negatives are cheap but weak, hard negatives are powerful but risk the false-negative trap this topic flagged, and mining them well is a topic of its own. Beyond the single-vector match, late-interaction retrieval generalizes the cosine logit to a many-to-many comparison between every query token and every document token, trained with the same contrastive principle. Each of those builds directly on the loss read three ways here.
Connections
- this is where the contrastive objective lands geometrically: the alignment-uniformity decomposition of InfoNCE pushes embeddings toward the exact uniform distribution on the sphere that topic characterized, and the temperature tau acts as an inverse von Mises-Fisher concentration — low temperature trains tight, high-kappa clusters, the precise sense in which that topic said tau is like one over kappa, so the cluster tightness it taught us to measure is the quantity this loss optimizes hypersphere-vmf-geometry
- the retrieval-problem defined relevance as a similarity functional and showed that on the sphere cosine, dot product, and Euclidean ranking coincide; InfoNCE is how that similarity functional is LEARNED — the loss turns the cosine logit between an L2-normalized query and document into the training signal that makes relevant pairs score high, so this topic supplies the encoder behind the scores that topic took as given the-retrieval-problem
- Matryoshka representation learning nests a contrastive objective at multiple truncation lengths, applying an InfoNCE-style loss to every prefix of the embedding; the temperature and negative-sampling analysis here is exactly what governs each of those nested losses, so the nested-dimension trick is this objective replicated down a ladder of dimensions matryoshka-nested-representations
- the uniformity term of the decomposition spreads embeddings toward the uniform sphere whose near-orthogonality and equatorial concentration that topic established; the one-over-d variance and near-orthogonality it proved are what maximal uniformity converges to, so the contrastive loss is, in its uniformity half, training toward the high-dimensional geometry that topic described high-dimensional-geometry
References & Further Reading
- paper Representation Learning with Contrastive Predictive Coding — van den Oord, Li & Vinyals (2018) The InfoNCE loss and the proof that minimizing it maximizes a lower bound on mutual information, ceilinged at log(N+1) — Movement 1 and Theorem 1, and the source of the saturation caveat
- paper Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere — Wang & Isola (2020) The asymptotic decomposition of InfoNCE into alignment and uniformity on the sphere, the geometric heart of Theorem 2 and the direct bridge to the hypersphere-vMF topic
- paper Dense Passage Retrieval for Open-Domain Question Answering — Karpukhin, Oguz, Min, Lewis, Wu, Edunov, Chen & Yih (2020) The retrieval framing: a dual encoder trained with in-batch-negative InfoNCE, the canonical instantiation of this objective for dense retrieval and the source of the in-batch-negative practice
- paper A Simple Framework for Contrastive Learning of Visual Representations — Chen, Kornblith, Norouzi & Hinton (2020) SimCLR: the normalized temperature-scaled cross-entropy (NT-Xent) form of InfoNCE and the empirical demonstration that the temperature is a critical, tuned hyperparameter — Movement 3
- paper Understanding the Behaviour of Contrastive Loss — Wang & Liu (2021) The hardness-aware temperature analysis: small temperature concentrates the gradient on the hardest negatives, and the uniformity-tolerance dilemma that makes the right temperature empirical — the gradient theorem and the third rigorFlag caveat
- paper Improved Deep Metric Learning with Multi-class N-pair Loss Objective — Sohn (2016) The N-pair loss, the multi-negative softmax objective that InfoNCE generalizes — the immediate ancestor of the (N+1)-way cross-entropy form
- paper Noise-contrastive estimation: A new estimation principle for unnormalized statistical models — Gutmann & Hyvarinen (2010) Noise-contrastive estimation, the founding principle of learning by discriminating data from noise that InfoNCE descends from — the NCE in InfoNCE
- documentation Sentence-Transformers — losses (MultipleNegativesRankingLoss) — Reimers & Gurevych (2024) The production realization: MultipleNegativesRankingLoss is in-batch-negative InfoNCE with a scale (inverse temperature), the concrete form a finance encoder is trained with