Lecture 14 · Self-Supervised Learning II: Contrastive and Joint-Embedding Methods

Deep Unsupervised Learning · Lecture 14。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 7 · Thu 2/29/2024 · Self-Supervised Learning, second part (slides 86–186): Contrastive Predictive Coding (speech, ImageNet, natural language, reinforcement learning; CPCv2 and data-efficient recognition), instance discrimination (MoCo v1–v3, SimCLR, MoCo v2 vs SimCLR), BYOL and the batch-norm debate, DINO, iBOT, DINOv2, JEPA, I-JEPA, V-JEPA. Basis: The slides present each method through its paper’s figures. These notes derive the common core — InfoNCE as a classification problem and as a mutual-information bound — check it where the mutual information is known in closed form, run CPC on a toy speech world whose exact phoneme and speaker posteriors are computable, and train every image method of the slides on ShapeWorld with Lecture 13’s probe protocol, including the ablations that make methods without negatives collapse. Code: code/lecture14/ (4 scripts + joint_embedding.py, building on Lecture 13’s ssl_tools.py; PyTorch (CPU); 19 networks, cached; first runs from 4 minutes to about an hour per script on one core) Reading time: 3.5 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Write the InfoNCE loss, explain it as an NN-way classification, prove that it bounds mutual information from below and that the bound cannot exceed log⁡N\log N, and say what the critic’s form costs.
  2. Describe CPC (encoder, autoregressive context, bilinear predictions of the future) and explain why predicting in latent space avoids modelling irrelevant detail.
  3. Describe SimCLR and MoCo — augmentations, projection head, temperature, large batches vs a queue with a momentum encoder — and explain why the augmentations define what is learned.
  4. Explain why BYOL, SimSiam and DINO can work without negatives, what collapse is, and which ingredient prevents it in each method.
  5. Explain JEPA: predicting the representation of masked regions instead of their pixels.
  6. Compare all self-supervised families of Lectures 13–14 on one protocol.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 13 (pretext tasks, the probe protocol, ssl_tools.py)InfoNCE, CPC, SimCLR, MoCo, BYOL, SimSiam, DINO, I-JEPACLIP: contrastive learning across modalities (Lecture 15)
Lecture 1 (the “find my twin” puzzle: a first contrastive model)collapse diagnostics (effective rank)self-supervision for control (Lecture 15)
Lecture 9 (density-ratio estimation by classification)a toy speech world with exact HMM posteriors

0.3 Map

§1  from reconstruction to discrimination
§2  InfoNCE: a classification loss and a mutual-information bound        ← code 01, Parts 1-2
§3  Contrastive Predictive Coding                                         ← code 01, Part 3
§4  instance discrimination: SimCLR, MoCo -- augmentations and the head   ← code 02
§5  without negatives: BYOL, SimSiam, DINO, iBOT, DINOv2 -- and collapse  ← code 03
§6  predicting representations: JEPA, I-JEPA, V-JEPA                      ← code 04, Part 1
§7  the self-supervised leaderboard of Lectures 13-14                     ← code 04, Part 2
§8  summary   §9 pitfalls   §10 exercises   §11 further reading   §12 next lecture

0.4 Notation

ff an encoder, gg a projection head, z=g(f(x))z = g(f(x)); sim(u,v)=u⊤v/(∥u∥∥v∥)\mathrm{sim}(u, v) = u^\top v / (\lVert u\rVert\lVert v\rVert); τ\tau a temperature; NN the number of candidates in a contrastive classification (one positive, N−1N - 1 negatives); I(X;Y)I(X; Y) mutual information in nats (1 nat = 1.44 bits). “Views” are random augmentations of one image.

0.5 How the experiments are run

Image methods use Lecture 13’s protocol unchanged: the same 10,000 unlabeled training images, the same CNN encoder (128-dimensional per-panel read-out) or ViT, 3,000 steps each, and the same probes (left kind, size, top/bottom, same kind with 4,000 labels; left kind with 10 per class; fine-tuning on 10 per class). The default augmentation shifts the content of each panel independently by up to ±2 pixels and flips 3% of the pixels. Everything is seeded; reruns print identical numbers.


1. From reconstruction to discrimination

Lecture 13’s methods predict pixels. That has two costs. Pixels contain many details that are irrelevant for most downstream tasks (exact texture, noise), and a pixel loss must model all of them; and when several completions are plausible, a pixel loss produces their average (Lecture 13 §5: a blur). The slides’ CPC figure (from Alex Graves) makes the point: don’t predict xx directly. Instead, encode the data, and ask a much weaker question in representation space: which of these candidates is the right one?

That question is a classification, and classification is cheap: the network only needs features that tell the right candidate from the wrong ones. Whatever is needed to tell them apart is learned; everything else may be discarded. What counts as “the right candidate” is the design choice:

  • CPC: the future of a sequence, given its past (§3);
  • instance discrimination: another augmented view of the same image (§4);
  • CLIP: the caption of an image (Lecture 15).

2. InfoNCE: a classification loss and a mutual-information bound

2.1 The loss

Given a pair (x,y)(x, y) drawn from the joint p(x,y)p(x, y) and N−1N - 1 “negatives” y2,…,yNy_2, \ldots, y_N drawn from the marginal p(y)p(y), a critic f(x,y)f(x, y) scores every candidate, and the loss is the cross-entropy of picking the true one:

LNCE=−E[log⁡ef(x,y1)∑j=1Nef(x,yj)].\mathcal{L}_{\text{NCE}} = -E\Big[\log \frac{e^{f(x, y_1)}}{\sum_{j=1}^N e^{f(x, y_j)}}\Big].

The slides’ annotation: InfoNCE “can be viewed as categorical cross-entropy of classifying the positive sample correctly”. The Bayes-optimal classifier knows the posterior that candidate jj is the positive, which is proportional to the density ratio p(yj∣x)/p(yj)p(y_j \mid x)/p(y_j); so the optimal critic is f∗(x,y)=log⁡p(y∣x)−log⁡p(y)f^*(x, y) = \log p(y \mid x) - \log p(y) plus any function of xx alone (the same density-ratio-by-classification trick as the GAN discriminator of Lecture 9).

2.2 The bound and its cap

Define INCE=log⁡N−LNCEI_{\text{NCE}} = \log N - \mathcal{L}_{\text{NCE}}. Two facts (van den Oord et al., 2018; Poole et al., 2019):

  1. INCE≤I(X;Y)I_{\text{NCE}} \le I(X; Y) for every critic — a lower bound on mutual information, tight in the limit N→∞N \to \infty with the optimal critic.
  2. INCE≤log⁡NI_{\text{NCE}} \le \log N, because LNCE≥0\mathcal{L}_{\text{NCE}} \ge 0 (a probability is at most 1).

So maximizing InfoNCE maximizes a lower bound on mutual information, but the bound saturates at log⁡N\log N: with 256 candidates no more than 5.55 nats can ever be certified, however much information the two variables share. Alternatives such as NWJ / MINE (Nguyen, Wainwright & Jordan; Belghazi et al.) are not capped but have a variance that grows exponentially with the mutual information.

2.3 Checking the bound where the truth is known (script 01, Part 1)

For Gaussian pairs in dd = 8 dimensions, y=ρx+1−ρ2 ϵy = \rho x + \sqrt{1 - \rho^2}\,\epsilon, the mutual information is exactly −d2log⁡(1−ρ2)-\frac{d}{2}\log(1 - \rho^2) and the optimal critic is available in closed form. InfoNCE with the optimal critic (mean of 40 batches) and NWJ with its optimal critic:

true MI (nats)NN = 416642561024NWJ, NN = 256 (mean ± std per batch)
10.580.871.000.991.001.01 ± 0.08
20.971.511.841.931.982.02 ± 0.11
41.292.343.193.613.834.02 ± 0.13
81.392.754.085.306.348.14 ± 0.31
161.392.774.165.556.9316.60 ± 1.24
log⁡N\log N1.392.774.165.556.93

With 16 nats of mutual information, InfoNCE reads exactly log⁡N\log N at every NN: the bound is saturated. Even with a perfect critic, certifying II nats needs N≳eIN \gtrsim e^I candidates. NWJ gets the value right (16.60) but its spread across batches grows from 0.08 to 1.24 nats. That is why contrastive methods want many negatives — and why, as we will see, the number of negatives is not the whole story.

2.4 Learned critics (script 01, Part 2)

NN = 128 (log⁡N\log N = 4.85), 3,000 training batches:

true MIoptimal criticbilinear x⊤Wyx^\top W y (CPC)separable g(x)⊤h(y)g(x)^\top h(y) (SimCLR, CLIP)concatenation MLP([x,y])([x, y])
21.871.541.881.90
43.442.403.373.41
84.723.144.684.71

The separable critic — two encoders and a dot product, the form every image–image and image–text method uses because it scores all N2N^2 pairs with 2N2N encoder passes — matches the optimal critic. CPC’s bilinear critic falls short: for these Gaussians the optimal critic contains a term in ∥y∥2\lVert y\rVert^2 alone (Exercise 3), which no bilinear form can express. The concatenation critic is the most flexible and the most expensive (N2N^2 network evaluations).


3. Contrastive Predictive Coding

3.1 The model

CPC (van den Oord, Li & Vinyals, 2018) for a sequence x1,x2,…x_1, x_2, \ldots:

  • an encoder zt=genc(xt)z_t = g_{\text{enc}}(x_t) (a strided convolution on raw audio, a ResNet on image patches);
  • an autoregressive context ct=gar(z≤t)c_t = g_{\text{ar}}(z_{\le t}) (a GRU, or a masked convolution — “a PixelCNN” on the slides for images);
  • for each distance kk, a bilinear score zt+k⊤Wkctz_{t+k}^\top W_k c_t, trained with InfoNCE: the positive is the true zt+kz_{t+k}, negatives are other zz‘s from the batch.

It models the slowly varying, shared information between the context and the future — the phoneme being spoken, the speaker, the object in an image — and ignores the local noise that a pixel- or sample-level model would have to reproduce. The slides show it on speech (linear probes on ctc_t for phones and speakers), ImageNet (an image cut into a grid of overlapping patches; rows predicted from the rows above), natural language (sentence encoders) and reinforcement learning (as an auxiliary loss). CPCv2 (Hénaff et al., 2019) scaled it up (a larger ResNet, layer normalization instead of batch normalization, patch-level augmentations, predictions in all directions, negatives from other patches in the image and from other images) and showed data-efficient recognition: with few labels, a classifier on CPCv2 features beat supervised training from pixels.

3.2 Experiment: toy speech with exact posteriors (script 01, Part 3)

SpeechWorld: 10 speakers, 8 phonemes; a phoneme lasts 5 frames on average and moves to its “successor” 70% of the time it changes (the future is partly predictable); every frame is a 16-dimensional vector = phoneme mean + speaker offset + noise. The hidden state (speaker, phoneme) has 80 values, so the forward / forward–backward recursions give the exact posteriors — the best classifier that sees one frame, the frames up to tt, or the whole sequence. CPC (MLP encoder to 32 dims, GRU context of 64, predictions 1–4 steps ahead, 128 negatives), 3,000 steps of 64 fresh sequences:

features (one per frame)phoneme probespeaker probe
raw frame xtx_t (16-d)59.4%25.8%
untrained CPC: ztz_t54.9%24.3%
untrained CPC: ctc_t69.8%45.0%
CPC: ztz_t (32-d)59.0%25.9%
CPC: ctc_t (64-d)76.7%83.5%
EXACT from the frame alone59.7%—
EXACT from frames 1..t1..t (filtering)78.5%87.2%
EXACT from the whole sequence87.5%99.5%

InfoNCE saturates at log N; CPC features vs the exact HMM posteriors

The context ctc_t — which sees exactly what the filtering posterior sees, frames 1..t1..t — comes within 2 points of the best possible phoneme classifier and 4 points of the best speaker classifier, from a linear probe, with no labels in training. Yet CPC picks the true future frame among 129 candidates only 5% of the time (the frames are noisy): solving the pretext task well is not the point, its byproduct is. The per-frame code ztz_t is as good as the best single-frame classifier (59.0% vs 59.7%) — context is what the GRU adds — and even an untrained GRU helps (69.8%), simply by averaging frames.


4. Instance discrimination: SimCLR and MoCo

4.1 The methods

Instance discrimination treats every image as its own class (Wu et al., 2018): two augmented views of the same image should be close, views of different images far apart (“attract / repel” on the slides).

SimCLR (Chen et al., 2020): for a batch of NN images, make 2N2N views; encode with ff (a ResNet), project with a small MLP head gg, and apply InfoNCE over the batch — each view must find its partner among the other 2N−12N - 1 views (the NT-Xent loss, cosine similarity divided by a temperature τ\tau). Findings the slides list: the composition of augmentations matters most (random crop + color distortion above all); the projection head improves the representation below it, which is the one kept; large batches (4,096–8,192) and long training help; the temperature matters.

MoCo (He et al., 2019) decouples the number of negatives from the batch size: the negatives are a queue of the last KK keys (65,536), encoded by a momentum encoder whose weights are an exponential moving average of the online encoder (mm = 0.999). Why the momentum: the keys in the queue were produced over many steps; if the key encoder changed quickly, old and new keys would be inconsistent and the classification meaningless. MoCo v2 adopted SimCLR’s MLP head and augmentations and matched SimCLR with small batches; MoCo v3 moved to Vision Transformers and found training instabilities that freezing the random patch-projection layer fixed.

4.2 Batch size, temperature, a queue (script 02, Parts 1–2)

modelfinal loss (nats)cap log⁡(candidates)\log(\text{candidates})pretext accuracyeffective rankleft kindleft sizetop / bottomsame kindleft kind, 10 / class
SimCLR, batch 160.393.4396.3%29.299.8%99.9%93.8%56.8%82.7%
SimCLR, batch 641.034.8488.5%30.6100.0%100.0%81.4%56.8%88.3%
SimCLR, batch 2562.066.2466.8%33.4100.0%100.0%63.3%56.0%90.1%
SimCLR, 256, τ = 0.050.586.2477.4%35.6100.0%100.0%98.3%56.9%83.6%
SimCLR, 256, τ = 1.05.276.2458.1%25.399.5%99.5%68.7%57.8%79.9%
MoCo, batch 16, queue 4,0964.318.3293.8%18.098.1%97.5%85.0%57.6%75.4%

(Default τ = 0.2. Effective rank: exp⁡\exp of the entropy of the normalized singular values of the 128-d features.) Contrastive learning learns the shapes almost perfectly — 100% with 4,000 labels and 83–90% with 10 per class, far above Lecture 13’s DAEs and MAE (≤ 66%). Then:

  • Bigger batches give better few-label features (82.7% → 88.3% → 90.1%) — and discard more position (top/bottom 93.8% → 81.4% → 63.3%). With more negatives, the encoder is pushed harder to keep only what identifies an image across its views — and our views differ precisely in position.
  • Temperature: τ = 0.05 sharpens the softmax onto the hardest negatives and keeps position (98.3%); τ = 1.0 is too soft — the loss barely leaves its cap (5.27 of 6.24 nats) and features suffer.
  • MoCo’s queue did not substitute for a large batch here: 4,096 negatives with batch 16 gave 75.4% with 10 labels, below SimCLR at batch 256 (90.1%) and even at batch 16 (82.7%). Plan vs reality: we expected MoCo to match the large batch. Possible reasons: our toy has 10,000 images, so the queue holds 40% of the dataset, encoded by older networks; 3,000 small-batch steps may be too few for the momentum encoder.

4.3 Augmentations are the invariances; the head absorbs them (script 02, Parts 3–4)

SimCLR, batch 256pretext accuracyleft kindsizetop / bottomsame kind10 / class
shifts ±2 per panel + 3% flips (default)66.8%100.0%100.0%63.3%56.0%90.1%
flips only (no shifts)97.9%85.6%90.4%99.0%56.5%47.1%
shifts ±4 + flips57.3%100.0%99.7%64.6%58.7%88.5%
default + swap the panels half the time57.5%100.0%100.0%80.5%58.3%91.4%

Without shifts, matching two views is trivial (97.9%: compare pixels) and the kind is learned badly (47.1% with 10 labels) — the same lesson as Lecture 13’s shortcut: a too-easy pretext task teaches little. Every augmentation is an invariance we ask for: shifts make position disappear. But the panel swap — which should make “left” and “right” indistinguishable — left the left-kind probe at 100%. Where did the invariance go? Probing the head’s output instead of the encoder’s:

SimCLR, batch 256left kind: encoderheadtop/bottom: encoderheadsame kind: encoderhead
default augmentation100.0%100.0%63.3%50.4%56.0%87.8%
flips only85.6%39.9%99.0%82.3%56.5%60.3%
shifts ±4100.0%100.0%64.6%50.6%58.7%88.4%
default + panel swap100.0%80.9%80.5%62.6%58.3%97.9%

SimCLR: negatives and augmentations

The projection head absorbs the invariances: its output is exactly position-blind (50% = chance) and, with swaps, partly blind to which panel is which (80.9%), while the encoder below keeps both. The head also computes cross-panel features: “same kind” is 88–98% readable from the head (with swaps the head must represent the unordered pair of kinds) but only ~57% from the encoder. This is the mechanism behind SimCLR’s finding that the representation before the head is better: the loss’s invariances are enforced at the top, and the information they would destroy survives below.


5. Without negatives: BYOL, SimSiam, DINO

5.1 The methods and the collapse problem

Negatives are expensive (large batches or queues) and sometimes wrong (two images of the same kind are pushed apart). Can we only pull views together? The obvious problem: mapping every image to the same vector makes the views agree perfectly — collapse.

  • BYOL (Grill et al., 2020): an online network (encoder, projector, predictor) predicts the projection of the other view computed by a target network that is an exponential moving average of the online one, with a stop-gradient on the target; the loss is the squared error between normalized vectors (2−2cos⁡2 - 2\cos). Nothing in the loss forbids collapse; the dynamics avoid it. The slides cite a blog post (Fetterman & Albrecht, 2020) arguing that batch normalization in the heads is essential: it subtracts the batch mean, so the outputs implicitly compare each example with the others — a hidden contrastive term. (BYOL’s authors later showed it can work without batch statistics with careful normalization and initialization.)
  • SimSiam (Chen & He, 2021): BYOL without the moving average — the stop-gradient (with the predictor) is what matters.
  • DINO (Caron et al., 2021): self-distillation with no labels. Student and teacher (a moving average of the student) output a softmax over KK “prototypes”; the student matches the teacher’s distribution for another view (cross-entropy), with multi-crop (global views for the teacher, global and small local views for the student). Two forces prevent collapse: centering (subtract a running mean of the teacher’s logits — no prototype may win for every image) and sharpening (a low teacher temperature — targets must be confident). Each alone collapses: centering alone towards a uniform output, sharpening alone towards one prototype. Its ViT’s attention maps segment objects without supervision.
  • iBOT (Zhou et al., 2022) adds masked image modelling with the teacher as an online tokenizer (DINO on masked patches); DINOv2 (Oquab et al., 2023) scales DINO + iBOT to a curated dataset of 142M images and ViT-g, giving frozen features good for classification, retrieval, segmentation and depth.

5.2 Provoking collapse (script 03)

modelfinal lossencoder: eff. rankstdprojection: eff. rankleft kindtop / bottomleft kind, 10 / class
BYOL (predictor, stop-grad, EMA, BN)0.06218.00.02612.393.3%86.3%60.7%
BYOL without the predictor0.0069.40.0267.691.0%73.5%60.4%
BYOL without batch norm in the heads0.0024.60.0124.169.8%80.1%43.8%
SimSiam (no moving average)0.05010.00.0226.077.3%85.5%48.1%
SimSiam without the stop-gradient0.0003.70.0352.256.9%68.8%35.5%

(std: mean per-dimension spread of the L2-normalized features; isotropic 128-d features would give 0.088, a collapsed network 0.)

  • BYOL works without a single negative (93.3%, 60.7% with 10 labels).
  • Without batch norm in its heads, BYOL collapses (loss 0.002, rank 4.6, a probe of 69.8% — below an untrained encoder’s 77%): the blog post’s claim holds in our setting.
  • Without the stop-gradient, SimSiam collapses completely: loss 0.000, a projection of rank 2.2, 56.9% — Chen & He’s central finding.
  • Without the predictor, BYOL only half-collapses (projection rank 7.6, loss 0.006) and its encoder stays useful (91.0%) — batch norm alone keeps it alive here.
  • SimSiam without the moving average works but learns less in 3,000 steps (77.3%).

DINO:

modelfinal lossHH(mean pp)H(p)H(p)prototypes usedeff. rankleft kindleft kind, 10 / class
DINO (centering + sharpening, teacher τ 0.04)0.184.59 bits0.0734 of 6425.199.3%81.8%
without centering0.092.880.038 of 6422.095.5%65.0%
without sharpening (teacher τ 0.1)4.045.995.8313 of 649.784.8%60.7%

(HH(mean pp): entropy of the batch-averaged teacher distribution — 6 bits if the 64 prototypes are used evenly; H(p)H(p): average entropy of one image’s teacher distribution — 0 if confident.) DINO is the best method without negatives (99.3%, 81.8%), and the two collapse modes appear exactly as described: without centering the teacher concentrates on a few prototypes (8 used; the average distribution has 2.88 bits), without sharpening every image gets a nearly uniform distribution (5.83 of 6 bits). In both cases the encoder still carries information (85–96%) — collapse is rarely total below the heads — but much less of it with few labels.

Collapse vs feature quality


6. Predicting representations: JEPA

6.1 The idea

LeCun’s Joint-Embedding Predictive Architecture (2022): encode both the context and the target, and predict the target’s representation from the context’s — an energy-based view in which incompatible pairs get high energy, but without pixel reconstruction (MAE) and without hand-designed view augmentations (SimCLR, DINO). I-JEPA (Assran et al., 2023): a context encoder (ViT) sees a large block of the image; a target encoder — a moving average of the context encoder, as in BYOL — encodes the full image; a narrow predictor receives the context tokens plus mask tokens at the positions of several target blocks and predicts the target encoder’s tokens there. Target blocks are large (semantic) and the context excludes them. The slides visualize predictions by decoding them with a representation-conditioned diffusion model: they capture what is in a region, not its exact pixels. V-JEPA (Bardes et al., 2024) does the same in video with ~90% masking (short-range masks of 8 blocks covering ~15% of each frame each, long-range masks of 2 blocks covering ~70%), trained on ~2 million public videos; the slides report it beats pixel-prediction methods when the encoder is frozen and needs shorter training.

6.2 Experiment: I-JEPA vs MAE (script 04, Part 1)

The same ViT as Lecture 13’s MAE (context encoder = MAE’s encoder without a decoder), a moving-average target encoder (momentum 0.996), a 2-block predictor of width 32; two random target blocks of 2 × 2 patches per image (up to 8 of the 32 patches), the context = all other patches; 3,000 steps. The training loss (MSE between predicted and layer-normalized target tokens) went 0.324 → 0.172.

representationleft kindsizetop / bottomsame kind10 / classeff. rankfine-tune, 10 / class
random ViT / ViT from scratch76.4%86.2%92.0%59.0%30.4%25.761.1%
MAE, 15% masked (Lecture 13)92.3%95.2%98.5%59.9%59.3%67.468.8%
MAE, 50% masked95.1%97.1%99.6%54.2%66.2%63.673.5%
MAE, 75% masked94.4%93.7%98.2%59.8%66.4%55.774.6%
I-JEPA89.8%91.8%96.7%71.0%55.7%67.367.0%

Plan vs reality. The slides’ claim — feature prediction beats pixel prediction when the encoder is frozen — is not reproduced here: I-JEPA’s frozen features are below every MAE on the kind (89.8% vs 92–95%; 55.7% vs 59–66% with 10 labels) and so is its fine-tuning (67.0% vs 69–75%). What it does learn better than any MAE except the 90% one is the relation between the panels (“same kind” 71.0% vs 54–60%): predicting the target encoder’s tokens for a hidden block of one panel rewards knowing what the other panel implies. Our images are tiny and nearly noise-free, so the advantage JEPA is designed for — not having to model unpredictable pixel detail — has little to work on; a pixel loss on 3 × 3 binary patches is already almost semantic.


7. The self-supervised leaderboard of Lectures 13–14 (script 04, Part 2)

All self-supervised families of Lectures 13–14 on one protocol (for Lecture 13, the best variant of each family as in its leaderboard), with the generative models of earlier lectures and the baselines:

familyrepresentationleft kindsizetop / bottomsame kind10 / class (frozen)fine-tune, 10 / class
baselineraw pixels64.6%78.0%99.4%50.6%42.2%—
baselinerandom CNN / CNN from scratch77.0%81.0%91.6%53.8%42.5%52.5%
generativeVAE encoder mean (Lecture 7)80.8%68.0%99.8%55.6%58.1%—
generativediffusion U-Net, tt = 0.2 (Lecture 11)99.6%99.8%92.8%66.5%81.2%—
reconstructDAE, masking 50%, corrupted-only loss86.5%95.8%99.3%57.1%45.9%48.4%
reconstructMAE 50%95.1%97.1%99.6%54.2%66.2%73.5%
reconstructcontext encoder, right panel91.8%79.5%87.8%58.6%73.7%76.4%
reconstructcolorization, tied colors, L2100.0%95.0%90.8%56.9%92.7%75.4%
puzzlerotation86.2%75.0%90.3%54.4%53.6%72.6%
contrastiveSimCLR, batch 256100.0%100.0%63.3%56.0%90.1%76.5%
contrastiveMoCo, batch 16 + queue98.1%97.5%85.0%57.6%75.4%74.3%
no negativesBYOL93.3%82.8%86.3%57.4%60.7%63.1%
no negativesSimSiam77.3%76.1%85.5%57.1%48.1%52.5%
no negativesDINO99.3%99.5%92.5%55.9%81.8%63.0%
feature predictionI-JEPA89.8%91.8%96.7%71.0%55.7%67.0%

The self-supervised leaderboard of Lectures 13-14

What the table says:

  1. For the semantic target with few labels, the winners are methods whose pretext task needs the kind: colorization in a world where color depends on it (92.7%), and instance discrimination, whose views share the kind and differ in position (SimCLR 90.1%, DINO 81.8%); the diffusion model is close (81.2%).
  2. Invariance has a price. Contrastive methods discard position (SimCLR top/bottom 63.3%), reconstruction keeps it (MAE 99.6%). There is no universally best representation, only one that matches the downstream task — Lecture 15’s control task will make this concrete.
  3. Frozen and fine-tuned rankings differ. On 80 labeled images, fine-tuning from SimCLR, the context encoder, colorization, MAE or MoCo gives 73.5–76.5%; DINO and BYOL drop to 63% — below DINO’s frozen probe (81.8%). Fine-tuning can destroy what a frozen probe reads, and the slides’ papers report both protocols for a reason.
  4. The copy rule is hard for everyone: no representation makes “same kind” more than ~72% linearly readable — except a projection head (§4.3, up to 98%). Relations between parts are a separate thing to learn.

8. Summary

  1. InfoNCE is a classification of the true partner among NN candidates. It bounds mutual information from below and cannot exceed log⁡N\log N: with 16 nats of true information it read exactly log⁡N\log N at every NN from 4 to 1,024. NWJ is uncapped but noisy. A separable critic (two encoders + dot product) reached the optimal critic; CPC’s bilinear critic did not.
  2. CPC predicts the future in latent space; on toy speech its context vector reached 76.7% (phoneme) and 83.5% (speaker) under linear probes, against 78.5% and 87.2% for the exact filters — while solving its own task only 5% of the time.
  3. SimCLR learned the shapes almost perfectly (100%; 90.1% with 10 labels at batch 256). Bigger batches gave better few-label features and discarded more position; temperature trades the two; MoCo’s queue did not replace a large batch in our toy.
  4. Augmentations define the invariances, and the projection head absorbs them: its output was position-blind (50%) while the encoder below kept position, and the head computed cross-panel relations the encoder did not.
  5. Without negatives, BYOL (93.3%), SimSiam and DINO (99.3%, 81.8% with 10 labels) avoid collapse only through their ingredients: removing BYOL’s batch norm or SimSiam’s stop-gradient collapsed them (loss ≈ 0, rank 2–5, probes below an untrained encoder); DINO without centering used 8 of 64 prototypes, without sharpening gave near-uniform outputs.
  6. I-JEPA (prediction in representation space) did not beat MAE with frozen features on our tiny images, but learned the most relational ViT features.
  7. Across Lectures 13–14: methods win on the target their pretext task needs; frozen and fine-tuned evaluations rank them differently; invariance is both the source of good semantic features and a loss of information.

9. Common pitfalls

  1. Reading InfoNCE as a mutual-information estimate. It is a lower bound capped at log⁡N\log N; with 16 nats of true information and 256 candidates it reads 5.55. Compare models by downstream probes, not by their InfoNCE values.
  2. Too-easy views. If two views can be matched by comparing pixels (no shifts: 97.9% pretext accuracy), the encoder learns little (47.1% with 10 labels).
  3. Forgetting that augmentations remove information. Shifts made position unreadable from the head and much less readable from the encoder; a downstream task that needs position (Lecture 15’s control task) suffers.
  4. Probing the projection head. The head is where the invariances live; probe (and fine-tune) the encoder below it.
  5. Assuming more negatives always help. A queue of stale keys from a momentum encoder did not replace a large fresh batch in our toy (75.4% vs 90.1%).
  6. Removing a “small” ingredient of a non-contrastive method. Batch norm in BYOL’s heads, the stop-gradient in SimSiam, centering or sharpening in DINO: each removal collapsed the method or degraded it badly.
  7. Watching only the loss. A collapsed SimSiam has the best loss (0.000). Track the effective rank or the spread of normalized features during training.
  8. Judging a pretext task by its accuracy. CPC’s future-frame accuracy was 5%, yet its context features were near-optimal.

10. Exercises

Exercise 1 (the cap). Show that log⁡N−LNCE≤log⁡N\log N - \mathcal{L}_{\text{NCE}} \le \log N, and that with the optimal critic and N→∞N \to \infty it approaches I(X;Y)I(X; Y).

Answer

LNCE\mathcal{L}_{\text{NCE}} is an expected negative log-probability, so ≥0\ge 0. With f∗=log⁡p(y∣x)/p(y)f^* = \log p(y \mid x)/p(y): log⁡N−L=E[log⁡r(x,y1)1N∑jr(x,yj)]\log N - \mathcal{L} = E\big[\log \frac{r(x, y_1)}{\frac1N\sum_j r(x, y_j)}\big] with r=p(y∣x)/p(y)r = p(y \mid x)/p(y). As N→∞N \to \infty, 1N∑jr(x,yj)→1Nr(x,y1)+Ey∼p(y)[r(x,y)]→1\frac1N\sum_{j} r(x, y_j) \to \frac{1}{N} r(x, y_1) + E_{y \sim p(y)}[r(x, y)] \to 1 (the negatives’ average of a density ratio is 1), so the expression tends to E[log⁡r(x,y)]=I(X;Y)E[\log r(x, y)] = I(X; Y).

Exercise 2 (the bound — derivation). Show I(X;Y)≥log⁡N−LNCEI(X; Y) \ge \log N - \mathcal{L}_{\text{NCE}} for any critic. (Hint: the probability that a classifier identifies the positive among NN cannot exceed that of the Bayes-optimal one, and compare the Bayes-optimal classifier’s loss with log⁡N−I\log N - I.)

Answer

Let CC be the index of the positive (uniform on 1..N1..N) and S=(x,y1,…,yN)S = (x, y_1, \ldots, y_N) the shuffled candidates. Any critic defines a classifier q(C∣S)q(C \mid S), and its cross-entropy is at least the conditional entropy: LNCE≥H(C∣S)=log⁡N−I(C;S)\mathcal{L}_{\text{NCE}} \ge H(C \mid S) = \log N - I(C; S). Since SS reveals CC only through the pairing of xx with yCy_C, the data-processing inequality gives I(C;S)≤I(X;Y)I(C; S) \le I(X; Y) (Poole et al., 2019, give the full argument). Hence log⁡N−LNCE≤I(C;S)≤I(X;Y)\log N - \mathcal{L}_{\text{NCE}} \le I(C; S) \le I(X; Y).

Exercise 3 (why the bilinear critic falls short). For the Gaussian pair, expand f∗(x,y)=log⁡p(y∣x)−log⁡p(y)f^*(x, y) = \log p(y \mid x) - \log p(y). Which term can a bilinear critic x⊤Wyx^\top W y not express, and why does it matter for InfoNCE?

Answer

With s2=1−ρ2s^2 = 1 - \rho^2: f∗=ρs2x⊤y−ρ22s2∥y∥2+c(x)f^* = \frac{\rho}{s^2}x^\top y - \frac{\rho^2}{2s^2}\lVert y\rVert^2 + c(x). Terms in xx alone cancel in the softmax over candidates yjy_j, but the term in ∥yj∥2\lVert y_j\rVert^2 does not: it down-weights candidates far from the origin. A bilinear critic sets it to zero and loses classification accuracy — 3.14 vs 4.72 nats at 8 nats of MI in script 01. A separable critic g(x)⊤h(y)g(x)^\top h(y) can include ∥y∥2\lVert y\rVert^2 as a coordinate of hh with a constant coordinate in gg, and matches the optimum.

Exercise 4 (temperature and hard negatives — derivation). For one anchor with similarities sjs_j to the candidates (positive j=1j = 1), compute the gradient of −log⁡es1/τ∑jesj/τ-\log\frac{e^{s_1/\tau}}{\sum_j e^{s_j/\tau}} with respect to each negative’s sjs_j, and explain what a small τ\tau does.

Answer

∂L/∂sj=1τ softmaxj(s/τ)\partial \mathcal{L}/\partial s_j = \frac{1}{\tau}\,\mathrm{softmax}_j(s/\tau) for j≠1j \ne 1 (and −1τ(1−softmax1)-\frac{1}{\tau}(1 - \mathrm{softmax}_1) for the positive). Each negative is pushed away in proportion to its softmax weight; small τ\tau concentrates that weight on the hardest (most similar) negatives. In script 02, τ = 0.05 kept position information (98.3%): the hardest negatives are images that differ only in position, so position became worth keeping. Too large a τ (1.0) treats all negatives alike and the loss hardly moves.

Exercise 5 (why a momentum encoder). In MoCo the keys in the queue were computed by the key encoder at earlier steps. What goes wrong if the key encoder is simply the current online encoder (no momentum)?

Answer

The queue then mixes keys produced by many different encoders: recent keys live in the current embedding space, old ones in spaces the network has since moved away from. The query can tell the positive apart from stale negatives by their “age” rather than their content — a shortcut — and the loss stops measuring similarity. He et al. report that training fails without momentum (or with too small a momentum); a slowly moving average keeps all keys in the queue nearly consistent.

Exercise 6 (collapse is a minimum). Show that for BYOL’s loss 2−2cos⁡(pθ(z1),zˉ2)2 - 2\cos(p_\theta(z_1), \bar z_2), any network whose projection is a constant vector cc and whose predictor maps cc to a multiple of cc reaches the global minimum 0. What prevents gradient descent from going there?

Answer

If every image gives z=cz = c and p(c)=λcp(c) = \lambda c with λ>0\lambda > 0, then cos⁡(p(z1),zˉ2)=cos⁡(λc,c)=1\cos(p(z_1), \bar z_2) = \cos(\lambda c, c) = 1 and the loss is 0, its minimum. Nothing in the loss excludes this; the dynamics do: with the stop-gradient the target is a fixed regression target at each step, the predictor tracks it, and (Tian et al., 2021) the combined dynamics of predictor and online network preserve the dominant eigen-directions of the feature covariance instead of shrinking them. Batch norm additionally makes a constant output impossible for its layer. Remove the stop-gradient and the loss gradient also moves the target towards the prediction: both meet at a constant (script 03: loss 0.000, rank 2.2).

Exercise 7 (DINO’s two collapses). With teacher logits tt, center cc and temperature τt\tau_t, the target is softmax((t−c)/τt)\mathrm{softmax}((t - c)/\tau_t). Argue that centering alone drives targets towards uniform and sharpening alone towards a single prototype for every image.

Answer

Centering subtracts the running mean of the logits: a prototype that scores high for every image gets its advantage removed, so no prototype can dominate across images — but nothing prevents all logits from becoming equal, and an equal-logit target is uniform (high H(p)H(p)). Sharpening (small τt\tau_t) turns any logit difference into a near one-hot target; if the network gives the same top prototype to every image, the student matches it trivially (low H(mean p)H(\text{mean } p)). With both, the only way to have confident targets that are spread over prototypes is to give different images different prototypes. Script 03: no centering → 8 prototypes used, H(mean p)H(\text{mean}\,p) = 2.88; no sharpening → H(p)H(p) = 5.83 of 6 bits.

Exercise 8 (CPC and the filter). Why should a linear probe on CPC’s ctc_t be compared with the filtering posterior and not with the smoothing one?

Answer

ct=gar(z≤t)c_t = g_{\text{ar}}(z_{\le t}) is a function of frames 1..t1..t only; no function of the past can beat the Bayes-optimal classifier given the past, which is the filtering posterior p(phonemet∣x1..t)p(\text{phoneme}_t \mid x_{1..t}) (78.5%). The smoothing posterior also uses future frames (87.5%) and is out of reach for any causal representation. CPC’s 76.7% is therefore 98% of what is achievable with its inputs.

Exercise 9 (coding). In script 02, add a “color” augmentation on Lecture 13’s colored ShapeWorld (re-draw each panel’s palette color). Predict which probe (a color probe vs the kind probe) changes, then check.

Answer

(Run it.) With color re-drawn between views, color carries no information about which views belong together, so the contrastive head becomes color-blind; following §4.3, the encoder may keep some color information below the head. SimCLR’s paper found color distortion to be one of the two most important augmentations on ImageNet precisely because color histograms otherwise give a shortcut for matching crops.


11. Further reading

From the slides

  • A. van den Oord, Y. Li, O. Vinyals. Representation Learning with Contrastive Predictive Coding, 2018; O. Hénaff et al. Data-Efficient Image Recognition with Contrastive Predictive Coding (CPCv2), ICML 2020.
  • K. He et al. Momentum Contrast for Unsupervised Visual Representation Learning (MoCo), CVPR 2020; X. Chen et al. Improved Baselines with Momentum Contrastive Learning (MoCo v2), 2020; X. Chen, S. Xie, K. He. An Empirical Study of Training Self-Supervised Vision Transformers (MoCo v3), ICCV 2021.
  • T. Chen et al. A Simple Framework for Contrastive Learning of Visual Representations (SimCLR), ICML 2020.
  • J.-B. Grill et al. Bootstrap Your Own Latent (BYOL), NeurIPS 2020; A. Fetterman, J. Albrecht. Understanding Self-Supervised and Contrastive Learning with “Bootstrap Your Own Latent”, blog post, 2020.
  • M. Caron et al. Emerging Properties in Self-Supervised Vision Transformers (DINO), ICCV 2021; J. Zhou et al. iBOT, ICLR 2022; M. Oquab et al. DINOv2, 2023.
  • Y. LeCun. A Path Towards Autonomous Machine Intelligence, 2022; M. Assran et al. Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture (I-JEPA), CVPR 2023; A. Bardes et al. Revisiting Feature Prediction for Learning Visual Representations from Video (V-JEPA), 2024.

Added by these notes

  • B. Poole et al. On Variational Bounds of Mutual Information, ICML 2019.
  • Z. Wu et al. Unsupervised Feature Learning via Non-Parametric Instance Discrimination, CVPR 2018.
  • X. Chen, K. He. Exploring Simple Siamese Representation Learning (SimSiam), CVPR 2021; Y. Tian, X. Chen, S. Ganguli. Understanding Self-Supervised Learning Dynamics without Contrastive Pairs, ICML 2021.
  • T. Wang, P. Isola. Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere, ICML 2020.

12. Next lecture

Lecture 15 takes contrastive learning across modalities: CLIP pairs images with their captions (on ShapeWorld we can check zero-shot classification and retrieval against perfect captions), SigLIP replaces the softmax by sigmoids, LiT locks a pretrained image tower. Then self-supervision for control (R3M, MVP, CURL), where the invariances learned here turn out to be a liability — and language: word2vec as implicit matrix factorization, BERT against the exact optimal masked-word predictor, and what causal and bidirectional objectives put into a sentence vector.

← 返回课程目录