AI Logic

Self-Supervised Learning

SwAV

Updated:

Training flow of SwAV. The left side shows two data augmentations of an image passing through an encoder f_θ with shared weights and shared prototypes C to produce scores, which feed the swapped prediction loss. The right side shows computing codes q that spread B scores evenly over the prototypes with Sinkhorn-Knopp, dividing scores by τ and applying softmax to get probabilities p, and using the probabilities of views t and s to predict each other's codes crosswise

Background and Overview

SwAV (Swapping Assignments between multiple Views) is a self-supervised learning method that assigns image features to learnable prototypes (representative vectors of clusters) and predicts the assignment of one view from the features of another view. It was proposed in 2020 by Caron et al. at Inria and Facebook AI Research and presented at NeurIPS 2020. In linear evaluation on ImageNet, it reached 75.3% top-1 accuracy with ResNet-50, narrowing the gap with supervised pretraining to 1.2 points.

Contrastive methods such as SimCLR and MoCo compare features pair by pair, pulling views of the same image together and pushing other images away. Good results require many comparison partners, which means large mini-batches or a queue that stores past features.

Instead of comparing features directly, SwAV compares cluster assignments (codes). The idea is that if two views of the same image carry the same information, the features of one view should be able to predict which cluster the other view was assigned to. As an analogy, rather than comparing two photos side by side, each photo is sorted onto shelves such as "dog-like" or "indoor-like", and the check is whether both land on the same shelves. Because assignments are computed only within the mini-batch, SwAV clusters online while training, unlike earlier clustering methods that pass over the whole dataset repeatedly.

The paper also proposes multi-crop, a data augmentation that adds more views by mixing crops of different resolutions.

Theory (Training Procedure and Loss)

The SwAV network consists of an encoder fθf_\theta and KK prototypes {c1,…,cK}\{c_1, \dots, c_K\} (the columns of a matrix CC). The encoder is a ResNet-50 followed by a two-layer projection MLP (128-dimensional output), and the same weights are used for both views. The prototypes are also shared between the two views and are learned by gradient descent together with the encoder.

Following the pseudocode in the paper's appendix, one training step proceeds as follows.

  1. Apply random data augmentations tt and ss to the BB images in the mini-batch to create two views.
  2. Pass them through the encoder and normalize the features to unit length to obtain ztz_t and zsz_s.
  3. Compute the inner products (scores) z⊤Cz^\top C between the features and the prototypes.
  4. For each view, compute codes qtq_t and qsq_s from the BB scores in the mini-batch with the Sinkhorn-Knopp algorithm. No gradient flows through this step.
  5. Divide the scores by a temperature τ\tau and apply softmax to obtain probabilities ptp_t and psp_s over the prototypes.
  6. Use as the loss the cross-entropy of predicting the code of view tt from the probabilities of view ss and the code of view ss from the probabilities of view tt, and update the encoder and the prototypes.
  7. Renormalize the prototypes to unit length.

The loss in step 6 is called the "swapped prediction" because the codes are swapped before being predicted.

L(zt,zs)=ℓ(zt,qs)+ℓ(zs,qt)L(z_t, z_s) = \ell(z_t, q_s) + \ell(z_s, q_t)

ℓ\ell is the cross-entropy between a code qq and the probability pp computed from a feature zz (kk indexes the prototypes).

ℓ(zt,qs)=−∑kqs(k)log⁡pt(k),pt(k)=exp⁡(1τzt⊤ck)∑k′exp⁡(1τzt⊤ck′)\ell(z_t, q_s) = -\sum_k q_s^{(k)} \log p_t^{(k)}, \qquad p_t^{(k)} = \frac{\exp\left(\frac{1}{\tau} z_t^\top c_k\right)}{\sum_{k'} \exp\left(\frac{1}{\tau} z_t^\top c_{k'}\right)}

The code computation in step 4 is what prevents collapse (every image receiving the same code). The codes Q=[q1,…,qB]Q = [q_1, \dots, q_B] that assign the mini-batch features Z=[z1,…,zB]Z = [z_1, \dots, z_B] to the prototypes are chosen so that they grow with the similarity between features and prototypes while splitting the images in the mini-batch evenly across all prototypes.

max⁡Q∈Q Tr(Q⊤C⊤Z)+εH(Q),Q={Q∈R+K×B | Q1B=1K1K, Q⊤1K=1B1B}\max_{Q \in \mathcal{Q}} \ \mathrm{Tr}\left(Q^\top C^\top Z\right) + \varepsilon H(Q), \qquad \mathcal{Q} = \left\{ Q \in \mathbb{R}_+^{K \times B} \ \middle|\ Q \mathbf{1}_B = \tfrac{1}{K}\mathbf{1}_K,\ Q^\top \mathbf{1}_K = \tfrac{1}{B}\mathbf{1}_B \right\}

H(Q)=−∑ijQijlog⁡QijH(Q) = -\sum_{ij} Q_{ij} \log Q_{ij} is the entropy, and ε\varepsilon controls the smoothness of the assignment. The constraints in Q\mathcal{Q} require equal row sums (the amount assigned to each prototype) and equal column sums (the total assignment of each image). The solution is obtained with the Sinkhorn-Knopp algorithm, which alternately rescales rows and columns, and the paper found three iterations sufficient.

The figure at the top illustrates this flow. The left side shows the two views passing through the same encoder and prototypes into the swapped prediction loss; the right side shows the code computation, the probability computation, and the swapped prediction.

Why It Avoids Collapse Without Negatives, and Multi-Crop

SwAV can learn without negatives because of the equipartition constraint. A collapsed solution that gives every image the same code cannot satisfy the condition "split the images in the mini-batch evenly across all prototypes". As a result, the codes differ from image to image, and the features are trained to predict them.

  • Swapped prediction: Predicting the code of view ss from the features of view tt requires the features to retain information shared by both views (the kind and shape of the objects shown). Whereas contrastive learning learns "whether two views come from the same image", SwAV learns "whether they fall into the same cluster".
  • Soft codes: The Sinkhorn-Knopp solution is used as continuous values rather than rounded to 0 or 1. In the paper, rounded codes performed worse when training with mini-batches. The paper explains that rounding is a more aggressive step than a gradient update, so it may converge quickly but tends to fall into poor solutions.
  • Keep ε\varepsilon small: If the entropy term is too strong (large ε\varepsilon), every image is assigned evenly to every prototype, and the model collapses. The paper uses ε=0.05\varepsilon = 0.05.
  • Multi-crop: In addition to two 224×224 crops, VV small 96×96 crops covering only part of the image are used. Small crops are cheap to compute, so adding views barely increases the compute cost. Codes are computed only from the two large crops, and the features of all views are used to predict those codes.

With multi-crop, the loss is summed over pairs of the two large code-producing crops i∈{1,2}i \in \{1, 2\} and all views vv.

L(zt1,zt2,…,ztV+2)=∑i∈{1,2}∑v=1V+21v≠i ℓ(ztv,qti)L\left(z_{t_1}, z_{t_2}, \dots, z_{t_{V+2}}\right) = \sum_{i \in \{1,2\}} \sum_{v=1}^{V+2} \mathbb{1}_{v \neq i}\, \ell\left(z_{t_v}, q_{t_i}\right)

SwAV does not need to share the feature matrix across all GPUs. Sinkhorn-Knopp only shares the row and column sums. The paper notes that this makes SwAV easier to distribute across many machines than SimCLR or MoCo.

Experimental Results

The paper's experiments center on pretraining on the ImageNet training set (ResNet-50) and linear evaluation with frozen features.

Linear evaluation (Figure 2 of the paper): ResNet-50 reached 75.3% (800 epochs, mini-batch 4096). In the same table, SimCLR scores 70.0%, MoCo v2 71.1%, and supervised pretraining 76.5%. ResNet-50 models widened 2×, 4×, and 5× reached 77.3%, 77.9%, and 78.5%.

Effect of multi-crop (Figure 3 of the paper, 400 epochs):

Method2 × 224×2242 × 160×160 + 4 × 96×96Difference
Supervised76.5%76.0%−0.5
SimCLR68.2%70.6%+2.4
DeepCluster-v270.2%74.3%+4.1
SwAV70.1%74.1%+4.0

Multi-crop improves every self-supervised method by 2–4 points, and works especially well for clustering-based methods. It has almost no effect on supervised training.

Small mini-batches (Table 3 of the paper, mini-batch 256):

MethodStored featuresCropsEpochsAccuracy
SimCLR02 × 22420061.9%
MoCo v265,5362 × 22420067.5%
MoCo v265,5362 × 22480071.1%
SwAV3,8402 × 160 + 4 × 9620072.0%
SwAV3,8402 × 224 + 6 × 9640074.3%

SwAV outperformed MoCo v2 with a quarter of the epochs. However, each epoch takes about 1.4 times as long as MoCo v2 because of the additional backward passes.

Transfer (Table 2 of the paper): SwAV outperformed supervised ImageNet pretraining on all of linear evaluation on Places205, VOC07, and iNaturalist2018, object detection on PASCAL VOC (Faster R-CNN, AP50 82.6 versus 81.3 for supervised), and object detection on COCO (Mask R-CNN, AP 41.6 versus 39.7).

Training with few labels (Table 1 of the paper): Fine-tuning with 1% and 10% of the ImageNet labels gave 53.9% and 70.2% (SimCLR: 48.3% and 65.6%).

Practical Considerations

  • Main settings: temperature τ=0.1\tau = 0.1, Sinkhorn ε=0.05\varepsilon = 0.05 (3 iterations), 3000 prototypes, LARS (learning rate 4.8, warmup over the first 10 epochs, then decayed with a cosine schedule to 0.0048), and weight decay 10−610^{-6}. With a mini-batch of 4096 on 64 V100 GPUs, 100 epochs took about 6 hours (72.1% accuracy) and 800 epochs about 50 hours (75.3%).
  • Number of prototypes: The paper's appendix reports 72.8% with 300 prototypes, 73.9% with 3000, and 73.8% with 100,000, so changing the number by a factor of 10 makes little difference.
  • Data augmentation: Large crops cover 14–100% of the image area and are resized to 224×224; small crops cover 5–14% and are resized to 96×96. On top of that, the same horizontal flip, color distortion, and Gaussian blur as SimCLR are applied.
  • Small mini-batches: If the number of images BB in the mini-batch is smaller than the number of prototypes KK, an even split is impossible. In that case, features from previous mini-batches are stored in a queue (about 3840) and added to the Sinkhorn-Knopp computation, while the loss uses only the codes of the current mini-batch.

During the first epoch of training, the prototypes are frozen and not updated. The paper does this to help training get started. The prototypes are also renormalized to unit length after every update. Omitting these steps may prevent training from progressing as in the paper's setup.

Comparison with Other Methods

The table below compares SwAV with methods from the same "pull two views together" family along the same axes.

MethodWhat is comparedNegativesCollapse preventionSuitable when
SimCLRFeaturesUsed (within the same mini-batch)Pushing away negativesLarge batches are feasible
MoCoFeaturesUsed (queue of past keys)Pushing away negativesMany negatives are wanted with small batches
BYOLFeatures (via prediction)Not usedPredictor and a target updated by moving averageHigh performance without negatives is wanted
SwAVCluster assignmentsNot usedSpreading assignments evenly over prototypesHigh performance with short training, or training on very many images
SimSiamFeatures (via prediction)Not usedPredictor and stop-gradientThe simplest possible mechanism is wanted
DINODistribution of the teacher's outputNot usedCentering and sharpeningSelf-supervised training of ViTs

SwAV sits between clustering-based methods (such as DeepCluster) and contrastive learning. The paper shows that DeepCluster-v2, an improved DeepCluster, performs about as well as SwAV, but argues that SwAV, which does not need repeated passes over the whole dataset, is better suited to very large datasets such as one billion images. SwAV's multi-crop was later carried over into DINO.

PyTorch example

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

"""
One SwAV step written to follow the pseudocode in Appendix A.1 of the paper (two-view case).
Encoder = ResNet-50 + two-layer projection MLP (128-dim output), prototypes C = 3000
"""


@torch.no_grad()
def sinkhorn(scores, eps=0.05, n_iters=3):
  # scores: B x K. Returns soft codes Q (B x K, rows sum to 1) spread evenly over the prototypes
  Q = torch.exp(scores / eps).t()          # K × B
  Q /= Q.sum()
  K, B = Q.shape
  for _ in range(n_iters):
    Q /= Q.sum(dim=1, keepdim=True)        # equalize row (prototype) sums
    Q /= K
    Q /= Q.sum(dim=0, keepdim=True)        # equalize column (image) sums
    Q /= B
  Q *= B                                   # make column sums equal to 1
  return Q.t()


class SwAV(nn.Module):
  def __init__(self, feat_dim=128, n_prototypes=3000):
    super().__init__()
    backbone = models.resnet50()
    backbone.fc = nn.Identity()
    self.encoder = nn.Sequential(
      backbone,
      nn.Linear(2048, 2048), nn.BatchNorm1d(2048), nn.ReLU(inplace=True),
      nn.Linear(2048, feat_dim),
    )
    self.prototypes = nn.Linear(feat_dim, n_prototypes, bias=False)   # C: each weight row is a prototype

  @torch.no_grad()
  def normalize_prototypes(self):
    w = self.prototypes.weight
    w.copy_(F.normalize(w, dim=1))

  def forward(self, x_t, x_s, temp=0.1):
    B = x_t.size(0)
    z = F.normalize(self.encoder(torch.cat([x_t, x_s])), dim=1)   # 2B × D, unit length
    scores = self.prototypes(z)                                   # 2B × K (z^T C)
    scores_t, scores_s = scores[:B], scores[B:]
    q_t, q_s = sinkhorn(scores_t), sinkhorn(scores_s)             # codes (no gradient)
    log_p_t = F.log_softmax(scores_t / temp, dim=1)
    log_p_s = F.log_softmax(scores_s / temp, dim=1)
    # swapped prediction: predict q_t with p_s and q_s with p_t
    return -0.5 * ((q_t * log_p_s).sum(dim=1) + (q_s * log_p_t).sum(dim=1)).mean()


model = SwAV()
optimizer = torch.optim.SGD(model.parameters(), lr=0.6, momentum=0.9, weight_decay=1e-6)  # the paper uses LARS

model.train()
model.normalize_prototypes()
for step in range(2):
  x_t, x_s = torch.randn(8, 3, 224, 224), torch.randn(8, 3, 224, 224)   # two views of the same images
  loss = model(x_t, x_s)
  optimizer.zero_grad()
  loss.backward()
  freeze_prototypes = True   # do not update the prototypes during the first epoch
  if freeze_prototypes:
    model.prototypes.weight.grad = None
  optimizer.step()
  model.normalize_prototypes()   # renormalize the prototypes to unit length after every update

# Downstream tasks use only the backbone (ResNet-50). Switch to model.eval() for evaluation
backbone = model.encoder[0]

FAQ

Q. What are prototypes?
A.

They are a set of learnable vectors with the same dimension as the features (128), acting as the representative points of clusters. Unlike k-means centroids, they are not computed from the whole dataset at once but updated gradually by gradient descent together with the encoder. The inner products between an image's features and the prototypes determine how much the image belongs to each prototype (its code).

Q. Why is the gradient stopped when computing the codes?
A.

The codes play the role of targets, so the loss sends gradients only through the probabilities pp. In the pseudocode in the paper's appendix, the Sinkhorn-Knopp algorithm also runs in a block where gradients are not computed. The SimSiam paper reports that removing this gradient stop in SwAV made training diverge.

Q. Can multi-crop be used with other methods?
A.

Yes. In the paper, applying it to SimCLR improved linear evaluation by 2.4 points, and clustering-based methods improved by about 4 points. Small crops are cheap to compute, so adding views barely increases the compute cost. However, it has almost no benefit for supervised training, where accuracy dropped by 0.5 points.

References

  1. Caron, M., Misra, I., Mairal, J., Goyal, P., Bojanowski, P., & Joulin, A. (2020). Unsupervised Learning of Visual Features by Contrasting Cluster Assignments. NeurIPS 2020. arXiv:2006.09882.
  2. Chen, X., & He, K. (2021). Exploring Simple Siamese Representation Learning. CVPR 2021. arXiv:2011.10566.
  3. Cuturi, M. (2013). Sinkhorn Distances: Lightspeed Computation of Optimal Transport. NeurIPS 2013. arXiv:1306.0895.
  4. Official implementation (facebookresearch/swav)