Search

Search papers and lessons

Momentum Contrast for Unsupervised Visual Representation Learning

Kaiming He, Haoqi Fan, Yuxin Wu et al. · 2019

MoCo learns image features without labels by matching each image's views against a large queue of past keys, with a slowly moving key encoder that keeps the queue consistent.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Linear algebra
  • Neural network basics
  • Probability
  • Representation learning
  • ReadReady to readNot yet

TL;DR

Most image models are trained on human labels, and labels are expensive. MoCo trains an image encoder without labels by teaching it one task: given two random crops of the same photo, the encoder should give them similar vectors, and different photos should get different ones. It makes the comparison set large by keeping the vectors of recent images in a queue, and it keeps those stored vectors consistent by updating the second encoder slowly, as a moving average of the first. The features it learns transfer well to detection and segmentation.

Builds on: Contrastive Learning, Momentum Contrast, Exponential Moving Average, Cross-Entropy Loss · Leads to: later self-supervised vision methods that reuse the queue and momentum encoder, and the MoCo v2 variant

Why it mattered

For several years after 2019 the standard way to start a vision model was to pretrain it on ImageNet labels and then fine-tune. MoCo showed that a label-free pretraining method could match that supervised starting point on several tasks. Its results on PASCAL VOC and COCO object detection and segmentation, pretrained on nearly a billion uncurated Instagram photos, surpassed the ImageNet supervised baseline on several metrics. That made self-supervised pretraining a practical option for teams without large labeled sets. The paper's code is public, and its queue and momentum encoder became a common building block in later contrastive methods. Semantic Scholar records about 16,000 citations for it.

The paper also made a narrower point that carried over to other fields: the size of the set of negative examples and how consistently it is encoded matter as much as the loss function itself.

The problem

A contrastive loss compares one query against one positive key and many negative keys. More negatives give a harder and more informative test, so the number of negatives K is an important setting. Earlier methods had a dilemma. In the end-to-end approach, the negatives are the other images in the same mini-batch, both the query and the keys are encoded by the same network that is being trained, and so the number of negatives is limited by the batch size, which is limited by GPU memory. The memory bank approach stores one vector per image in the dataset and samples negatives from it, which allows a large K. But each stored vector was computed at a different time, so the negatives come from encoders that differ widely, and they are inconsistent.

The paper asks for both properties at once: a large dictionary of negatives that is also consistent. It also asks that the method work at billion-image scale, where a stored vector per image is impractical.

How it works

The walkthrough follows one training step for a mini-batch of N images. The diagram shows where each piece goes.

flowchart LR
  X[Mini-batch of N images] --> A1[Augment: two random views]
  A1 --> Q[Query encoder f_q]
  A1 --> K[Key encoder f_k, no gradient]
  Q --> L[Contrastive loss]
  K --> L
  Q2[Queue of K past keys] --> L
  K -->|enqueue new keys, dequeue oldest| Q2
  Q -->|momentum update of f_k| K
  1. Take a mini-batch of N images. For each image, make two random augmented views, such as a random crop, a color change and a flip. Call the views x_q and x_k.
  2. Pass the x_q views through the query encoder f_q, a convolutional network with a final 128-dimensional output, and normalize each output to length 1. These are the queries.
  3. Pass the x_k views through the key encoder f_k. Stop the gradient here, so no learning signal flows into the keys. These are the positive keys: the key from the same image is the match for each query.
  4. Each query has one positive key and K negative keys. The negatives are the keys stored in a queue from the most recent mini-batches. Compute a dot product between each query and its positive, and between each query and every queued key.
  5. Compute the loss. It is the cross-entropy loss of a classifier whose job is to pick the positive key out of K plus 1 options. Update the query encoder by gradient descent.
  6. Move the key encoder a small step toward the query encoder, using the momentum update. The key encoder is never trained directly.
  7. Add the current mini-batch's keys to the queue and remove the oldest mini-batch's keys, so the queue always holds the keys of the last several batches.

A tiny example makes steps 4 and 5 concrete. Take one query, one positive key with dot product 2.0 with the query, and two negative keys with dot products 1.0 and 0.0. Use temperature 1, so the scores are not rescaled. The softmax over the three scores gives the probability of the positive as e2/(e2+e1+e0)e^2 / (e^2 + e^1 + e^0). Since e2≈7.39e^2 \approx 7.39, e1≈2.72e^1 \approx 2.72 and e0=1e^0 = 1, the probability is 7.39/11.11≈0.6657.39 / 11.11 \approx 0.665. The loss is −log⁡(0.665)≈0.41-\log(0.665) \approx 0.41. If the positive scored higher, the loss would fall toward zero; if a negative scored higher, it would rise.

The math

Let fqf_q and fkf_k be the query and key encoders, with parameters θq\theta_q and θk\theta_k. The query for image xx is q=fq(xq)\mathbf{q} = f_q(x^q) and the key is k=fk(xk)\mathbf{k} = f_k(x^k), both normalized to length 1. The queue holds KK keys k0,…,kK−1\mathbf{k}_0, \ldots, \mathbf{k}_{K-1}, and k+\mathbf{k}_+ is the positive key for q\mathbf{q}.

Steps 4 and 5 in symbols: the InfoNCE loss

The loss for one query is

Lq=−log⁡exp⁡(q⋅k+/τ)∑i=0Kexp⁡(q⋅ki/τ),\mathcal{L}_q = -\log \frac{\exp(\mathbf{q}\cdot\mathbf{k}_+ / \tau)}{\sum_{i=0}^{K} \exp(\mathbf{q}\cdot\mathbf{k}_i / \tau)},

where the sum includes the positive and the KK negatives, the dot product measures similarity, and τ\tau is a temperature. The paper uses τ=0.07\tau = 0.07. A small temperature sharpens the softmax, so the loss punishes near-misses more strongly. This is the log loss of a (K+1)(K+1)-way softmax classifier, and the paper frames it as a dictionary look-up: pick the key that matches the query out of K+1K+1 candidates.

Step 5 in symbols: the gradient step

Only θq\theta_q receives gradients. The loss is averaged over the mini-batch and minimized by stochastic gradient descent with momentum 0.9 and weight decay 0.0001, in the paper's ImageNet setting.

Step 6 in symbols: the momentum update

The key encoder is updated by

θk←m θk+(1−m) θq,m∈[0,1).\theta_k \leftarrow m\,\theta_k + (1 - m)\,\theta_q, \qquad m \in [0, 1).

Take θk=1.0\theta_k = 1.0 and θq=0.0\theta_q = 0.0 for one parameter, with m=0.999m = 0.999. After one update, θk=0.999×1.0+0.001×0.0=0.999\theta_k = 0.999 \times 1.0 + 0.001 \times 0.0 = 0.999. The key encoder moves by a thousandth of the gap each step, so it changes slowly even when the query encoder changes quickly. The paper's default is m=0.999m = 0.999.

Step 7 in symbols: the queue

The queue is a first-in, first-out buffer of length K. Each step, NN new keys go in and the NN oldest keys come out. So the keys in the queue come from the last K/NK / N mini-batches. In the ImageNet setting with K = 65536 and N = 256, that is the last 256 mini-batches.

Why the key encoder must move slowly

Consider the consistency requirement in symbols. The queue holds keys computed at different steps, t,t−1,…,t−K/Nt, t-1, \ldots, t - K/N. If θk\theta_k changed a lot between those steps, the keys in the queue would be produced by different functions, and the loss would compare them unfairly. The momentum update keeps the change between consecutive key encoders small, so the queue behaves like a set of keys from one slowly changing function.

Results

With a standard ResNet-50 pretrained on ImageNet without labels (about 1.28 million images) and then tested with a linear classifier on frozen features, MoCo reaches 60.6 percent top-1 accuracy. A version with a 4 times wider ResNet-50 reaches 68.6 percent. The paper's comparison table places MoCo above all earlier methods with models of about 24 million parameters, and the authors note that their approach needs no special architecture for the pretext task. An extended version, MoCo v2, reaches 71.1 percent with ResNet-50 after small changes to augmentation and the output head.

The ablations in the paper support the design. With a queue of 4096 negatives, the momentum value matters: m = 0 fails to converge, m = 0.9 gives 55.2 percent, m = 0.99 gives 57.8, m = 0.999 gives 59.0, and m = 0.9999 gives 58.9. Among the three contrastive mechanisms, the memory bank reaches 58.0 percent with the same loss, which is 2.6 points below MoCo. The end-to-end mechanism is competitive only while the batch is small, because its negatives are limited by the batch size.

For transfer, MoCo pretrained on the 1.28 million ImageNet images matches the supervised ImageNet baseline on PASCAL VOC detection with one backbone and beats it on another. Pretrained on the roughly 940 million Instagram images, MoCo is ahead of the supervised baseline on VOC AP50 (81.6 against 81.4) and on the stricter metrics. On COCO detection and segmentation, the Instagram-pretrained model matches the supervised model on bounding-box AP (38.9 against 38.9) and gives an equal mask AP.

Limits. The paper uses a single pretext task, instance discrimination with two views of the same image, and its main experiments use ResNet encoders. Its training runs are long: the ImageNet run takes about 53 hours on 8 GPUs for ResNet-50, and the billion-image run takes about 6 days on 64 GPUs. The transfer runs reuse the supervised baseline's hyperparameters and fine-tuning schedule, which the authors say may put MoCo at a disadvantage, so the detection comparisons are not tuned for MoCo.

Common misreadings. It is tempting to think MoCo learns from the labels of its negatives. In fact it uses no labels at all; the only positive pairs come from two augmentations of the same image. It is tempting to think a bigger queue always helps. In fact a larger K helps only while the keys stay consistent, which is why the momentum update is needed. It is tempting to think the key encoder is a second network that is trained. In fact it receives no gradients and is only an average of the query encoder over time.

Reading guide

The chain of ideas is: a contrastive loss that needs many negatives, the queue that supplies them without a large batch, the momentum encoder that keeps the queue consistent, and the transfer results that show the features are useful. Read the sections in this order.

Check yourself

QuestionA query has one positive key with dot product 3.0 and two negative keys with dot products 1.0 and 1.0, at temperature 1. What is the loss for this query?Show answer

The three exponentials are e3≈20.09e^3 \approx 20.09 for the positive and e1≈2.72e^1 \approx 2.72 for each negative. The sum is 20.09+2.72+2.72=25.5320.09 + 2.72 + 2.72 = 25.53. The probability of the positive is 20.09/25.53≈0.78720.09 / 25.53 \approx 0.787. The loss is −log⁡(0.787)≈0.24-\log(0.787) \approx 0.24.

QuestionWith momentum m = 0.999, a key encoder parameter is 0.5 and the matching query encoder parameter is 0.9. What is the key encoder parameter after one momentum update?Show answer

The update is θk←m θk+(1−m) θq=0.999×0.5+0.001×0.9=0.4995+0.0009=0.5004\theta_k \leftarrow m\,\theta_k + (1 - m)\,\theta_q = 0.999 \times 0.5 + 0.001 \times 0.9 = 0.4995 + 0.0009 = 0.5004. The key encoder moved by 0.0004, which is a thousandth of the gap of 0.4.

QuestionWhy does the paper keep the key encoder out of gradient descent, instead of training it like the query encoder?Show answer

Back-propagating into the key encoder would need gradients to reach every key in the queue, which the paper calls intractable. Simply copying the query encoder into the key encoder and ignoring that gradient gave poor results, and the paper attributes this to the keys drifting apart as the encoder changes. Updating the key encoder as a slow moving average keeps the keys in the queue consistent with one another without any gradient.

Sources

Read the full paper

Kaiming He, Haoqi Fan, Yuxin Wu et al., 2019. arXiv:1911.05722

MoCo paper explained · ungoon.me