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?
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 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 , create two augmented views and using different transformations. Pass each through a shared encoder to get features and . Each feature is then compared to all prototype vectors to produce a code — a probability distribution over prototypes.
The key trick: the code for view is predicted using the feature of view , 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.
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 received, using only the feature vector of view ?" 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 and each prototype (via a ), applying a -scaled softmax to get a probability , and then measuring how well this probability matches the code of the other view using cross-entropy.
Prototypes: learnable cluster centers
The prototype vectors live in the same as the features. Think of them as "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, prototypes are used. The prototypes form the columns of a matrix , where is the feature dimension. Computing the code for a feature is simply a matrix multiplication 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 .
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 , 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 must have rows that sum to (equal mass per prototype) and columns that sum to (each image gets a valid distribution). The Sinkhorn-Knopp algorithm finds this doubly-stochastic matrix by alternating row and column normalizations:
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 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, extra views adds only ~20% compute but boosts performance by ~2% on ImageNet.
Putting it together: SwAV pseudocode
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 () 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 .
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 matrix (e.g., ), they add negligible memory. The Sinkhorn-Knopp step operates on a 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
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.
2020
SimCLR
Simple contrastive framework with aggressive augmentation. Achieved strong results but required batch sizes of 4096–8192 for enough negatives.
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.
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.
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
- Self-Supervised Learningالتعلم ذاتي الإشراف
- Contrastive Learningالتعلم التبايُني
- Clusteringالعنقَدة
- Prototypeنموذج أوّلي
- Soft Assignmentالانتساب الناعم
- Optimal Transportالنقل الأمثل
- Data Augmentationتعزيز البيانات
- Multi-Cropالقصّ المتعدّد
- Representation Learningتعلم التمثيلات الرقمية
- Feature Extractionاستخلاص السمات
- Cosine Similarityتشابه جيب التمام
- Temperatureالحرارة
- Projection Headرأس الإسقاط
- Backboneالبنية الأساسية
- Linear Probeالمسبار الخطي