AI Logic

Self-Supervised Learning

BYOL

Updated:

BYOL training flow. The left side shows an image turned into two augmented views, one passing through the online network (encoder f_θ, projection head g_θ, predictor q_θ) and the other through the target network (dashed encoder f_ξ and projection head g_ξ, then z′ after stop-gradient), both feeding into a mean squared error. The right side shows the loss computation (normalize lengths, then 2 − 2 × cosine similarity), the moving-average update rule for the target, and a graph of the schedule that raises τ from 0.996 to 1

Background and Overview

BYOL (Bootstrap Your Own Latent) is a self-supervised learning method that predicts the features of one view of an image from the features of another view, without using negatives. It was proposed by Grill et al. at DeepMind in 2020 and presented at NeurIPS 2020. It reaches a top-1 accuracy of 74.3% with ResNet-50 under linear evaluation on ImageNet, surpassing earlier self-supervised methods.

Contrastive methods such as SimCLR and MoCo pull two views of the same image together and push them away from other images (negatives). Negatives are needed because, with "pulling together" alone, the loss is minimized by outputting the same feature for every image. This is called collapse. Preparing many negatives, however, requires large minibatches or a queue.

BYOL asks whether collapse can be avoided without negatives, and shows that it can by using two networks. An online network trained by gradients predicts the output of a target network that moves slowly as a moving average of the weights. The name, "bootstrap your own latent," refers to the cycle of improving the current self (online) by using a slightly earlier self (target) as a teacher, and then using the improved self as the next teacher. As an analogy, it is like rereading yesterday's notes to rewrite today's.

Theory (Training Procedure and Loss)

BYOL uses two networks: an online network and a target network.

  • Online (weights θ\theta): three stages, an encoder fθf_\theta, a projection head gθg_\theta, and a predictor qθq_\theta. It is updated by gradients.
  • Target (weights ξ\xi): an encoder fξf_\xi and a projection head gξg_\xi with the same architecture as the online network, but without a predictor. It is not updated by gradients but by a moving average of the online weights.

One training step proceeds as follows.

  1. Apply random data augmentations tt and t′t' independently to an image xx to create two views v=t(x)v = t(x) and v′=t′(x)v' = t'(x).
  2. Pass vv through the online network to obtain the representation yθ=fθ(v)y_\theta = f_\theta(v), the projection zθ=gθ(yθ)z_\theta = g_\theta(y_\theta), and the prediction qθ(zθ)q_\theta(z_\theta).
  3. Pass v′v' through the target network to obtain the projection zξ′=gξ(fξ(v′))z'_\xi = g_\xi(f_\xi(v')). No gradient flows here (stop-gradient).
  4. Normalize the prediction qθ(zθ)q_\theta(z_\theta) and zξ′z'_\xi to unit length, and take their squared distance as the loss Lθ,ξ\mathcal{L}_{\theta,\xi}.
  5. Swap vv and v′v', repeat the same computation, and add the loss L~θ,ξ\tilde{\mathcal{L}}_{\theta,\xi} (symmetrization).
  6. Using the combined loss, update only the online weights θ\theta with the optimizer.
  7. Update the target weights ξ\xi as a moving average with θ\theta.

The loss in step 4 is the mean squared error between unit-length vectors and can be rewritten in terms of cosine similarity. qˉ\bar{q} and zˉ′\bar{z}' are qθ(zθ)q_\theta(z_\theta) and zξ′z'_\xi normalized to unit length.

Lθ,ξ=∥qˉ−zˉ′∥22=2−2⋅⟨qθ(zθ),zξ′⟩∥qθ(zθ)∥2 ∥zξ′∥2\mathcal{L}_{\theta,\xi} = \left\| \bar{q} - \bar{z}' \right\|_2^2 = 2 - 2 \cdot \frac{\langle q_\theta(z_\theta), z'_\xi \rangle}{\| q_\theta(z_\theta) \|_2 \, \| z'_\xi \|_2}

The moving average in step 7 is given by the following, where τ∈[0,1]\tau \in [0, 1] is the target decay rate.

θ←optimizer(θ,∇θLθ,ξBYOL,η),ξ←τξ+(1−τ) θ\theta \leftarrow \mathrm{optimizer}\left(\theta, \nabla_\theta \mathcal{L}^{\mathrm{BYOL}}_{\theta,\xi}, \eta\right), \qquad \xi \leftarrow \tau \xi + (1 - \tau)\,\theta

Here Lθ,ξBYOL=Lθ,ξ+L~θ,ξ\mathcal{L}^{\mathrm{BYOL}}_{\theta,\xi} = \mathcal{L}_{\theta,\xi} + \tilde{\mathcal{L}}_{\theta,\xi} and η\eta is the learning rate. τ\tau starts at τbase=0.996\tau_{\mathrm{base}} = 0.996 at the beginning of training and is raised to 1 toward the end. With kk the current step and KK the total number of steps, τ=1−(1−τbase) (cos⁡(πk/K)+1)/2\tau = 1 - (1 - \tau_{\mathrm{base}})\,(\cos(\pi k / K) + 1)/2.

The figure at the top illustrates this flow. The left side shows the online (solid) and target (dashed) paths, making clear that the predictor exists only in the online network and that gradients are stopped on the target side. The right side shows the loss computation, the target update rule, and a graph of the τ\tau schedule drawn from the formula.

After training, keep only the encoder fθf_\theta and use the representation yθy_\theta (2048 dimensions after average pooling for ResNet-50) for downstream tasks. Discard the projection head, the predictor, and the target.

Why It Does Not Collapse Without Negatives

Why collapse, in which every image gets the same feature, does not occur despite the absence of negatives is not fully proven even in the paper. The paper offers the following explanations.

  • It is not loss minimization: the target weights ξ\xi move as a moving average of the online weights, not in the direction of the loss gradient. The paper hypothesizes that the overall dynamics of BYOL cannot be written as gradient descent on a single loss with respect to both θ\theta and ξ\xi. There is therefore no reason for it to head toward a collapsed solution (one of the minima of the loss).
  • When the predictor is near optimal: assuming an optimal predictor, the online update moves in the direction that reduces the conditional variance of the target projection given the online projection. If the online projection is constant (collapsed), this variance actually increases, so collapse is considered an unstable state.
  • The role of the moving average: copying the online weights directly to the target would still pass on new information. However, if the target changes abruptly, the predictor drifts away from its optimum. The paper hypothesizes that the main role of the moving average is to keep the predictor near optimal.

There is also an experiment that served as the paper's starting point. Even when the target is a randomly initialized, frozen network, the online representation trained to predict it reaches 18.8% under linear evaluation, whereas the frozen network itself gives 1.4%. If a representation better than its teacher can be learned, the learned representation can serve as the new teacher and the process can be repeated. This is the idea behind BYOL.

What prevents collapse is the combination of the predictor and a target that moves by moving average. In the paper's comparison, removing either the predictor or the target network in a setting without negatives dropped linear evaluation accuracy to 0.3% or below. Do not omit the predictor or make the target identical to the online network to simplify the implementation.

Experimental Results

The paper's experiments center on pretraining on the ImageNet training set and linear evaluation with frozen features.

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

MethodEncoderAccuracy
SimCLRResNet-5069.3%
MoCo v2ResNet-5071.1%
BYOLResNet-5074.3%
SimCLRResNet-50 (4× wider)76.5%
BYOLResNet-50 (4× wider)78.6%
BYOLResNet-200 (2× wider)79.6%

Fine-tuning with few labels (Table 2 of the paper, ResNet-50): using only 1% and 10% of ImageNet labels, BYOL reaches 53.2% and 68.8%, SimCLR 48.3% and 65.6%, and training on the labels alone 25.4% and 56.4%.

Transfer to other tasks (Table 4 of the paper): semantic segmentation on PASCAL VOC 2012 gives mIoU 76.3 (74.4 with supervised pretraining), and object detection on VOC 2007 gives AP50 77.5 (74.4 with supervised pretraining).

Robustness to minibatch size and data augmentation (comparison at 300 epochs): SimCLR's accuracy drops quickly as the minibatch shrinks, whereas BYOL's stays nearly unchanged from 256 to 4096. Removing color jittering from the augmentations lowers BYOL by 9.1 points and SimCLR by 22.2 points. With cropping only, BYOL reaches 59.4% and SimCLR 40.3%.

Target decay rate τbase\tau_{\mathrm{base}} (300 epochs, Table 5a of the paper):

Targetτbase\tau_{\mathrm{base}}Accuracy
Frozen random network118.8%
Moving average of the online network0.99969.8%
Moving average of the online network0.9972.5%
Moving average of the online network0.968.4%
Online network used as is00.3%

Copying the target every step makes training unstable, while never updating it is stable but does not improve the representation. Any value from 0.9 to 0.999 gave 68.4% or higher.

Practical Considerations

  • Network architecture: the projection head and the predictor are both MLPs of the form "linear layer with 4096 outputs → batch normalization → ReLU → linear layer with 256 outputs." Unlike SimCLR, no batch normalization is applied to the final output.
  • Data augmentation: the same cropping, horizontal flipping, color jittering, grayscale conversion, and Gaussian blur as SimCLR, plus solarization (inverting the brightness of bright pixels).
  • Optimization: the paper trains for 1000 epochs with LARS and a cosine learning rate schedule (with a warmup over the first 10 epochs). The base learning rate is 0.2×batch size/2560.2 \times \text{batch size} / 256 and weight decay is 1.5×10−61.5 \times 10^{-6}, excluding biases and batch normalization parameters. A minibatch of 4096 runs on 512 TPU v3 cores, taking about 8 hours for ResNet-50.
  • Minibatch size: since it uses no negatives, it tolerates smaller minibatches than SimCLR. However, in the paper accuracy dropped when the minibatch fell below 256, which the paper attributes to batch normalization in the encoder.

In the paper, training diverged for both BYOL and SimCLR when weight decay was removed. Even methods that use no negatives cannot do without weight regularization.

Comparison with Other Methods

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

MethodNegativesHow collapse is preventedTarget-side networkBest suited for
SimCLRYes (within the same minibatch)Pushes away from negativesSame as online (gradients also flow)When large batches are feasible
MoCoYes (queue of past keys)Pushes away from negativesUpdated by moving average (to produce negatives)Using many negatives with small batches
BYOLNoPredictor and a target updated by moving averageUpdated by moving average (to produce prediction targets)High performance without negatives
SimSiamNoPredictor and stop-gradientSame weights as online (only gradients stopped)Keeping it simple by also dropping the moving average
Barlow TwinsNoA loss that decorrelates feature dimensionsSame as onlineAvoiding a predictor and a moving average

BYOL's idea of "predicting a target that moves by moving average" carries over to DINO, which applies self-supervised learning to ViT. Like BYOL, it also resembles the semi-supervised method Mean Teacher in using a slightly earlier self as the teacher. According to the paper, however, simply matching a moving-average network without a predictor, as Mean Teacher does, collapses in the absence of a label loss.

PyTorch example

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

"""
One BYOL step written to follow Sections 3.1 and 3.3 of the paper.
Online: encoder f → projection head g → predictor q; target: moving average of f and g (no predictor)
"""


def mlp(in_dim, hidden=4096, out_dim=256):
  # Linear 4096 → batch norm → ReLU → linear 256 (no batch norm on the final output)
  return nn.Sequential(nn.Linear(in_dim, hidden), nn.BatchNorm1d(hidden), nn.ReLU(inplace=True), nn.Linear(hidden, out_dim))


class BYOL(nn.Module):
  def __init__(self, tau_base=0.996):
    super().__init__()
    encoder = models.resnet50()
    encoder.fc = nn.Identity()                        # Representation y: 2048 dims after average pooling
    self.online = nn.Sequential(encoder, mlp(2048))   # f_θ and g_θ
    self.predictor = mlp(256)                         # q_θ: exists only in the online network
    self.target = copy.deepcopy(self.online)          # f_ξ and g_ξ: start with the same values as online
    for p in self.target.parameters():
      p.requires_grad = False                         # The target is not updated by gradients
    self.tau_base = tau_base

  @staticmethod
  def loss_fn(p, z):
    # ‖p̄ − z̄‖² = 2 − 2 cos(p, z) (Eq. (2)). No gradient flows into z
    return 2 - 2 * F.cosine_similarity(p, z.detach(), dim=-1)

  def forward(self, v1, v2):
    p1 = self.predictor(self.online(v1))
    p2 = self.predictor(self.online(v2))
    with torch.no_grad():
      z1, z2 = self.target(v1), self.target(v2)
    # Also add the loss with v and v′ swapped (symmetrization)
    return (self.loss_fn(p1, z2) + self.loss_fn(p2, z1)).mean()

  @torch.no_grad()
  def update_target(self, step, total_steps):
    # τ = 1 − (1 − τ_base)(cos(πk/K) + 1)/2, ξ ← τ ξ + (1 − τ) θ (Eq. (1))
    tau = 1 - (1 - self.tau_base) * (math.cos(math.pi * step / total_steps) + 1) / 2
    for pt, po in zip(self.target.parameters(), self.online.parameters()):
      pt.mul_(tau).add_(po, alpha=1 - tau)
    for bt, bo in zip(self.target.buffers(), self.online.buffers()):
      bt.copy_(bo)                                    # Copy batch norm statistics as is (an implementation simplification)


model = BYOL()
# The paper uses LARS. SGD is used here for simplicity (only the online network and predictor are passed)
params = list(model.online.parameters()) + list(model.predictor.parameters())
optimizer = torch.optim.SGD(params, lr=0.2, momentum=0.9, weight_decay=1.5e-6)

total_steps = 1000
model.train()   # Batch norm uses minibatch statistics
for step in range(2):
  v1, v2 = torch.randn(8, 3, 224, 224), torch.randn(8, 3, 224, 224)  # Two views of the same images
  loss = model(v1, v2)
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()
  model.update_target(step, total_steps)

# After training, use only the online encoder f_θ. Switch to model.eval() for evaluation
encoder = model.online[0]

FAQ

Q. Why is the predictor attached only to the online network?
A.

To deliberately make the two networks asymmetric. In the paper, removing the predictor in a setting without negatives caused collapse, with every image mapped to the same feature, and linear evaluation fell to 0.3% or below. The paper hypothesizes that keeping the predictor near optimal is the key to avoiding collapse.

Q. How does it differ from MoCo's moving-average encoder?
A.

Both drive a second network with a moving average of the weights of the network updated by gradients. The difference is the purpose: MoCo uses it to produce consistent negative keys stored in a queue, while BYOL uses it to stabilize the prediction target. The paper also shows that simply adding a moving-average target to SimCLR improves it by 1.6 points without changing the number of negatives.

Q. Can it be used on a small GPU?
A.

Since it uses no negatives, it depends less on minibatch size than SimCLR, and in the paper accuracy stayed nearly unchanged from 256 to 4096. Below 256, however, accuracy drops because of batch normalization in the encoder. The paper's appendix also lists hyperparameters for a minibatch of 512.

References

  1. Grill, J.-B., Strub, F., Altché, F., Tallec, C., Richemond, P. H., et al. (2020). Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning. NeurIPS 2020. arXiv:2006.07733.
  2. Chen, T., Kornblith, S., Norouzi, M., & Hinton, G. (2020). A Simple Framework for Contrastive Learning of Visual Representations. ICML 2020. arXiv:2002.05709.
  3. He, K., Fan, H., Wu, Y., Xie, S., & Girshick, R. (2020). Momentum Contrast for Unsupervised Visual Representation Learning. CVPR 2020. arXiv:1911.05722.
  4. Official implementation (byol in google-deepmind/deepmind-research)