Search

Search papers and lessons

Unsupervised Learning of Visual Features by Contrasting Cluster Assignments

Mathilde Caron, Ishan Misra, Julien Mairal et al. · 2020

Caron and colleagues' SwAV learns image features online by predicting one augmented view's cluster code from another view, with no pairwise feature comparisons.

On this page

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

TL;DR

SwAV is a self-supervised method for image features. It takes two augmented views of each image, turns each view's features into a cluster code by matching them against a set of learned prototype vectors, and trains the network so that each view predicts the other view's code. Because the comparison happens between codes rather than between pairs of images, the method needs no large memory bank or momentum encoder, and it can be trained online on minibatches. It reaches 75.3 percent top-1 accuracy on ImageNet with a linear classifier on a ResNet-50.

Builds on: Self-Supervised Learning, Contrastive Learning, K-Means Clustering, Sinkhorn-Knopp · Leads to: clustering-based self-supervision that works online and at scale, and a standard reference point for self-supervised vision pretraining.

Why it mattered

Contrastive instance learning had become the strongest family of self-supervised vision methods, but it works by comparing many pairs of images. That comparison is expensive, and the usual remedies, a large memory bank or a momentum encoder, cost memory and complexity. The clustering methods that avoided pairwise comparisons, such as DeepCluster, were offline: they needed a full pass over the dataset to form their targets, which does not suit very large or streaming data.

SwAV keeps the clustering idea and makes it online. The authors report that it beats supervised ImageNet pretraining on several downstream tasks, and that it is the first method to do so using only a linear classifier on frozen features, without fine-tuning. The same paper also introduces multi-crop, a cheap way to use more views per image. The two ideas can be used separately, and the authors show that multi-crop improves several other self-supervised methods by two to four points.

The problem

Self-supervised learning removes manual labels and trains on a pretext task. For instance discrimination, each image and its transformations form their own class, and a contrastive loss pushes the features of different images apart while pulling views of the same image together. The loss is only practical if the comparisons are approximated, which means either a memory bank of past features or a momentum encoder, and both add cost.

Clustering offers a different route. Cluster the features, use the cluster index as a pseudo-label, and train a classifier on it. The DeepCluster method of Caron and colleagues did this, but its clusters were formed over the whole dataset in alternation with training. That is the bottleneck SwAV removes. The paper's question is whether the cluster codes can be computed online, from the minibatch, and still avoid the trivial solution in which every image gets the same code. Their answer has two parts: an equal-partition constraint on each batch, solved with a fast normalisation step, and a swapped prediction between views.

How it works

The input is a batch of images. Each image is cropped and augmented twice. The output is a convolutional encoder whose features cluster the images in a way that is consistent across augmentations.

flowchart LR
  X["Two augmented views of each image"] --> F["Encoder and projection give unit-length features z"]
  F --> S["Scores against K learned prototypes"]
  S --> Q["Sinkhorn step turns batch scores into codes q"]
  S --> P["Softmax with temperature gives predictions p"]
  Q -->|"codes of one view supervise the other view"| P
  1. Augment each image twice. Two random crops of the same image give views tt and ss. Check: both views show the same object, so their correct codes should agree.
  2. Encode and normalise. The encoder and a small projection head map each view to a feature, which is scaled to unit length. Check: the feature lies on a sphere, so comparisons depend on direction only.
  3. Score against prototypes. Each feature is dotted with KK learned prototype vectors. A tiny instance: with two prototypes and temperature τ=0.2\tau = 0.2, view tt scores (0.5,0.3)(0.5, 0.3). Check: the first prototype is slightly closer to view tt.
  4. Compute the code of the other view. For a batch, a Sinkhorn step converts the scores into soft codes that spread the batch evenly over prototypes. In the tiny instance, suppose the code for view ss is (0.7,0.3)(0.7, 0.3). Check: the code is soft, not a hard one-hot choice.
  5. Predict the swapped code. The softmax of view tt's scores gives p=(0.731,0.269)p = (0.731, 0.269), since e2.5/(e2.5+e1.5)≈0.731e^{2.5} / (e^{2.5} + e^{1.5}) \approx 0.731. The cross-entropy is −∑kqs(k)log⁡p(k)=−(0.7log⁡0.731+0.3log⁡0.269)≈0.613-\sum_k q_s^{(k)} \log p^{(k)} = -(0.7 \log 0.731 + 0.3 \log 0.269) \approx 0.613. Check: the loss is small only when view tt's prediction agrees with view ss's code.
  6. Swap and sum. The same term is computed with the roles of the views exchanged, and the two terms are added. Check: each view both predicts and supplies a code, so the prototypes and encoder are trained from both directions.
  7. Update and repeat. Gradients update the encoder and prototypes, and the prototypes are renormalised. For multi-crop, extra small views each predict the codes of the two full-size views. Check: no pairwise feature comparison appears anywhere in the loss.

The equal-partition constraint in step 4 is what prevents collapse. Without it, the easiest solution is to give every image the same code, which makes the swapped prediction trivially correct. The paper notes that a strong entropy term makes all samples spread uniformly, which is also a collapse, so the smoothing parameter must stay low.

The math

Features, prototypes and the swapped loss

Let fθf_\theta be the encoder. Each augmented view xntx_{nt} of image xnx_n gives a unit-length feature znt=fθ(xnt)/∥fθ(xnt)∥2\mathbf{z}_{nt} = f_\theta(x_{nt}) / \|f_\theta(x_{nt})\|_2. A matrix C=[c1,…,cK]\mathbf{C} = [\mathbf{c}_1, \dots, \mathbf{c}_K] holds KK trainable prototypes. For two views tt and ss, the code of each view is a vector over prototypes, qt\mathbf{q}_t and qs\mathbf{q}_s. The softmax prediction for view tt is

pt(k)=exp⁡(1τzt⊤ck)∑k′exp⁡(1τzt⊤ck′),ℓ(zt,qs)=−∑kqs(k)log⁡pt(k).p_t^{(k)} = \frac{\exp\big(\tfrac{1}{\tau}\mathbf{z}_t^{\top}\mathbf{c}_k\big)}{\sum_{k'} \exp\big(\tfrac{1}{\tau}\mathbf{z}_t^{\top}\mathbf{c}_{k'}\big)}, \qquad \ell(\mathbf{z}_t, \mathbf{q}_s) = -\sum_k \mathbf{q}_s^{(k)} \log p_t^{(k)}.

Here τ\tau is a temperature. The symbol ℓ\ell is the cross-entropy between the code of one view and the prediction from the other. The swapped loss adds the two directions, L(zt,zs)=ℓ(zt,qs)+ℓ(zs,qt)L(\mathbf{z}_t, \mathbf{z}_s) = \ell(\mathbf{z}_t, \mathbf{q}_s) + \ell(\mathbf{z}_s, \mathbf{q}_t). The tiny instance in "How it works" uses τ=0.2\tau = 0.2 and scores (0.5,0.3)(0.5, 0.3), so the scaled scores are (2.5,1.5)(2.5, 1.5), and the code is (0.7,0.3)(0.7, 0.3).

Codes as an optimal-transport problem

The codes come from an optimal transport problem: maximise a similarity between features and prototypes, with an entropy term that keeps them soft. For a batch of BB features Z=[z1,…,zB]\mathbf{Z} = [\mathbf{z}_1, \dots, \mathbf{z}_B] and a code matrix Q\mathbf{Q},

max⁡Q∈QTr⁡(Q⊤C⊤Z)+εH(Q),H(Q)=−∑ijQijlog⁡Qij,\max_{\mathbf{Q} \in \mathcal{Q}} \operatorname{Tr}\big(\mathbf{Q}^{\top} \mathbf{C}^{\top} \mathbf{Z}\big) + \varepsilon H(\mathbf{Q}), \qquad H(\mathbf{Q}) = -\sum_{ij} \mathbf{Q}_{ij} \log \mathbf{Q}_{ij},

where ε\varepsilon controls smoothness. The feasible set enforces the equal partition,

Q={ Q∈R+K×B:Q1B=1K1K, Q⊤1K=1B1B }.\mathcal{Q} = \big\{\, \mathbf{Q} \in \mathbb{R}_+^{K \times B} : \mathbf{Q}\mathbf{1}_B = \tfrac{1}{K}\mathbf{1}_K,\ \mathbf{Q}^{\top}\mathbf{1}_K = \tfrac{1}{B}\mathbf{1}_B \,\big\}.

Each prototype receives roughly B/KB / K of the batch, and each image's codes sum to one. The solution has the form Q∗=Diag⁡(u)exp⁡(C⊤Z/ε)Diag⁡(v)\mathbf{Q}^{*} = \operatorname{Diag}(\mathbf{u})\exp(\mathbf{C}^{\top}\mathbf{Z}/\varepsilon)\operatorname{Diag}(\mathbf{v}), where the vectors u\mathbf{u} and v\mathbf{v} are found by a few Sinkhorn-Knopp normalisation passes. The paper uses three passes, with ε=0.05\varepsilon = 0.05, and keeps the soft codes rather than rounding them, because rounding made the online setting converge to a worse solution.

Multi-crop

If the image gives two full-size views t1,t2t_1, t_2 and VV small views, the loss generalises to

L=∑i∈{1,2}∑v=1V+21v≠i ℓ(ztv,qti).L = \sum_{i \in \{1,2\}} \sum_{v=1}^{V+2} \mathbf{1}_{v \neq i}\, \ell(\mathbf{z}_{t_v}, \mathbf{q}_{t_i}).

Codes are computed only from the full-size views. The small views are cheap because they are low resolution, and the paper reports that computing codes from them hurts transfer, since a small crop covers only a small part of the scene.

Results

ImageNet. With a ResNet-50 and a linear classifier on frozen features, SwAV reaches 75.3 percent top-1 accuracy after 800 epochs with batches of 4096. The paper reports this as 4.2 points above the previous state of the art and 1.2 points below a fully supervised model. A wider ResNet reaches 78.5 percent.

Semi-supervised. Fine-tuning with 1 percent of ImageNet labels, SwAV gets 53.9 top-1 and 78.5 top-5, against 48.3 and 75.5 for SimCLR and 25.4 and 48.4 for supervised training on the same labels. With 10 percent of the labels it gets 70.2 top-1 and 89.9 top-5, against 65.6 for SimCLR. FixMatch reaches 71.5 at 10 percent, but it uses label propagation, not self-supervision alone.

Small batches. With batches of 256 and a queue of 3,840 stored features, SwAV reaches 72.0 after 200 epochs and 74.3 after 400 epochs with more crops. MoCov2 needs 65,536 stored features and a momentum encoder, and it reaches 71.1 only after 800 epochs. The paper reports that one SwAV epoch takes longer in wall-clock time than one SimCLR or MoCov2 epoch, but SwAV needs far fewer epochs, and its 200-epoch run takes about 102 hours.

Transfer. Linear classification on frozen features gives 56.7 on Places205, 88.9 on VOC07 and 48.6 on iNaturalist 2018, all above the supervised backbone (53.2, 87.5 and 46.7). Object detection with fine-tuning gives 82.6 AP50 on VOC07+12 with Faster R-CNN, and 41.6 AP on COCO with Mask R-CNN, both above supervised pretraining (81.3 and 39.7). The paper says SwAV is the first self-supervised method to beat supervised ImageNet features on the three linear-classification datasets, Places205, VOC07 and iNaturalist 2018.

Ablations and comparisons. At matched settings, SwAV and DeepCluster-v2 outperform SimCLR by 2 points without multi-crop and by 3.5 points with it. Multi-crop improves each method it is applied to by two to four points. DeepCluster-v2 run with SwAV's best settings reaches 75.2 percent, against 75.3 for SwAV, so the online method matches the offline one on ImageNet while scaling better.

Uncurated data. Pretraining on 1 billion random public Instagram images, SwAV keeps a gain of about 6 points over SimCLR, the same gain as on ImageNet. Pretraining on those images improves over training from scratch on ImageNet by 1.3 points.

Limits.

  • The main results need large-scale compute. The best model takes 800 epochs with batches of 4096 on 64 V100 GPUs, and the paper's own timing puts 100 epochs at about six hours on that hardware.
  • The equal-partition constraint assumes the batch should spread evenly over the prototypes. The paper tests uncurated data, but it does not study strongly imbalanced classes directly, so the effect of imbalance is an open question from the text.
  • The soft-code smoothing must stay low, because high smoothing collapses the codes. The right value is a tuning choice that the paper fixes at 0.05 for all its runs.
  • The experiments are on images, mostly with ResNet-50 and ImageNet-style data. The paper says SwAV is not tuned for semi-supervised learning, and it lists combining it with a momentum encoder and a large queue as future work.

Reading guide

Read the paper in this order. The right column names the lessons on this site that cover what each section assumes.

SectionWhat it coversLessons to have in hand
1 IntroductionInstance discrimination, the contrastive loss, and the swapped-prediction ideaSelf-Supervised Learning, Contrastive Learning
2 Related workMemory banks, momentum encoders, DeepCluster and its offline natureK-Means Clustering, Transfer Learning
3.1 Online clusteringThe swapped loss, the equal-partition codes, and small-batch queueSoftmax, Softmax Temperature, Cross-Entropy Loss, Optimal Transport, Entropy
3.2 Multi-cropUsing many low-resolution views at small costData Augmentation
4 Main resultsLinear evaluation, semi-supervised learning, transfer and small batchesDeep Residual Learning for Image Recognition (ResNet), A Simple Framework for Contrastive Learning of Visual Representations (SimCLR), Momentum Contrast for Unsupervised Visual Representation Learning
5 AblationsClustering baselines, multi-crop on other methods, longer training, uncurated dataA Simple Framework for Contrastive Learning of Visual Representations (SimCLR)
Appendix APseudo-code, Sinkhorn-Knopp, and every training detailSinkhorn-Knopp Algorithm

Check yourself

QuestionRecall: what does SwAV use in place of the pairwise feature comparisons of contrastive learning, and why does that help?Show answer
SwAV compares codes instead of features. Each view's features are matched to a set of prototypes to give a cluster code, and the other view must predict that code. Because the comparison goes through prototypes, SwAV needs no large memory bank of past features and no momentum encoder, and it can work online on each minibatch.
QuestionComputation: with two prototypes, temperature tau = 0.2, scores (0.5, 0.3) for view t, and a code (0.7, 0.3) for view s, what is the loss ell for predicting the code from view t?Show answer
Divide the scores by 0.2 to get (2.5,1.5)(2.5, 1.5). The softmax is p=(e2.5,e1.5)/(e2.5+e1.5)≈(0.731,0.269)p = (e^{2.5}, e^{1.5}) / (e^{2.5} + e^{1.5}) \approx (0.731, 0.269). The loss is −(0.7log⁡0.731+0.3log⁡0.269)≈0.613-(0.7 \log 0.731 + 0.3 \log 0.269) \approx 0.613.
QuestionWhy: why must the codes be computed under an equal-partition constraint rather than by taking each image's most similar prototype?Show answer
Taking the most similar prototype per image has an easy solution in which every image maps to the same prototype, so the swapped prediction is trivially correct and the features learn nothing. The equal-partition constraint forces the batch to spread over the prototypes, so codes stay distinct across images. The Sinkhorn step makes this affordable on a GPU, and the soft codes beat hard rounding in the online setting.
QuestionApplied: a lab has a million unlabelled microscopy images, where a few cell types make up most of the data, and wants to pretrain with SwAV. What would you check first, and what would you change?Show answer
The equal-partition constraint pushes each batch toward spreading evenly over the prototypes, so common cell types may be split across several prototypes and rare ones may be forced onto prototypes that look wrong. I would check the prototype usage and the cluster sizes on a sample, and look at whether the codes match the cell types on a few labelled examples. I would also check that the augmentations keep the biological content, since the method depends on views of one image agreeing. If the imbalance is strong, I would consider fewer prototypes or a batch sampler that balances cell types, and I would measure the result on a held-out labelled set from the same microscope.

Sources

Read the full paper

Mathilde Caron, Ishan Misra, Julien Mairal et al., 2020. arXiv:2006.09882