InfoNCE is Probability All The Way Down
June 2026

There is a version of the contrastive learning story where you take two augmented views of the same image, push their representations together, push representations of different images apart, train on enough GPUs, get good features. This version is not wrong. It just skips the part that makes it interesting.

Contrastive learning is the natural consequence of asking a very old question. How do we bring a model distribution close to a data distribution? Then following the mathematics honestly until the computation becomes intractable, and asking how to escape the intractability. Every piece of the modern contrastive objective, the positive pairs, the temperature, the denominator that grows with batch size, the reason more negatives help, falls out of this derivation without any additional assumptions. The loss function is not designed, but derived.

I aim to start from the basics and derieve every step towards InfoNCE. We start from the existence of a data distribution and end at the NT-Xent loss of SimCLR[1] and the InfoNCE bound of CPC[2]. The goal. isto show that contrastive learning is probability all the way down.

The Distribution We Cannot Write Down

Every observed data point (image, text caption, autio) is a realization of a random variable. We assume all such realizations are drawn from a single fixed distribution over the input space :

We will never write in closed form, and we cannot. It encodes every regularity in the natural world that produced the data and we only have a finite collection of samples drawn from it. These samples define the empirical distribution, which places a point mass of at each observed point:

where is the Dirac delta. The empirical distribution is a crude approximation of . It assigns zero probability to every point not in , even though the true distribution almost certainly has support far beyond those points. The entire purpose of machine learning is to use to learn something useful about the structure of .

Before we can speak of learning, we need the concept of expectation or the average value of a function under a distribution. For any measurable :

We, ofcourse, cannot evaluate this because is unknown. But the law of large numbers guarantees that if the samples in are drawn independently from the same distribution, the sample average converges almost surely to the true expectation as :

This convergence makes the empirical distribution useful. But it requires the samples to be independent and identically distributed (IID). Identically distributed, i.e. each . Independent, i.e. the joint distribution factorizes. So, the probability of observing this particular dataset, under ​, is the product of the individual probabilities

The independence condition transforms the log-likelihood of an entire dataset into a sum. Without it, would be a single intractable expression coupling every data point to every other. With it, the probability of observing this same dataset, but now evaluated under the model rather than under becomes

Where each term depends only on a single example. Stochastic gradient descent is justified precisely because this sum means each term is an unbiased estimate of the full gradient. The IID assumption is not a probabilistic nicety, it is what makes learning with large datasets tractable.

Measuring the Distance Between Distributions

We have a model and a target . We want the model to be close to the data distribution. To evalutate this, we must arrive at a mathematical approach to measure closeness between two distributions, which will require a brief detour through information theory. For a discrete random variable with distribution , the Shannon entropy is[3]:

Entropy measures the average uncertainty of the distribution, i.e. how surprised we are, on average, when we observe a sample. A distribution concentrated at a single point has : no uncertainty - this can be quickly assessed by substituting into . A uniform distribution over outcomes has : maximum uncertainty. For continuous distributions we write the differential entropy:

Note: The negative sign exists because is always negative or zero. Probabilities are between 0 and 1, and of any number in is . So without the negative sign, entropy would always be negative or zero, which wouldbe a strange convention for something we want to interpret as a positive measure of uncertainty.

which can be negative but satisfies the same intuitions. The logarithm base determines the units — base 2 gives bits, base gives nats. We use nats throughout.

Now suppose the true distribution generating messages is , but we design an encoding scheme optimized for a different distribution , i.e. our assumption of . A code optimized for assigns a codeword of length bits to outcome . Common outcomes under get short codewords, rare ones get long codewords. But the messages are actually drawn from , not . So the average code length we actually pay is not determined by alone — it is the code lengths weighted by how often each outcome actually occurs, which is :

When , the code is perfectly matched to reality and , the minimum possible average code length. Any mismatch between and forces us to use more bits than necessary. The excess is the KL divergence .[4]

The KL divergence is always non-negative, with equality if and only if almost everywhere. This follows from Jensen’s inequality: for any concave function , . Since is concave:

So , with equality iff . Jensen’s inequality is a one-line proof of a fundamental fact, and it will return several more times in this derivation.

The KL divergence is asymmetric: in general. It is not a metric. But it is the natural measure of the information lost when we approximate with , and that is exactly what we care about.

Maximum Likelihood as KL Minimization

We want to minimize over . Expanding:

The entropy of does not depend on . Minimizing over is therefore identical to maximizing:

This is maximum likelihood estimation (MLE). The identity MLE is exact, not approximate. Every cross-entropy loss in machine learning is a KL divergence in disguise, with the entropy of the data distribution as an additive constant that disappears in the gradient.

Since is unknown, we replace the expectation with its Monte Carlo estimate under the empirical distribution, justified by the law of large numbers under IID:

This is equivalently the minimization of the negative log-likelihood (NLL):

Written this way, the NLL is recognizable as the empirical risk i.e. the average loss over the dataset under the loss function . Empirical risk minimization (ERM) is the general framework: choose any loss and minimize its empirical average,

with the goal of making the empirical risk approximate the population risk . MLE is the special case . The gap between empirical and population risk or the generalization error is controlled by the complexity of the function class and the size of the dataset, which is the subject of statistical learning theory[5].

The Latent Structure of

Consider what it means to sample a random image from the internet. You do not get a uniformly random arrangement of pixels; you get a cat, or a ship, or a face. The vast majority of pixel space is garbage that never appears in natural data. The distribution concentrates its mass in a small number of semantically coherent regions, and those regions are organized by an underlying concept that we never directly observe.

This hidden concept is the latent variable . Think of the data as being generated by a two-step process: first, nature picks a class — “cat”, “ship”, “face” — according to some prior probability . Then, given that class, nature generates a specific image according to . The image is what we see. The class is what we do not. Summing this process over all possible classes gives the mixture:

The data distribution is a weighted average of within-class distributions, with the weights being how common each class is. We observe samples from this mixture, which means we observe with summed out and forgotten. The joint distribution is the object that knows both. It assigns probability to every possible (image, class) pair. Summing out recovers the marginal we actually sample from:

Dividing the joint by the marginal of the conditioning variable recovers any conditional. The distribution over images given class is:

where rescales the joint into a proper distribution that integrates to 1 over . Now the key move: the joint factors in two equally valid ways:

Setting these equal and solving for gives Bayes’ theorem:

It answers: given that I observed image , how likely is it that the class was ? The answer is proportional to how likely was under class , weighted by how common class is, normalized so everything sums to 1. The posterior is exactly what a supervised classifier learns — given an image, what class does it belong to? But in self-supervised learning we never observe , so we cannot train on this target directly. What we can do is exploit the structure of the joint without labels — and to see how, we need to understand what information and actually share.

Mutual Information

The mutual information between and measures how much knowing one reduces uncertainty about the other. It is defined as the KL divergence between the joint distribution and the product of the marginals:

If and are independent, and the KL divergence is zero: . Non-zero mutual information means the joint carries more information than the product of marginals — knowing tells you something about , and vice versa. Since KL is non-negative, always.

Expanding using the conditional:

where the second equality uses Bayes’ theorem: . The quantity inside the expectation is the pointwise mutual information (PMI):

The PMI at a specific pair tells us how much more likely this co-occurrence is than if and were independent. High PMI means this pair appears together far more often than chance would predict. Mutual information is the average PMI over the joint distribution.

We can also decompose mutual information in terms of entropy. Using the chain rules and :

Mutual information is the reduction in entropy about when is known. Equivalently, by symmetry, . These two decompositions give the same value — mutual information is symmetric: .

The reason we care about mutual information in the context of self-supervised learning is now becoming visible. The latent class that we never observe is the thing that defines semantic similarity. Two images of the same cat have high PMI with the same class. A cat and a ship have low PMI with each other’s classes. A representation that captures has learned to encode semantic content. The question is how to maximize without ever observing . The answer involves replacing with something observable — a second view — and a crucial density ratio.

The Wall: Intractable Partition Functions

Before we arrive at contrastive objectives, we must understand why the direct approach fails. Suppose we try to model explicitly with an energy-based model (EBM)[6]. We define an energy function and write the unnormalized density:

This is non-negative everywhere. To obtain a proper probability distribution, we must divide by the partition function:

The name “partition function” comes from statistical physics, where sums over all microstates of a system[7]. The log-likelihood of a data point is:

The gradient with respect to is:

The first term is easy. The second is not. By Leibniz’s integral rule:

which simplifies to:

The gradient of the log partition function is an expectation under the model distribution . To compute it, we need samples from — the model we are currently trying to train. This is circular. In practice, MCMC methods like Contrastive Divergence[8] approximate this expectation by running a Markov chain for a few steps from each data point, but in high dimensions these chains mix poorly and the estimates are biased.

For images in , the integral defining runs over an astronomically large space. There is no analytical solution and no practical numerical approximation. This is the wall that direct maximum likelihood hits when the model is expressive enough to be interesting.

There are several paths around it. Each corresponds to a different family of modern self-supervised methods.


First Escape: Variational Bounds and Latent Variables

One path replaces the intractable marginal with a tractable lower bound. Introduce a latent variable with prior and a generative model . The log-likelihood of a data point is:

Introduce a variational posterior — a parametric approximation to the true posterior . Multiply and divide inside the log by :

Apply Jensen’s inequality ( is concave, so ):

This is the Evidence Lower BOund (ELBO)[9]:

The gap between the log-likelihood and the ELBO is exactly . Maximizing the ELBO over simultaneously pushes the likelihood up and drives the variational posterior toward the true posterior.

The reconstruction term is a denoising objective in disguise. If we choose to be a fixed corruption process — add Gaussian noise, mask patches, drop tokens — then we are asking the decoder to reconstruct the original from a corrupted version . This is exactly the objective of denoising autoencoders[10], masked autoencoders (MAE)[11], and BERT[12]. These methods are not heuristics. They are approximations to variational inference under specific choices of corruption process.


Second Escape: Noise-Contrastive Estimation

The variational approach requires a latent variable structure. A different escape from the partition function wall works for any unnormalized model. Noise-Contrastive Estimation (NCE) (Gutmann & Hyvärinen, 2010)[13] converts density estimation into binary classification.

Introduce a known, tractable noise distribution — for example, a uniform distribution or a Gaussian. Mix the data and noise in ratio : for every data point, draw noise samples. Define a binary label with if a sample came from and if it came from . The prior on is:

The marginal density of an observed sample in this mixture is:

By Bayes’ theorem, the posterior probability that came from the data — not the noise — is:

We now replace with our parametric model , where is a free scalar parameter to be learned alongside . The classifier output becomes:

and we train this classifier by minimizing the binary cross-entropy against the true labels :

Gutmann & Hyvärinen proved that as , the minimizer satisfies . The partition function is estimated by gradient descent alongside the energy parameters, without ever computing the integral. The intractable normalizer has been turned into a free parameter learned through the classification objective.

This is a beautiful idea. The partition function is what makes the normalization constraint hard — but from the perspective of the classifier, it is just a scalar that shifts all the scores uniformly. Let the optimizer find it.


From NCE to Contrastive Self-Supervised Learning

NCE draws negatives from a fixed noise distribution . The step to modern self-supervised learning replaces the fixed with the empirical data distribution , and replaces binary “real vs noise” classification with multiclass “which sample is the true positive” classification.

Here is the setup. We have an anchor and a context — in the image domain, could be a second augmented view of the same image; in the temporal domain, it could be a past segment of a sequence. The pair is drawn from a joint distribution that has positive mutual information . We also draw negative samples independently from the marginal , forming a set where one element (at position , uniform over ) is the true positive and the rest are negatives.

A scorer assigns a score to each candidate. We build a classifier over positions:

What is the optimal ? The true posterior over positions is, by Bayes’ theorem — with the uniform prior for all canceling — proportional to the likelihood of observing in position given that position is the positive:

The optimal score function is therefore:

The optimal scorer is the exponentiated pointwise mutual information — the same density ratio that appeared in the mutual information decomposition, and the same object that Bayes’ theorem says is the posterior-to-prior ratio . We parametrize the critic as and train it to correctly identify the positive by minimizing the cross-entropy of the -way classification:

This is the InfoNCE loss of van den Oord et al. (2018)[2:1]. The denominator is a Monte Carlo approximation of the partition function , evaluated with samples from . The intractable integral that killed direct maximum likelihood has been replaced by a finite sum over the batch.


The Mutual Information Bound

Van den Oord et al. showed that minimizing the InfoNCE loss maximizes a lower bound on the mutual information . The bound is:

The proof is short and the mechanism is illuminating. At the optimal , the optimal loss value is:

Focusing on the argument of the outer expectation, note that is an empirical average of the density ratio over samples from . By the law of large numbers, . So for large , the denominator concentrates around 1, and:

More precisely, by Jensen’s inequality applied to the concave :

giving , or equivalently .

The bound tightens as grows. With , the bound gives , which is trivially true and useless. With , the Monte Carlo estimate of the partition function converges to its true value, the classifier approaches the optimal Bayes classifier, and the bound approaches from below. Every additional negative is one more sample in the partition function approximation, tightening both the statistical estimate and the MI bound simultaneously. This is why more negatives improve contrastive representations: it is not a heuristic. It is a direct consequence of the Monte Carlo approximation getting more accurate.


The NT-Xent Loss of SimCLR

In SimCLR[1:1], the critic takes the specific form:

where is the projected representation, is cosine similarity, and is a temperature parameter. A batch of images produces augmented views — two augmentations per image — and both views of image serve as positives for each other, while all other views are negatives. The NT-Xent loss (Normalized Temperature-scaled Cross Entropy) for a positive pair is:

and the total loss is the average over all positive pairs: where is the index of the second view of image .

The denominator is a sum over exponentials. At SimCLR’s default batch size of 4096, this is terms per anchor — 8191 Monte Carlo samples of the partition function . This is why SimCLR needs large batches — it is not a memory issue or a stability issue. It is that the quality of the partition function approximation, and therefore the tightness of the mutual information bound, grows with the number of negatives.

MoCo[14] addresses this by maintaining a momentum-updated queue of embeddings from previous batches. The queue decouples the size of the partition function approximation from the memory cost of the current mini-batch. The key encoder is updated by exponential moving average of the query encoder weights, with , which keeps the queue embeddings approximately consistent with the current encoder without requiring backpropagation through the key branch.

The temperature controls the sharpness of the distribution over negatives. Small concentrates probability mass on the hardest negatives — the ones with the highest cosine similarity to the anchor — and pushes them apart aggressively. Large spreads probability more uniformly. Wang & Liu (2021)[15] showed that the gradient of the InfoNCE loss has the form of a weighted sum where the weights on each negative are proportional to , confirming that the loss implicitly focuses on hard negatives without requiring explicit mining — a property that Tian (2022)[16] connected to the general theory of contrastive losses as minimizers of a family parameterized by monotone functions.


The Full Chain

We began by assuming data is drawn IID from an unknown — IID being required so that the dataset log-likelihood decomposes into a sum and gradient descent is tractable. We defined expectation and invoked the law of large numbers to justify approximating population expectations with empirical averages. We introduced entropy as average uncertainty, derived cross-entropy as the cost of mismatched encoding, and showed that KL divergence is their difference — so that minimizing KL is identical to minimizing cross-entropy, which is identical to maximum likelihood, which in practice is empirical risk minimization over the NLL. We recognized that has mixture structure over a latent class , introduced conditional probability as the joint divided by the marginalizer, and derived Bayes’ theorem as the consequence of writing the joint two ways. We defined mutual information as the KL divergence between joint and product-of-marginals, identified the PMI as the per-sample quantity whose expectation gives MI, and showed via Bayes’ theorem that the PMI equals the log posterior-to-prior ratio — the thing a classifier learns.

We then hit the wall: direct maximum likelihood on an unnormalized model requires computing , an expectation under the model, which is intractable in high dimensions. The variational escape introduces a latent variable and bounds the log-likelihood from below using Jensen’s inequality, turning the problem into optimizing the ELBO — which is a reconstruction term plus a KL regularizer, and corresponds to denoising objectives. The NCE escape introduces a noise distribution and converts normalization into binary classification using Bayes’ theorem, letting the partition function be a free parameter learned by the optimizer. Replacing the fixed noise distribution with in-batch negatives and the binary classification with an -way classification gives InfoNCE, whose denominator is a finite Monte Carlo approximation of the partition function, and whose gap from the true MI bound shrinks as grows, by the law of large numbers applied to the importance weights.

It is probability all the way down.



  1. Chen, T., Kornblith, S., Norouzi, M., & Hinton, G. (2020). A Simple Framework for Contrastive Learning of Visual Representations. ICML 2020. ↩︎ ↩︎

  2. van den Oord, A., Li, Y., & Vinyals, O. (2018). Representation Learning with Contrastive Predictive Coding. arXiv:1807.03748. ↩︎ ↩︎

  3. Shannon, C. E. (1948). A Mathematical Theory of Communication. Bell System Technical Journal, 27(3), 379–423. ↩︎

  4. Kullback, S., & Leibler, R. A. (1951). On information and sufficiency. Annals of Mathematical Statistics, 22(1), 79–86. ↩︎

  5. Vapnik, V. N. (1998). Statistical Learning Theory. Wiley-Interscience. ↩︎

  6. LeCun, Y., Chopra, S., Hadsell, R., Ranzato, M., & Huang, F. J. (2006). A tutorial on energy-based learning. In Predicting Structured Data, MIT Press. ↩︎

  7. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning, Chapter 18: Confronting the Partition Function. MIT Press. deeplearningbook.org. ↩︎

  8. Hinton, G. E. (2002). Training products of experts by minimizing contrastive divergence. Neural Computation, 14(8), 1771–1800. ↩︎

  9. Kingma, D. P., & Welling, M. (2013). Auto-Encoding Variational Bayes. ICLR 2014. ↩︎

  10. Vincent, P., Larochelle, H., Lajoie, I., Bengio, Y., & Manzagol, P.-A. (2010). Stacked Denoising Autoencoders. JMLR, 11, 3371–3408. ↩︎

  11. He, K., Chen, X., Xie, S., Li, Y., Dollár, P., & Girshick, R. (2022). Masked Autoencoders Are Scalable Vision Learners. CVPR 2022. ↩︎

  12. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL 2019. ↩︎

  13. Gutmann, M., & Hyvärinen, A. (2010). Noise-Contrastive Estimation: A New Estimation Principle for Unnormalized Statistical Models. AISTATS 2010. ↩︎

  14. He, K., Fan, H., Wu, Y., Xie, S., & Girshick, R. (2020). Momentum Contrast for Unsupervised Visual Representation Learning. CVPR 2020. ↩︎

  15. Wang, T., & Isola, P. (2020). Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere. ICML 2020. ↩︎

  16. Tian, Y. (2022). Understanding Deep Contrastive Learning via Coordinate-Wise Optimization. NeurIPS 2022. ↩︎