1. Why Normalization Hurts#
Given a context and model parameters , predicting the next word uses the softmax:
where is the logit (score) for word , is the unnormalized score, and is the partition function that sums over every word in the vocabulary .
When ranges from to , each training step must enumerate the entire vocabulary just to compute . The MLE gradient reveals the bottleneck:
The core problem: MLE demands the gradient of at every step, and that gradient is an expectation over the model’s own distribution , which covers the entire vocabulary. Millions of training steps times a -word sum is infeasible.
To see exactly how this gradient breaks down, start from the MLE objective: maximize the expected log-probability . Write the log-probability as . The second term does not depend on which was drawn from the data, so it sits outside the expectation over . Taking the derivative: .
The first term only touches words that actually appear in the training batch — cheap. The second term is the problem. Expanding it step by step: (chain rule on ), then (expand ‘s definition), then (swap sum and derivative), then (chain rule: ), then (push back into the sum), which is .
That last line is the killer: means every word in the vocabulary contributes to the gradient, weighted by the model’s own softmax probability. Expanding it explicitly: . Each word needs one forward pass (computing ) times one backward pass (computing ). For a 100,000-word vocabulary, each gradient descent step costs 100,000 forward-backward passes.
In plain terms: MLE pushes the score of the correct word up, but to prevent the model from cheating — giving every word an infinite score — it also pushes all word scores down, weighted by how likely the model currently thinks each word is. That “push all scores down” step runs over the whole vocabulary. NCE sidesteps this by reformulating the problem entirely.
Notation and Probability Quick-Start#
If the equations feel unfamiliar, the issue is likely probability notation, not NCE itself. Here is a minimal primer.
| Symbol | How to read it | Meaning | Example |
|---|---|---|---|
| ”probability of “ | Probability a random variable takes the value | means cat appears 30% of the time | |
| ”probability of given “ | Conditional probability: ‘s probability once we know | Given the previous word is “the”, how likely is the next word “cat”? | |
| ” follows distribution ” | is sampled from the probability distribution | means comes from the data distribution | |
| ”expectation of under “ | Weighted average, using as the weights | For details see the explanation below | |
| ”sum over all “ | Add up over every possible value | means summing over the whole vocabulary | |
| data distribution | The true frequency of word given context in training data | How often “cat” really follows “the” in human text | |
| model distribution | The model’s predicted probability of given (with parameters ) | The softmax output | |
| noise distribution | An arbitrary distribution we choose ourselves | A unigram frequency distribution (common words get higher probability) | |
| “partial derivative with respect to “ | Gradient: how the function changes when moves | is the gradient of the loss |
The expectation is simply a weighted average: . Take each possible value of , multiply it by how often it occurs under , and sum. If your vocabulary has three words and your model assigns , , , with scores , , , then . That is all there is to it.
The vertical bar in means “under the condition that.” is the baseline; is the updated belief once you have seen clouds. In language modeling, is the probability of “cat” given that the preceding word was “the.”
Bayes’ rule is the central tool in NCE’s derivation. Its essence is flipping conditions around: , which says: the probability of A once you know B is the fraction of times A and B occur together, divided by how often B occurs at all. If “cat and from real data” happens 5 times out of 100, and “cat” appears 20 times total (real or noise), then a cat-token is from real data with probability . NCE applies exactly this logic: given a word , work backwards to decide whether it came from real data or from noise.
2. Core Idea: Classification, Not Counting#
NCE introduces a noise distribution (a simple, fast-to-sample distribution like unigram frequency) and defines a binary classification problem:
| Label | Meaning | Sampling ratio |
|---|---|---|
| The word came from real data | ||
| The word came from noise |
where is the theoretical ratio of noise samples to real samples.
The derivation proceeds through Bayes’ rule. The joint probability of drawing a word with label is : first pick the “real data” source (probability ), then sample from the data distribution. Similarly, . The marginal probability of seeing word at all (from either source) is .
Given a word , what is the posterior probability that it came from real data?
We do not know — that is the distribution we want to learn. So we substitute the model’s prediction in its place:
The intuition: when dominates , the model believes this word is real; when the noise term dominates, the model leans toward fake. NCE trains the model to make converge to the true through this proxy classification task.
To turn this into a loss function, start from the standard binary log loss . NCE substitutes as the classifier’s output and as the label: when , the loss is ; when , the loss is . The total loss weights every sample according to its source.
Expanding the expectation over the full mixture distribution and substituting the two conditional probabilities:
The constant factor is dropped (it does not affect optimization). The first term encourages the model to assign high scores to real words; the second term, weighted by because there are times as many noise samples, encourages the model to assign low scores to noise words. Together they form a weighted binary classification log loss.
3. The Critical Result: NCE Approaches MLE When #
In NCE we do not compute explicitly. Instead we introduce a learnable parameter as a per-context scaling factor: , where is the unnormalized score from the neural network , and approximates the normalization constant. The full parameter set is .
And yet, the most remarkable property of NCE is that in practice you can simply fix and not learn it at all. The model will learn to self-normalize: the score magnitudes will automatically adjust so that . This sounds like it should not work. If we are not learning the normalization factor, what stops the network from pushing all scores to infinity?
The answer is in the structure of the binary classification loss. Suppose the network goes haywire and assigns enormous to every word, real or fake. In every term’s denominator , the term dominates and the noise term is washed out. For noise words, the loss becomes : the loss explodes. For real words, the loss becomes : loss is zero, which cannot offset the explosion from the noise terms. Conversely, if the network pushes all scores toward zero, the real-word loss explodes while the noise-word loss sits at zero. Either extreme is punished. The only equilibrium is . The binary classification loss is a natural braking mechanism: push too high and the noise terms penalize you; push too low and the real terms penalize you. The math itself enforces normalization, no explicit partition function required.
Gradient Derivation#
Computing gives the core insight. Using Leibniz rule to move the derivative inside the expectations:
For the first term, instead of attacking the fraction directly, rewrite it to avoid the quotient rule:
After algebraic simplification: .
The second term follows similarly: .
Combining both expectations:
Writing these expectations as discrete sums reveals the structure more clearly:
Now take the derivative with respect to (the network parameters, excluding the normalization parameter ). Since and does not depend on , the term simplifies to :
Now the critical step: take . The weighting factor because dominates in both numerator and denominator. The gradient becomes:
This is exactly the MLE gradient. Recall from Section 1: the MLE gradient was , and here . The two expressions are identical.
So . The crucial difference: in MLE, the sum over runs over the entire vocabulary (because is the full softmax). In NCE, the sum only runs over the positive sample plus noise samples. The complexity drops from to .
4. NCE in Practice: Sigmoid + Log Loss#
The posterior probability can be rewritten in a much more practical form. Divide numerator and denominator by to get , then rewrite the fraction inside using : . Pulling out a negative sign gives , which is exactly the sigmoid function with input .
In practice we set (self-normalization), so and . This yields:
Define . This quantity asks a natural question: how much higher is the model’s score for this word compared to its expected score if it were random noise? The larger the gap, the more likely the word is real.
The empirical loss function (following the original paper’s recommendation of real sample and noise samples) becomes:
The computation flow: take one real word (label = 1) and noise words (label = 0); for each word compute ; pass through sigmoid; compute binary cross-entropy; backpropagate.
5. A Common Confusion: vs #
Nearly every blog post and even TensorFlow’s tf.nn.nce_loss gets this wrong. The two parameters are conceptually distinct.
is the theoretical ratio of noise samples to real samples. A larger brings NCE closer to MLE in the limit. is the actual number of noise samples drawn from for Monte Carlo estimation of the noise expectation. A larger gives a more accurate estimate of the expectation. Confusing them does not break anything in practice when is large enough, but conceptually they are independent design choices.
6. Limitations#
NCE only speeds up training, not inference. At test time you still need to enumerate the vocabulary if you want to generate the next word — NCE does not bypass the partition function at inference. The noise distribution matters: if it is too far from the true data distribution, the classifier never sees difficult negative examples and the learned model degrades. And NCE does not guarantee a properly normalized probability distribution (though self-normalization works well in practice, the output is not a strict probability).
7. From NCE to InfoNCE#
NCE is the mathematical foundation of InfoNCE loss. InfoNCE generalizes the idea from language modeling to representation learning, making essentially one change: instead of independent binary classifications, it poses a single -way classification.
In NCE, each negative sample is judged independently: “are you real or fake?” In InfoNCE, the question becomes “among these candidates, which one is the real positive?” The negatives compete with each other, and only one can win.
NCE’s loss for a positive sample plus negatives: . InfoNCE transforms this into a softmax over all samples: .
| NCE | InfoNCE | |
|---|---|---|
| Problem | Language modeling (predict the next word) | Representation learning (classify positive vs. negative pairs) |
| Positive | from training data | A positive pair |
| Negatives | Sampled from | Other samples in the batch or a memory bank |
| Classification | independent binary (Sigmoid) | One -way classification (Softmax) |
| Normalization | Not needed (each Sigmoid is independent) | Required — denominator sums |
| Negative relationship | Independent | Competitive |
Why “Info” NCE: From Loss to Mutual Information#
This is InfoNCE’s deepest theoretical contribution. Many sources give the conclusion without the derivation; here is the full chain.
Start with the InfoNCE loss: , where is the positive sample for and are negatives drawn independently from the marginal . The scoring function is what the model learns — for instance, in SimCLR.
At optimality, the scoring function converges to a density ratio: . The model’s score estimates how much more likely is to appear when paired with , compared to appearing randomly in the dataset. A high ratio means a strong association.
Substituting this optimal form back into the loss and noting that negative samples are drawn independently from (so ), we get:
where the approximation holds when is large and the density ratio is small relative to . Now recall the definition of mutual information: . Mutual information measures how much uncertainty about is removed by knowing .
This yields , and since any trained loss is at least the optimal loss, . Rearranging gives the useful bound:
The quantity is a lower bound on the mutual information . Minimizing the InfoNCE loss pushes this lower bound upward: the model is forced to preserve more shared information between positive pairs. A large tightens the bound (the term grows), which is why contrastive learning craves large numbers of negatives.
The narrative flow is worth tracing in full. InfoNCE sets up a game: among candidates, find the real positive. This game has a theoretical ceiling — the best any classifier can do is determined by the mutual information shared between positive pairs. When the model plays well (low loss), its representations retain a lot of mutual information. When it cannot tell positives from negatives (high loss), the representations have discarded most of that shared structure. Minimizing InfoNCE is not an arbitrary trick; it is mathematically equivalent to maximizing a lower bound on mutual information.
In SimCLR, a batch of images, each with two augmented views, produces representations. For each positive pair , the loss takes the form , where is typically cosine similarity and is a temperature parameter controlling the sharpness of the distribution. This is InfoNCE (also called NT-Xent loss): the denominator sums over all other samples as negatives. InfoNCE has been adopted by SimCLR, MoCo, CPC, BYOL, and essentially all major contrastive learning methods.
Why InfoNCE Outperforms NCE in Representation Learning#
NCE was built for language modeling; InfoNCE was built for representation learning. When compared within the representation learning setting, InfoNCE has several structural advantages.
The key difference is negative competition. In NCE, each negative is judged independently — even a hard negative (one very similar to the positive) gets the same treatment as an easy one: just another “fake” label. In InfoNCE, all negatives share the same denominator. To win the softmax, the positive must not only score highly but must outrank every negative. A strong hard negative steals probability mass from the positive, producing a stronger gradient.
The gradient itself reveals this property. For each negative , . The penalty on a negative is proportional to the probability the model mistakenly assigns to it being the positive. The more a negative resembles the positive, the higher its softmax probability, and the harder the gradient hits it. The loss is doing automatic hard negative mining — no manual filtering needed. NCE’s sigmoid has no equivalent mechanism: all negatives receive equal gradient weight regardless of difficulty.
InfoNCE also removes the need for an external noise distribution. NCE requires choosing by hand; a poor choice degrades performance. InfoNCE uses the batch itself as the negative pool, with zero overhead. MoCo extends this further with a momentum encoder maintaining a large negative queue for when the batch alone is too small.
The temperature parameter in the softmax provides a tunable difficulty knob: concentrates all gradient signal on the hardest negative; treats all negatives equally. SimCLR’s was found through tuning. NCE’s sigmoid has no comparable control.
And as shown in the derivation above, InfoNCE provides an information-theoretic guarantee: . Minimizing the loss is mathematically equivalent to maximizing the mutual information between positive pairs while minimizing it for negative pairs. NCE cannot make this claim.
In short, replacing independent sigmoids with a shared softmax denominator triggers a cascade of consequences — negative competition, automatic hard negative mining, mutual information interpretation, and temperature control. NCE’s binary classifier is solving an easier problem, and in representation learning, that produces a less tightly organized representation space.
Related Reading#
- Contrastive Predictive Coding — the paper that proposed InfoNCE and extended NCE to representation learning
- SimCLR ↗ — InfoNCE applied to visual contrastive learning
- MoCo ↗ — momentum queue for scaling negative samples
- BYOL ↗ — contrastive learning without negative samples
References#
- Lei Mao’s Blog: Noise Contrastive Estimation ↗
- Gutmann & Hyvarinen (2012). Noise-Contrastive Estimation of Unnormalized Statistical Models
- Mnih & Teh (2012). A Fast and Simple Algorithm for Training Neural Probabilistic Language Models
- Ma & Collins (2018). Noise Contrastive Estimation and Negative Sampling for Conditional Models: Consistency and Statistical Efficiency