Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Remember past examples as negatives
Contrastive learning works best with many negatives, but big batches need big computers. MoCo keeps a rolling memory (a queue) of codes from recent batches and uses them as extra negatives. There is a catch: the network keeps changing, so codes computed a few steps ago may no longer be comparable. MoCo fixes this by computing the remembered codes with a slowly changing copy of the network, the momentum encoder. The demo shows how the contrastive softmax depends on the temperature and on the negatives.
MoCo-style training gets strong self-supervised features on modest hardware, which suits teams pre-training on their own unlabelled sensor data.
- 1. MoCo stores past codes in…
- 2. The momentum encoder changes…
- 3. MoCo avoids needing…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Query and key: q = f_q(x₁) from the trained encoder; k = f_k(x₂) from the momentum encoder (no gradient).
- Momentum update: θ_k ← m θ_k + (1 − m) θ_q with m = 0.999 (0.99 here).
- From θ_k = 1 and θ_q = 0, one step gives 0.99 with m = 0.99.
- The half-life is ln 0.5/ln m: about 69 steps for m = 0.99 and 693 for m = 0.999.
- Loss: InfoNCE over [q·k₊, q·queue] / τ with τ = 0.07. After each step, the new keys are enqueued and the oldest dropped.
- Queue size: MoCo’s 65,536 keys span the last 256 batches of 256.
- False negatives: with C balanced classes, a fraction 1/C of random negatives share the anchor’s class (10% for 10 classes).
- 1. Key-encoder value after one update from 1 toward 0 with m = 0.99:
- 2. Batches held by a 65,536-key queue with batch 256:
- 3. Does the key encoder receive gradients?
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.MoCo in code
Exercise 1.
- The momentum update and the queue (newest keys first, oldest dropped) were implemented.
- MoCo’s logits put the positive in column 0.
Practice.
- Use the official MoCo implementations or
lightly,solo-learnorVISSL. MoCo v2 settings: MLP head, blur augmentation, cosine schedule, m = 0.999, τ = 0.2, queue 65,536. - Shuffle batch norm across GPUs, so queries and keys do not leak batch statistics.
- MoCo v3 (ViT): no queue, batch 4096, symmetric loss; freezing the patch-embedding layer stabilises training.
q = F.normalize(proj_q(enc_q(x1)), dim=1)
with torch.no_grad():
momentum_update(enc_k, enc_q, m=0.999)
k = F.normalize(proj_k(enc_k(x2)), dim=1)
logits = torch.cat([(q * k).sum(1, keepdim=True), q @ queue.T], 1) / tau
loss = F.cross_entropy(logits, torch.zeros(len(q), dtype=torch.long))
queue = torch.cat([k, queue])[:K] # enqueue newest, drop oldest- 1. Shuffled batch norm prevents…
- 2. MoCo v3 for ViTs uses…
- 3. MoCo v2 added…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Why momentum.
- Queued keys were computed by past versions of the key encoder. If it changes quickly (m = 0, a copy of the query encoder), keys from different steps live in inconsistent embedding spaces.
- The query can then tell queued keys from the current positive by their age rather than their content, a shortcut that makes contrastive learning fail.
- A slow moving average keeps all keys in nearly the same space.
Decoupling negatives from batch size. The queue gives many negatives at the cost of a forward pass on the keys, with no gradient through them. That is cheaper than SimCLR’s huge batches.
When more negatives do not help. If the number of semantic classes is small, many negatives are false negatives (same class), and adding more increases the pressure to separate same-class images. The benefit of a large queue then levels off or reverses. It is largest on diverse data such as ImageNet.
- 1. Without momentum, queued keys are…
- 2. The failure exploits…
- 3. Large queues help most on…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.What do the queue and the momentum encoder each contribute?
History.
- K. He, H. Fan, Y. Wu, S. Xie and R. Girshick, “Momentum contrast for unsupervised visual representation learning” (CVPR 2020).
- X. Chen, H. Fan, R. Girshick and K. He, “Improved baselines with momentum contrastive learning” (MoCo v2, 2020).
- X. Chen, S. Xie and K. He, “An empirical study of training self-supervised Vision Transformers” (MoCo v3, ICCV 2021).
Exercise 2.
- Setup: the same style-dominated world, encoder and probe as the SimCLR page, with a small batch of 16 (τ = 0.1, 800 steps).
- Variants:
- in-batch negatives only (15 per query);
- a queue of 256 or 1024 past keys, with momentum m = 0.99;
- a 1024 queue without momentum (m = 0).
| variant | probe accuracy |
|---|---|
| raw observations | 0.522 |
| batch-only negatives, m = 0.99 | 0.742 |
| queue 256, m = 0.99 | 0.762 |
| queue 1024, m = 0.99 | 0.726 |
| queue 1024, no momentum | 0.184 |
- Momentum is essential once a queue is used: without it, training failed on all three seeds (0.18, 0.23, 0.18), even below raw features. The query learned to tell stale queued keys apart from fresh ones instead of learning content.
- Queue size brought little here: 256 was slightly better than batch-only on two of three seeds, and 1024 slightly worse. With only 10 classes, 10% of negatives are false negatives, and more of them add pressure to split same-class images.
- Lesson: MoCo’s mechanism is the consistent key encoder. The benefit of the large queue depends on data diversity.
MoCo in AI, robotics and aerospace
- Modest-hardware pre-training: learning from unlabelled imagery on a few GPUs.
- Video and robotics: queues of past frames’ keys as negatives for temporal contrastive learning.
- Design lesson: when reusing representations computed earlier, keep the encoder that produces them slowly changing. Size the negative pool to the diversity of the data.
References
- K. He, H. Fan, Y. Wu, S. Xie and R. Girshick (2020). “Momentum contrast for unsupervised visual representation learning.” Proc. CVPR.
- X. Chen, H. Fan, R. Girshick and K. He (2020). “Improved baselines with momentum contrastive learning.” arXiv:2003.04297.
- X. Chen, S. Xie and K. He (2021). “An empirical study of training self-supervised Vision Transformers.” Proc. ICCV.