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
- 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.
- 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.
- 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.
- 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.
- 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.
- Move the key encoder a small step toward the query encoder, using the momentum update. The key encoder is never trained directly.
- 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 . Since , and , the probability is . The loss is . If the positive scored higher, the loss would fall toward zero; if a negative scored higher, it would rise.
The math
Let and be the query and key encoders, with parameters and . The query for image is and the key is , both normalized to length 1. The queue holds keys , and is the positive key for .
Steps 4 and 5 in symbols: the InfoNCE loss
The loss for one query is
where the sum includes the positive and the negatives, the dot product measures similarity, and is a temperature. The paper uses . A small temperature sharpens the softmax, so the loss punishes near-misses more strongly. This is the log loss of a -way softmax classifier, and the paper frames it as a dictionary look-up: pick the key that matches the query out of candidates.
Step 5 in symbols: the gradient step
Only 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
Take and for one parameter, with . After one update, . 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 .
Step 7 in symbols: the queue
The queue is a first-in, first-out buffer of length K. Each step, new keys go in and the oldest keys come out. So the keys in the queue come from the last 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, . If 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.
- Section 1, Introduction: the claim, the queue idea, and the billion-image transfer results. Needs Contrastive Learning and Self-Supervised Learning.
- Section 2, Related work: the loss families and the pretext tasks. Needs Cross-Entropy Loss and Representation Learning.
- Section 3.1, Contrastive learning as dictionary look-up: Equation 1 and Figure 2. Needs Dot Product and Softmax Temperature.
- Section 3.2, Momentum contrast: the queue, Equation 2 and the pseudocode in Algorithm 1. Needs Momentum Contrast and Exponential Moving Average.
- Section 3.3, Pretext task and shuffling BN: why batch normalization leaks information across the batch and how the paper blocks it. Needs Batch Normalization and Data Augmentation.
- Section 4.1, Linear classification: the ablations in Figure 3 and the momentum table, then Table 1. Needs Stochastic Gradient Descent and Momentum.
- Section 4.2, Transferring features: detection and segmentation under the same fine-tuning settings as the supervised baseline. Needs Transfer Learning, Fine-Tuning and Object Detection.
- Section 5, Discussion: the authors' view on how far the approach goes. Read it last.
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 for the positive and for each negative. The sum is . The probability of the positive is . The loss is .
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 . 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
- He et al., "Momentum Contrast for Unsupervised Visual Representation Learning", arXiv:1911.05722, 2019 (CVPR 2020): https://arxiv.org/abs/1911.05722
- DOI record: https://doi.org/10.48550/arXiv.1911.05722