Self-Supervised Learning2020intermediate11 min read

SwAV: Unsupervised Learning of Visual Features by Contrasting Cluster Assignments

SwAV: تعلُّم السمات البصرية دون إشراف عبر مقارنة تعيينات العنقدة

Caron, M. · Misra, I. · Mairal, J. · Goyal, P. · Bojanowski, P. · Joulin, A. — NeurIPS

The problem

Self-supervised contrastive methods like SimCLR and MoCo learn powerful visual representations by pulling augmented views of the same image together and pushing different images apart. But they rely on explicit pairwise feature comparisons — which means they need either very large batch sizes (SimCLR uses 8192), a large memory bank, or a to provide enough negative samples. This is computationally expensive and memory-intensive, limiting scalability.

The contribution

SwAV replaces pairwise feature comparison with an online approach. Features are mapped to learnable vectors, and a "" mechanism enforces that two views of the same image receive consistent cluster assignments. The Sinkhorn-Knopp algorithm solves the assignment as an problem, preventing trivial collapse. A new strategy uses 2 full-resolution + V low-resolution crops to capture more information without proportionally increasing cost. SwAV achieves 75.3% top-1 on ImageNet with ResNet-50, surpassing all prior self-supervised methods and even beating supervised pretraining on transfer tasks.

The impact

SwAV showed that does not require pairwise comparisons, opening a new family of clustering-based self-supervised methods. Its strategy became a standard augmentation technique adopted across the field. SwAV directly inspired DINO, which used prototypes with Vision Transformers and discovered emergent segmentation properties. The online clustering paradigm influenced subsequent work on at scale.

Imagine a crowded conference where delegates wear no name tags. To figure out who shares interests, you could shake hands with every single person and compare notes — that's pairwise contrastive learning. It works, but with 1000 people you'd need 500,000 handshakes.

SwAV takes a smarter approach: place topic tables around the room (these are the prototypes). Each person walks to the table that matches their expertise. If two photographs of the same person — taken from different angles — consistently sit down at the same table, you know the seating captures something real about them. No need to compare every pair of people directly.

The twist: SwAV doesn't just check that both photos sit at the same table — it swaps the check. It predicts which table photo A belongs to by looking only at photo B's representation, and vice versa. If both predictions land correctly, the prototypes and the representations must be learning meaningful structure.

The cost of pairwise comparison

Contrastive learning methods like SimCLR learn representations by creating two augmented views of each image, passing them through an , and then comparing their features. The model is trained to make the two views of the same image similar () while making views of different images dissimilar (negative pairs).

The catch: you need a lot of negative pairs for this to work well. SimCLR uses batch sizes of 4096–8192, meaning each positive pair is compared against thousands of negatives. MoCo builds a momentum-maintained of 65,536 negatives. Both approaches work, but they introduce significant computational or architectural overhead.

What if you could get the benefits of contrastive learning — learning without labels by comparing views — without the cost of comparing every feature pair?

Open in Lab
Left: pairwise contrastive learning compares every feature pair directly. Right: SwAV routes features through shared prototypes, avoiding pairwise comparison entirely.
The demo wakes as you arrive…

The SwAV idea: cluster, then swap

SwAV — Swapping Assignments between Views — replaces direct feature comparison with an elegant two-step dance. First, it maps every feature to a set of KK learnable prototype vectors, producing a soft cluster assignment (a "code"). Second, it enforces consistency by predicting the code of one view from the representation of another view.

Here is the pipeline: take an image xnx_n, create two augmented views xn,tx_{n,t} and xn,sx_{n,s} using different transformations. Pass each through a shared encoder fθf_\theta to get features ztz_t and zsz_s. Each feature is then compared to all KK prototype vectors {c1,…,cK}\{c_1, \ldots, c_K\} to produce a code — a probability distribution over prototypes.

The key trick: the code for view tt is predicted using the feature of view ss, and vice versa. If both views truly capture the same content, then knowing one view's representation should be enough to predict the other view's cluster assignment. This "swapped" prediction is what gives SwAV its name.

Open in Lab
Two views of the same image produce features z_t and z_s. Each gets a code (cluster assignment). SwAV predicts each code from the OTHER view's feature. Click views to trace the swapped prediction flow.
The demo wakes as you arrive…

The loss: cross-entropy with swapped codes

Before seeing the formula, let's understand what SwAV is optimizing. For each image, we have two views. Each view produces a and a code (soft cluster assignment). The loss asks: "Can I predict the code that view tt received, using only the feature vector of view ss?" If the encoder and prototypes are good, the answer should be yes — because both views depict the same image.

The prediction works by computing the similarity between a feature zsz_s and each prototype ckc_k (via a ), applying a -scaled softmax to get a probability ps(k)p_s^{(k)}, and then measuring how well this probability matches the code qtq_t of the other view using cross-entropy.

L(zt,zs)=ℓ(zt,qs)+ℓ(zs,qt)\mathcal{L}(z_t, z_s) = \ell(z_t, q_s) + \ell(z_s, q_t)
SwAV loss — symmetric swapped prediction — The total loss sums two cross-entropy terms. The first predicts the code qsq_s of view ss from the feature ztz_t of view tt. The second does the reverse. Symmetry ensures both views contribute equally to learning.
ℓ(zt,qs)=−∑k=1Kqs(k)log⁡pt(k),pt(k)=exp⁡ ⁣(zt⊤ckτ)∑k′exp⁡ ⁣(zt⊤ck′τ)\ell(z_t, q_s) = - \sum_{k=1}^{K} q_s^{(k)} \log p_t^{(k)}, \quad p_t^{(k)} = \frac{\exp\!\left(\frac{z_t^\top c_k}{\tau}\right)} {\sum_{k'} \exp\!\left(\frac{z_t^\top c_{k'}}{\tau}\right)}
Cross-entropy between code and softmax similarity — For each prototype kk, pt(k)p_t^{(k)} is the probability that feature ztz_t belongs to prototype ckc_k, computed as a temperature-scaled softmax of their dot product. The code qs(k)q_s^{(k)} is the target — the soft assignment of the OTHER view ss to prototype kk. The temperature τ\tau controls how peaked the distribution is.

Prototypes: learnable cluster centers

The prototype vectors {c1,…,cK}\{c_1, \ldots, c_K\} live in the same as the features. Think of them as KK "topic anchors" — fixed reference points that the features are compared against. Unlike k-means centroids that are recomputed from scratch, SwAV prototypes are learned end-to-end via alongside the encoder.

In practice, K=3000K = 3000 prototypes are used. The prototypes form the columns of a matrix C∈RD×KC \in \mathbb{R}^{D \times K}, where DD is the feature dimension. Computing the code for a feature zz is simply a matrix multiplication C⊤zC^\top z followed by the Sinkhorn-Knopp normalization.

Because the prototypes are shared across all images and all batches, they act as a persistent clustering structure. Each batch updates the prototypes slightly through , so the clustering evolves smoothly over .

Open in Lab
Features (dots) are assigned to learnable prototypes (stars). Drag the slider to simulate training steps: watch how prototypes shift and features re-cluster.
The demo wakes as you arrive…

Avoiding collapse: the Sinkhorn-Knopp trick

A critical danger in clustering-based methods is collapse: the model assigns every image to the same cluster and achieves zero loss by ignoring all differences. This is the trivial solution — and it is catastrophic.

SwAV prevents collapse by formulating the code computation as an optimal transport problem. Instead of simply taking the argmax or softmax of C⊤zC^\top z, SwAV requires that across all images in a batch, the cluster assignments are equipartitioned — every prototype gets roughly the same total assignment mass. This means no single prototype can hoard all the features.

The constraint is: the assignment matrix QQ must have rows that sum to 1/K1/K (equal mass per prototype) and columns that sum to 1/B1/B (each image gets a valid distribution). The Sinkhorn-Knopp algorithm finds this doubly-stochastic matrix by alternating row and column normalizations:

Q∗=Diag(u) exp⁡ ⁣(C⊤Zε)Diag(v)Q^* = \text{Diag}(u) \, \exp\!\left(\frac{C^\top Z}{\varepsilon}\right) \text{Diag}(v)
Sinkhorn-Knopp — optimal transport assignment — ZZ is the matrix of all features in the batch, CC is the prototype matrix, and ε\varepsilon is a regularization parameter. Vectors uu and vv are found by 3 iterations of alternating row/column renormalization. This produces a soft assignment where every prototype is used equally — the equipartition constraint that prevents collapse.
Open in Lab
Watch Sinkhorn-Knopp iterations balance the assignment matrix. Without it, all features collapse to one prototype. With it, features spread evenly across all prototypes.
The demo wakes as you arrive…

Multi-crop: more views, same cost

Standard contrastive methods create two views per image, both at full resolution (e.g. 224×224). Increasing the number of views quadratically increases compute in pairwise methods (more pairs to compare). But SwAV doesn't compare pairs — it compares features to prototypes. So adding more views only increases compute linearly.

The authors exploit this by proposing multi-crop: instead of 2 full-resolution views, use 2 full-resolution views (160×160) plus VV small views (96×96). The small views cover different parts of the image, capturing local details like textures, edges, and small objects. The full views capture global structure.

The key insight: the loss only computes codes from the two full-resolution views (which are high quality), but uses ALL views for the prediction term. This means the small views provide additional training signal without needing expensive code computation. In practice, V=4V=4 extra views adds only ~20% compute but boosts performance by ~2% on ImageNet.

Open in Lab
Multi-crop creates 2 full-resolution views (global) plus V small views (local). Toggle crops to see what each view captures from the original image.
The demo wakes as you arrive…

Putting it together: SwAV pseudocode

SwAV training step (simplified PyTorch)python

Simplified to show the idea — not the real implementation.

# Two augmented views of the same image
z_t = normalize(projection_head(encoder(aug_t(x))))
z_s = normalize(projection_head(encoder(aug_s(x))))

# Compute scores: similarity to each prototype
scores_t = z_t @ prototypes.T / temperature   # (B, K)
scores_s = z_s @ prototypes.T / temperature   # (B, K)

# Compute codes via Sinkhorn-Knopp (target assignments)
with torch.no_grad():
    q_t = sinkhorn(scores_t)   # soft assignment for view t
    q_s = sinkhorn(scores_s)   # soft assignment for view s

# Swapped cross-entropy loss
loss = - 0.5 * (q_s * log_softmax(scores_t)).sum(dim=1).mean()
     - 0.5 * (q_t * log_softmax(scores_s)).sum(dim=1).mean()

loss.backward()   # updates encoder, projection head, AND prototypes

Results: bridging the gap to supervised learning

SwAV with ResNet-50 achieves 75.3% top-1 accuracy on ImageNet linear evaluation — a jump of +4.2% over SimCLR (71.1%) and +4.2% over MoCo-v2 (71.1%). This was the first self-supervised method to close the gap with supervised pretraining (76.5%) to just 1.2 percentage points.

On transfer tasks, the picture is even more striking. SwAV representations surpass supervised pretraining on all considered downstream benchmarks — on VOC and COCO, on COCO, and on Places205 and iNaturalist. This suggests that self-supervised features generalize better than supervised ones, which may overfit to ImageNet's label distribution.

The multi-crop strategy contributes significantly: without it, SwAV achieves 72.7%. Adding 4 small views (V=4V=4) pushes it to 75.3%, a gain of +2.6% for minimal extra cost. The number of prototypes (from 3K to 100K) has little effect — performance varies by only ±0.3%, showing that SwAV is robust to this .

Open in Lab
ImageNet top-1 accuracy comparison across self-supervised methods. SwAV closes the gap to supervised pretraining and surpasses it on transfer tasks.
The demo wakes as you arrive…

Why SwAV works: no memory bank, no momentum encoder

MoCo maintains a momentum-updated copy of the entire encoder, doubling memory. SimCLR needs batch sizes in the thousands. SwAV needs neither. The prototypes serve as a compact, persistent summary of the data distribution — replacing both the memory bank and the large batch requirement.

Because the prototypes are just a D×KD \times K matrix (e.g., 256×3000256 \times 3000), they add negligible memory. The Sinkhorn-Knopp step operates on a K×BK \times B matrix, which is also tiny. The dominant cost is the forward pass through the encoder — the same as any other method.

This architectural simplicity also makes SwAV easier to scale. It works with batch sizes from 256 to 4096. It can use a small queue of recent features (2–3 batches) to stabilize the Sinkhorn step for small batches, but this queue stores only features, not gradients, so it is much cheaper than MoCo's momentum encoder.

Timeline: from clustering to prototypes

  1. 2018

    DeepCluster

    Alternated between k-means clustering on features and training the network to predict cluster assignments. Offline: required full-dataset clustering between training epochs.

  2. 2020

    SimCLR

    Simple contrastive framework with aggressive augmentation. Achieved strong results but required batch sizes of 4096–8192 for enough negatives.

  3. 2020

    MoCo v2

    Momentum contrast with a queue of 65K negatives. Memory-efficient but required maintaining a momentum encoder — a slowly-updated copy of the full network.

  4. 2020

    SwAV (this paper)

    Online clustering with learnable prototypes and swapped prediction. No memory bank, no momentum encoder. Multi-crop augmentation. 75.3% top-1 on ImageNet.

  5. 2021

    DINO

    Extended SwAV's prototype idea to Vision Transformers with self-distillation. Discovered emergent segmentation properties in attention maps. Multi-crop strategy inherited directly from SwAV.

SwAV stands at the crossroads of two traditions: offline clustering (DeepCluster, SeLa) and online contrastive learning (SimCLR, MoCo). By making clustering online through learnable prototypes and Sinkhorn-Knopp, and by replacing pairwise comparison with swapped prediction, SwAV combined the best of both worlds. Its multi-crop augmentation became a default tool, and the prototype-based architecture directly seeded DINO, one of the most influential self-supervised methods for vision.

CitationCaron, Misra, Mairal, Goyal, Bojanowski, Joulin. Unsupervised Learning of Visual Features by Contrasting Cluster Assignments. NeurIPS, 2020.

Terms in this paper