AI Logic

Architectures

DeiT

Updated:

Architecture of DeiT. The left panel shows the overall flow of DeiT-B with distillation (the image is split into 196 patches of 16×16 and embedded, a [class] token and a distillation token are added, position embeddings are added, the sequence passes through 12 encoder layers, and the [class] output feeds the class head while the distillation-token output feeds the distillation head). The right panel shows training (a loss that uses the CNN teacher's prediction y_t as the target of the distillation head) and inference (adding the softmax outputs of the two heads)

Background and overview

DeiT (Data-efficient image Transformers) is an image classification model that keeps the ViT architecture unchanged, improves the training recipe, and adds knowledge distillation through a Transformer-specific "distillation token", matching CNN accuracy using only ImageNet (about 1.3 million images). It was published in 2020 by Touvron et al. at Facebook AI and Sorbonne University.

The ViT paper assumed pretraining on 300 million private images (JFT-300M) and concluded that Transformers "do not generalize well when trained on insufficient amounts of data". ViT-B/16 trained on ImageNet alone reached only 77.9% accuracy, falling short even of a ResNet of similar size. Handling images with Transformers was therefore thought to require huge datasets and compute.

DeiT overturned this assumption with two ideas:

  • Training recipe: it combines strong data augmentation (RandAugment, Mixup, CutMix, Random Erasing, repeated augmentation) with regularization (Stochastic Depth, Label Smoothing) and trains with AdamW for 300 epochs. DeiT-B, whose architecture is identical to ViT-B, rose to 81.8%.
  • Distillation token: separately from the [class] token, a "distillation token" whose target is the CNN teacher's prediction is added to the input. DeiT-B reached 83.4%, and 85.2% with longer training at higher resolution.

Training takes 2–3 days on a single machine with 8 GPUs (53 hours for DeiT-B pretraining). DeiT became the standard recipe for training image Transformers on ImageNet alone, and it underlies the training recipes of many later models (such as ConvNeXt and ResMLP).

Architecture

The architecture of DeiT is the same as ViT except for the added distillation token. The left side of the figure at the top of the article shows the overall flow of DeiT-B with distillation, and the right side shows how the two heads are used in training and inference.

An image flows as follows (DeiT-B, 224×224 input):

  1. Split into patches and embed: the image is split into N=14×14=196N = 14 \times 14 = 196 patches of 16×16, and a linear layer maps each to D=768D = 768 dimensions.
  2. Add tokens: a [class] token is prepended, followed by a distillation token. Both are learned vectors. After adding learned position embeddings, there are 198 tokens.
  3. Pass through the encoder: the tokens pass through 12 Transformer encoder layers, the same as ViT-B. Each layer pairs multi-head attention with an MLP that expands the hidden layer 4× with GELU in between, each with a residual connection and layer normalization.
  4. Classify with two heads: a linear layer (head) is attached to the output at the [class] token position and another to the output at the distillation token position. Unlike ViT, no MLP head is used even in pretraining; each head is a single linear layer.

Self-attention follows Equation (1) of the paper:

Attention(Q,K,V)=Softmax ⁣(QK⊤d)V\mathrm{Attention}(Q, K, V) = \mathrm{Softmax}\!\left(\frac{QK^{\top}}{\sqrt{d}}\right) V

Like the [class] token, the distillation token exchanges information with all patches through self-attention. The only difference is what its last-layer output is trained to match.

Model sizes (Table 1 of the paper; the dimension per head is fixed at 64)

ModelEmbedding dim DDHeadsLayersParametersThroughput (images/s)
DeiT-Ti1923125M2536
DeiT-S38461222M940
DeiT-B768121286M292

DeiT-B has exactly the same architecture as ViT-B. DeiT-S and DeiT-Ti are new smaller models introduced in the paper, which it describes as counterparts of ResNet-50 and ResNet-18, respectively.

Theory: knowledge distillation with a distillation token

Knowledge distillation trains a student model using the outputs of a strong teacher model as a guide. DeiT uses a CNN (RegNetY-16GF, 82.9% on ImageNet) as the teacher and trains a Transformer student.

Standard (soft) distillation

This brings the output probability distributions of the teacher and student closer. With student and teacher logits ZsZ_s and ZtZ_t, softmax ψ\psi, temperature τ\tau, weight λ\lambda and ground-truth label yy, the loss is (Equation (2) of the paper):

Lglobal=(1−λ) LCE(ψ(Zs),y)+λτ2 KL(ψ(Zs/τ), ψ(Zt/τ))\mathcal{L}_{\text{global}} = (1 - \lambda)\, \mathcal{L}_{\text{CE}}(\psi(Z_s), y) + \lambda \tau^2\, \mathrm{KL}\bigl(\psi(Z_s / \tau),\ \psi(Z_t / \tau)\bigr)

KL is the KL divergence and LCE\mathcal{L}_{\text{CE}} is the cross-entropy.

Hard-label distillation

DeiT treats the class the teacher considers most likely, yt=arg⁡max⁡cZt(c)y_t = \arg\max_c Z_t(c), as a second ground-truth label (Equation (3) of the paper):

LglobalhardDistill=12LCE(ψ(Zs),y)+12LCE(ψ(Zs),yt)\mathcal{L}_{\text{global}}^{\text{hardDistill}} = \frac{1}{2} \mathcal{L}_{\text{CE}}(\psi(Z_s), y) + \frac{1}{2} \mathcal{L}_{\text{CE}}(\psi(Z_s), y_t)

It is simple, with no temperature τ\tau or weight λ\lambda to tune.

Distillation token

The core of DeiT's proposal is to assign the two terms above to separate tokens. The procedure is:

  1. Prepare two tokens: feed the [class] token and the distillation token into the encoder together with the patch tokens.
  2. Compute the teacher's prediction: feed the same image (after data augmentation) to the CNN teacher and obtain yty_t.
  3. Compute the loss with two heads: match the output of the [class] token head to the ground-truth label yy and the output of the distillation token head to the teacher's prediction yty_t, and add the two cross-entropies with weight one half each.
  4. Combine the two at inference: add the softmax outputs of the two heads and predict the class with the largest value.

Computing the teacher's prediction per image and per augmentation has a purpose. For example, if random cropping removes the cat from a landscape photo labeled "cat", the ground-truth label no longer matches the image content. The teacher's prediction gives a label that follows what is actually visible.

The two tokens learn different things

The learned input vectors of the [class] token and the distillation token had a cosine similarity of only 0.06, meaning they were barely alike. At the output of the last layer they converge to 0.93 but never reach 1. In contrast, when two [class] tokens targeting the same ground-truth label were used instead of a distillation token, the two became nearly identical during training (cosine similarity 0.999) and accuracy did not improve. The distillation token therefore brings in information from the teacher that differs from the [class] token.

Using a CNN rather than a Transformer as the teacher gave higher student accuracy (Table 2 of the paper). The paper attributes this to the CNN's inductive biases, such as "looking at nearby pixels", being passed on to the Transformer through distillation. In fact, the predictions of the distilled DeiT were closer to those of the CNN teacher than the predictions of DeiT without distillation.

Training recipe

DeiT's training recipe differs substantially from the settings in the ViT paper (Table 9 of the paper).

ItemViT-BDeiT-B
Epochs300300
Batch size40961024
OptimizerAdamWAdamW
Learning rate0.0030.0005×batch size/5120.0005 \times \text{batch size} / 512
Learning rate decayCosineCosine
Weight Decay0.30.05
Warmup3.4 epochs5 epochs
Label SmoothingNone0.1
Dropout0.1None
Stochastic DepthNone0.1
Repeated augmentationNoneYes (3 times)
RandAugmentNone9 / 0.5
Mixup / CutMixNone0.8 / 1.0
Random ErasingNone0.25

The key points the paper highlights are:

  • Weight initialization: Transformers are sensitive to initialization, and some methods did not converge. DeiT initializes with a truncated normal distribution.
  • Data augmentation: Transformers, which have no convolutions, need strong data augmentation to train on the same amount of data. Almost every augmentation tried helped; only dropout was removed.
  • Repeated augmentation: each batch contains three copies of the same image with different augmentations. The paper calls this one of the keys to a large gain in accuracy.
  • Optimization: pretraining with SGD instead of AdamW dropped DeiT-B from 81.8% to 74.5% (Table 8 of the paper). Weight decay of 0.3 as in ViT also converged poorly and was lowered to 0.05.
  • Exponential moving average of weights: it gives a 0.1-point gain, but the difference disappears after fine-tuning at higher resolution.

Fine-tuning at higher resolution

After training at 224×224, the model is fine-tuned at 384×384. The patch size is unchanged, so the number of patches (and position embeddings) increases. The position embeddings are therefore interpolated; the paper notes that bilinear interpolation shrinks the norm of the interpolated vectors and greatly reduces accuracy, so it uses bicubic interpolation, which roughly preserves the norm. During fine-tuning, the teacher's predictions are used together with the ground-truth labels.

Experimental results

Comparison of distillation methods (ImageNet accuracy %, 300 epochs; Table 3 of the paper)

MethodDeiT-TiDeiT-SDeiT-BDeiT-B (384)
No distillation72.279.881.883.1
Standard (soft) distillation72.279.881.883.2
Hard-label distillation ([class] token only)74.380.983.084.0
Distillation token: inference with [class] head only73.980.983.084.2
Distillation token: inference with distillation head only74.681.183.184.4
Distillation token: both heads combined74.581.283.484.5

For Transformers, soft distillation had almost no effect while hard-label distillation helped substantially. The distillation token improves results further, and combining the two heads is best.

Effect of the teacher (student: DeiT-B with distillation token; Table 2 of the paper)

TeacherTeacher accuracyStudent accuracyStudent (fine-tuned at 384)
DeiT-B (Transformer)81.881.983.1
RegNetY-4GF (CNN)80.082.783.6
RegNetY-8GF (CNN)81.782.783.8
RegNetY-16GF (CNN)82.983.184.2

Even with a CNN teacher less accurate than the student (RegNetY-4GF at 80.0%), the student reached 82.7%, surpassing the teacher.

Comparison with other models (trained on ImageNet only; throughput is images per second on one V100; ⚗ denotes the distillation token; Table 5 of the paper)

ModelParametersResolutionThroughputAccuracy
ResNet-5025M2241226.176.2
RegNetY-16GF84M224334.782.9
EfficientNet-B312M300732.181.6
EfficientNet-B766M60055.184.3
ViT-B/1686M38485.977.9
DeiT-S22M224940.479.8
DeiT-B86M224292.381.8
DeiT-B⚗87M224290.983.4
DeiT-B⚗ (384, 1000 epochs)87M38485.885.2

DeiT is nearly 6 points higher than ViT-B/16 trained on ImageNet alone, and with distillation it surpasses EfficientNet in the accuracy–throughput trade-off. 85.2% is higher even than ViT-B pretrained on JFT-300M (84.15% at 384). The distilled DeiT kept improving when training was extended to 1000 epochs, while DeiT without distillation plateaued at around 400 epochs.

Transfer learning: fine-tuning the ImageNet-trained DeiT-B gave results on par with CNNs, such as 99.1% on CIFAR-10 and 90.8% on CIFAR-100 (Table 7 of the paper).

Practical notes

Keep the following points in mind when using DeiT:

  • Do not drop parts of the training recipe: DeiT's accuracy rests on the combination of strong data augmentation and regularization. In the paper, merely switching the optimizer to SGD cost more than 7 points.
  • Distillation needs pretrained teacher weights: the paper's teacher, RegNetY-16GF, was trained on the same data with the same augmentation as DeiT. Teacher inference also adds to the training cost.
  • Distilled models use two heads at inference: a model with a distillation token combines the outputs of both heads to predict. Either head alone works, but accuracy drops slightly.
  • Interpolate position embeddings bicubically when changing resolution: bilinear interpolation shrinks the vector norms and greatly reduces accuracy.
  • Where to get it in PyTorch: the official pretrained weights can be loaded from torch.hub (facebookresearch/deit) or the timm library (official repository).

"DeiT can be trained on ImageNet alone" assumes a long 300-epoch schedule and strong data augmentation. Training from scratch on a small dataset of thousands to tens of thousands of images does not necessarily beat a CNN. For small datasets, the standard approach is to fine-tune from DeiT's pretrained weights.

Comparison with other models

DeiT makes the ViT architecture trainable on ImageNet alone through its training recipe and distillation. Compared from the same perspective:

ModelArchitecturePretraining dataDistillationImageNet accuracy (224)
ViT-B/16TransformerJFT-300M (lower with ImageNet only)None77.9 (ImageNet only, 384)
DeiT-BSame as ViT-BImageNet onlyNone81.8
DeiT-B⚗ViT-B + distillation tokenImageNet onlyHard labels from a CNN83.4
ResMLP-B24MLP (no attention)ImageNet onlyNone81.0
ConvNeXt-BCNNImageNet onlyNone83.8

Rough guidelines for choosing:

  • Training a Transformer on ImageNet-scale data: DeiT's training recipe is the starting point. If a CNN teacher is available, the distillation token can raise accuracy further.
  • Fine-tuning pretrained weights for another task: DeiT's weights are public, and transfer learning gave results on par with CNNs.
  • Top accuracy at the same compute: later hierarchical models (such as Swin Transformer and ConvNeXt) achieve higher accuracy on ImageNet as well as detection and segmentation.

PyTorch example

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

"""
A small implementation of DeiT's distillation token and hard-label distillation (Section 4, Eq. (3) of the paper).
The encoder is substituted with PyTorch's nn.TransformerEncoderLayer (Pre-LN, GELU, 4x MLP)
"""


class DistilledViT(nn.Module):
  def __init__(self, img_size=224, patch=16, dim=768, depth=12, heads=12, num_classes=1000):
    super().__init__()
    n = (img_size // patch) ** 2                                    # 196
    self.patch_embed = nn.Conv2d(3, dim, kernel_size=patch, stride=patch)
    self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))           # [class] token
    self.dist_token = nn.Parameter(torch.zeros(1, 1, dim))          # Distillation token
    self.pos_embed = nn.Parameter(torch.zeros(1, n + 2, dim))       # Position embeddings for 196 + 2 tokens
    for p in (self.cls_token, self.dist_token, self.pos_embed):
      nn.init.trunc_normal_(p, std=0.02)                             # Truncated normal initialization
    layer = nn.TransformerEncoderLayer(dim, heads, 4 * dim, dropout=0.0, activation="gelu",
                                       batch_first=True, norm_first=True)
    self.encoder = nn.TransformerEncoder(layer, depth)
    self.norm = nn.LayerNorm(dim)
    self.head = nn.Linear(dim, num_classes)        # Class head
    self.head_dist = nn.Linear(dim, num_classes)   # Distillation head

  def forward(self, img):
    x = self.patch_embed(img).flatten(2).transpose(1, 2)            # [B, 196, D]
    b = x.shape[0]
    x = torch.cat([self.cls_token.expand(b, -1, -1), self.dist_token.expand(b, -1, -1), x], dim=1)
    x = self.norm(self.encoder(x + self.pos_embed))                 # [B, 198, D]
    out_cls, out_dist = self.head(x[:, 0]), self.head_dist(x[:, 1])
    if self.training:
      return out_cls, out_dist                     # Training: return the two outputs separately
    return (out_cls.softmax(-1) + out_dist.softmax(-1)) / 2         # Inference: combine the two softmaxes


def hard_distillation_loss(out_cls, out_dist, labels, teacher_logits):
  """Eq. (3): 1/2 CE(class head, y) + 1/2 CE(distillation head, y_t). Label smoothing 0.1 on y"""
  y_t = teacher_logits.argmax(dim=1)                                # Class the teacher considers most likely
  return 0.5 * F.cross_entropy(out_cls, labels, label_smoothing=0.1) + 0.5 * F.cross_entropy(out_dist, y_t)


student = DistilledViT(dim=192, heads=3)           # DeiT-Ti size
teacher = nn.Sequential(nn.Conv2d(3, 8, 3, padding=1), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(8, 1000))  # In practice, a pretrained RegNetY-16GF etc.
teacher.eval()

images, labels = torch.randn(4, 3, 224, 224), torch.randint(0, 1000, (4,))   # Images after data augmentation
student.train()
with torch.no_grad():
  teacher_logits = teacher(images)                 # Teacher predictions on the same (augmented) images
out_cls, out_dist = student(images)
loss = hard_distillation_loss(out_cls, out_dist, labels, teacher_logits)
loss.backward()

student.eval()
with torch.no_grad():
  probs = student(images)                          # [4, 1000]

# Official pretrained weights (torch.hub):
# model = torch.hub.load("facebookresearch/deit:main", "deit_base_patch16_224", pretrained=True)

FAQ

Q. What is the difference between DeiT and ViT?
A.

DeiT-B has exactly the same architecture as ViT-B. The difference is the training recipe: by combining strong data augmentation and regularization, AdamW, repeated augmentation and more, it reaches 81.8% using only ImageNet (ViT-B/16 trained on ImageNet alone reaches 77.9%). DeiT⚗, which adds a distillation token, learns from a CNN teacher and rises to 83.4%.

Q. Why is a CNN a good teacher?
A.

In the paper, students taught by a CNN were more accurate than those taught by a Transformer of similar accuracy. The paper attributes this to the CNN's inductive biases (such as looking at nearby pixels) being passed on to the Transformer through distillation. The predictions of the distilled DeiT were closer to those of the CNN teacher than the predictions of DeiT without distillation.

Q. Why use hard-label distillation instead of soft distillation?
A.

Because in the paper's experiments, hard-label distillation was clearly better for Transformers. With DeiT-B, soft distillation gave 81.8% (the same as no distillation) and hard-label distillation gave 83.0%. Hard-label distillation is also easier to use, since there is no temperature τ\tau or weight λ\lambda to tune.

References

  1. Touvron, H., Cord, M., Douze, M., Massa, F., Sablayrolles, A., & Jégou, H. (2021). Training data-efficient image transformers & distillation through attention. ICML 2021. arXiv:2012.12877.
  2. facebookresearch/deit (official implementation and pretrained weights).
  3. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021. arXiv:2010.11929.
  4. Hinton, G., Vinyals, O., & Dean, J. (2015). Distilling the Knowledge in a Neural Network. arXiv:1503.02531.