Noise-Contrastive Estimation and InfoNCE: How Partition Function Elimination and Mutual Information Lower Bounds Power Modern AI
In statistical machine learning and generative modeling, evaluating the exact probability of an observed event frequently requires calculating a normalizing constant known as the partition function. For continuous spaces or discrete spaces with high cardinality, such as a natural language vocabulary spanning over one hundred thousand tokens or high-dimensional pixel distributions, computing this partition function directly is computationally intractable.
Noise-Contrastive Estimation (NCE), introduced by Michael Gutmann and Aapo Hyvarinen in 2010, transformed unnormalized statistical modeling by converting density estimation into a supervised binary classification task between true data and synthetic noise. In 2018, Aaron van den Oord, Yazhe Li, and Oriol Vinyals generalized this framework into the InfoNCE loss within Contrastive Predictive Coding (CPC), establishing a mathematical bridge between multi-class classification and variational lower bounds on mutual information.
From word embeddings and audio pre-training to contrastive vision-language architectures like CLIP and dense text retrievers, NCE and InfoNCE remain fundamental mathematical primitives of modern self-supervised representation learning.
The Partition Function Bottleneck
Consider an energy-based model or a probabilistic language model parameterized by . The probability of a data point is expressed via an unnormalized score function or energy :
where the partition function is defined as:
When training under standard Maximum Likelihood Estimation (MLE), the objective minimizes the negative log-likelihood:
Taking the gradient with respect to yields:
The second expectation requires computing expectations over the model distribution at every single optimization step. In continuous spaces, this necessitates Markov Chain Monte Carlo (MCMC) sampling or Contrastive Divergence, which is notoriously slow, unstable, and prone to mode collapse. In discrete spaces with vocabulary size , computing requires evaluating the full softmax denominator over all classes, which becomes a severe computational bottleneck during training.
Noise-Contrastive Estimation (NCE)
Gutmann and Hyvarinen (2010) resolved this bottleneck by redefining the learning objective. Instead of directly modeling the normalized density , NCE trains a non-linear binary classifier to discriminate between genuine samples drawn from the true data distribution and synthetic noise samples drawn from a known, tractable noise distribution .
Suppose for every genuine data sample , we draw noise samples . The joint dataset contains data points labeled with (true data) with prior probability and noise points labeled with with prior probability .
Applying Bayes' theorem, the posterior probability that a given sample came from the true data distribution is:
Letting , where is a learned scalar representing the log partition function , the posterior becomes:
where denotes the standard sigmoid activation function.
The NCE objective function maximizes the log-posterior likelihood of the binary classification task:
Expanding this into sigmoid form yields:
Key Mathematical Properties of NCE
- Consistent Parameter Estimation: Gutmann and Hyvarinen proved that under mild regularity conditions, if the model family contains the true data distribution , the NCE estimator converges almost surely to the true parameter as sample size .
- Asymptotic Convergence to MLE: As the noise ratio , the asymptotic variance of the NCE estimator approaches the Cramer-Rao lower bound, matching the statistical efficiency of exact Maximum Likelihood Estimation without ever summing over the state space.
- Self-Normalization in Neural Language Modeling: In 2012, Andriy Mnih and Yee Whye Teh applied NCE to train neural probabilistic language models. They discovered that by fixing (setting the partition function ), neural networks naturally learn self-normalizing output distributions with negligible loss in modeling perplexity, completely bypassing the softmax normalization during inference.
True Data Distribution p_data(x) --------> Positive Sample (D=1)
|
v
Noise Distribution q_n(y) ---------------> Negative Samples (D=0)
|
v
[ Binary Logistic Classifier ]
|
v
L_NCE = Log-Loss(Data vs Noise)Negative Sampling vs. Formal NCE
In 2013, Tomas Mikolov and colleagues introduced Skip-Gram with Negative Sampling (SGNS) in Word2Vec. While SGNS is frequently described as NCE, it is a simplified heuristic approximation.
SGNS simplifies the objective by omitting the explicit noise density ratio :
Because SGNS ignores the noise distribution terms inside the sigmoid, it does not estimate a normalized probability distribution. As proved by Omer Levy and Yoav Goldberg in 2014, SGNS instead computes an implicit low-rank matrix factorization of the Pointwise Mutual Information (PMI) matrix shifted by .
Multi-Class Generalization: InfoNCE and Contrastive Predictive Coding

While classical NCE operates as a binary classification problem between one data point and noise points, modern self-supervised learning frequently structures the problem as categorical selection across multiple candidate samples.
In 2018, Aaron van den Oord, Yazhe Li, and Oriol Vinyals introduced Contrastive Predictive Coding (CPC) and formulated the InfoNCE objective. Given a context representation and a set of candidate samples containing exactly one positive target drawn from the conditional distribution and negative samples drawn from the proposal distribution , the InfoNCE loss is defined as:
Here, is a parameterized density ratio critic. Commonly, , where is cosine similarity, and are neural encoders, and is a learnable or fixed temperature parameter.
Proof: InfoNCE as a Lower Bound on Mutual Information
A fundamental theoretical contribution of CPC is proving that minimizing maximizes a variational lower bound on the mutual information between the context and the target variable .
The mutual information between two random variables and is defined as:
Let be a set of samples where index is the true positive sample generated from , and all remaining samples are drawn independently from . The probability that index is the positive sample given set and context is:
Setting the optimal density ratio critic , the expected categorical cross-entropy loss becomes:
Rewriting the argument of the logarithm:
Taking the expectation over the negative samples , since $\mathbb{E}_{x \sim p(x)}\left[\frac{p(x|c)}{p(x)}\right] = \int p(x) \frac{p(x|c)}{p(x)} dx = \int p(x|c) dx = 1$:
Applying Jensen's inequality to the concave logarithm function yields:
Therefore:
Context c ---------> Encoder h(c) ------------\
Cosine Similarity Matrix
Target x_+ --------> Encoder g(x_+) ----------/ (scaled by 1/tau)
|
Distractors x_- ---> Encoder g(x_-) -----------------> |
v
Categorical Softmax
|
v
Loss = -log P(Positive)
|
v
Mutual Information Bound:
I(X; C) >= log(K) - LThe Mutual Information Bottleneck
The inequality exposes a crucial structural limitation analyzed by Ben Poole et al. (2019) and David McAllester and Karl Stratos (2020): the InfoNCE lower bound is mathematically capped at .
Even if the true mutual information between representations is exceptionally high (e.g., in paired audio or image crops where nats), an InfoNCE estimator trained with negative samples can never report or leverage a mutual information bound greater than nats.
This mathematical property explains the evolutionary trajectory of modern contrastive architectures:
- SimCLR (Chen et al., 2020): Relied on massive batch sizes () on specialized TPU clusters to push the boundary.
- MoCo (He et al., 2020): Decoupled dictionary size from mini-batch size using a dynamic memory queue ( nats).
- CLIP (Radford et al., 2021): Utilized synchronized distributed matrix multiplications across hundreds of GPUs to compute contrastive losses across batches of 32,768 text-image pairs.
Contrastive Learning in Modern Architectures
The principles established by NCE and InfoNCE govern several major branches of contemporary AI systems:
1. Vision-Language Alignment (CLIP and SigLIP)
OpenAI's CLIP trains dual encoders (image) and (text) across a batch of image-text pairs using symmetric InfoNCE:
In 2023, Xiaohua Zhai and colleagues introduced SigLIP (Sigmoid Loss for Language-Image Pre-training), which replaces the categorical InfoNCE multi-class softmax with pairwise binary classification. By evaluating each pair independently via sigmoid loss, SigLIP eliminates the global normalization denominator, removing cross-device communication overhead during distributed training and improving scaling efficiency.
2. Dense Information Retrieval and Embedding Models
Modern embedding models (e.g., BGE, E5, Sentence-Transformers, ColBERT) optimize dense text retrieval using InfoNCE with hard negative mining:
By pairing standard in-batch negatives with hard negatives mined via lexical BM25 search or cross-encoder re-rankers, InfoNCE forces the embedding space to separate semantically distinct documents with identical keyword profiles.
3. Self-Supervised Speech and Audio (wav2vec 2.0)
Meta's wav2vec 2.0 uses InfoNCE over masked continuous latent speech representations. The model quantizes latent speech features into discrete codebook entries and optimizes an InfoNCE critic to select the true quantized representation corresponding to masked audio frames among distractors sampled from other time steps in the same utterance.
Practical Implementation: InfoNCE in PyTorch
Below is a complete, numerical-precision-stabilized PyTorch implementation of the symmetric InfoNCE loss with in-batch negatives:
import torch
import torch.nn as nn
import torch.nn.functional as F
class InfoNCELoss(nn.Module):
"""
Symmetric InfoNCE Loss for dual-encoder representation learning.
Computes contrastive loss using in-batch negatives.
"""
def __init__(self, temperature: float = 0.07, learnable_temp: bool = False):
super().__init__()
if learnable_temp:
self.log_inv_tau = nn.Parameter(torch.tensor(torch.log(torch.tensor(1.0 / temperature))))
else:
self.register_buffer("log_inv_tau", torch.tensor(torch.log(torch.tensor(1.0 / temperature))))
def forward(self, query_embeddings: torch.Tensor, key_embeddings: torch.Tensor) -> torch.Tensor:
"""
Args:
query_embeddings: Tensor of shape (batch_size, embedding_dim)
key_embeddings: Tensor of shape (batch_size, embedding_dim)
Returns:
Scalar tensor representing symmetric contrastive cross-entropy loss.
"""
# Step 1: Normalize embeddings onto unit hypersphere (L2 normalization)
queries = F.normalize(query_embeddings, p=2, dim=-1)
keys = F.normalize(key_embeddings, p=2, dim=-1)
# Step 2: Compute cosine similarity matrix: shape (batch_size, batch_size)
inv_tau = torch.exp(self.log_inv_tau)
logits = torch.matmul(queries, keys.transpose(0, 1)) * inv_tau
# Step 3: Ground-truth target indices lie along the main diagonal
batch_size = queries.size(0)
labels = torch.arange(batch_size, device=queries.device, dtype=torch.long)
# Step 4: Compute symmetric cross-entropy loss across rows and columns
loss_queries = F.cross_entropy(logits, labels)
loss_keys = F.cross_entropy(logits.transpose(0, 1), labels)
return (loss_queries + loss_keys) / 2.0Comparison of Optimization Approaches
- Standard Maximum Likelihood Estimation (MLE): Solves exact generative density estimation. Requires computing the full partition function sum or evaluating an intractable integral over the state space. Minimizes forward KL divergence . Used primarily in autoregressive language generation and small-vocabulary classification.
- Noise-Contrastive Estimation (NCE): Converts density estimation into binary classification discriminating true data from synthetic noise. Replaces the partition function with a learned parameter or fixes in neural language models. Eliminates the partition function sum while maintaining asymptotic consistency with MLE as the noise sample count grows.
- InfoNCE and Contrastive Predictive Coding (CPC): Generalizes NCE to multi-class categorical selection across positive targets and negative distractors. Cancels the partition function entirely in the probability ratio. Maximizes a variational lower bound on mutual information . Powers multimodal alignment (CLIP), self-supervised vision (SimCLR, MoCo), audio pre-training (wav2vec 2.0), and dense text retrieval.
By transforming intractable partition function integrals into classification objectives and establishing rigorous variational bounds on mutual information, Noise-Contrastive Estimation and InfoNCE provided the mathematical foundation that unlocked large-scale self-supervised learning across modalities.
Sources
- Noise-contrastive estimation: A new estimation principle for unnormalized statistical models (Gutmann & Hyvarinen, AISTATS 2010)
- A Fast and Simple Algorithm for Training Neural Probabilistic Language Models (Mnih & Teh, ICML 2012)
- Representation Learning with Contrastive Predictive Coding (van den Oord, Li, & Vinyals, 2018)
- On Variational Bounds of Mutual Information (Poole et al., ICML 2019)
- Learning Transferable Visual Models From Natural Language Supervision (Radford et al., 2021)
- Sigmoid Loss for Language-Image Pre-Training (Zhai et al., ICCV 2023)
- Neural Word Embedding as Implicit Matrix Factorization (Levy & Goldberg, NeurIPS 2014)



