AI Logic

Self-Supervised Learning

MoCo

Updated:

MoCo training flow. The left side shows an image turned into two augmented views: an encoder f_q updated by gradients produces the query q, and an encoder f_k updated by moving average (dashed) produces the key k+; together with a queue of past keys, they feed into the InfoNCE loss. The right side shows the queue that adds keys one minibatch at a time and discards the oldest ones, the positive and negatives, the per-query loss computation, and the momentum update rule for f_k

Background and Overview

MoCo (Momentum Contrast) is a contrastive learning method that stores features from past minibatches in a queue to use as negatives, and slowly updates the encoder that produces the queue with a moving average of the weights. It was proposed by He et al. at Facebook AI Research in 2019 and presented at CVPR 2020. Trained only on unlabeled images, it reaches a top-1 accuracy of 60.6% with ResNet-50 under linear evaluation on ImageNet, and on seven downstream tasks such as object detection it outperforms supervised pretraining.

Contrastive learning trains a model to recognize two views created from one image as "the same" and other images as "different" (see SimCLR for the idea). The more comparison targets (negatives) there are, the better the learned features. However, when negatives are taken from the same minibatch, their number is determined by the minibatch size, which is limited by GPU memory.

MoCo solves this problem by viewing contrastive learning as a dictionary lookup. One view serves as the "query," while the other view and past images serve as the "keys" of a dictionary, and the model must find the key that matches the query. A queue decouples the dictionary from the minibatch so it can grow large, and the encoder that produces the keys is moved slowly so the contents of the queue stay consistent. As an analogy, it is like a vocabulary notebook whose entries are replaced a little each day, always written by someone whose handwriting barely changes.

Theory (Training Procedure and Loss)

MoCo training repeats the following steps, as in Algorithm 1 of the paper.

  1. Sample a minibatch of NN images.
  2. Apply random data augmentation twice, independently, to each image to create xqx^q for the query and xkx^k for the key.
    • The augmentations are a 224×224 crop from a randomly resized image, color jittering, horizontal flipping, and random grayscale conversion.
  3. Pass them through the query encoder fqf_q to obtain the query q=fq(xq)q = f_q(x^q), and through the key encoder fkf_k to obtain the key k=fk(xk)k = f_k(x^k). No gradient flows through the keys.
    • The encoder is a ResNet whose final fully connected layer outputs 128 dimensions, normalized to unit length (L2 norm).
  4. Treat the kk from the same image as the positive k+k_+ and the KK keys in the queue as negatives, and compute the InfoNCE loss.
  5. Compute gradients from the loss and update only fqf_q with SGD.
  6. Update the weights of fkf_k as a moving average with the weights of fqf_q (momentum update).
  7. Push the current kk into the queue and remove the keys of the oldest minibatch from it.

The loss in step 4 is InfoNCE with the dot product as similarity.

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)}

The sum in the denominator runs over one positive and KK negatives. In other words, Lq\mathcal{L}_q is the cross-entropy of a classification problem that "identifies qq's partner among K+1K+1 keys." τ\tau is the temperature, 0.07 in the paper. In implementations, K+1K+1 scores are built with the dot product with the positive placed first, and cross-entropy is computed with the correct index set to 0.

The momentum update in step 6 is given by the following, where θk\theta_k are the weights of fkf_k and θq\theta_q those of fqf_q.

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

m∈[0,1)m \in [0, 1) is the momentum coefficient, m=0.999m = 0.999 by default. Only θq\theta_q is updated by gradients, and θk\theta_k gradually follows θq\theta_q. At the start of training, θk\theta_k is initialized to the same values as θq\theta_q.

The figure at the top illustrates this flow. The left side shows the two views passing through their respective encoders into the loss; the right side shows the queue replacement, the loss computation, and the momentum update.

After training, use the query encoder fqf_q for downstream tasks. For linear evaluation, a linear classifier is placed on the features after average pooling.

Why the Queue and Momentum Update Work

The core of MoCo is the hypothesis that a good dictionary needs two things: it must be large and consistent. The larger the dictionary, the more finely it covers the continuous, high-dimensional space of images. And if the dictionary keys are produced by the same or a similar encoder, they are compared with the query on a consistent basis. The queue and the momentum update are the mechanisms that satisfy both at once.

  • Queue: it decouples the dictionary size KK from the minibatch size NN. With N=256N = 256, a dictionary as large as K=65536K = 65536 can be used. Because the oldest keys are discarded first, the keys most inconsistent with the current encoder disappear first.
  • Momentum update: the keys in the queue are produced by the encoder at slightly different points in time. Moving fkf_k slowly keeps those differences small. Backpropagating through all keys in the queue would be too expensive, so fkf_k is not updated by gradients.
  • Shuffling BN: because batch normalization in the encoder uses statistics within the minibatch, positive pairs can leak information through those statistics, letting the model "cheat" to lower the loss easily. MoCo trains on multiple GPUs and, only before feeding samples to fkf_k, shuffles their order across GPUs. This way, the query and its positive key are normalized with statistics from different GPUs.

The paper explains where MoCo stands by comparing it with two other approaches.

ApproachDictionary (negatives)Key encoderDictionary sizeConsistency
End-to-end (SimCLR, etc.)Within the same minibatchUpdated by gradients like the queryDetermined by minibatch sizeHigh
Memory bankDrawn from a table storing features for the whole datasetNone (table features are from when each sample was last seen)Can be largeLow (features from scattered points over the past epoch)
MoCoQueue of keys from past minibatchesUpdated slowly by moving averageCan be largeHigh (when mm is large)

The momentum coefficient mm must be large. In the paper, m=0m = 0 (copying fqf_q directly every step) made the loss oscillate and training failed, and even m=0.9m = 0.9 lowered accuracy considerably. This is thought to be because a rapidly changing fkf_k destroys the consistency among the keys in the queue.

Experimental Results

The paper's experiments center on pretraining on the roughly 1.28 million images of the ImageNet training set (called IN-1M in the paper) and linear evaluation (top-1 accuracy) on frozen ResNet-50 features.

Number of negatives KK and comparison of approaches (Figure 3 of the paper): the three approaches are compared with the same pretext task and the same InfoNCE loss.

Number of negatives KK2561024409665536
End-to-end54.9%57.3%——
Memory bank50.0%54.1%56.5%58.0%
MoCo54.7%57.5%59.0%60.6%

Every approach improves as KK grows. End-to-end was limited to a minibatch of 1024 on eight 32 GB GPUs. The memory bank can scale KK up but is 2.6% below MoCo.

Momentum coefficient mm (K=4096K = 4096):

mm00.90.990.9990.9999
AccuracyTraining fails55.2%57.8%59.0%58.9%

Model size (Table 1 of the paper, K=65536K = 65536, m=0.999m = 0.999): ResNet-50 reaches 60.6%, ResNeXt-50 63.9%, ResNet-50 with 2× width 65.4%, and with 4× width 68.6%.

Transfer to downstream tasks: what the paper emphasizes is performance when the pretrained weights are fine-tuned. On PASCAL VOC object detection (Faster R-CNN, R50-C4, Table 2 of the paper), the results are as follows.

PretrainingAP50APAP75
Random initialization60.233.833.1
Supervised (ImageNet)81.353.558.8
MoCo (ImageNet)81.555.962.6
MoCo (about 1 billion Instagram images)82.257.263.7

The paper reports that MoCo outperforms supervised ImageNet pretraining on seven detection and segmentation tasks, including detection and segmentation on COCO.

MoCo v2, mentioned in the paper, raises ResNet-50 linear evaluation from 60.6% to 71.1% simply by slightly changing the data augmentation and the output projection head following SimCLR. The MoCo framework (queue and momentum update) is used as is.

Practical Considerations

  • Training settings: the paper's ImageNet setup uses SGD (weight decay 0.0001, momentum 0.9), a minibatch of 256 (8 GPUs), and a learning rate starting at 0.03 and multiplied by 0.1 at epochs 120 and 160, for 200 epochs in total. ResNet-50 took about 53 hours.
  • Temperature: τ=0.07\tau = 0.07. Changing the temperature changes how strongly confusing negatives are pushed away (see the NT-Xent article).
  • Learning rate for linear evaluation: in the paper, the optimal learning rate for the linear classifier was 30 with weight decay 0, very different from the case of features learned with labels. This is because the distribution of feature magnitudes differs; for fine-tuning as well, the normalization layers are trained to match the scale.

Using batch normalization as is on a single GPU can leak information about positive pairs through the minibatch statistics, lowering only the apparent loss. The paper's shuffling BN assumes multiple GPUs, so when experimenting on one GPU, make sure the query and its positive key are not normalized with the same statistics, for example by splitting the batch into small groups within the GPU for normalization.

Comparison with Other Methods

After MoCo, a series of methods followed the same idea of "pulling two views together" while changing how negatives are handled. The table compares them from the same perspectives.

MethodNegativesHow collapse (every image getting the same feature) is preventedBest suited for
SimCLRYes (within the same minibatch)Pushes away from negativesWhen compute allows large batches
MoCoYes (queue of past keys)Pushes away from negatives; the key side uses an encoder updated by moving averageWhen batches cannot be large but many negatives are wanted
BYOLNoPredictor and a target network updated by moving averageEliminating the effort of collecting negatives
SimSiamNoPredictor and stopping gradients on one side (stop-gradient)Keeping the mechanism as simple as possible
SwAVNo (compares cluster assignments)Distributes assignments equally across clustersLearning without directly comparing features

MoCo's "second encoder that moves with a moving average of the weights" carries over to BYOL and DINO, which use no negatives. For contrastive learning with limited memory, MoCo is the starting point; with ample compute and a desire for maximum simplicity, SimCLR is.

PyTorch example

Show code
python
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models

"""
One MoCo (v1) step written to follow Algorithm 1 of the paper.
The encoder is ResNet-50 whose final fully connected layer outputs 128 dims (Section 3.3).
"""


class MoCo(nn.Module):
  def __init__(self, dim=128, K=65536, m=0.999, tau=0.07):
    super().__init__()
    self.K, self.m, self.tau = K, m, tau
    self.encoder_q = models.resnet50(num_classes=dim)   # f_q: updated by gradients
    self.encoder_k = copy.deepcopy(self.encoder_q)      # f_k: initialized with the same values as f_q
    for p in self.encoder_k.parameters():
      p.requires_grad = False                           # No gradient flows into f_k
    # Queue: K keys (normalized to unit length). One key per column
    self.register_buffer("queue", F.normalize(torch.randn(dim, K), dim=0))
    self.register_buffer("ptr", torch.zeros(1, dtype=torch.long))

  @torch.no_grad()
  def momentum_update(self):
    # θ_k ← m θ_k + (1 − m) θ_q (Eq. (2))
    for pk, pq in zip(self.encoder_k.parameters(), self.encoder_q.parameters()):
      pk.mul_(self.m).add_(pq.detach(), alpha=1 - self.m)

  @torch.no_grad()
  def enqueue(self, k):
    # Insert the current keys, overwriting the oldest ones (K must be a multiple of N)
    n, p = k.size(0), int(self.ptr)
    self.queue[:, p:p + n] = k.t()
    self.ptr[0] = (p + n) % self.K

  def forward(self, x_q, x_k):
    q = F.normalize(self.encoder_q(x_q), dim=1)          # Queries: N × C
    with torch.no_grad():
      self.momentum_update()
      # The paper uses multiple GPUs and shuffles the sample order only here (shuffling BN)
      k = F.normalize(self.encoder_k(x_k), dim=1)        # Keys: N × C
    l_pos = (q * k).sum(dim=1, keepdim=True)             # Positive scores: N × 1
    l_neg = q @ self.queue.clone().detach()              # Negative scores: N × K
    logits = torch.cat([l_pos, l_neg], dim=1) / self.tau  # N × (1 + K)
    labels = torch.zeros(logits.size(0), dtype=torch.long, device=logits.device)  # The correct index is 0
    loss = F.cross_entropy(logits, labels)               # InfoNCE (Eq. (1))
    self.enqueue(k)
    return loss


# Usage: x_q and x_k are the same images with different data augmentations
model = MoCo(K=4096)
optimizer = torch.optim.SGD(model.encoder_q.parameters(), lr=0.03, momentum=0.9, weight_decay=1e-4)

model.train()   # Batch norm uses minibatch statistics
x_q, x_k = torch.randn(8, 3, 224, 224), torch.randn(8, 3, 224, 224)
loss = model(x_q, x_k)
optimizer.zero_grad()
loss.backward()
optimizer.step()

# Use f_q for downstream tasks. For evaluation, call model.eval() to switch batch norm to the statistics collected during training
backbone = model.encoder_q
backbone.fc = nn.Identity()   # Extract the 2048-dim features after average pooling

FAQ

Q. Can the key encoder simply be a copy of the query encoder?
A.

Copying fqf_q directly every step (m=0m = 0) made the loss oscillate and training failed in the paper. Since the queue accumulates keys produced by the encoder at slightly different points in time, a rapidly changing encoder is thought to make the keys in the queue no longer comparable on a consistent basis. The default m=0.999m = 0.999 moves fkf_k toward fqf_q very slowly.

Q. How should the queue size $K$ be chosen?
A.

In the paper, linear evaluation accuracy kept increasing as KK grew from 256 to 65536, and the default is 65536. Since the queue merely stores 128-dimensional vectors, its memory cost is small. However, a larger queue keeps old keys around longer, so the momentum coefficient mm must be large enough to slow down changes in the encoder.

Q. Should I use MoCo or [SimCLR](/self-supervised-learning/simclr)?
A.

Both use a loss of the InfoNCE form that pulls two views together and pushes them away from negatives. The difference lies in how negatives are collected: SimCLR takes them from the same minibatch, while MoCo takes them from a queue of past keys. If minibatches of several thousand are not feasible, MoCo is the better fit. MoCo v2 adopts SimCLR's data augmentation and projection head and reaches 71.1% with ResNet-50 after 800 epochs of training, still with a minibatch of 256.

References

  1. He, K., Fan, H., Wu, Y., Xie, S., & Girshick, R. (2020). Momentum Contrast for Unsupervised Visual Representation Learning. CVPR 2020. arXiv:1911.05722.
  2. Chen, X., Fan, H., Girshick, R., & He, K. (2020). Improved Baselines with Momentum Contrastive Learning. arXiv:2003.04297.
  3. Wu, Z., Xiong, Y., Yu, S. X., & Lin, D. (2018). Unsupervised Feature Learning via Non-Parametric Instance-level Discrimination. CVPR 2018. arXiv:1805.01978.
  4. Official implementation (facebookresearch/moco)