AI Logic

Self-Supervised Learning

Barlow Twins

Updated:

Barlow Twins training flow. The left side shows an image turned into two augmented views, each passed through an encoder (ResNet-50) and a projection head with shared weights to produce embeddings Z^A and Z^B, which form the cross-correlation matrix C fed into the Barlow Twins loss. The right side shows, for D = 8, the target values of C (1 on the diagonal for invariance, 0 off the diagonal for redundancy reduction) and the order of the loss computation: per-dimension standardization, C = Z^A⊤Z^B ÷ N, and the sum of (C − I)² with off-diagonal terms weighted by λ

Background and Overview

Barlow Twins is a self-supervised learning method that builds a cross-correlation matrix between the dimensions of the embeddings of two views of the same image and pushes it toward the identity matrix. It was proposed by Zbontar et al. at Facebook AI Research in 2021 and presented at ICML 2021. Without negatives, a predictor, or a moving-average network, it reaches a top-1 accuracy of 73.2% with ResNet-50 under linear evaluation on ImageNet.

Learning that pulls together the features of two views faces the problem of collapse: the loss can be lowered simply by outputting the same feature for every image. Earlier methods avoided collapse through implementation tricks such as negatives (SimCLR), a predictor and a moving average (BYOL), or a predictor and stop-gradient (SimSiam).

Barlow Twins instead designs the loss function itself so that it does not allow collapse. Setting the diagonal of the cross-correlation matrix to 1 aligns the embeddings of the two views. Setting the off-diagonal entries to 0 decorrelates the embedding dimensions from one another, so each dimension carries different information. The paper states that this loss avoids collapsed solutions by construction, even though the two networks remain symmetric.

The name comes from neuroscientist H. Barlow's redundancy-reduction principle (the hypothesis that the goal of sensory processing is to recode redundant inputs into a representation whose components are statistically independent) and from the two networks with shared weights (twins). As an analogy, take two photos of the same person from different angles: the idea is to make the per-item ratings ("hair color," "face shape," and so on) agree between the photos, while keeping the items from merely restating one another.

Theory (Training Procedure and Loss)

The Barlow Twins network is a single network fθf_\theta made of an encoder (ResNet-50) followed by a projection head, and the two views share the same weights. The encoder output is called the representation, the projection head output is called the embedding, and the loss is computed on the embeddings.

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

  1. Apply random data augmentation twice, independently, to a minibatch of NN images XX to create views YAY^A and YBY^B.
  2. Pass both through fθf_\theta to obtain embeddings ZAZ^A and ZBZ^B (each N×DN \times D).
  3. Standardize each embedding dimension along the batch to mean 0 and standard deviation 1.
  4. Compute the cross-correlation matrix C\mathcal{C} (D×DD \times D).
  5. Compute the loss from the difference between C\mathcal{C} and the identity matrix, and update fθf_\theta.

The entry Cij\mathcal{C}_{ij} of the cross-correlation matrix in step 4 is the correlation, over the NN samples in the minibatch (indexed by bb), between dimension ii of ZAZ^A and dimension jj of ZBZ^B. Its value lies between −1-1 (perfect anti-correlation) and 11 (perfect correlation).

Cij=∑bzb,iA zb,jB∑b(zb,iA)2 ∑b(zb,jB)2\mathcal{C}_{ij} = \frac{\sum_b z^A_{b,i}\, z^B_{b,j}}{\sqrt{\sum_b \left(z^A_{b,i}\right)^2}\ \sqrt{\sum_b \left(z^B_{b,j}\right)^2}}

The loss in step 5 consists of two terms: one for the diagonal and one for the off-diagonal entries.

LBT=∑i(1−Cii)2⏟invariance term+λ∑i∑j≠iCij2⏟redundancy reduction term\mathcal{L}_{\mathcal{BT}} = \underbrace{\sum_i \left(1 - \mathcal{C}_{ii}\right)^2}_{\text{invariance term}} + \lambda \underbrace{\sum_i \sum_{j \neq i} \mathcal{C}_{ij}^2}_{\text{redundancy reduction term}}

λ\lambda is a positive constant that balances the two terms; the paper uses λ=5×10−3\lambda = 5 \times 10^{-3}. Since there are about DD times as many off-diagonal entries as diagonal ones, λ\lambda is set to a small value.

The figure at the top illustrates this flow. The left side shows the two views passing through the encoder and projection head with shared weights, then through the cross-correlation matrix into the loss; the right side shows the target of the cross-correlation matrix (1 on the diagonal, 0 elsewhere) and the order of the loss computation.

After training, discard the projection head and use the encoder output (a 2048-dimensional representation for ResNet-50) for downstream tasks.

How the Two Terms Prevent Collapse

The two terms play different roles.

  • Invariance term (diagonal to 1): Cii=1\mathcal{C}_{ii} = 1 means that, for every image, dimension ii of view AA and dimension ii of view BB move in perfect lockstep. This makes the embeddings insensitive to data augmentation.
  • Redundancy reduction term (off-diagonal to 0): it removes the correlation between embedding dimensions so that each dimension carries non-overlapping information. The paper explains that this term can be viewed as a soft constraint that whitens the embeddings (decorrelating the dimensions and equalizing their variances). It holds back the drift toward collapse that the invariance term alone would cause.

The paper also explains the loss through the information bottleneck principle from information theory: a good representation keeps as much information about the image as possible while carrying as little information as possible about the applied data augmentation.

The difference from InfoNCE is also clear. Both have a term that aligns the two views and a term that spreads out the embeddings, and both use minibatch statistics. They differ in how they spread out the embeddings.

AspectInfoNCE (SimCLR, etc.)Barlow Twins
How it spreads embeddingsPushes samples apart from each otherDecorrelates embedding dimensions
Unit of comparisonPairs of images in the minibatch (N×NN \times N)Pairs of embedding dimensions (D×DD \times D)
Minibatch sizeLarger is better (more negatives)Barely drops even at 256
Embedding dimensionPlateaus quickly as it growsLarger is better (up to 16384 in the paper)

The cross-correlation matrix is computed after standardizing the embeddings along the batch. In the paper's comparison, removing the batch normalization in the projection head and also dropping this standardization (turning it into a cross-covariance matrix) lowered accuracy from 71.4% to 53.4%. In implementations, take care to compute the mean and standard deviation along the sample axis, not along the feature axis (which would normalize each sample to unit length).

Experimental Results

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

Linear evaluation (Table 1 of the paper, top-1 accuracy):

MethodAccuracy
Supervised76.5%
SimCLR69.3%
MoCo v271.1%
SimSiam71.3%
SwAV (without multi-crop)71.8%
Barlow Twins73.2%
BYOL74.3%
SwAV (with multi-crop)75.3%

Learning with few labels (Table 2 of the paper): fine-tuning on 1% of ImageNet labels gives 55.0%, slightly above the compared methods (BYOL 53.2%, SwAV 53.9%); with 10% of labels it reaches 69.7%, on par with them.

Transfer (Table 4 of the paper): object detection on PASCAL VOC (Faster R-CNN, VOC07+12) gives AP 56.8 (53.5 with supervised pretraining), and object detection on COCO (Mask R-CNN) gives AP 39.2 (38.2 with supervised pretraining), on par with or slightly above other self-supervised methods.

Removing loss terms (300 epochs, Table 5 of the paper):

LossAccuracy
Baseline (both terms)71.4%
Invariance term only57.3%
Redundancy reduction term only0.1%
Normalization along the feature axis69.8%
No batch normalization in the projection head71.2%
Above, plus no standardization along the batch53.4%
Replaced with cross-entropy with temperature63.3%

Adding asymmetric components (Table 6 of the paper): adding stop-gradient as in BYOL and SimSiam gives 70.5%, adding a predictor gives 70.2%, and adding both gives 61.3%, all below the baseline. Barlow Twins does not need an asymmetric network to prevent collapse.

Practical Considerations

  • Network architecture: the projection head consists of three linear layers, each with 8192 output dimensions. Batch normalization and ReLU follow the first two layers. In the paper, accuracy increases as the output dimension of the projection head grows, while the number of layers plateaus at three.
  • Optimization: following the BYOL setup, training uses LARS for 1000 epochs with a minibatch of 2048. The learning rate is 0.2 for weights and 0.0048 for biases and batch normalization parameters, both multiplied by batch size ÷ 256. The first 10 epochs are a warmup, after which the rate decays with a cosine schedule down to 1/1000. Weight decay is 1.5×10−61.5 \times 10^{-6}. Training took about 124 hours on 32 V100 GPUs (BYOL took about 113 hours in the same environment).
  • Minibatch size: accuracy barely changes even with a minibatch of 256 (SimCLR drops by about 4 points). The best result in the paper's comparison was with 1024.
  • λ\lambda: varying it in the range 0.002–0.02 is reported to change accuracy only slightly.
  • Data augmentation: the same as BYOL (cropping, horizontal flipping, color jittering, grayscale conversion, Gaussian blur, and solarization).

Barlow Twins loses much of its performance when data augmentation is reduced. The paper reports that it behaves like SimCLR in this respect and unlike BYOL. When changing the combination of augmentations, treat it as a method whose performance drops easily and verify the result. Also, with 8192-dimensional embeddings the cross-correlation matrix is 8192×81928192 \times 8192, which requires a corresponding amount of memory.

Comparison with Other Methods

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

MethodNegativesHow collapse is preventedNetwork asymmetryBest suited for
SimCLRYes (within the same minibatch)Pushes away from negativesNoneWhen 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 averagePredictor, moving average, stop-gradientAiming for high performance with long training
SimSiamNoPredictor and stop-gradientPredictor, stop-gradientKeeping the mechanism as simple as possible
SwAVNoDistributes assignments equally across prototypesStop-gradient (when computing codes)High performance from short training with multi-crop
Barlow TwinsNoA loss that decorrelates dimensionsNonePreventing collapse with the loss alone, training with small batches

A distinctive feature of Barlow Twins is that its mechanism is fully explained by the loss formula alone. On the other hand, its linear evaluation accuracy falls short of BYOL and SwAV with multi-crop, and it depends heavily on data augmentation, so these points should be weighed when choosing a method.

PyTorch example

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

"""
Barlow Twins written to follow Algorithm 1 and Section 2.2 of the paper.
Encoder = ResNet-50 (2048-dim representation), projection head = 3 linear layers (8192 dims each)
"""


def off_diagonal(x):
  # Return the off-diagonal elements of a square matrix as a 1-D tensor
  n = x.size(0)
  return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()


class BarlowTwins(nn.Module):
  def __init__(self, dim=8192, lambd=5e-3):
    super().__init__()
    self.backbone = models.resnet50()
    self.backbone.fc = nn.Identity()                  # Representation: 2048 dims
    self.projector = nn.Sequential(                   # Embedding: 8192 dims
      nn.Linear(2048, 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),
    )
    # Standardize each embedding dimension along the batch (mean 0, std 1; no learnable parameters)
    self.bn = nn.BatchNorm1d(dim, affine=False)
    self.lambd = lambd

  def forward(self, y_a, y_b):
    z_a = self.projector(self.backbone(y_a))          # N × D
    z_b = self.projector(self.backbone(y_b))
    n = z_a.size(0)
    c = self.bn(z_a).t() @ self.bn(z_b) / n           # Cross-correlation matrix: D × D (Eq. (2))
    on_diag = (torch.diagonal(c) - 1).pow(2).sum()    # Invariance term
    off_diag = off_diagonal(c).pow(2).sum()           # Redundancy reduction term
    return on_diag + self.lambd * off_diag            # Eq. (1)


model = BarlowTwins(dim=1024)   # A smaller dimension for illustration; the paper uses 8192
optimizer = torch.optim.SGD(model.parameters(), lr=0.2, momentum=0.9, weight_decay=1.5e-6)  # The paper uses LARS

model.train()   # During training, standardize with minibatch statistics
y_a, y_b = torch.randn(16, 3, 224, 224), torch.randn(16, 3, 224, 224)  # Two views of the same images
loss = model(y_a, y_b)
optimizer.zero_grad()
loss.backward()
optimizer.step()

# For downstream tasks, discard the projection head and use the backbone output (2048 dims). Switch to model.eval() for evaluation
features = model.backbone

FAQ

Q. Why is $\lambda$ applied only to the off-diagonal term?
A.

There are DD diagonal entries but D(D−1)D(D-1) off-diagonal entries, so without weighting, the off-diagonal term would dominate the loss. The paper uses λ=5×10−3\lambda = 5 \times 10^{-3} and reports that accuracy changes little within the range 0.002–0.02.

Q. Is the redundancy reduction term alone enough?
A.

No. In the paper's comparison, using only the redundancy reduction term gave 0.1% under linear evaluation. Without the invariance term that aligns the two views, there is no reason to learn features that are insensitive to data augmentation. Conversely, the invariance term alone reaches only 57.3%, so both terms are necessary.

Q. How large should the embedding dimension be?
A.

In the paper, accuracy kept increasing as the output dimension of the projection head grew, all the way up to the largest tested value of 16384. The default is 8192. This contrasts with SimCLR and BYOL, which plateau quickly as the dimension grows. However, the cross-correlation matrix grows with the square of the dimension, so choose it with memory in mind.

References

  1. Zbontar, J., Jing, L., Misra, I., LeCun, Y., & Deny, S. (2021). Barlow Twins: Self-Supervised Learning via Redundancy Reduction. ICML 2021. arXiv:2103.03230.
  2. Grill, J.-B., et al. (2020). Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning. NeurIPS 2020. arXiv:2006.07733.
  3. Official implementation (facebookresearch/barlowtwins)