Search

Search papers and lessons

A Simple Framework for Contrastive Learning of Visual Representations (SimCLR)

Ting Chen, Simon Kornblith, Mohammad Norouzi et al. · 2020

SimCLR learns image features by pulling together two random crops of the same photo and pushing apart crops of different photos, a simple recipe that, with a 4x-wide ResNet-50, matches supervised training.

On this page

  • Colour = topic mix
  • Linear algebra
  • Representation learning
  • Calculus
  • Neural network basics
  • Learning basics
  • Losses & regularization
  • Sign in to see your progress

TL;DR

SimCLR learns visual features without labels. For each photo it makes two random views, by cropping, recolouring and blurring, and trains a network so that the two views of the same photo give matching embeddings while views of other photos in the batch do not. The method uses no special architecture and no memory bank, and it depends mostly on the choice of augmentations, a learned projection head, and large batches.

Where you'll see it: as the reference recipe for contrastive pre-training of image encoders, and as the baseline that later contrastive vision methods are measured against.

The problem

Supervised pre-training was then the strongest way to learn image features, and it needs large labelled datasets. Self-supervised methods had two weaknesses. Many relied on hand-designed pretext tasks such as predicting image rotations, solving jigsaw puzzles or colourising grey images, and those heuristics limited what the features could learn. The strongest contrastive methods, such as memory-bank approaches, were complicated: they needed special architectures or stored a bank of past embeddings.

The authors ask what makes contrastive prediction tasks produce good representations, and they study the parts of the framework one at a time instead of proposing a new architecture. Their stated aim is a simpler method that does better than the complicated ones.

Key idea

The framework has four parts, shown in the diagram below.

  1. A stochastic augmentation that turns each image into two correlated views, x~i\tilde{\mathbf{x}}_i and x~j\tilde{\mathbf{x}}_j. They form a positive pair.
  2. A base encoder ff, a ResNet, that maps a view to a representation h\mathbf{h}.
  3. A projection head gg, a small MLP with one hidden layer, that maps h\mathbf{h} to z\mathbf{z}. The loss is computed on z\mathbf{z}.
  4. A contrastive loss that asks, for each view, which of the other views in the batch is its partner.
flowchart LR
  X[Image] --> A1[Augment: view 1]
  X --> A2[Augment: view 2]
  A1 --> F1[ResNet f]
  A2 --> F2[ResNet f shared weights]
  F1 --> H1[h1] --> G1[Head g] --> Z1[z1]
  F2 --> H2[h2] --> G2[Head g] --> Z2[z2]
  Z1 --> L[Contrastive loss pulls z1 and z2 together, pushes others apart]
  Z2 --> L

After training, the head is thrown away. The representation h\mathbf{h} is what gets used for downstream tasks. The paper's three most important findings are that the augmentation pair matters a great deal, that the head helps, and that the loss benefits from large batches and long training.

The method

The contrastive loss

Each minibatch has NN images. Two augmented views of each image give 2N2N points, so each point has one positive partner and 2N−22N - 2 negatives. The similarity is cosine similarity between normalised embeddings, sim⁡(u,v)=u⊤v/(∥u∥∥v∥)\operatorname{sim}(\mathbf{u}, \mathbf{v}) = \mathbf{u}^\top \mathbf{v} / (\lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert). For a positive pair (i,j)(i, j) the loss is

ℓi,j=−log⁡exp⁡(sim⁡(zi,zj)/τ)∑k=12N1[k≠i]exp⁡(sim⁡(zi,zk)/τ)\ell_{i,j} = -\log \frac{\exp\big(\operatorname{sim}(\mathbf{z}_i, \mathbf{z}_j) / \tau\big)}{\sum_{k=1}^{2N} \mathbb{1}_{[k \neq i]} \exp\big(\operatorname{sim}(\mathbf{z}_i, \mathbf{z}_k) / \tau\big)}

where τ\tau is a temperature. The paper calls this NT-Xent, for normalised temperature-scaled cross entropy. The final loss averages ℓi,j\ell_{i,j} over all positive pairs in both orders. It is a softmax cross-entropy in which the correct answer is the partner view, so it is the same shape of loss as classification, with the other views in the batch as the classes.

Example
One anchor, four views

Take two photos, so four views: views 1 and 2 come from photo A, views 3 and 4 from photo B. Use temperature τ=0.5\tau = 0.5. Anchor is view 1, its positive is view 2, and the negatives are views 3 and 4. Suppose the cosine similarities are s12=0.9s_{12} = 0.9, s13=0.1s_{13} = 0.1 and s14=−0.2s_{14} = -0.2.

  1. Positive term: exp⁡(0.9/0.5)=exp⁡(1.8)=6.050\exp(0.9 / 0.5) = \exp(1.8) = 6.050.
  2. Negative terms: exp⁡(0.1/0.5)=exp⁡(0.2)=1.221\exp(0.1 / 0.5) = \exp(0.2) = 1.221 and exp⁡(−0.2/0.5)=exp⁡(−0.4)=0.670\exp(-0.2 / 0.5) = \exp(-0.4) = 0.670.
  3. Denominator: 6.050+1.221+0.670=7.9416.050 + 1.221 + 0.670 = 7.941.
  4. Probability the positive is picked: 6.050/7.941=0.7626.050 / 7.941 = 0.762.
  5. Loss for this anchor: −ln⁡(0.762)=0.272-\ln(0.762) = 0.272.

Interpretation: the loss is small because the positive is much closer than the negatives. If s13s_{13} rose to 0.9, the first negative would match the positive, the denominator would grow to 6.050+6.050+0.670=12.7706.050 + 6.050 + 0.670 = 12.770, the probability would fall to 6.050/12.770=0.4746.050 / 12.770 = 0.474, and the loss would rise to about 0.75. A real batch of N=4096N = 4096 photos gives each anchor 2×4096−2=81902 \times 4096 - 2 = 8190 negatives instead of two.

The loss is computed over the full batch, so no negatives are stored. This is the main simplification relative to memory-bank methods, which keep a large set of past embeddings as negatives.

Augmentation defines the task

The paper's first main claim is that the augmentation pair defines the prediction task. Random cropping alone produces many views that share a colour distribution, so a network can recognise two crops of the same photo just by matching their colours. The paper shows with colour histograms that this is possible, and so colour distortion is needed to remove the shortcut.

The default policy composes three augmentations:

  • Random crop and resize to 224 by 224, using Inception-style cropping with an area between 8 and 100 percent of the original, followed by a horizontal flip with probability one half.
  • Colour distortion, with brightness, contrast and saturation each jittered by up to 0.8 times a strength value, and hue by up to 0.2. Jitter is applied with probability 0.8, and grayscale with probability 0.2. The default strength is 1.
  • Gaussian blur with probability one half, with sigma sampled from 0.1 to 2.0 and a kernel about 10 percent of the image size.

No single augmentation is enough. Figure 5 of the paper shows that a single transformation leaves the contrastive task easy to solve and produces weak features, while the composition of crop and colour produces strong ones. The paper also finds that contrastive learning needs stronger colour augmentation than supervised learning. In Table 1, linear accuracy rises from 59.6 to 64.5 percent as colour strength goes from 1/8 to the default with blur, while the supervised model drops from 77.0 to 75.4 over the same range.

The projection head

The most unusual finding is about the head. The paper compares three heads: none, a linear projection, and a nonlinear projection with one hidden layer and a ReLU. The nonlinear head beats the linear one by about 3 points, and beats no head by more than 10 points. The representation before the head, h\mathbf{h}, is also more than 10 points better than the one after it, z\mathbf{z}.

The authors' explanation is that the contrastive loss asks z\mathbf{z} to be invariant to the augmentations. So gg can throw away information the downstream task needs, such as colour or orientation. To test this, they train small classifiers to predict which transformation was applied. On h\mathbf{h} they predict colour versus grayscale with 99.3 percent accuracy, and on z\mathbf{z} with 97.4 percent. For rotation the figures are 67.6 and 25.6 percent. The head keeps the loss happy while h\mathbf{h} keeps the information.

Batch size, optimiser and normalisation

The batch size varies from 256 to 8192. The paper uses the LARS optimiser for every batch size, because standard SGD with momentum may be unstable at large batches when the learning rate is scaled linearly. The default is batch 4096 for 100 epochs, with a learning rate of 0.3 times the batch size divided by 256, which is 4.8 at the default, weight decay of 10−610^{-6}, 10 warm-up epochs and cosine decay. Training ResNet-50 this way takes about 1.5 hours on 128 TPU v3 cores.

Batch normalisation creates a shortcut. If the statistics are computed on each device separately, the two views of a photo sit on the same device and share statistics, and the network can exploit that. The paper computes the batch-norm statistics across all devices, which removes the leak.

Loss choices and temperature

The paper compares NT-Xent with a logistic loss and a margin loss, with and without semi-hard negative mining. NT-Xent reaches 63.9 percent linear accuracy, while the best alternative reaches 57.9. The authors attribute the gap to two properties of the normalised loss. The normalisation and temperature weight the negatives by how hard they are, so the loss focuses on confusable negatives without needing a mining step. Without normalisation and a tuned temperature, accuracy falls sharply. In the paper's temperature sweep on normalised embeddings, τ=0.1\tau = 0.1 gave the best linear accuracy (64.4 percent), against 59.7 at 0.05, 60.7 at 0.5 and 58.0 at 1.

Results

The main numbers use a ResNet-50 and linear evaluation on ImageNet, where a linear classifier is trained on frozen features.

MethodArchitectureTop-1 linear accuracy
Local aggregationResNet-5060.2
MoCoResNet-5060.6
CPC v2ResNet-5063.8
SimCLRResNet-5069.3
SimCLRResNet-50 (2 times wider)74.2
SimCLRResNet-50 (4 times wider)76.5

The 4 times wider model matches a supervised ResNet-50, which is the headline result. It is about 7 percent better in relative terms than the previous best, 71.5 for CPC v2 with a ResNet-161.

With a few labels the gap is larger. Fine-tuning on 1 percent of ImageNet labels, the 4 times wider model reaches 85.8 percent top-5 accuracy, against 48.4 for a supervised baseline. With 10 percent of the labels it reaches 92.6 percent, against 80.4.

On transfer, the paper fine-tunes on 12 natural-image datasets. The self-supervised model is significantly better than the supervised baseline on 5 of them, worse on 2, which are Pets and Flowers, and statistically tied on the other 5. Those results are for the 4 times wider model. Appendix B.8 gives results for the standard ResNet-50.

Two cost points matter for reading the table. The method trains for 1000 epochs in the comparison, against the 100 used in ablations, and it needs large batches. The paper says training longer and at larger batch sizes helps, and it does not claim that the small-budget numbers are the best.

Why it mattered

The paper showed that contrastive learning did not need special architectures or a memory bank. A standard ResNet, a two-layer head and a well-chosen augmentation pair were enough to match supervised pre-training on ImageNet. That made the method easy to reproduce and to adapt.

It also gave a clear picture of what matters. Augmentation and the projection head are as important as the loss, and the best representation is not the one the loss is computed on.

The paper's own results show where the cost lies. The best numbers use batches of thousands, trained on 32 to 128 TPU cores, and an augmentation policy tuned for natural images. The framework is simple, but the recipe is not cheap. The conclusion argues that self-supervised learning remains undervalued, and that the difference from supervised ImageNet training comes down to augmentation, the head and the loss.

Reading guide

Read these sections in order. The prerequisites matter for the parts shown.

  1. Section 1, Introduction. Needs Self-Supervised Learning for the pretext-task framing and Contrastive Learning for the basic idea that positives are pulled together and negatives pushed apart.
  2. Section 2.1, The framework. Needs Cosine Similarity for the normalised dot product, Softmax Temperature for the temperature τ\tau, and Cross-Entropy Loss for the softmax form of NT-Xent. Convolutional Neural Network and Deep Residual Learning for Image Recognition (ResNet) cover the encoder.
  3. Section 2.2, Large batches. Needs Momentum for the SGD baseline, and Batch Normalization for the cross-device statistics issue.
  4. Section 3, Data augmentation. Needs Data Augmentation for the basic ideas, and Representation Learning for why a shortcut like colour histograms can hurt the learned features.
  5. Section 4, Architectures for encoder and head. Needs Representation Learning for what the head is protecting. Table 3 is easiest after reading the invariance argument.
  6. Section 5, Loss functions and batch size. Needs Softmax Temperature again for the temperature sweep, and Transfer Learning for the linear and fine-tuning protocols in Section 6.
  7. Section 6, Comparison with state of the art. Needs Transfer Learning for the transfer results and Fine-Tuning for the semi-supervised fine-tuning setup.

Check yourself

QuestionIn one sentence, what does SimCLR use as the positive pair for a training image, and what does it use as negatives?Show answer

The positive pair is two random augmented views of the same image. The negatives are the augmented views of every other image in the same minibatch. No negatives are stored in a memory bank.

QuestionA minibatch has 4096 images, so 8192 views. How many negative views does each anchor have in the NT-Xent loss, and what is the learning rate at this batch size if the paper's rule is 0.3 times batch size divided by 256?Show answer

Each anchor has 2×4096−2=81902 \times 4096 - 2 = 8190 negatives, since it excludes itself and its positive. The learning rate is 0.3×4096/256=0.3×16=4.80.3 \times 4096 / 256 = 0.3 \times 16 = 4.8.

QuestionWhy does the paper use the representation before the projection head for downstream tasks, rather than the output of the head?Show answer

The loss asks the head output to be invariant to the augmentations, so the head can discard information such as colour or orientation that a downstream task may need. The paper shows that the layer before the head predicts the applied transformation far better, with 99.3 percent against 97.4 percent for colour, and 67.6 percent against 25.6 percent for rotation. The head serves the loss, and the earlier layer keeps the information.

QuestionRandom cropping alone is a popular augmentation. Why does SimCLR add colour distortion, and what would go wrong without it?Show answer

Crops of the same image share a colour distribution, so the network can match two crops by their colour histograms rather than learning shape or texture. Colour distortion removes that shortcut, so the positive pair becomes a harder task that forces the network to learn structure. Without it, the features are much weaker. Table 1 shows linear accuracy rising from 59.6 to 64.5 percent as colour strength increases.

QuestionA team wants to pre-train a small encoder on 200,000 unlabelled product photos with only 8 GPUs and limited memory. They are considering SimCLR. Which parts of the recipe would be most at risk, and what would they change first?Show answer

The batch size is the main risk. SimCLR gets its negatives from the batch, so a small batch means few negatives, and the paper finds that large batches help. The team could use a smaller batch with more epochs, since the paper shows the batch-size gap shrinks with longer training, or use a memory bank or a momentum encoder at extra cost. They should also keep cross-device batch norm statistics in mind, and tune colour strength and crop size for their product images rather than copying ImageNet settings.

Sources

  • Chen, Kornblith, Norouzi and Hinton, A Simple Framework for Contrastive Learning of Visual Representations, 2020. arxiv.org/abs/2002.05709
  • He, Fan, Wu, Xie and Girshick, Momentum Contrast for Unsupervised Visual Representation Learning, 2019. arxiv.org/abs/1911.05722
  • van den Oord, Li and Vinyals, Representation Learning with Contrastive Predictive Coding, 2018. arxiv.org/abs/1807.03748

Read the full paper

Ting Chen, Simon Kornblith, Mohammad Norouzi et al., 2020. arXiv:2002.05709