AI Wiki中文/EN

Contrastive learning: the pair rule defines what to remember

对比学习

Train a positive/negative pair objective, inspect the learned invariance and construct a collapsed stationary point.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Suppose two recordings capture the same event with different background noise. A representation could be trained to bring those recordings together while separating recordings of different events. The supervision comes from the relation between examples. It may be derived from augmentation, time, multiple sensors or labels; it is not automatically free of assumptions.

Wang and Isola analyze alignment and uniformity for normalized contrastive representations. Contrastive Predictive Coding uses a candidate-classification objective. This introductory chapter uses a separate original smooth pair loss to expose attraction, repulsion and failure cases; InfoNCE and complete frameworks have their own chapters.

Definitions and derivation

Let P and N be explicitly declared positive and negative pairs. A linear encoder maps two input coordinates into two feature coordinates. Positive pairs pay squared distance; negative pairs pay a softplus of one minus squared distance:

zi=xiW,dij2=∥zi−zj∥2,L=∑(i,j)∈Pdij2+∑(i,j)∈Nlog⁡(1+e1−dij2)∣P∣+∣N∣+0.005∥W∥F2.z_i=x_iW,\quad d_{ij}^2=\|z_i-z_j\|^2,\qquad L=\frac{\sum_{(i,j)\in P}d_{ij}^2+\sum_{(i,j)\in N}\log(1+e^{1-d_{ij}^2})}{|P|+|N|} +0.005\|W\|_F^2.

This is a teaching objective, not the exact loss of SimCLR or the hypersphere analysis paper. No feature normalization is used. The small weight penalty limits growth of the unnormalized features. Positive distances are minimized, while the negative penalty decreases as distance increases. The softplus is computed with logaddexp for stability.

Writing δ=zᵢ−zⱼ, the pair gradients are:

∇ziℓij+=2(zi−zj),∇ziℓij−=−2σ(1−dij2)(zi−zj),∇zjℓij=−∇ziℓij.\nabla_{z_i}\ell^+_{ij}=2(z_i-z_j),\qquad \nabla_{z_i}\ell^-_{ij}=-2\sigma(1-d_{ij}^2)(z_i-z_j),\qquad \nabla_{z_j}\ell_{ij}=-\nabla_{z_i}\ell_{ij}.

The scalar sigmoid in the negative term reduces the repulsive force once a pair is far apart. Accumulate every pair contribution at both endpoints, average by the total number of declared pairs, and propagate to W using Xᵀ times the feature gradient. Add 0.01W for the weight penalty. Repeated pairs would receive repeated weight, so the pair list is part of the objective definition.

Our four rows are (1,0.3),(1,−0.3),(−1,0.4),(−1,−0.4). Positives pair the two views with first coordinate +1 and the two with first coordinate −1; negatives cross the two underlying objects. Under this construction, the second coordinate is a nuisance. The learned map retains and expands the first coordinate while suppressing the second. If the second coordinate were needed for the downstream task, this learned invariance would be harmful.

Negative terms make a constant representation costly, but they do not guarantee that gradient descent can escape every collapsed point. With all encoder weights zero, every pair difference is zero:

W=0⟹zi=0 ∀i,L=∣N∣∣P∣+∣N∣log⁡(1+e),∇WL=0.W=0\quad\Longrightarrow\quad z_i=0\ \forall i,\qquad L=\frac{|N|}{|P|+|N|}\log(1+e),\quad \nabla_WL=0.

Every pair gradient vanishes because it contains a difference vector. This is a stationary point with high loss, not the useful solution reached from our nonzero initialization. It illustrates the distinction between making collapse suboptimal and proving that training avoids collapse.

Run the calculation

Complete Python 3.12 / NumPy 1.26.4 program:

import numpy as np

X=np.array([[1.,.3],[1,-.3],[-1,.4],[-1,-.4]])
POS=[(0,1),(2,3)];NEG=[(0,2),(1,3)]


def objective(weight,positive=POS,negative=NEG):
    w=np.asarray(weight,dtype=float)
    if w.shape!=(2,2) or not np.isfinite(w).all():raise ValueError('Use a finite 2x2 encoder.')
    z=X@w;grad_z=np.zeros_like(z);loss=0.
    for pairs,is_positive in ((positive,True),(negative,False)):
        for i,j in pairs:
            delta=z[i]-z[j];distance2=float(delta@delta)
            if is_positive:value=distance2;derivative=1.
            else:value=float(np.logaddexp(0,1-distance2));derivative=-float(np.exp(-np.logaddexp(0,distance2-1)))
            loss+=value;g=2*derivative*delta;grad_z[i]+=g;grad_z[j]-=g
    count=len(positive)+len(negative)
    if not count:raise ValueError('At least one declared pair is required.')
    return loss/count+.005*np.sum(w*w),X.T@grad_z/count+.01*w,z


if __name__=='__main__':
    w=np.diag([.5,1.]);start=objective(w)[0]
    for _ in range(500):w-=.05*objective(w)[1]
    loss,g,z=objective(w);print('loss before/after',round(start,9),round(loss,9),'encoder',w.round(9).tolist());print('positive squared distances',[round(float(np.sum((z[i]-z[j])**2)),9) for i,j in POS]);print('negative squared distances',[round(float(np.sum((z[i]-z[j])**2)),9) for i,j in NEG])
    zero=np.zeros((2,2));loss,g,z=objective(zero);print('collapsed loss',round(loss,9),'collapsed gradient norm',round(float(np.linalg.norm(g)),12))

Actual output:

loss before/after 0.60032984 0.009988933 encoder [[1.317765877, 0.0], [0.0, 2.468e-06]]
positive squared distances [0.0, 0.0]
negative squared distances [6.946027624, 6.946027624]
collapsed loss 0.656630844 collapsed gradient norm 0.0

Five hundred updates reduce loss from 0.600329840 to 0.009988933. The encoder’s first scale becomes about 1.31777 and the nuisance scale about 2.47×10⁻⁶. Positive squared distances round to zero at nine decimals; negative squared distances are about 6.94603. At exactly zero weights, loss is 0.656630844 and gradient is zero.

Only the given pair relations are learned. This is not a measured semantic classification result. For a fixed encoder output dimension d, pair-distance work is O((|P|+|N|)d), plus encoder evaluation and backpropagation. All-pairs methods can instead require quadratic batch work. A larger set of negatives changes the objective and cost, not just its numerical precision.

When the method fails

False positives force unrelated examples together; false negatives repel examples that should share a task-relevant representation. A crop that removes the object, or an augmentation that changes the label, can invalidate the assumed positive relation. Hard-negative selection can amplify this problem and should be evaluated rather than automatically preferred.

Normalized methods prevent arbitrary scale growth but retain temperature and sampling choices. Good pair loss is not sufficient evidence of useful features. Evaluate frozen and fine-tuned representations with a stated protocol, inspect nuisance shifts, and keep final test labels out of pair construction and model selection.

Exercises with answers

  1. What invariance does the supplied pair rule encourage?

Answer 1: Ignoring the second coordinate while distinguishing the two objects by the first.

  1. Why is a weight penalty included?

Answer 2: Unnormalized negative-pair distances can otherwise encourage scale growth; the penalty trades that off.

  1. Why is the zero encoder stationary despite negative pairs?

Answer 3: Every distance derivative contains a zero pair-difference vector at collapse.

  1. Does the same positive augmentation suit every downstream task?

Answer 4: No. An augmentation may erase or change information required for another target.

Sources and next steps

Wang–Isola physical pages 3–4 state the positive-pair and marginal assumptions, normalized contrastive setup and alignment perspective. CPC physical pages 3–4 give a different candidate-classification contrastive loss. Our unnormalized softplus pair loss is explicitly separate from both published algorithms. Continue with InfoNCE and SimCLR to see concrete normalized objectives.

Make a prediction, then check

Why can a good positive-pair rule become harmful for another task?

Choose one answer

Learning objectives

  • Trace attraction and repulsion gradients from an explicit pair list.
  • Distinguish suboptimal collapse from impossible collapse.

Prerequisites & connections

Explore related knowledge →

References

  1. Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere
    Tongzhou Wang; Phillip Isola · 2020
  2. Representation Learning with Contrastive Predictive Coding — arXiv v2
    Aaron van den Oord; Yazhe Li; Oriol Vinyals · 2018

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.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.