Topic: ml-fundamentals · child page

Contrastive and self-supervised learning

How a network learns useful representations with no labels: the pairing is the label. Margins and triplets, InfoNCE and its temperature, SimCLR and MoCo, how BYOL, SimSiam, DINO and VICReg avoid collapse without negatives, masked modelling (MAE, I-JEPA), and CLIP and embedding models as the same loss across modalities. Real sentence embeddings, a real MAE checkpoint and toy runs on real digits, computed offline and checked. Data as of October 2026. Reading: 31 min, plus 8 in closed details.

The idea in one screen

Make the data supply its own target: two views of the same thing must land close in embedding space, and something must stop the trivial answer, every input mapped to one point. The methods differ only in that something: negatives pushed away (contrastive), an asymmetric pair of networks (BYOL, SimSiam, DINO), a statistic of the batch (Barlow Twins, VICReg), or predicting the hidden part of the input (MAE, I-JEPA).

Fig. 1 is one real batch before and after contrastive training: the diagonal stays high, everything else falls.

  1. Before: BERT, masked-LM only. Eight sentence pairs from the STS benchmark test split; rows are anchors, columns candidates, and each bar is the real cosine between an anchor and a candidate. Everything is high: the positives average 0.92 and the negatives 0.59.
  2. The diagonal is the label. Each anchor's positive (blue) is its own paraphrase; the pairing is the label, and the other seven candidates are negatives. Each row is one 8-way classification whose right answer is the diagonal: row 7's streams are as dense as a softmax at τ = 0.05 puts probability, 96% already on the positive, although candidate 3 scores 0.76 against the positive's 0.96.
  3. After: the same BERT, SimCSE. Contrastive training lowers every negative to a mean of 0.28 while the positives stay at 0.90; row 7 now puts 100% on its positive. Over the full 48-pair batch the mean negative cosine moves from 0.60 to 0.31 while the positives stay at 0.92 and 0.91 measured.
The eight pairs (rows and columns of Fig. 1)

You need: softmax cross entropy and its gradient p − y (Loss functions), cosine similarity of l2-normalised vectors, and for the masked-modelling section a ViT's patch tokens (ViT paper page). The parent (Topic: ml-fundamentals, "Beyond one network" and "Everything is cross entropy") places this paradigm beside supervised training; this page owns the mechanisms.

View
one augmented version of an input (a crop with colour jitter, the same sentence through dropout); two views of one input form a positive pair.
Anchor, positive, negative
the item being scored, the item it should match, and the items it should not.
Temperature τ
the divisor of the similarities before the softmax; small τ makes the loss care about the hardest negatives.
Projection head
a small MLP between the representation and the loss, thrown away after training.
Collapse
every input mapped to the same vector (complete) or into a few directions (dimensional); the loss can look excellent while it happens.
EMA, momentum encoder
a copy of the network whose weights are an exponential moving average of the trained one; it gets no gradient.
Stop-gradient
treating one branch's output as a constant target (detach()), so the gradient flows through the other branch only.

The five families in one table

FamilyPositive pair, or targetWhat stops a constant outputLandmarks
Contrastivetwo views of one input; an image and its captionnegatives: the rest of the batch, a memory bank or a queueCPC 2018, SimCLR 2020, MoCo 2019, CLIP 2021, SimCSE 2021
Self-distillation, no negativestwo views of one inputasymmetry: a predictor, a stop-gradient, a slow teacher; DINO adds centering and sharpeningBYOL 2020, SimSiam 2020, DINO 2021, DINOv2 2023, DINOv3 2025
Redundancy reductiontwo views of one inputa term on the batch's statistics: each output dimension must vary, dimensions must not correlateBarlow Twins 2021, VICReg 2021
Masked modellingthe hidden part of the input, in pixels or tokensnothing needed: the target is the data, so a constant output scores badlyBERT 2018, BEiT 2021, MAE 2021, SimMIM 2021
Joint-embedding predictionthe representation of the hidden part, from a slow target encoderthe EMA target encoder and a predictor, as in self-distillation; or a regulariser on the embeddings (SIGReg) in place of the teacherdata2vec 2022, I-JEPA 2023, V-JEPA 2024, V-JEPA 2 2025, LeWM 2026 (SIGReg)

Dates are first arXiv versions; each method is sourced where it is described below; the family tree in the closed Depth section puts them on one time axis.

Pairs and triplets: the margin losses

Early self-supervision invented pretext tasks whose answer the data already holds (which rotation was applied, where a patch sits, how to unshuffle a jigsaw); the features were good only insofar as the proxy needed them. Instance discrimination (Wu et al. 2018) made the geometry itself the goal: treat every image as its own class, keep each image's feature in a memory bank rather than a classifier's weights, and use noise-contrastive estimation to cope with a million classes. The losses that state the geometry are older.

The pretext tasks, with their sources (lineage)
Surrogate classes, each one image under many transformations (Dosovitskiy et al. 2014, Exemplar CNN); predict where a second patch sits relative to the first (Doersch et al. 2015); solve a jigsaw puzzle of tiles (Noroozi and Favaro 2016); recognise which 2-D rotation was applied (Gidaris et al. 2018). Each task was a proxy for the features, not the features themselves.

The contrastive loss with a margin (Hadsell, Chopra and LeCun 2006) scores one pair at a time at distance d: a similar pair pays ½d2, a dissimilar pair pays ½ max(0, m − d)2, so dissimilar pairs are pushed only while they sit inside the radius m. The triplet loss (FaceNet, Schroff, Kalenichenko and Philbin 2015) compares distances instead of thresholding them: an anchor a, a positive p of the same identity and a negative n, embedded on the unit hypersphere (‖f(x)‖2 = 1, 128 dimensions):

L = Σ max(0, ‖f(a) − f(p)‖2 − ‖f(a) − f(n)‖2 + α)
α
the margin the negative must clear beyond the positive; "The margin α is set to 0.2" (§3.3)
dap, dan
the two squared distances; on unit vectors ‖u − v‖2 = 2 − 2 cos(u, v)

A triplet already separated by the margin contributes nothing, neither loss nor gradient. So the loss lives or dies by which negatives it sees. FaceNet names three kinds: hard (closer than the positive), semi-hard ("further away from the anchor than the positive exemplar, but still hard because the squared distance is close to the anchor-positive distance. Those negatives lie inside the margin α", §3.2) and easy (beyond the margin). It mines them online inside mini-batches of "around 1,800 exemplars" with "around 40 faces" per identity, and picks semi-hard ones because "Selecting the hardest negatives can in practice lead to bad local minima early on in training, specifically it can result in a collapsed model (i.e. f(x) = 0)". The result was 99.63% on LFW and 95.12% on YouTube Faces.

Predict: with FaceNet's margin of 0.2, how many of this batch's 2,256 triplets (48 anchors, 47 negatives each) still contribute anything, before and after contrastive training? Then move the margin.

Two lessons carry over to everything below. A hinge spends its gradient on a handful of triplets and none on the rest, so it needs mining and big pools of candidates. And pushing hardest on the closest negatives can collapse the embedding. InfoNCE answers the first by scoring one positive against all the negatives at once, each weighted by a softmax; as τ → 0 it becomes max(0, maxj sij − sii)/τ, a margin-free hinge on the hardest negative alone derived. Listwise ranking losses are the same softmax over a list: with one relevant item ListNet's top-one loss is InfoNCE (Loss functions, "Ranking losses").

Most triplets are already satisfied: only negatives inside the margin get a gradient

hard: closer than the positivesemi-hard: inside the margineasy: no loss, no gradientthe positive

Squared distances 2 − 2 cos from the real cosines of the 48-pair batch (BERT first-last average pooling; SimCSE [CLS]), computed in the page. At α = 0.2, 21 of 2,256 triplets are active under BERT (1 hard, 20 semi-hard) and 1 after SimCSE, the false negative of anchor 31 below; at α = 0.8, 1,825 and 153 derived. Recomputed in src/recompute.py.

InfoNCE, the workhorse loss

On the hero's batch at τ = 0.05, BERT's mean loss is 0.29 nats and SimCSE's 0.04, and after SimCSE the single most similar negative takes almost half of each anchor's push. Both come from one formula:

Li = −log exp(sim(zi, zi+) / τ)Σk=1..N exp(sim(zi, zk) / τ)
zi
the anchor's embedding; zi+ its positive; the sum runs over the positive and the N − 1 negatives
sim
cosine similarity, the dot product of l2-normalised vectors, so every logit lies in [−1/τ, 1/τ]
τ
the temperature, a fixed hyperparameter or (in CLIP) learned

It is the softmax cross entropy of an N-way classification whose classes are the candidates in the batch and whose right answer is the positive (van den Oord et al. 2018, CPC, §2.3); temperature as a softmax knob in general is on Activation functions. Read as ranking, it is the listwise loss (ListNet's softmax over a list) with one relevant item, next to the pairwise and LambdaRank losses on Loss functions ("Ranking losses: only the order counts"). Three facts make it special.

1 · The gradient goes where the softmax puts its mass

Write sij for the cosine between anchor i and candidate j and pij for the softmax over sij/τ. Differentiating derived:

∂Li/∂sij = (pij − 1[j is the positive]) / τ

The positive is pulled up by (1 − ppositive)/τ and each negative is pushed down by pij/τ; the pushes add up to the pull. Unlike the triplet hinge, every negative gets some push, in proportion to how similar it already is. The temperature sets how sharply: as τ falls the push concentrates on the hardest negatives; as τ rises every negative gets the same small push. Wang and Liu (2021) call this the hardness-aware property ("the temperature τ controls the strength of penalties on hard negative samples"), and name the cost of going too low the "uniformity-tolerance dilemma": things that genuinely belong together get pushed apart.

Fig. 2 follows one anchor of the hero's batch through the formula, step by step.

  1. One anchor's 48 cosines. Anchor 31, "A woman is dancing in the rain.", against every candidate in the batch under BERT, the most similar in the middle: from 0.51 to 0.95. Its positive, "A woman dances in the rain out side.", scores 0.92; candidate 42, another pair's "A man and woman are dancing in rain.", scores 0.95.
  2. Divide by τ, take the softmax. At τ = 0.05 every logit lies in [−20, 20], and the softmax puts 23% on the positive and 45% on candidate 42; this anchor's loss is −ln p = 1.49 nats.
  3. The gradient: one pull, many pushes. The positive's cosine is pulled up by (1 − p)/τ = 15.5; each negative is pushed down by pij/τ, and the pushes add up to the pull. The front row draws each push as its share: candidate 42 takes 59%.
  4. Raise the temperature to τ = 1. The softmax flattens: the positive gets 2.6%, the push spreads almost evenly (candidate 42 takes 2.8%, against an even split of 1/47 = 2.1%), and the pull falls to 0.97.
  5. After SimCSE, back at τ = 0.05. The other negatives fall away, but candidate 42 really does mean nearly the same thing (cosine 0.92 against the positive's 0.87), so it takes 99% of the push: a false negative, pushed away hardest (fact 3 below). The positive gets 30%.

Predict: at τ = 1, what share of anchor 31's push does its hardest negative take, against an even split of 1/47 = 2%? And at τ = 0.01? Drag the temperature, then click other rows.

SimCLR's ImageNet sweep found τ = 0.1 best of {0.05, 0.1, 0.5, 1} at batch 4,096 (Chen et al. 2020, Table 5), 0.5 best on CIFAR-10 (Appendix B); SimCSE uses 0.05 (Gao et al. 2021, Table D.1); MoCo 0.07; CLIP learns it (below).

2 · The batch is the task

A model that knows nothing puts probability 1/N on the positive and scores ln N, so the batch size changes the task itself, not only the gradient noise: drag N above and watch the dotted chance line move. A lower loss at a bigger batch is not a better model; compare ln N − L, or better, a downstream probe. CPC proves the loss bounds the mutual information between the two views from below, I ≥ ln N − L, "which becomes tighter as N becomes larger" (§2.3), and the bound can never exceed ln N (Poole et al. 2019: "upper bounded by log K", K the batch size): ln 4,096 = 8.3 nats is the most a SimCLR batch can certify derived.

Correction to the old page
"Maximises a lower bound on mutual information" is true but often over-read. The bound is capped at ln N, it is loose when the true information is larger, and later work credits InfoNCE's success to the geometry it produces (alignment and uniformity) rather than to information it measures (Wang and Isola 2020). Also, in SimCLR each anchor has 2(N − 1) negatives, not N − 1: both augmented views of every other image count ("we treat the other 2(N−1) augmented examples within a minibatch as negative examples", §2.1).

Hence the engineering that buys negatives: big batches (SimCLR trains at 4,096 by default and sweeps 256 to 8,192, §2.2; CLIP uses 32,768); a memory bank of every image's last-seen feature (Wu et al. 2018: many negatives, but stale ones from older versions of the encoder); a queue fed by a momentum encoder (MoCo, next section), which decouples the number of negatives from the batch; or a sigmoid instead of the softmax: SigLIP scores every image-text pair as an independent binary decision, so the loss "does not require a global view of the pairwise similarities for normalization" (Zhai et al. 2023; the CLIP paper page animates softmax against sigmoid on one batch).

3 · Negatives are sampled, so some are wrong

Random negatives include items that share the anchor's meaning or class, and the loss pushes them away anyway. The batch has one: the only anchor either model gets wrong is row 31, "A woman is dancing in the rain.", whose nearest candidate is another pair's "A man and woman are dancing in rain." (cosine 0.92 after SimCSE) rather than its own positive, "A woman dances in the rain out side." (0.87). It is also the one triplet SimCSE leaves active above. Chuang et al. (2020) correct the objective for these false negatives; Robinson et al. (2021) go the other way and sample hard negatives on purpose, with a knob for how hard. In practice: deduplicate, use larger and more diverse batches, and when mining hard negatives for retrieval, filter the ones that are actually positives; how often a mined "negative" is really relevant on SciFact, and a positive-aware filter, are measured on Embedding models, sections 4 and 5.

Lower the temperature and the gradient piles onto the hardest negatives

Softmax over each row rows: anchors; columns: candidates; outlined: the positive; click a row
probability on that candidatepositiveselected anchor
Anchor where its gradient goes

Mean loss against temperature, this batch both models; dotted: chance, ln N

Forty-eight STS-B test pairs that human raters scored 4.5 to 5 out of 5; each first sentence is an anchor, its partner the positive, the other partners the negatives. Cosines are real (BERT-base before and after unsupervised SimCSE, computed offline by src/real_embeddings.py); the softmax, loss and gradient are computed in your browser and checked against PyTorch's cross_entropy and autograd (src/recompute.py). Averaged over the 48 anchors the hardest negative's share is 20% under BERT and 44% after SimCSE at τ = 0.05, and 3% at τ = 1 measured. The batch is easy (near-paraphrases sharing most words): raw BERT already ranks 47 of 48 positives first, and what contrastive training changes is the margin.

Two branches, six designs

Every method on this page runs two views of one input through two branches and compares the outputs. What differs is small and decisive: whether the branches share weights, whether one is a moving-average copy, whether a predictor or a stop-gradient breaks the symmetry, and where the negatives come from, if anywhere.

Fig. 3 draws that picture once and lights up what each design changes. Green plates are trained by the gradient, grey ones are moving-average copies that get none; blue dots are the data going forward, orange dots the gradient coming back, purple dots the weights copied into the slow branch.

  1. SimCLR: same weights, negatives from the batch. Both branches are the same network and both get gradients. Nothing is asymmetric, so the negatives (every other view in the batch) are the only thing stopping collapse; hence batch 4,096.
  2. MoCo: a slow key encoder and a queue. Still contrastive, but the negatives are past keys in a queue. The key encoder is a slow moving average (m = 0.999) and gets no gradient, so keys computed many steps apart stay comparable.
  3. BYOL: no negatives, a predictor and a slow target. The online side has an extra predictor and chases a slowly moving target; the target gets no gradient. The asymmetry, not the loss, is what keeps the constant solution out of reach.
  4. SimSiam: BYOL without the moving average. One shared encoder, a predictor on one side, a stop-gradient on the other. Remove the stop-gradient and ImageNet accuracy falls to 0.1%.
  5. DINO: a teacher's softmax, centred and sharpened. Self-distillation: the student matches the teacher's softmax over prototypes. Centering stops one prototype winning; the low teacher temperature (sharpening) stops the uniform answer.
  6. VICReg: symmetric again, a statistic of the batch. No negatives and no asymmetry: the variance hinge keeps every output dimension varying across the batch, and the covariance term decorrelates the dimensions.

SimCLR: the recipe most image methods inherit

SimCLR (Chen et al. 2020) calls the loss NT-Xent ("normalized temperature-scaled cross entropy") and finds three things matter. Augmentation: "the combination of random crop and color distortion is crucial" (§3). A projection head: a small MLP g maps the representation h to the z the loss sees; a nonlinear head beats a linear one by about 3% and no head by more than 10% (§4.2), and after training "we throw away the projection head" and use h (using z downstream is a common mistake). Scale: large batches and long training. Linear evaluation on ImageNet reaches 69.3% top-1 with a ResNet-50 and 76.5% with a ResNet-50 four times wider, "matching the performance of a supervised ResNet-50"; fine-tuned on 1% of the labels it reaches 85.8% top-5 (Table 6 and abstract).

Correction
SimCLR's often-quoted 76.5% is for ResNet-50 (4×), a network with four times the width; the plain ResNet-50 gets 69.3%. And the 1%-label result, 85.8%, is top-5 accuracy, not top-1.

MoCo: negatives from a queue

MoCo (He et al. 2019) encodes the query view with the trained encoder and the key view with a second encoder whose weights are a moving average of the first, θk ← mθk + (1 − m)θq. Each batch's keys join a queue of K = 65,536 and the oldest leave, so the negatives are many and, because the key encoder changes slowly, consistent with each other: a large momentum (m = 0.999) "works much better than a smaller value". τ = 0.07. The number of negatives no longer depends on the batch.

The six designs side by side

DesignSecond branchWhat stops collapseNumbers that define it
SimCLRsame weightsnegatives: the other 2(N − 1) views in the batchbatch 4,096; τ = 0.1; nonlinear projection head
MoComomentum (EMA) encoder for the keysnegatives from a queue of past keysK = 65,536 keys; m = 0.999; τ = 0.07
BYOLEMA target networka predictor on the online side plus the slow targetEMA rate from 0.996 to 1, cosine schedule
SimSiamsame weights, stop-gradientstop-gradient plus predictorno EMA; works from batch 64 to 4,096
DINOEMA teachercentering and sharpening of the teacher's softmaxteacher τ 0.04 to 0.07, student 0.1; centre momentum 0.9
VICRegsame weights, both traineda variance hinge per dimension over the batchλ = μ = 25, ν = 1; γ = 1

Alignment and uniformity: what the loss actually builds

Wang and Isola (2020) split what InfoNCE optimises on the unit hypersphere into two measurable properties, and show that as the number of negatives grows the loss optimises exactly these two:

ℒalign = E(x, y) positive ‖f(x) − f(y)‖2     ℒuniform = log Ex, y e−2‖f(x) − f(y)‖2
align
positives should land close: lower is better, 0 when the two views coincide
uniform
all embeddings should spread over the sphere: lower is better; 0 when every point is the same (the exponent is then 0 for every pair)
α, t
the exponents 2 and 2 are the paper's defaults (lalign(x, y, alpha=2), lunif(x, t=2))

The numerator of InfoNCE rewards alignment and the denominator rewards uniformity, and "directly optimizing for these two metrics leads to comparable or better performance than contrastive learning" (abstract). Seen this way, collapse is not mysterious: alignment alone is minimised perfectly by mapping everything to one point, and only the uniformity half stops it.

Predict: both runs in Fig. 4 start from the same weights and both pull two views of a digit together; only the left also pushes the negatives away. Which one shrinks towards a point first?

  1. Random initialisation. The untrained encoder already puts every digit on the sphere, but two augmented views of the same digit land far apart (alignment 0.93) and the points are bunched (uniformity -0.74). Both runs start from the same weights.
  2. Alignment wins first, on both sides. Pulling the two views together is the easy direction, and within a few dozen steps both runs shrink towards a point: by step 29 the left run's uniformity is -0.03, close to the 0 of a single point. Here InfoNCE collapses too, briefly.
  3. The negatives push back. Once every digit sits close to every other, each negative carries a large share of the softmax, so InfoNCE's push apart dominates and the left run re-expands (uniformity -1.54 by step 293). Nothing pushes on the right.
  4. Uniformity separates them. The left spreads over the sphere, uniformity -1.96 against −2.08 for a perfectly even sphere, with digits of a class gathering (labelled where they do; 5-NN accuracy 74.5%) although no label was used. The right has collapsed: alignment 0.00, uniformity 0.00, 5-NN 16.5% against a chance of 10%: perfect alignment, and useless.

Real hand-written digits (scikit-learn's 1,797 8 × 8 images, UCI) through an encoder with a 3-D output, so every image is a point on the unit sphere; colour is the digit, never seen by training. MLP 64-256-256-3, Adam (learning rate 10−3), 3,000 steps of 256 images, two views each (shift up to 2 pixels, 25% of pixels dropped, contrast jitter, noise); measured on 200 held-out digits; three seeds, seed 0 shown (src/train_toy.py sphere3, about a minute on two CPU threads). The "perfectly even sphere" uniformity is log((1 − e−8)/8) = −2.08 derived, since ‖u − v‖2 = 2 − 2 cos θ and cos θ is uniform on [−1, 1] over the sphere. A 3-D output is far too small for real use: at τ = 0.5 the trained sphere's 5-NN accuracy is 74.5 to 80.5% over three seeds, against 90% for the raw pixels toy (an earlier 2-D version of this toy, on a circle, reached about 50%); it is drawn because a sphere can be seen.

Two refinements matter in practice. Dimensional collapse: even with negatives, embeddings can end up spanning a lower-dimensional subspace than they have room for (Jing et al. 2021: "dimensional collapse also happens in contrastive learning"), which is why the collapse lab below reports an effective rank beside the std. Pretrained language-model embeddings are anisotropic: they occupy "a narrow cone in the vector space", so that in GPT-2's last layer "two random words will on average have almost perfect cosine similarity" (Ethayarajh 2019). That is a uniformity failure, and the hero batch shows it: random pairs of STS-B sentences have a mean cosine of 0.62 under BERT and 0.32 after SimCSE, while SimCSE's alignment is slightly worse (0.25 against 0.17), exactly SimCSE's own reading: "pre-trained embeddings have good alignment, their uniformity is poor" (§7, Figure 3). It also means a cosine threshold only means something for the model it was tuned on. The same narrow cone is why BERTScore offers a rescaled score (Evaluation metrics).

Without negatives: collapse and the defences against it

Negatives are expensive (big batches, queues) and some are false. Remove them and "two views of an input should have the same embedding" has a perfect and useless solution: a constant. Every method without negatives is a different way to make that solution unreachable or unstable, and the loss will not warn you: a collapsed SimSiam or VICReg run has an excellent loss. Watch the embedding std instead: the standard deviation of the l2-normalised output, about 1/√d when spread out and 0 when collapsed (SimSiam's monitor).

Predict: SimSiam with and without one detach(), everything else identical. Does the run without it lose by a little or by everything? The lab opens at the end of training (step 3,000); drag the scrubber back to watch it happen, then try the DINO pairs: two different ways to collapse.

Asymmetry: BYOL and SimSiam

BYOL (Grill et al. 2020) uses "two neural networks, referred to as online and target networks". The online network has an extra predictor MLP and is trained to predict the target network's projection of the other view; the target gets no gradient and is an exponential moving average of the online weights, with rate starting at τbase = 0.996 and increased to 1 on a cosine schedule (§3.3). "While state-of-the art methods rely on negative pairs, BYOL achieves a new state of the art without them": 74.3% ImageNet linear top-1 with a ResNet-50 and 79.6% with a larger ResNet.

SimSiam (Chen and He 2020) strips BYOL down: no moving average, one shared encoder, a predictor on one branch and a stop-gradient on the other. "A stop-gradient operation plays an essential role in preventing collapsing": removing it alone drops ImageNet accuracy to 0.1%, and removing the predictor also fails (§4.1, §4.2, Table 1a). The lab reproduces both failures at toy scale. Why asymmetry is enough is a dynamics question, not a property of the loss: the constant is still a minimum. Tian, Chen and Ganguli (2021) analyse "how multiple factors, like predictor networks, stop-gradients, exponential moving averages, and weight decay all come into play", and derive a predictor that can be set directly from the data's statistics (DirectPred).

SimSiam across batch sizes and epochs (published numbers)
SimSiam works from batch 64 to 4,096 (66.1% at 64, 68.1% at 256, 64.0% at 4,096; Table 2) and reaches 68.1% at 100 epochs, 71.3% at 800 (Table 4).
Correction
SimSiam's 71.3% ImageNet linear accuracy is its 800-epoch figure; at the 100 epochs most of its ablations use it is 68.1%.

Centering and sharpening: DINO

DINO (Caron et al. 2021) is self-distillation with no labels: a student matches the softmax output of a momentum teacher (momentum on a cosine schedule from 0.996 to 1) across different crops. Two operations on the teacher's output prevent collapse, and each alone causes a different one: "centering prevents one dimension to dominate but encourages collapse to the uniform distribution, while the sharpening has the opposite effect" (§3.1). Centering subtracts a running mean of the teacher's outputs; sharpening uses a low teacher temperature, warmed up from 0.04 to 0.07 over the first 30 epochs, against 0.1 for the student. The collapse measures are the teacher output's entropy (0 when one prototype wins, ln K when uniform) and its KL divergence from the student; in the lab, no centering drives the entropy to 0 and no sharpening to ln 32. With a ViT-B/8, DINO reaches 80.1% linear and 77.4% k-NN top-1 on ImageNet (Table 2).

DINO's centre momentum, DINOv2 and DINOv3 (depth)
A centre that updates too slowly (momentum 0.999) collapses; 0.9 gave the best k-NN accuracy in DINO's ablation (Appendix). DINOv2 (Oquab et al. 2023) scales DINO with data curation, "a small but diverse corpus of 142M images" (LVD-142M), and a ViT-g backbone of 1.1B parameters, reaching 86.5% linear top-1 on ImageNet-1k with frozen features (Table 4); it adds a masked-image objective (the iBOT loss: "We randomly mask some of the input patches given to the student, but not to the teacher"). Its features are the ones built to be used frozen with a linear probe, which made it a default frozen backbone for dense vision tasks. DINOv3 (Siméoni et al. 2025) trains "a DINO model with 7B parameters" on 1,689 million curated images (LVD-1689M) and adds Gram anchoring to stop dense feature maps degrading during long training. Distillation with temperature and soft targets in general is on Distillation and Small Language Models.

Statistics of the batch: Barlow Twins and VICReg

Barlow Twins (Zbontar et al. 2021) computes the cross-correlation matrix between the two views' embeddings over the batch and pushes it towards the identity: diagonal 1 (invariance), off-diagonal 0 (no redundancy between dimensions). VICReg (Bardes, Ponce and LeCun 2021) separates the jobs into three terms: invariance (mean squared distance between the views), variance (a hinge keeping each dimension's standard deviation over the batch above γ = 1) and covariance (off-diagonal covariances pushed to 0), weighted λ = μ = 25 and ν = 1. These use the batch as a statistic, not as negatives; the variance hinge alone is what blocks the constant, as the lab's VICReg pair shows. Collapse as one training failure among others is on the parent's When training goes wrong tab (Topic: ml-fundamentals).

Remove one defence and the embedding std falls to zero while the loss keeps improving

cosine 1 between class means (identical directions)cosine 0 or belowbars: std of each of the 16 output dimensions over the test digits
Embedding std through training, all eleven runs spread out: 1/√16 = 0.25; collapsed: 0; the selected pair drawn heavy

One small encoder (MLP 64-256-256-16) trained eleven ways on two augmented views of the same real digits, no labels; labels only measure. Seed 0 of three shown.

Final numbers over three seeds, and what the toy is not (reference)

The quoted toy numbers: the SimSiam run with stop-gradient ends with embedding std 0.24 and the run without it at 0.001; dropping VICReg's variance term collapses the run to a single point after a few hundred steps, in all three seeds; raw pixels give a 90% 5-NN accuracy and the untrained encoder 82%.

One real photograph: MAE predicts pixels, I-JEPA predicts representations

Scikit-image's "chelsea" photograph at 224 × 224. Model: facebook/vit-mae-base (encoder 12 layers of width 768; decoder 8 layers of width 512; its config sets norm_pix_loss to false, so it predicts plain normalised pixels), run offline with a fixed random mask (src/real_mae.py). The losses at 50%, 75% and 90% hidden are : harder as more is hidden, but the picture stays recognisable at 75%. No I-JEPA model is run (its predictions are vectors, with no picture to show); its blocks follow the paper's sampling: 4 target blocks with scale 0.15 to 0.2 and aspect ratio 0.75 to 1.5, one context block with scale 0.85 to 1.0 and unit aspect ratio, targets removed from it (§3); seeded draw in src/mk_data.py.

Masked modelling, and prediction in representation space

The other road needs no pairs at all: hide part of the input and predict it. A constant output cannot win, because the target is the data. BERT did this for text, masking 15% of tokens (BERT paper page, which runs a toy BERT live). For images the question is what to predict: discrete visual tokens from a separately trained tokenizer (BEiT, Bao et al. 2021: "recover the original visual tokens based on the corrupted image patches"); pixels (MAE, He et al. 2021; SimMIM, Xie et al. 2021, which "predicts raw pixel values of the randomly masked patches by a lightweight one-layer head" with an l1 loss); or representations from a slowly updated copy of the encoder (data2vec, Baevski et al. 2022, one recipe for speech, text and images; I-JEPA, Assran et al. 2023).

MAE rests on two choices. It masks "a high proportion of the input image, e.g., 75%", because images are redundant enough that a lower ratio is solved by interpolation (BERT's "typical masking ratio is 15%", §4.1); and its encoder "operates only on the visible subset of patches (without mask tokens), along with a lightweight decoder", so pretraining runs "3x or more" faster. The loss is the mean squared error on masked patches only, and predicting each patch's pixels normalised by that patch's own mean and variance "improves representation quality" (§3). A ViT-Huge pretrained this way reaches 87.8% on ImageNet-1K after fine-tuning; that headline is fine-tuned, and MAE features are not the ones to use frozen. I-JEPA keeps the masking but changes the target: predict the representations of several large target blocks from one context block, so the model is never asked for texture it cannot know. It trains a ViT-H/14 "using 16 A100 GPUs in under 72 hours", under 1,200 GPU hours and "over 10x more efficient than a ViT-H/14 pretrained with MAE".

Predict: at 75% hidden, will the released MAE checkpoint's reconstruction of a real photograph still be recognisable? Watch, then switch to 90% and to I-JEPA.

  1. One image, 196 patches. A 224 × 224 photograph cut into a 14 × 14 grid of 16 × 16 patches, as ViT-Base/16 does: 196 tokens of 16 × 16 × 3 = 768 numbers each.
  2. Hide 75% at random. 147 of 196 patches are hidden, uniformly at random. BERT hides 15% of words; an image is so redundant that hiding 15% leaves a task solved by copying neighbours, which is why MAE hides 75%.
  3. The encoder sees only what is left. Only the 49 visible patches enter the 12-layer encoder (width 768), with no mask tokens at all. Its token count falls to 25% and attention, which grows with the square, to 6%: this is where MAE's speed-up comes from.
  4. A light decoder fills the gaps. The decoder gets the encoded visible patches plus one shared, learned mask token at each hidden position (with position embeddings). It is small, 8 layers of width 512, and it is thrown away after pretraining.
  5. It predicts pixels. The released ViT-MAE-Base checkpoint's real output: hidden patches filled with its predictions, visible ones pasted back. Blurry, because the mean squared error rewards the average of every plausible patch.
  6. Loss on hidden patches only. Mean squared error over the hidden patches only, in ImageNet-normalised pixel units (this checkpoint was trained without the per-patch normalisation the paper prefers): 0.1025 for this image. The visible patches are not scored.

The split today is less "contrastive or not" than joint-embedding methods (contrastive, self-distillation, JEPA, which compare or predict embeddings) against masked generative methods (MAE, which reconstruct the input), with prediction in latent space favoured when the goal is semantic features. The camps meet in practice: DINOv2 adds a masked-image term to self-distillation, and I-JEPA borrows MAE's masking and BYOL's moving-average target. Patches and why ViT became the backbone for all of this are on the ViT paper page.

V-JEPA, V-JEPA 2 and where JEPA came from (depth)
V-JEPA (Bardes et al. 2024) applies the idea to video, "trained on 2 million videos collected from public datasets" with no pretrained image encoder, text, negatives or reconstruction. V-JEPA 2 (Assran et al. 2025) pretrains on "over 1 million hours of internet video" with encoders up to 1 billion parameters, then adds V-JEPA 2-AC, "a latent action-conditioned world model" trained on "less than 62 hours of unlabeled robot videos", deployed zero-shot on Franka robot arms. (The old page said V-JEPA 2 "extends to video"; V-JEPA was already a video model, and V-JEPA 2 adds scale and action conditioning.) The 2026 step drops the slow teacher: LeWM (Maes et al. 2026, NeurIPS 2026) trains a 15M-parameter JEPA world model end to end from pixels with no moving-average teacher and no pretrained encoder, using two losses: prediction in embedding space and SIGReg, the regulariser from LeJEPA (Balestriero and LeCun) that keeps the embeddings from collapsing; it plans Push-T well over short horizons (Model-based RL and planning, sections 11 and 13). The joint-embedding predictive architecture was proposed by Yann LeCun in "A Path Towards Autonomous Machine Intelligence" (version 0.9.2, 27 June 2022, as I-JEPA cites it; the page itself could not be fetched here) as a route to world models.

CLIP and embedding models: the same loss, and the objective makes the model

CLIP (Radford et al. 2021) is InfoNCE across modalities: an image encoder and a text encoder, a batch of 32,768 image-caption pairs, and the loss run in both directions (image picks its caption from the batch, caption picks its image; tick "Symmetric loss" on the InfoNCE lab to see it on real cosines). The temperature is learned, starting from 0.07 with the logit scale capped at 100. Writing the classes as text then gives zero-shot classification. CLIP as the vision encoder of multimodal models, beside SigLIP and plain ViT, is on Vision encoders: ViT, CLIP and SigLIP; a trained toy CLIP and its successors are on the CLIP paper page.

What the objective forces the model to output decides the architecture. A contrastive objective wants one vector per input, compared with other vectors; nothing is generated token by token, so an encoder suffices, which is why CLIP's towers, sentence embedders (SBERT, SimCSE, retrieval models) and reranker backbones are encoders. Next-token prediction must emit sequences and needs a decoder, and its representations are shaped for predicting the next token, not for comparison. BERT sits between: an encoder trained with a generative-style objective (masked tokens), whose raw embeddings are poor for similarity until contrastively fine-tuned. That last step is measurable.

SimCSE (Gao, Yao and Chen 2021) needs no labels: "we pass the same sentence to the pre-trained encoder twice: by applying the standard dropout twice, we can obtain two different embeddings as 'positive pairs'", with in-batch negatives, τ = 0.05 and batch 64. On the STS benchmark test set, the Spearman correlation between cosine and human similarity rises from 53.87 (BERT, Table 5) to 76.85, and the 7-task average reaches 76.3, 81.6 with supervised NLI pairs. This page recomputes both from the released checkpoints:

Spearman (× 100) between cosine and the human score over all 1,379 test pairs; alignment over pairs scored 4 or more; uniformity and mean cosine over random pairs of test sentences. Recomputed: unsup-SimCSE 76.84 against the paper's 76.85; BERT "embedding + last avg" 53.87, matching SimCSE's own Table 5 baseline, and BERT "first-last avg" 59.04, matching Su et al.'s figure (SimCSE Table B.2). The two baselines share the name "first-last avg." in the literature but average different layers: Su et al. the first and last transformer layers, SimCSE's Table 5 the embedding layer and the last one our finding; pooling details move results by several points. SimCSE's unsupervised model is read at the last layer's [CLS] vector without its training-time MLP, as the authors' repository does.

In 2026 contrastive training is the standard post-training recipe for embedding and retrieval models, applied to an encoder and, increasingly, to a decoder-only LLM with pooling: decoder LLMs are contrastively adapted precisely because next-token pretraining alone does not give a well-shaped similarity space. On the text side the same loss trains retrieval embedders on query-document pairs: Embedding models (a child of Topic: rag-and-retrieval) applies it to SciFact with mined hard negatives, a tiny fine-tune and model choice.

How the embedding recipes pool, and BERT-flow (per-model table)
ModelBackbonePoolingTraining signal
SBERT (2019)BERT, RoBERTa (encoder)mean of token vectors ("The default configuration is MEAN")siamese and triplet networks on NLI and STS
SimCSE (2021)BERT, RoBERTa[CLS]; unsupervised models drop the training-time MLP at testdropout views (unsupervised) or NLI entailment pairs
E5 (2022)encoderaverage pooling over the output layercontrastive pretraining on web text pairs (CCPairs), then fine-tuning
E5-Mistral (Dec 2023)Mistral-7B, decoder-onlythe last layer's vector at an appended [EOS] tokensynthetic data from proprietary LLMs in 93 languages
NV-Embed (2024)Mistral-7B, causal mask removed during contrastive traininga latent attention layer, which beat mean and last-token poolingtwo-stage contrastive instruction tuning
Qwen3-Embedding (2025)Qwen3, causal attention keptthe last layer's hidden state at an appended [EOS] tokenmulti-stage training with synthetic data generated by Qwen3
Correction to the old page
The old page listed "Qwen-Embedding"; the model is Qwen3-Embedding (2025). Unlike NV-Embed it keeps the causal attention mask and pools the [EOS] token's last hidden state.

Before contrastive training, post-processing was the fix on offer: BERT-flow maps the "non-smooth anisotropic semantic space of sentences" to an isotropic one with a normalising flow (Li et al. 2020).

Depth

Family tree: every method on one time axis (lineage)

First arXiv (or conference) dates; colour is the family from the table at the top. Click a family to dim the others.

Common mistakes (each shown in the core above; collected)
  • Comparing InfoNCE losses across batch sizes: chance is ln N; compare ln N − L or a downstream probe.
  • Using the projection head's output downstream: SimCLR's z is over 10% worse than h on linear evaluation (§4.2); SimCSE drops its training-time MLP too.
  • Trusting the loss to detect collapse: monitor the normalised embedding's std (about 1/√d when healthy) and an effective rank.
  • Treating every in-batch item as a true negative: duplicates, paraphrases and same-class items are pushed apart too.
  • Comparing cosine scores across embedding models: random sentences score about 0.62 under raw BERT and 0.32 after SimCSE.
  • Calling "first-last avg." one thing: 59.04 and 53.87 are two different poolings under one name.
  • Expecting MAE features to work frozen: its 87.8% is after fine-tuning; DINOv2's features are the frozen ones.
  • Mining only the hardest triplets: FaceNet reports a collapsed model, f(x) = 0; use semi-hard negatives.