Search

Search papers and lessons

Momentum Contrast

Level 4 · 12 min read

Momentum Contrast keeps a long queue of past encoded images as negatives, and updates the encoder that makes those keys slowly, so the queue stays consistent and large.

On this page

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

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 fqf_q and the key encoder fkf_k are two copies of the same network, with different weights. Each image gives two random augmented crops. The crop that goes through fqf_q is the query, and the crop that goes through fkf_k is the key. The queue holds keys from earlier steps.

  1. Take an image xx and make two crops, x1x_1 and x2x_2, with random cropping, colour changes and flips. This is Data Augmentation at work. Feed x1x_1 through fqf_q to get a query qq. Feed x2x_2 through fkf_k to get a positive key k+k_+. Check: qq and k+k_+ come from the same image, so they should match.
  2. Look up the queue. It contains 4 older keys, k0,k1,k2,k3k_0, k_1, k_2, k_3, 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 k+k_+.
  3. Score each key by the dot product with the query. Suppose the scores are q⋅k+=2q \cdot k_+ = 2 and q⋅ki=0,1,−1,0q \cdot k_i = 0, 1, -1, 0 for the four queue keys. Larger means more alike. Divide each score by a temperature τ\tau to sharpen the differences. Here τ=1\tau = 1 to keep the numbers small. Check: the positive has the highest score, which is what we want.
  4. 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.
  5. Update the query encoder fqf_q by gradient descent, the way any network is trained. Update the key encoder fkf_k differently: it moves a little toward fqf_q, using a moving average, and gets no gradient at all. Check: only fqf_q receives gradients.
  6. 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: qq the query vector, k+k_+ the positive key, kik_i the keys in the queue, KK the number of keys in the queue, τ\tau the temperature, and mm the momentum coefficient. Vectors are normalised to length one, so the dot product equals the cosine similarity.

Definition: Momentum Contrast loss
For one query qq with positive key k+k_+ and queue keys k1,…,kKk_1, \dots, k_K, the loss is Lq=−log⁡exp⁡(q⋅k+/τ)∑i=0Kexp⁡(q⋅ki/τ)\mathcal{L}_q = -\log \frac{\exp(q \cdot k_+ / \tau)}{\sum_{i=0}^{K} \exp(q \cdot k_i / \tau)}, where k0=k+k_0 = k_+ and the sum runs over the positive and the KK negatives.

Step 3 in symbols: the scores

Each score is si=q⋅ki/τs_i = q \cdot k_i / \tau. The dot product is taken over the vector of 128 numbers the encoder outputs for each crop. Dividing by τ\tau scales the scores, so that small differences in similarity become large differences in the exponent. The paper uses τ=0.07\tau = 0.07. The walkthrough used τ=1\tau = 1 only so the numbers stay small.

Step 4 in symbols: the loss

The fraction inside the logarithm is a softmax over K+1K+1 scores, evaluated at the positive. Taking the negative logarithm gives Cross-Entropy Loss for a classifier that must pick the positive out of K+1K+1 choices. Minimising Lq\mathcal{L}_q pushes q⋅k+q \cdot k_+ up and every q⋅kiq \cdot k_i down. The loss is smallest when the positive dominates the softmax.

Step 5 in symbols: the momentum update

Let θq\theta_q be the weights of fqf_q and θk\theta_k those of fkf_k. Only θq\theta_q is updated by gradient descent. After each step, θk\theta_k is updated as

θk←m θk+(1−m) θq\theta_k \leftarrow m\,\theta_k + (1 - m)\,\theta_q

with m∈[0,1)m \in [0, 1). This is an Exponential Moving Average of the query weights. With m=0.999m = 0.999, 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 m=0m = 0, which copies the query weights straight across, gives much worse results, and that mm values from 0.99 to 0.9999 work well.

The plot shows how much of an old key encoder survives after nn steps with m=0.999m = 0.999. The weight fraction is mnm^n, and the point marks the half-life.

050010001500200000.20.40.60.81training steps nshare remaining
  • share of old key weights, m = 0.999
After about 693 steps, half of the old key weights have been replaced.

Step 6 in symbols: the queue

The queue has KK keys. Each step adds NN keys, one for each image in the batch, and removes the NN oldest. A key therefore lives in the queue for K/NK / N steps. With K=4096K = 4096 and N=256N = 256, that is 16 steps.

Worked examples

Example
One query, one positive, two negatives

Take τ=1\tau = 1, K=2K = 2, and scores q⋅k+=2q \cdot k_+ = 2, q⋅k1=0q \cdot k_1 = 0, q⋅k2=−2q \cdot k_2 = -2.

  1. Exponentiate each score: exp⁡(2)≈7.389\exp(2) \approx 7.389, exp⁡(0)=1\exp(0) = 1, exp⁡(−2)≈0.135\exp(-2) \approx 0.135.
  2. Add the three numbers: 7.389+1+0.135=8.5247.389 + 1 + 0.135 = 8.524.
  3. Divide the positive by the sum: 7.389/8.524≈0.8677.389 / 8.524 \approx 0.867.
  4. Take the negative logarithm: −ln⁡(0.867)≈0.143-\ln(0.867) \approx 0.143.

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 ln⁡3≈1.10\ln 3 \approx 1.10.

Example
The standard case with temperature 0.07

Take τ=0.07\tau = 0.07, K=3K = 3, and cosine similarities 0.50.5 for the positive and 0.60.6, 0.10.1 and −0.2-0.2 for the negatives. Here one negative is more similar to the query than the positive is, which is a hard case.

  1. Divide each similarity by 0.070.07: positive 7.1437.143, negatives 8.5718.571, 1.4291.429 and −2.857-2.857.
  2. Subtract the largest score, 8.5718.571, from every score, for numerical stability. The values become −1.429-1.429 (positive), 00, −7.143-7.143 and −11.429-11.429.
  3. Exponentiate: exp⁡(−1.429)≈0.240\exp(-1.429) \approx 0.240, 11, exp⁡(−7.143)≈0.0008\exp(-7.143) \approx 0.0008, and exp⁡(−11.429)≈0.00001\exp(-11.429) \approx 0.00001.
  4. Add them: 0.240+1+0.0008+0.00001≈1.24080.240 + 1 + 0.0008 + 0.00001 \approx 1.2408.
  5. The positive's share is 0.240/1.2408≈0.1930.240 / 1.2408 \approx 0.193.
  6. The loss is −ln⁡(0.193)≈1.64-\ln(0.193) \approx 1.64.

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.

Example
How long the queue remembers, with realistic settings

The paper's ImageNet setting uses a batch of N=256N = 256 images, a queue of K=4096K = 4096 keys, and momentum m=0.999m = 0.999.

  1. Each step adds 256 keys, so the queue holds 4096/256=164096 / 256 = 16 batches. A key stays in the queue for 16 steps.
  2. Over those 16 steps, the key encoder weights are replaced at the rate mm per step. The share of the key encoder at the start that remains is 0.99916≈0.9840.999^{16} \approx 0.984.
  3. 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.
  4. The half-life of the key encoder is ln⁡(0.5)/ln⁡(0.999)≈693\ln(0.5) / \ln(0.999) \approx 693 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 m=0.999m = 0.999, what share of the old key weights remains? Compute 0.9991000.999^{100} with the help of ln⁡(0.999)≈−0.0010005\ln(0.999) \approx -0.0010005.

Answer: 0.999100=exp⁡(100×−0.0010005)=exp⁡(−0.10005)≈0.9050.999^{100} = \exp(100 \times -0.0010005) = \exp(-0.10005) \approx 0.905. 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 m=0m = 0, 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 θk←mθk+(1−m)θq\theta_k \leftarrow m\theta_k + (1-m)\theta_q, so the stored keys stay consistent.
  • The loss is a softmax cross-entropy over one positive and KK negatives, with temperature τ\tau.
  • 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.

Check yourself

QuestionIn MoCo, which encoder receives gradients, and how is the other one updated?Show answer
Only the query encoder receives gradients. The key encoder is updated as a moving average of the query encoder's weights, with no gradient, so it changes slowly.
QuestionWith τ=1\tau = 1, one positive score of 1 and one negative score of 1, what is the contrastive loss?Show answer
Both scores have the same exponent, so each gets half the softmax probability. The loss is −ln⁡(0.5)=ln⁡2≈0.693-\ln(0.5) = \ln 2 \approx 0.693.
QuestionWith N=128N = 128 and K=8192K = 8192, how many steps does a key stay in the queue?Show answer
K/N=8192/128=64K / N = 8192 / 128 = 64 steps.
QuestionWhy does MoCo use a momentum value near 1 instead of copying the query encoder into the key encoder each step?Show answer
Copying the weights each step, which is m=0m = 0, makes the keys in the queue come from encoders that differ too much, and the paper reports much worse results. A momentum near 1 keeps the key encoder slowly changing, so the keys stored over many steps stay consistent with each other.
QuestionYou train a model on a small dataset with a batch of 32 and want many negatives. Which MoCo idea helps most, and what would you watch for?Show answer
The queue helps most, because it supplies many negatives without needing a large batch. Watch for drift: keys in the queue should come from a slowly changing key encoder, so a momentum close to 1 is needed, and an overly large queue can hold keys from encoders too far apart.

Sources