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θ and K prototypes {c1,…,cK} (the columns of a matrix C). 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.
Apply random data augmentations t and s to the B images in the mini-batch to create two views.
Pass them through the encoder and normalize the features to unit length to obtain zt and zs.
Compute the inner products (scores) z⊤C between the features and the prototypes.
For each view, compute codes qt and qs from the B scores in the mini-batch with the Sinkhorn-Knopp algorithm. No gradient flows through this step.
Divide the scores by a temperature τ and apply softmax to obtain probabilities pt and ps over the prototypes.
Use as the loss the cross-entropy of predicting the code of view t from the probabilities of view s and the code of view s from the probabilities of view t, and update the encoder and the prototypes.
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)
ℓ is the cross-entropy between a code q and the probability p computed from a feature z (k indexes the prototypes).
The code computation in step 4 is what prevents collapse (every image receiving the same code). The codes Q=[q1,…,qB] that assign the mini-batch features Z=[z1,…,zB] 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.
H(Q)=−∑ijQijlogQij is the entropy, and ε controls the smoothness of the assignment. The constraints in 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 s from the features of view t 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 ε small: If the entropy term is too strong (large ε), every image is assigned evenly to every prototype, and the model collapses. The paper uses ε=0.05.
Multi-crop: In addition to two 224×224 crops, V 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} and all views v.
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):
Method
2 × 224×224
2 × 160×160 + 4 × 96×96
Difference
Supervised
76.5%
76.0%
−0.5
SimCLR
68.2%
70.6%
+2.4
DeepCluster-v2
70.2%
74.3%
+4.1
SwAV
70.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):
Method
Stored features
Crops
Epochs
Accuracy
SimCLR
0
2 × 224
200
61.9%
MoCo v2
65,536
2 × 224
200
67.5%
MoCo v2
65,536
2 × 224
800
71.1%
SwAV
3,840
2 × 160 + 4 × 96
200
72.0%
SwAV
3,840
2 × 224 + 6 × 96
400
74.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, Sinkhorn ε=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 decay10−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 B in the mini-batch is smaller than the number of prototypes K, 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.
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 p. 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.