AI Logic

Self-Supervised Learning

SimSiam

Updated:

SimSiam training flow. The left side shows an image turned into two augmented views, both passed through an encoder f with shared weights; one side becomes p₁ after the predictor h, and the other becomes zā‚‚ after stop-gradient, both feeding into the negative cosine similarity. The right side shows the symmetrized loss that adds half of each direction, and a table of the components that SimCLR, BYOL, SwAV, and SimSiam use to prevent collapse (negatives, moving-average encoder, Sinkhorn-Knopp, predictor, stop-gradient)

Background and Overview

SimSiam (Simple Siamese) is a self-supervised learning method that learns features simply by passing two views through an encoder with shared weights, attaching a predictor to one side, and stopping the gradient on the other. It was proposed by Chen and He at Facebook AI Research in 2020 and presented at CVPR 2021. Without negatives, large minibatches, or a moving-average encoder, it reaches a top-1 accuracy of 68.1% (100 epochs) with ResNet-50 under linear evaluation on ImageNet.

Methods that learn by pulling two views together face a pitfall called collapse, in which every image gets the same feature. Earlier methods each relied on one special component to prevent collapse: negatives in SimCLR, clustering in SwAV, and a moving-average encoder in BYOL.

SimSiam shows that it does not collapse even with all of these components removed, and identifies stop-gradient (the operation that stops gradients) as what really matters. In the paper's words, SimSiam is "BYOL without the momentum encoder," "SimCLR without negative pairs," and "SwAV without online clustering." Because it is the simplest form, it serves as a baseline for comparing other methods. The "Siamese" in the name refers to a network with two branches that share the same weights (a Siamese network).

Theory (Training Procedure and Loss)

The SimSiam network has only two parts: an encoder ff and a predictor hh.

  • Encoder ff: a backbone (such as ResNet) combined with a projection MLP. The two views share the same weights.
  • Predictor hh: a small MLP that maps the output of ff to match the output of the other view.

Training repeats the following steps, as in Algorithm 1 of the paper.

  1. Apply random data augmentation twice, independently, to the images xx in a minibatch to create views x1x_1 and x2x_2.
  2. Pass both through the encoder to obtain z1=f(x1)z_1 = f(x_1) and z2=f(x2)z_2 = f(x_2).
  3. Pass both through the predictor to obtain p1=h(z1)p_1 = h(z_1) and p2=h(z2)p_2 = h(z_2).
  4. Compute the negative cosine similarity between p1p_1 and z2z_2 and between p2p_2 and z1z_1. No gradient flows into the zz side here.
  5. Update ff and hh with SGD using the average of the two as the loss.

The similarity in step 4 is given by the following (āˆ„ā‹…āˆ„2\|\cdot\|_2 is the L2 norm).

D(p1,z2)=āˆ’p1∄p1∄2ā‹…z2∄z2∄2\mathcal{D}(p_1, z_2) = -\frac{p_1}{\|p_1\|_2} \cdot \frac{z_2}{\|z_2\|_2}

This is equivalent, up to a constant factor and an additive constant, to the mean squared error between unit-length vectors. Writing stop-gradient as stopgrad\mathrm{stopgrad}, the symmetrized loss is as follows.

L=12D(p1,stopgrad(z2))+12D(p2,stopgrad(z1))\mathcal{L} = \frac{1}{2}\mathcal{D}\bigl(p_1, \mathrm{stopgrad}(z_2)\bigr) + \frac{1}{2}\mathcal{D}\bigl(p_2, \mathrm{stopgrad}(z_1)\bigr)

stopgrad(z2)\mathrm{stopgrad}(z_2) means that z2z_2 is treated as a constant in this term. The encoder on the x2x_2 side receives no gradient from z2z_2 in the first term but does receive one from p2p_2 in the second term. The loss is computed per image and averaged, with a minimum of āˆ’1-1.

The figure at the top illustrates this flow. The left side shows the two views passing through the same encoder, with only one side going through the predictor and the gradient stopped on the other. The right side shows the symmetrized loss and, following the paper's comparison, a table of which components each method uses to prevent collapse.

Why Stop-Gradient Prevents Collapse

The paper investigates what prevents collapse by removing components one at a time.

  • Stop-gradient: without it, the loss quickly reaches its minimum of āˆ’1-1, and all outputs become the same vector, i.e., collapse. Linear evaluation gives 0.1% (equal to chance on ImageNet). Since the predictor, batch normalization, and L2 normalization remain in place, this shows that the network architecture alone cannot prevent collapse.
  • Predictor hh: removing it (making it the identity map) causes collapse (0.1%). With the symmetrized loss, the gradient direction without a predictor is the same whether or not stop-gradient is applied. Freezing the predictor at its random initialization does not cause collapse but makes training fail to converge (1.5%).
  • Minibatch size, batch normalization, form of the similarity, symmetrization: the paper concludes that each of these affects accuracy but is unrelated to preventing collapse. For example, changing the similarity from cosine to cross-entropy does not cause collapse (63.2%), nor does dropping symmetrization (64.8%).

So what does stop-gradient do? The paper hypothesizes that SimSiam is an EM-like method that alternately optimizes two sets of variables. Treating the network weights Īø\theta and the per-image representations Ī·x\eta_x as separate variables, consider the following loss.

L(Īø,Ī·)=Ex,T[∄FĪø(T(x))āˆ’Ī·x∄22]\mathcal{L}(\theta, \eta) = \mathbb{E}_{x, \mathcal{T}}\Bigl[\bigl\| \mathcal{F}_\theta(\mathcal{T}(x)) - \eta_x \bigr\|_2^2\Bigr]

FĪø\mathcal{F}_\theta is the network and T\mathcal{T} is the data augmentation. Splitting this into a step that solves for Īø\theta with Ī·\eta fixed and a step that solves for Ī·\eta with Īø\theta fixed, and alternating between them, gives the same form as k-means (clustering that alternately updates centers and assignments). When solving for Īø\theta, Ī·\eta is a constant, so it is natural that no gradient flows into Ī·\eta. The optimal Ī·x\eta_x is the average over data augmentations, ET[FĪø(T(x))]\mathbb{E}_\mathcal{T}[\mathcal{F}_\theta(\mathcal{T}(x))], but SimSiam approximates it with a single augmentation, FĪø(T′(x))\mathcal{F}_\theta(\mathcal{T}'(x)). The paper suggests that the predictor hh learns to compensate for this omitted averaging.

This hypothesis explains "what is being optimized." The paper states that why collapse is prevented is still at the stage of empirical observation. It notes that the output of a randomly initialized network is unlikely to be constant from the start, and that alternating optimization probably has difficulty moving from there toward a solution that outputs the same Ī·x\eta_x for all images.

Experimental Results

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

Removing collapse-preventing components (100 epochs):

SettingAccuracy
SimSiam (baseline)67.7% (68.1% without decaying the predictor's learning rate)
No stop-gradient0.1%
No predictor0.1%
Predictor fixed at random values1.5%

Minibatch size (100 epochs, Table 2 of the paper):

Minibatch64128256512102420484096
Accuracy66.1%67.3%68.1%68.1%68.0%67.9%64.0%

Results are nearly identical from 256 to 2048, and even 64 drops by only 2.0 points. The paper explains that the drop at 4096 is because plain SGD is not suited to overly large minibatches.

Comparison with other methods (Table 4 of the paper; all reproduced by the paper's authors with ResNet-50 and two 224Ɨ224 views):

MethodMinibatchNegativesMoving average100 epochs200 epochs400 epochs800 epochs
SimCLR4096YesNo66.5%68.3%69.8%70.4%
MoCo v2256YesYes67.4%69.9%71.0%72.2%
BYOL4096NoYes66.5%70.6%73.2%74.3%
SwAV4096NoNo66.5%69.1%70.7%71.8%
SimSiam256NoNo68.1%70.0%70.8%71.3%

SimSiam is the best at 100 epochs and beats SimCLR at every training length. On the other hand, it gains less from longer training and falls short of BYOL and MoCo v2 at 800 epochs.

Transfer (Table 5 of the paper, 200 epochs of pretraining): on PASCAL VOC object detection (Faster R-CNN, VOC 07+12), SimSiam reaches AP 56.4 (57.0 with a different learning rate and weight decay), versus 53.5 for supervised pretraining. On COCO detection and instance segmentation (Mask R-CNN), it is on par with supervised pretraining.

Practical Considerations

  • Network architecture: the projection MLP has three layers, with batch normalization applied to every fully connected layer including the output layer, and no ReLU on the output layer (2048 dimensions for both hidden and output layers). The predictor has two layers, with batch normalization applied only to the hidden layer. The predictor's hidden layer is 512 dimensions, a bottleneck narrower than its input and output (2048 dimensions). The paper notes that making the hidden layer as wide as the output sometimes made training unstable or caused it to fail.
  • Optimization: SGD (learning rate 0.05ƗbatchĀ size/2560.05 \times \text{batch size} / 256 with cosine decay, weight decay 0.0001, momentum 0.9), with a default minibatch of 512. Large-batch optimizers such as LARS are unnecessary. Keeping only the predictor's learning rate constant, without decay, gives a slight improvement.
  • Data augmentation: as in SimCLR, random cropping (20–100% of the area), horizontal flipping, color jittering, grayscale conversion, and Gaussian blur.

Applying batch normalization to the predictor's output makes training unstable and causes the loss to oscillate (Table 3 of the paper). Removing batch normalization from the MLPs entirely avoids collapse but lowers accuracy to 34.6%. Keep the combination of using batch normalization everywhere except on the predictor's output.

Comparison with Other Methods

The table compares SimSiam with other methods in the same family of "pulling two views together," from the same perspectives.

MethodNegativesHow collapse is preventedWeights of the two branchesBest suited for
SimCLRYes (within the same minibatch)Pushes away from negativesSharedWhen large batches are feasible
MoCoYes (queue of past keys)Pushes away from negativesOne side is a moving averageUsing many negatives with small batches
BYOLNoPredictor and a target updated by moving averageOne side is a moving averageAiming for top performance with long training
SwAVNoEqualizes assignments across clustersSharedComparing via cluster assignments
SimSiamNoPredictor and stop-gradientSharedLimited compute and a simple mechanism
Barlow TwinsNoA loss that decorrelates feature dimensionsSharedAvoiding both a predictor and stop-gradient

As a rule of thumb, if only a few GPUs are available, minibatches are limited to a few hundred, and quick results from short training are wanted, SimSiam is an easy starting point. For top performance with long training such as 800 epochs, BYOL and MoCo v2 came out ahead in the paper's comparison.

PyTorch example

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

"""
SimSiam written to follow Algorithm 1 and Section 3 of the paper.
Encoder f = ResNet-50 + 3-layer projection MLP, predictor h = 2-layer MLP (bottleneck)
"""


class SimSiam(nn.Module):
  def __init__(self, dim=2048, pred_dim=512):
    super().__init__()
    backbone = models.resnet50()
    prev = backbone.fc.in_features   # 2048
    backbone.fc = nn.Identity()
    projector = nn.Sequential(       # Batch norm on every fully connected layer. No ReLU on the output
      nn.Linear(prev, dim, bias=False), nn.BatchNorm1d(dim), nn.ReLU(inplace=True),
      nn.Linear(dim, dim, bias=False), nn.BatchNorm1d(dim), nn.ReLU(inplace=True),
      nn.Linear(dim, dim, bias=False), nn.BatchNorm1d(dim, affine=False),
    )
    self.encoder = nn.Sequential(backbone, projector)   # f: shared weights for both views
    self.predictor = nn.Sequential(                      # h: batch norm on the hidden layer only, not on the output
      nn.Linear(dim, pred_dim, bias=False), nn.BatchNorm1d(pred_dim), nn.ReLU(inplace=True),
      nn.Linear(pred_dim, dim),
    )

  def forward(self, x1, x2):
    z1, z2 = self.encoder(x1), self.encoder(x2)
    p1, p2 = self.predictor(z1), self.predictor(z2)
    return p1, p2, z1.detach(), z2.detach()              # Stop-gradient on the z side


def D(p, z):
  # Negative cosine similarity (Eq. (1)). z is already detached
  return -F.cosine_similarity(p, z, dim=-1).mean()


model = SimSiam()
batch_size = 512
lr = 0.05 * batch_size / 256
# Keeping only the predictor's learning rate constant helps slightly (Table 1c of the paper). Split into param groups here
optimizer = torch.optim.SGD([
  {"params": model.encoder.parameters(), "fix_lr": False},
  {"params": model.predictor.parameters(), "fix_lr": True},
], lr=lr, momentum=0.9, weight_decay=1e-4)

model.train()
x1, x2 = torch.randn(8, 3, 224, 224), torch.randn(8, 3, 224, 224)  # Two views of the same images
p1, p2, z1, z2 = model(x1, x2)
loss = 0.5 * D(p1, z2) + 0.5 * D(p2, z1)                 # Symmetrized loss (Eq. (4)). Minimum is āˆ’1
optimizer.zero_grad()
loss.backward()
optimizer.step()
# With cosine decay, leave the learning rate of param groups with fix_lr = True unchanged

# Use only the backbone for downstream tasks. Switch to model.eval() for evaluation
backbone = model.encoder[0]

FAQ

Q. How does it differ from BYOL?
A.

In the paper's words, SimSiam is "BYOL without the momentum encoder." BYOL moves the weights of the other side (the target) as a moving average of the online network, whereas SimSiam uses the same weights for both branches and simply stops the gradient on one side. The paper concludes that what prevents collapse is stop-gradient, not the moving average; the moving average can help improve accuracy but is not directly related to preventing collapse.

Q. Which branch gets the stop-gradient?
A.

The output zz on the side that does not go through the predictor. In the loss D(p1,stopgrad(z2))\mathcal{D}(p_1, \mathrm{stopgrad}(z_2)), z2z_2 is treated as a constant. In the symmetrized loss, the roles swap in the other term, D(p2,stopgrad(z1))\mathcal{D}(p_2, \mathrm{stopgrad}(z_1)), so gradients reach the encoder for both views through the predictor side.

Q. Can it be tried on small datasets?
A.

The paper's appendix reports that on CIFAR-10 it also trains without collapse, just as on ImageNet. The setup is a CIFAR variant of ResNet-18 with a 2-layer projection MLP (2048-dimensional output), SGD (base learning rate 0.03, cosine decay, weight decay 0.0005), a minibatch of 512 for 800 epochs, and no Gaussian blur.

References

  1. Chen, X., & He, K. (2021). Exploring Simple Siamese Representation Learning. CVPR 2021. arXiv:2011.10566.
  2. Grill, J.-B., et al. (2020). Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning. NeurIPS 2020. arXiv:2006.07733.
  3. Chen, T., Kornblith, S., Norouzi, M., & Hinton, G. (2020). A Simple Framework for Contrastive Learning of Visual Representations. ICML 2020. arXiv:2002.05709.
  4. Official implementation (facebookresearch/simsiam)