AI Logic

Self-Supervised Learning

DINO

Updated:

DINO training flow. The left side shows an image turned into two augmented views: the student g_θs (ViT and projection head) produces P_s via softmax (τs = 0.1), and the teacher g_θt (dashed, a moving average of the student) produces P_t via centering, softmax (τt = 0.04→0.07), and stop-gradient; both feed into a cross-entropy. The right side shows the update rules for the teacher weights and the center c, and a schematic bar chart showing that centering alone collapses to a uniform output, sharpening alone collapses to a single dominant dimension, and both together stay balanced

Background and Overview

DINO (self-DIstillation with NO labels) is a self-supervised learning method based on label-free self-distillation that matches the output distribution of a student network to that of a teacher network moving as a moving average of the weights. It was proposed by Caron et al. at Facebook AI Research and Inria in 2021 and presented at ICCV 2021. Combined with ViT, it reaches a top-1 accuracy of 80.1% with ViT-B/8 under linear evaluation on ImageNet.

The paper asks whether self-supervised learning gives ViT new properties that convolutional networks lack. In answer, ViTs trained with DINO show two striking properties.

  • They find object regions: overlaying the attention weights of the [CLS] token in the last layer on the image reveals regions that follow object outlines, even though the model has never seen a label. These regions are far less clear in ViTs trained with labels or in convolutional networks.
  • They classify well with nearest neighbors: with frozen features, a simple k-nearest-neighbor (k-NN) classifier that counts nearby examples reaches 78.3% with a small ViT.

DINO's mechanism resembles knowledge distillation (having a small student model imitate the outputs of a large teacher model). The difference is that the teacher is not prepared in advance but built from a moving average of the student's own past weights. As an analogy, it is like a classroom without a teacher, where students align today's answers with a "model answer" made by averaging their own notes from recent days.

Theory (Training Procedure and Loss)

DINO uses two networks with the same architecture but different weights.

  • Student gθsg_{\theta_s}: updated by gradients.
  • Teacher gθtg_{\theta_t}: not updated by gradients but by a moving average of the student's weights.

Each network g=h∘fg = h \circ f consists of a backbone ff (ViT or ResNet) and a projection head hh. The projection head is a 3-layer MLP with 2048-dimensional hidden layers, followed by L2 normalization and a weight-normalized fully connected layer with KK dimensions. Unlike BYOL, there is no predictor, and the student and teacher have exactly the same architecture.

Training repeats the following steps, as in Algorithm 1 of the paper (for two views).

  1. Apply random data augmentation twice, independently, to the images in a minibatch to create views x1x_1 and x2x_2.
  2. Pass both through the student and the teacher to obtain KK-dimensional outputs.
  3. Turn the student's output into probabilities PsP_s with a softmax at temperature τs\tau_s.
  4. Subtract the center cc from the teacher's output (centering), then turn it into probabilities PtP_t with a softmax at a low temperature τt\tau_t (sharpening). No gradient flows on the teacher side.
  5. Take the cross-entropy between PtP_t of one view and PsP_s of the other, average it over both pairings, and use it as the loss.
  6. Update the student by gradients, and update the teacher weights and the center cc by moving averages.

The student's probabilities are a softmax over the KK outputs (ii indexes the output dimension).

Ps(x)(i)=exp⁡(gθs(x)(i)/τs)∑k=1Kexp⁡(gθs(x)(k)/τs)P_s(x)^{(i)} = \frac{\exp\left(g_{\theta_s}(x)^{(i)} / \tau_s\right)}{\sum_{k=1}^{K} \exp\left(g_{\theta_s}(x)^{(k)} / \tau_s\right)}

The teacher's probabilities PtP_t take the same form with temperature τt\tau_t. The student learns to minimize the cross-entropy with the teacher's distribution, H(Pt,Ps)=−Ptlog⁡PsH(P_t, P_s) = -P_t \log P_s.

Multi-crop: in practice, DINO uses the same multi-crop strategy as SwAV. From one image it creates two 224×224 global views x1g,x2gx^g_1, x^g_2 covering a large area of the original image (for example, more than 50%) and several 96×96 local views covering small areas, and collects them into a set VV. All views go to the student, while only the two global views go to the teacher. This teaches the model to infer the whole from its parts.

min⁡θs∑x∈{x1g,x2g} ∑x′∈Vx′≠xH(Pt(x),Ps(x′))\min_{\theta_s} \sum_{x \in \{x^g_1, x^g_2\}} \ \sum_{\substack{x' \in V \\ x' \neq x}} H\left(P_t(x), P_s(x')\right)

Updating the teacher and the center: the teacher weights are updated by θt←λθt+(1−λ) θs\theta_t \leftarrow \lambda \theta_t + (1 - \lambda)\,\theta_s, with λ\lambda raised from 0.996 to 1 along a cosine schedule during training. The center cc is the mean of the teacher outputs over the BB samples in a minibatch, smoothed by a moving average (m>0m > 0 is the update rate).

c←m c+(1−m) 1B∑i=1Bgθt(xi)c \leftarrow m\,c + (1 - m)\,\frac{1}{B} \sum_{i=1}^{B} g_{\theta_t}(x_i)

The figure at the top illustrates this flow. The left side shows the student (solid) and teacher (dashed) paths, making clear that centering and sharpening apply only to the teacher's output and that gradients are stopped on the teacher side. The right side shows the update rules for the teacher and the center, along with a schematic showing that using only one of centering or sharpening leads to collapse.

How Centering and Sharpening Prevent Collapse

DINO uses neither negatives nor a predictor. What prevents collapse is the combination of centering and sharpening applied to the teacher's output. The paper explains that collapse takes two forms.

  • Collapse to one dominant dimension: for every image, only the same output dimension becomes large. Centering (subtracting the batch mean) prevents this, but on its own it pushes the output toward a uniform distribution.
  • Collapse to a uniform distribution: for every image, the output takes the same value in all dimensions. Sharpening (lowering the teacher temperature τt\tau_t) prevents this, but on its own it pushes toward one dominant dimension.

Applying both at once balances their effects and avoids collapse. The paper verifies this by decomposing the cross-entropy into the entropy hh of the teacher's distribution and the KL divergence.

H(Pt,Ps)=h(Pt)+DKL(Pt ∣ Ps)H(P_t, P_s) = h(P_t) + D_{\mathrm{KL}}(P_t \,|\, P_s)

The KL divergence is 0 when the output is constant regardless of the input, that is, when the model has collapsed. Removing either operation drove the KL divergence toward 0 during training. In that case, the entropy approached 0 without centering and log⁡K\log K without sharpening, showing that the two operations each prevent a different form of collapse. Because centering uses only the batch mean (a first-order statistic), it also has the advantage of being relatively insensitive to minibatch size.

The role of the moving-average teacher also differs from MoCo. In MoCo it keeps the queue of negatives consistent, but DINO has neither a queue nor negatives. The paper interprets the moving-average teacher as consistently outperforming the student throughout training and giving the student a better target through the ensembling effect of model averaging (Polyak-Ruppert averaging with exponential decay). The paper also notes that this is close to Mean Teacher in semi-supervised learning.

Departing from the settings for centering and sharpening quickly leads to collapse. In the paper's appendix, making the center's moving-average rate too slow at m=0.999m = 0.999 caused collapse (0.1% with k-NN), and fixing the teacher temperature τt\tau_t at a value above 0.06 also caused collapse. In practice, τt\tau_t is raised gradually from 0.04 to 0.07 over the first 30 epochs.

Experimental Results

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

Comparison with the same architecture (Table 2 of the paper, top-1 accuracy):

MethodArchitectureLineark-NN
BYOLResNet-5074.4%64.8%
SwAVResNet-5075.3%65.7%
DINOResNet-5075.3%67.5%
BYOL (run by the paper's authors)ViT-S71.4%66.6%
MoCo v2 (same)ViT-S72.7%64.4%
SwAV (same)ViT-S73.5%66.3%
DINOViT-S77.0%74.5%

With ResNet-50 it matches the state of the art, but with ViT the gap widens: it beats the other methods by 3.5 points in linear evaluation and 7.9 points in k-NN. The paper notes that the small gap between k-NN and linear evaluation (74.5% vs. 77.0%) is a property that appears only when DINO is combined with ViT.

Larger architectures: ViT-B/16 reaches 78.2% (k-NN 76.1%), ViT-S/8 reaches 79.7% (k-NN 78.3%), and ViT-B/8 reaches 80.1% (k-NN 77.4%). Shrinking the patches from 16×16 to 8×8 improves performance but reduces throughput in images processed.

Object regions: building masks by keeping the top 60% of the [CLS] token's attention weights and comparing their overlap (Jaccard index) with the ground-truth masks of PASCAL VOC 2012, DINO scores 45.9 with ViT-S/16, versus 27.3 for a model trained with labels.

Effect of each component (ViT-S/16, 300 epochs, Table 7 of the paper):

Settingk-NNLinear
DINO (moving-average teacher, multi-crop, cross-entropy)72.8%76.1%
No moving-average teacher0.1%0.1%
No multi-crop67.9%72.5%
Cross-entropy replaced with mean squared error52.6%62.4%
Predictor added to the student71.8%75.6%

Without the moving-average teacher the model collapses, and a predictor has almost no effect (in BYOL it is essential for preventing collapse). Comparing ways of building the teacher, a teacher copied directly from the student or the student from the previous step fails to learn (0.1%), while using the student from one epoch earlier as the teacher gives 66.6%.

Transfer (Table 6 of the paper): fine-tuning ViT-S/16 on each dataset gives 81.5% on ImageNet (79.9% for a model trained with labels) and 72.0% on iNaturalist 2018 (70.7%), transferring better than supervised pretraining.

Practical Considerations

  • Main settings: AdamW with a minibatch of 1024 (16 GPUs for ViT-S/16). The learning rate is warmed up over the first 10 epochs to 0.0005×batch size/2560.0005 \times \text{batch size} / 256, then decayed with a cosine schedule. Weight decay is also raised from 0.04 to 0.4 along a cosine schedule. The student temperature is τs=0.1\tau_s = 0.1, and the teacher temperature is raised from 0.04 to 0.07 over the first 30 epochs. Data augmentation uses the same color jittering, Gaussian blur, and solarization as BYOL, plus multi-crop.
  • Output dimension KK: the default is 65536 (with a 256-dimensional bottleneck before L2 normalization). In the paper's appendix, performance tended to improve as KK increased.
  • No batch normalization: ViT does not use batch normalization to begin with, so when applying DINO to ViT, batch normalization is also left out of the projection head, making the whole system free of batch normalization.
  • Compute: training ViT-S/16 on two machines with 8 GPUs each for 300 epochs with multi-crop (2 global + 10 local views) takes about 3 days and reaches 76.1%. Adding 10 local views and training for 100 epochs (about 24 hours) gives higher accuracy than training for 300 epochs without multi-crop (2 global views only, about 46 hours). However, memory per GPU increases from 9.3 GB to 15.4 GB.
  • Minibatch size: with 100 epochs and no multi-crop, k-NN accuracy is 57.9% with a minibatch of 128 and 59.9% with 1024, so training works even with small minibatches (128 runs on a single GPU).

A strength of DINO features is that they can be used directly for nearest-neighbor search. In the paper, frozen features with k-NN or cosine similarity also performed well on landmark image retrieval and on copy detection, which finds images altered by blurring, printing, and similar transformations.

Comparison with Other Methods

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

MethodNegativesHow collapse is preventedOther-side networkLoss
SimCLRYesPushes away from negativesSame weightsNT-Xent
MoCoYes (queue)Pushes away from negativesMoving averageInfoNCE
BYOLNoPredictor and a moving-average targetMoving averageNormalized mean squared error
SwAVNoDistributes assignments equally across prototypes (Sinkhorn-Knopp)Same weightsCross-entropy
DINONoCentering and sharpening the teacher's outputMoving averageCross-entropy

DINO can be seen as combining BYOL's "moving-average teacher" with SwAV's "multi-crop and cross-entropy," while reducing the collapse-prevention mechanism to just centering and temperature. It is well suited to self-supervised learning of ViT, especially when object regions are wanted from the attention weights or when the features will be used for nearest-neighbor search. It differs in approach from MAE, another self-supervised method for ViT that masks parts of an image and reconstructs them.

PyTorch example

Show code
python
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
One DINO step written to follow Algorithm 1 and Section 3.1 of the paper (for two views).
The backbone is assumed to be a ViT that returns the [CLS] output (e.g., timm's vit_small_patch16_224).
"""


class DINOHead(nn.Module):
  # 3-layer MLP (hidden 2048) → L2 normalization (bottleneck 256) → weight-normalized K-dim fully connected layer
  def __init__(self, in_dim, out_dim=65536, hidden=2048, bottleneck=256):
    super().__init__()
    self.mlp = nn.Sequential(
      nn.Linear(in_dim, hidden), nn.GELU(),
      nn.Linear(hidden, hidden), nn.GELU(),
      nn.Linear(hidden, bottleneck),
    )
    self.last = nn.utils.parametrizations.weight_norm(nn.Linear(bottleneck, out_dim, bias=False))

  def forward(self, x):
    return self.last(F.normalize(self.mlp(x), dim=-1))


class DINOLoss(nn.Module):
  def __init__(self, out_dim, tau_s=0.1, center_m=0.9):   # center_m = 0.9, the best value in the appendix
    super().__init__()
    self.tau_s, self.m = tau_s, center_m
    self.register_buffer("center", torch.zeros(1, out_dim))

  def H(self, t, s, tau_t):
    t = F.softmax((t - self.center) / tau_t, dim=-1).detach()   # Center and sharpen. No gradient flows
    return -(t * F.log_softmax(s / self.tau_s, dim=-1)).sum(dim=-1).mean()

  def forward(self, s1, s2, t1, t2, tau_t):
    loss = self.H(t1, s2, tau_t) / 2 + self.H(t2, s1, tau_t) / 2
    with torch.no_grad():   # c ← m c + (1 − m) × mean of teacher outputs (Eq. (4))
      self.center.mul_(self.m).add_(torch.cat([t1, t2]).mean(dim=0, keepdim=True), alpha=1 - self.m)
    return loss


def make_dino(backbone, embed_dim, out_dim=65536):
  student = nn.Sequential(backbone, DINOHead(embed_dim, out_dim))
  teacher = copy.deepcopy(student)            # The teacher starts with the same values as the student
  for p in teacher.parameters():
    p.requires_grad = False                   # The teacher is not updated by gradients
  return student, teacher


@torch.no_grad()
def update_teacher(student, teacher, lam):
  # θ_t ← λ θ_t + (1 − λ) θ_s. λ is raised from 0.996 to 1 along a cosine schedule
  for ps, pt in zip(student.parameters(), teacher.parameters()):
    pt.mul_(lam).add_(ps.detach(), alpha=1 - lam)


# Usage example (backbone is a network that returns [CLS] features; 384 dims for ViT-S)
backbone = nn.Sequential(nn.Flatten(), nn.Linear(3 * 32 * 32, 384))   # Stand-in for a quick test. Use a ViT in practice
student, teacher = make_dino(backbone, embed_dim=384, out_dim=4096)
criterion = DINOLoss(out_dim=4096)
optimizer = torch.optim.AdamW(student.parameters(), lr=0.0005 * 64 / 256, weight_decay=0.04)

student.train()
teacher.train()
x1, x2 = torch.randn(64, 3, 32, 32), torch.randn(64, 3, 32, 32)   # Two views of the same images
s1, s2 = student(x1), student(x2)
with torch.no_grad():
  t1, t2 = teacher(x1), teacher(x2)
loss = criterion(s1, s2, t1, t2, tau_t=0.04)
optimizer.zero_grad()
loss.backward()
optimizer.step()
update_teacher(student, teacher, lam=0.996)

# Downstream tasks often use the teacher's backbone ([CLS] features). Switch to eval() for evaluation
features = teacher[0].eval()

FAQ

Q. How does it differ from knowledge distillation?
A.

In knowledge distillation, a pretrained teacher model exists in advance, and the student imitates its outputs. DINO has no pretrained teacher; the teacher is a moving average of the student's own weights, and no labels are used. Because the form of the loss (cross-entropy between the teacher's and the student's probability distributions) is the same, the paper calls DINO "self-distillation with no labels."

Q. After training, should the student or the teacher be used?
A.

The paper reports that the moving-average teacher outperforms the student throughout training, so using the teacher is the natural choice. In either case, discard the projection head and use the backbone output (the [CLS] token features for ViT) for downstream tasks.

Q. Does it work with ResNet?
A.

Yes. In the paper, ResNet-50 reaches 75.3% in linear evaluation and 67.5% with k-NN, on par with other state-of-the-art methods. However, the emergence of object regions in the attention weights and k-NN accuracy close to linear evaluation are properties that stand out particularly when DINO is combined with ViT.

References

  1. Caron, M., Touvron, H., Misra, I., Jégou, H., Mairal, J., Bojanowski, P., & Joulin, A. (2021). Emerging Properties in Self-Supervised Vision Transformers. ICCV 2021. arXiv:2104.14294.
  2. Grill, J.-B., et al. (2020). Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning. NeurIPS 2020. arXiv:2006.07733.
  3. Caron, M., Misra, I., Mairal, J., Goyal, P., Bojanowski, P., & Joulin, A. (2020). Unsupervised Learning of Visual Features by Contrasting Cluster Assignments. NeurIPS 2020. arXiv:2006.09882.
  4. Official implementation (facebookresearch/dino)