TL;DR
Momentum Contrast (MoCo) is a way to train an image encoder without labels. It asks the encoder to recognise two augmented crops of the same image as a match, and to tell them apart from many other images. It stores the encodings of recent images in a queue, so the number of negatives is large and does not depend on the batch size. The second encoder that makes the stored keys changes slowly, by a moving average of the first, so the keys in the queue stay consistent with each other.
Builds on: Contrastive Learning, Exponential Moving Average, Softmax · Leads to: Momentum Contrast for Unsupervised Visual Representation Learning, Emerging Properties in Self-Supervised Vision Transformers
Where it's used
Pretraining image features without labels. MoCo was introduced for unsupervised pretraining on ImageNet, which has about 1.28 million images in 1,000 classes. The paper trained a ResNet-50 without using a single label, then froze its features and trained only a linear classifier on top. That classifier reached 60.6 percent top-1 accuracy. The encoder could then be fine-tuned for detection and segmentation.
Transfer to detection. The same pretraining transfers to object detection on PASCAL VOC and COCO. The paper reports that MoCo pretraining, with no labels, matched or beat ImageNet-supervised pretraining on several of these downstream tasks. This is why it became a standard starting point when labelled data is scarce.
The pattern behind later methods. Several later self-supervised methods use the same design: a slowly moving copy of the network produces the targets, and a queue or a similar memory supplies many negatives. Reading MoCo first makes those later designs easier to follow.
How it works
Trace one tiny instance: one image, one step, a queue of only 4 stored keys. The goal is for the query made from one crop to match the key made from another crop of the same image, and to differ from the other keys.
Setup: the query encoder and the key encoder are two copies of the same network, with different weights. Each image gives two random augmented crops. The crop that goes through is the query, and the crop that goes through is the key. The queue holds keys from earlier steps.
- Take an image and make two crops, and , with random cropping, colour changes and flips. This is Data Augmentation at work. Feed through to get a query . Feed through to get a positive key . Check: and come from the same image, so they should match.
- Look up the queue. It contains 4 older keys, , each from a different past image. These are the negatives. They are negatives because they come from other images. Check: the queue has 4 keys, none of which is .
- Score each key by the dot product with the query. Suppose the scores are and for the four queue keys. Larger means more alike. Divide each score by a temperature to sharpen the differences. Here to keep the numbers small. Check: the positive has the highest score, which is what we want.
- Turn the five scores into probabilities with Softmax. The positive gets the largest share. The loss is the negative log of that share. A high share means a small loss. Check: if the positive had the highest score by a big margin, the loss would be near zero.
- Update the query encoder by gradient descent, the way any network is trained. Update the key encoder differently: it moves a little toward , using a moving average, and gets no gradient at all. Check: only receives gradients.
- Put the current batch's keys into the queue, and remove the oldest keys from the front. The queue is a sliding window of recent images. Check: the queue still has 4 keys, now including the newest one.
Now the two ideas have names. The queue lets the negatives outnumber the batch. The momentum update keeps the keys in the queue consistent, because they all come from a key encoder that changes only slowly.
flowchart LR X[Image x] --> C1[Crop x1] X --> C2[Crop x2] C1 --> FQ[Query encoder fq] --> Q[query q] C2 --> FK[Key encoder fk] --> KP[positive key k+] Q --> L[Contrastive loss] KP --> L QU[Queue of past keys] --> L FQ -. gradient .-> FQ FQ -- momentum update --> FK KP --> QU
The math
Each step of the walkthrough has a formal version. The symbols are: the query vector, the positive key, the keys in the queue, the number of keys in the queue, the temperature, and the momentum coefficient. Vectors are normalised to length one, so the dot product equals the cosine similarity.
Step 3 in symbols: the scores
Each score is . The dot product is taken over the vector of 128 numbers the encoder outputs for each crop. Dividing by scales the scores, so that small differences in similarity become large differences in the exponent. The paper uses . The walkthrough used only so the numbers stay small.
Step 4 in symbols: the loss
The fraction inside the logarithm is a softmax over scores, evaluated at the positive. Taking the negative logarithm gives Cross-Entropy Loss for a classifier that must pick the positive out of choices. Minimising pushes up and every down. The loss is smallest when the positive dominates the softmax.
Step 5 in symbols: the momentum update
Let be the weights of and those of . Only is updated by gradient descent. After each step, is updated as
with . This is an Exponential Moving Average of the query weights. With , each step keeps 99.9 percent of the old key weights and adds 0.1 percent of the new query weights. The paper reports that , which copies the query weights straight across, gives much worse results, and that values from 0.99 to 0.9999 work well.
The plot shows how much of an old key encoder survives after steps with . The weight fraction is , and the point marks the half-life.
- share of old key weights, m = 0.999
Step 6 in symbols: the queue
The queue has keys. Each step adds keys, one for each image in the batch, and removes the oldest. A key therefore lives in the queue for steps. With and , that is 16 steps.
Worked examples
Take , , and scores , , .
- Exponentiate each score: , , .
- Add the three numbers: .
- Divide the positive by the sum: .
- Take the negative logarithm: .
Interpretation: the positive takes 86.7 percent of the probability, so the loss is small. If the positive were tied with the negatives, each would get a third and the loss would be .
Take , , and cosine similarities for the positive and , and for the negatives. Here one negative is more similar to the query than the positive is, which is a hard case.
- Divide each similarity by : positive , negatives , and .
- Subtract the largest score, , from every score, for numerical stability. The values become (positive), , and .
- Exponentiate: , , , and .
- Add them: .
- The positive's share is .
- The loss is .
Interpretation: the loss is large because a negative beats the positive. The gradient will push the query toward the positive and away from the hard negative. This is the signal that teaches the encoder fine distinctions.
The paper's ImageNet setting uses a batch of images, a queue of keys, and momentum .
- Each step adds 256 keys, so the queue holds batches. A key stays in the queue for 16 steps.
- Over those 16 steps, the key encoder weights are replaced at the rate per step. The share of the key encoder at the start that remains is .
- So the oldest key in the queue was made by an encoder that is 98.4 percent the same as the current one. The keys are consistent enough to be compared directly.
- The half-life of the key encoder is steps, far longer than the 16-step life of a key. That gap is the point of the design.
Try it: After 100 steps with , what share of the old key weights remains? Compute with the help of .
Answer: . About 90.5 percent of the old key weights remain.
Common mistakes and tradeoffs
It is tempting to think that the key encoder should be trained by gradient descent like the query encoder. In fact the keys in the queue come from many past steps, and back-propagating through all of them is too expensive. Making the key encoder a slow moving average avoids that cost and also keeps the keys consistent. Updating it by gradient would make the keys in the queue come from encoders that differ too much to be compared fairly.
It is tempting to think that a bigger queue is always better. In fact the keys in a very long queue come from encoders far apart in time, which is the problem the momentum update is meant to solve. A memory bank of keys from the whole dataset, which is the extreme case, performs worse than MoCo, because its keys were made by very different encoders. Size and consistency have to be balanced.
It is tempting to think that the momentum is a tuning detail. In fact the paper reports much worse results with , and good results for values from 0.99 to 0.9999. Momentum is what makes the queue work at all.
When to use it: when labels are scarce, when you want a large set of negatives without a huge batch, and when you can afford two encoders in memory during training. The second encoder is never trained by gradient, so it adds memory but not much compute.
When not to use it: when you have plenty of labelled data for the task, where supervised training is simpler and usually stronger. Also avoid it if your batch is already large enough to supply the negatives, since end-to-end contrastive learning with a large batch can work without a queue.
Alternatives include the end-to-end method, which uses only the current batch as negatives, and methods such as Self-Supervised Learning with other pretext tasks. The paper compares these directly.
History
Before 2019, contrastive methods for images had a choice. Using the current batch as negatives needs very large batches to get enough of them. Storing the features of the whole dataset in a memory bank gives many negatives, but the stored features come from very different encoders and are inconsistent. Both approaches had clear limits, and they were the starting point for the design.
Kaiming He and colleagues at Facebook AI Research introduced MoCo in a preprint in November 2019, and the paper was later published at CVPR 2020. Their key move was the queue combined with the momentum encoder. The result was unsupervised pretraining that beat ImageNet supervised pretraining on several detection and segmentation benchmarks, which made the method catch on quickly. Later work extended the same design.
Recap
- MoCo treats contrastive learning as a dictionary lookup: a query must find its matching key among many stored keys.
- The queue decouples the number of negatives from the batch size, so the dictionary can be large.
- The key encoder is an exponential moving average of the query encoder, updated as , so the stored keys stay consistent.
- The loss is a softmax cross-entropy over one positive and negatives, with temperature .
- Read next: Momentum Contrast for Unsupervised Visual Representation Learning for the full experiments, and Emerging Properties in Self-Supervised Vision Transformers for a related design that also uses a slowly moving teacher.