InfoNCE: identify the positive among candidates
InfoNCE
Compute stable candidate cross-entropy and its gradient, then evaluate a mutual-information bound exactly in a binary example.
infonceStart with the problem
An anchor is paired with one positive candidate and several alternatives. InfoNCE asks a scoring model to identify the positive. This makes it a familiar classification problem with an unusual way of constructing examples, rather than a mysterious standalone measure of representation quality.
Contrastive Predictive Coding introduces the named objective and a mutual-information interpretation. Poole and colleagues analyze variational bounds and their limitations. We separate the score-level calculation from the distributional conditions needed to interpret its expected value.
Definitions and derivation
Let K count every candidate, including the positive. Given real similarity scores s and temperature τ>0, the loss is ordinary softmax cross-entropy:
The gradient lowers nonpositive scores relative to the positive during gradient descent. Adding the same constant to all scores changes nothing, and the score gradients sum to zero. Subtract the maximum scaled score before exponentiating. Temperature changes probabilities and scales derivatives; it is part of the objective, not only a numerical stabilization setting.
When all K scores are equal, loss is log K. For K=1 there is no competitor, so loss and score gradient are zero regardless of the sole score. This trivial success carries no information about whether an encoder distinguishes inputs. A score-level gradient still has to be propagated through the actual encoder and similarity function.
Under the usual construction, the positive is sampled from the joint/conditional distribution with the anchor, while negatives are independent draws from the corresponding marginal. With the proper expectation over such candidate sets, one obtains:
The right expression cannot exceed log K because cross-entropy is nonnegative. Therefore a finite candidate count caps the attainable bound even if true mutual information is much larger. An arbitrary batch score is not itself a certified MI estimate. Dependent negatives, a different proposal distribution or label-based candidate selection can change the assumptions; a negative lower-bound value can also be valid but uninformative.
For an exactly solvable example, let X=Y be a uniformly random bit, so true MI is log 2 nats. Draw K−1 negative bits independently and uniformly. A Bayes-optimal score gives nonmatching bits zero weight and matching bits equal positive weight, understood as a limiting log-score if necessary. If M candidates match the anchor, the model cannot identify which matching one was designated positive and assigns it probability 1/M:
This explicitly includes negative draws with the same bit value as the positive. They are legitimate marginal draws in this mathematical construction. Removing them would change the sampling distribution and invalidate this particular bound calculation. The binomial sum computes the expected optimal loss without sampling noise.
Run the calculation
Complete Python 3.12 / NumPy 1.26.4 program:
import math
import numpy as np
def loss_gradient(scores,temperature=1.,positive=0):
scores=np.asarray(scores,dtype=float)
if scores.ndim!=1 or not 1<=len(scores)<=64 or not np.isfinite(scores).all() or not np.isfinite(temperature) or temperature<=0 or type(positive) is not int or not 0<=positive<len(scores):raise ValueError('Use finite candidate scores, positive temperature and one valid positive index.')
logits=scores/temperature;shift=logits.max();logz=shift+np.log(np.exp(logits-shift).sum());p=np.exp(logits-logz);gradient=p.copy();gradient[positive]-=1
return float(logz-logits[positive]),gradient/temperature,p
def exact_binary_bound(candidates):
if type(candidates) is not int or not 1<=candidates<=64:raise ValueError('Use 1..64 candidates.')
loss=sum(math.comb(candidates-1,k)*math.log(k+1) for k in range(candidates))/(2**(candidates-1))
return loss,math.log(candidates)-loss
if __name__=='__main__':
loss,g,p=loss_gradient([2.,0.,-1.],.5);print('loss',round(loss,9),'probabilities',p.round(9).tolist(),'score gradient',g.round(9).tolist())
print('equal four scores loss',round(loss_gradient(np.zeros(4))[0],9),'singleton loss',loss_gradient([3.])[0])
for k in (1,2,4,16,64):
loss,bound=exact_binary_bound(k);print('candidates',k,'Bayes expected loss',round(loss,9),'MI lower bound',round(bound,9),'true MI',round(math.log(2),9))
Actual output:
loss 0.020581139 probabilities [0.979629207, 0.017942535, 0.002428258] score gradient [-0.040741586, 0.03588507, 0.004856516]
equal four scores loss 1.386294361 singleton loss 0.0
candidates 1 Bayes expected loss 0.0 MI lower bound 0.0 true MI 0.693147181
candidates 2 Bayes expected loss 0.34657359 MI lower bound 0.34657359 true MI 0.693147181
candidates 4 Bayes expected loss 0.845196596 MI lower bound 0.541097765 true MI 0.693147181
candidates 16 Bayes expected loss 2.111768812 MI lower bound 0.66081991 true MI 0.693147181
candidates 64 Bayes expected loss 3.473610765 MI lower bound 0.685272318 true MI 0.693147181
For scores (2,0,−1) at τ=0.5, loss is 0.020581139 and the positive probability is 0.979629207. This score calculation is independent of the binary MI experiment. In that experiment K=2 gives bound 0.346573590, K=4 gives 0.541097765, and K=64 gives 0.685272318, approaching but remaining below log 2≈0.693147181.
Candidate softmax and its score gradient cost O(K); computing similarities and encodings adds their own cost. The binary expectation uses K binomial terms and is not an implementation of CPC’s sequential encoder or autoregressive context network. Reporting its exact bound does not claim that real learned representations achieve the Bayes critic.
When the method fails
A good candidate classifier may exploit shortcuts shared by positive views, including augmentation artifacts or batch statistics. More negatives can change false-negative frequency and optimization difficulty. The sampling process deserves the same care as the formula.
The MI interpretation is useful under its assumptions, but maximizing a bound need not select the features desired by a downstream task. Evaluate representations separately, state whether candidate scores are cosine similarities or another critic, and avoid comparing raw losses across different K and temperatures as if they shared one scale.
Exercises with answers
- Does K count only negatives?
Answer 1: No. Here K includes one positive and K−1 negatives.
- What happens with a single candidate?
Answer 2: Loss and gradient are zero, so there is no discrimination signal.
- Why is loss log M in the binary example?
Answer 3: The M matching candidates have equal Bayes weight, so the designated positive has probability 1/M.
- Can a single arbitrary minibatch certify a mutual-information lower bound?
Answer 4: No. The bound concerns an expectation under the specified joint and marginal sampling construction.
Sources and next steps
CPC physical pages 3–4, Section 2.3 and Equation 4, specify candidates and the MI interpretation. Poole et al. physical page 4, Equation 10, gives a related expectation-based proof and the log-K limitation. Our binomial calculation is an original exact example. Continue with SimCLR for in-batch symmetric candidates and MoCo for a changing queue.
Make a prediction, then check
Why is the attainable InfoNCE MI bound capped by log K?
Learning objectives
- Compute stable InfoNCE loss and score derivatives.
- State candidate-sampling assumptions before interpreting an MI bound.
Prerequisites & connections
Explore related knowledge →References
- Representation Learning with Contrastive Predictive Coding — arXiv v2
Aaron van den Oord; Yazhe Li; Oriol Vinyals · 2018 - On Variational Bounds of Mutual Information
Ben Poole; Sherjil Ozair; Aäron van den Oord; Alexander A. Alemi; George Tucker · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 checks passed per chapter: independent finite differences, exact covariance/binomial references, queue transitions, stopped versus full gradients, batch-normalization derivatives and collapse/rank counterexamples as applicable. All ten programs use NumPy 1.26.4. This scoped final record supersedes the generic carried-over checklist in the frozen metadata; original drafts are retained.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
- Bilingual Matplotlib 3.9.1 charts use executed article functions: exact denoising scales, binomial expected InfoNCE bounds and actual trained cross-correlations. Both locale SVGs and samples are hash-bound. Variance, expectation, shared color scales and finite-optimization limits are explicit.
Source locations checked:
- Representation Learning with Contrastive Predictive Coding — arXiv v2 · Physical pages 3–4, Section 2.3 Equation 4: one conditional positive, marginal negatives, InfoNCE and expected MI bound.
- On Variational Bounds of Mutual Information · Physical page 4, Equation 10 and following paragraph: independent-sample lower bound and log-K cap.
Related topics