AI Logic

Architectures

DistilBERT

Updated:

Distillation in DistilBERT. The left panel shows the distillation flow during pretraining (the same input goes into the teacher BERT-base and the student DistilBERT; L_ce and L_mlm are computed from the word probabilities and L_cos from the last-layer outputs). The right panel shows how the student is built (a 6-layer student is initialized by taking every other layer of the teacher's 12) and a table comparing size and inference time with BERT-base

Background and overview

DistilBERT is a small, fast language model that halves the number of layers of BERT-base through knowledge distillation. It was proposed by Sanh et al. at Hugging Face in 2019.

Pretrained language models such as BERT often have hundreds of millions of parameters, making them hard to run on devices such as smartphones or with limited compute. Earlier work on distilling BERT mostly shrank task-specific models after fine-tuning. By distilling during pretraining, DistilBERT produced a small general-purpose model that can be fine-tuned for any task.

The paper's results are:

  • Parameters drop from 110M in BERT-base to 66M, a 40% reduction
  • CPU inference is 60% faster (668 s → 410 s)
  • The score on the GLUE validation sets retains 97% of BERT-base (79.5 → 77.0)

Training uses a combination of three losses: a loss that imitates the outputs of the teacher (BERT-base), the masked language modeling loss, and a loss that aligns the directions of the teacher's and student's hidden states.

Architecture

The architecture of DistilBERT (the student) is the same stack of Transformer encoder layers as BERT. It changes three things from BERT-base. The left side of the figure at the top of the article shows the distillation flow during pretraining, and the right side shows how the student is built.

  • Half the layers: 12 layers → 6 layers. The hidden size of 768 and the number of heads are unchanged.
  • No token type embeddings: the embeddings that distinguish sentence A from sentence B (token type) are not used.
  • No pooler: the fully connected layer (pooler) that BERT applies to the [CLS] output is not used.
ModelLayersHidden sizeParametersCPU inference time
BERT-base12768110M668 s
DistilBERT676866M410 s

The inference time is the total for running the GLUE STS-B validation set on a CPU with batch size 1.

The number of layers was reduced instead of the hidden size because, in the paper's investigation, for the same number of parameters, changing the number of layers affected computation speed much more than changing the hidden size. The paper explains that the main operations inside a Transformer (fully connected layers and layer normalization) are well optimized in modern linear algebra libraries, so differences in hidden size have little effect on speed.

The student's initialization also matters. Since teacher and student share the same hidden size, the student's 6 layers are initialized by taking every other layer from the teacher's 12.

Training: distillation with three losses

In DistilBERT pretraining, the pretrained BERT-base is frozen as the teacher, and only the student is trained, as follows:

  1. Create inputs in which 15% of the tokens are masked (dynamic masking, re-sampled each time).
  2. Feed the same input to both the teacher and the student, and compute the word probabilities at each position and the last-layer outputs (hidden states).
  3. Compute the three losses and add them with weights.
  4. Update only the student's weights with the combined loss.

The three losses are:

  • Distillation loss LceL_{ce}: the cross-entropy of the student's probabilities sis_i with the teacher's word probabilities tit_i as the target.
  • Masked language modeling loss LmlmL_{mlm}: as in BERT, the loss for predicting the masked words correctly.
  • Cosine loss LcosL_{cos}: a loss that aligns the directions of the teacher's and student's hidden-state vectors.

The distillation loss is:

Lce=−∑itilog⁡siL_{ce} = -\sum_i t_i \log s_i

Both tit_i and sis_i are computed with a softmax at the same temperature TT:

pi=exp⁡(zi/T)∑jexp⁡(zj/T)p_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}

ziz_i is the score (logit) of word ii. A larger TT flattens the distribution, so information in the probabilities the teacher assigns to "second and third most likely words" also reaches the student. At inference, TT is set back to 1.

The final loss is the weighted sum of the three losses:

L=αceLce+αmlmLmlm+αcosLcosL = \alpha_{ce} L_{ce} + \alpha_{mlm} L_{mlm} + \alpha_{cos} L_{cos}

The paper does not state the values of TT or the weights, but in the official training code T=2T = 2 is the default, and the training example uses αce=5\alpha_{ce} = 5, αmlm=2\alpha_{mlm} = 2 and αcos=1\alpha_{cos} = 1. In the official code, the cosine loss is 1−cos⁡(ht,hs)1 - \cos(\boldsymbol{h}^{t}, \boldsymbol{h}^{s}) between the last-layer outputs.

The teacher's probabilities contain information beyond the correct word. In the paper's example, for "I think this is the beginning of a beautiful [MASK]", BERT-base assigns high probabilities to "day" and "life" and small probabilities to "future", "story", "world" and others. Imitating this distribution of "other plausible words" teaches the student more than giving it only the single correct word.

The training procedure follows the practices shown to be effective in RoBERTa.

ItemValue
TeacherBERT-base (pretrained, weights frozen)
DataThe same English Wikipedia and BooksCorpus as BERT
BatchVery large batches of up to 4,000 examples via gradient accumulation
MaskingDynamic masking (re-sampled each time)
Next sentence predictionNot used
HardwareAbout 90 hours on 8 16GB V100 GPUs

The paper notes that DistilBERT pretraining needs far less compute than RoBERTa, which took one day on 1,024 32GB V100s.

Fine-tuning works as in BERT: an output layer is added and the whole model is retrained. For question answering (SQuAD) fine-tuning, the paper also tries distilling again, using a BERT fine-tuned on SQuAD as the teacher.

Why it keeps its performance despite being small

There are three main reasons why DistilBERT retains 97% of BERT-base's performance:

  • Learning from the teacher's probability distribution: the target includes not only the single correct word but also the probabilities the teacher assigns to other words, so each example carries more information. This is the basic idea of knowledge distillation.
  • Aligning the directions of hidden states: not only the output probabilities but the last-layer representations themselves are pulled toward the teacher, making it easier to imitate how the teacher "understands" sentences.
  • Initializing from the teacher's layers: starting from weights the teacher has already learned leads to a much better solution than starting from random values. In the paper's experiments, random initialization lowered the GLUE score by 3.69 points, the largest effect of the three factors.

Think of a master craftsman (teacher) teaching an apprentice (student). Showing the reasoning — "this is best, but that is also possible" — helps the apprentice improve with less experience than just giving the answer. Handing over some of the master's tools directly (initializing from the teacher's layers) also gets the apprentice up to speed faster than gathering everything from scratch.

Distillation generally cannot be expected to exceed the teacher's performance. In the paper, DistilBERT falls below BERT-base on every GLUE task except WNLI, with especially large gaps on small or difficult tasks such as RTE (69.3 → 59.9) and CoLA (56.3 → 51.3). When accuracy is the top priority, use the original BERT or a larger model.

Experimental results

GLUE (validation sets; BERT and DistilBERT are medians of 5 runs; the score is the average over 9 tasks)

ModelScoreCoLAMNLIMRPCQNLIQQPRTESST-2STS-BWNLI
ELMo68.744.168.676.671.186.253.491.570.456.3
BERT-base79.556.386.788.691.889.669.392.789.053.5
DistilBERT77.051.382.287.589.288.559.991.386.956.3

DistilBERT is always on par with or better than the ELMo baseline and retains 97% of BERT-base's score.

Downstream tasks (IMDb: test accuracy; SQuAD 1.1: validation EM / F1)

ModelIMDbSQuAD 1.1
BERT-base93.4681.2 / 88.5
DistilBERT92.8277.7 / 85.8
DistilBERT (also distilled during fine-tuning)—79.1 / 86.9

On IMDb sentiment classification, the gap to BERT-base was 0.6 points. On SQuAD, distilling from a SQuAD-tuned BERT during fine-tuning as well narrowed the gap further.

Effect of losses and initialization (difference in GLUE score from the model using all three losses and teacher initialization)

ChangeGLUE score difference
Remove LceL_{ce} and LcosL_{cos} (LmlmL_{mlm} only)−2.96
Remove LcosL_{cos}−1.46
Remove LmlmL_{mlm}−0.31
Random initialization of the student−3.69

Removing the masked language modeling loss changes little; the two distillation losses account for most of the performance. Initialization from the teacher has a larger effect than any loss.

Speed on device: in an experiment running a question answering app on an iPhone 7 Plus, DistilBERT was 71% faster than BERT-base for inference excluding tokenization, and the whole model weighed 207MB.

Practical notes

Keep the following points in mind when using DistilBERT:

  • Do not use token_type_ids: there are no embeddings distinguishing sentence A from sentence B, so two sentences are separated only by the [SEP] token. When porting code written for BERT, do not pass this argument.
  • No [CLS] pooler: code that relies on BERT's pooler output will not work as is. Hugging Face's classification model applies the classification layer directly to the output at the [CLS] position.
  • The tokenizer is the same as BERT's: it uses the same WordPiece vocabulary as the teacher BERT-base. Choose a model whose casing (uncased / cased) matches the teacher.
  • Inputs up to 512 tokens: as with BERT, split long documents.
  • Combine methods to shrink further: the paper notes that pruning and quantization are orthogonal to DistilBERT and can be combined with it. For devices, quantization can make it even smaller.

How the student is initialized strongly affects performance when you rebuild DistilBERT yourself (random initialization lowers the GLUE score by 3.69). The paper says "one out of two layers", but the extraction script in the official training code uses teacher layers 0, 2, 4, 7, 9 and 11. If teacher and student have different hidden sizes, this initialization cannot be used as is.

Comparison with other models

Comparing models that make BERT smaller or more efficient from the same perspective:

ModelWhat is reducedHowInference speedPerformance
BERT-base(baseline)—BaselineBaseline
DistilBERTNumber of layers (12 → 6)Knowledge distillation during pretraining60% faster (CPU)97% of BERT-base on GLUE
ALBERTNumber of parametersFactorized embeddings and cross-layer weight sharingAbout the same as BERT for the same shapeSlightly below BERT in small configurations

Other distilled versions of BERT include TinyBERT. DistilBERT and ALBERT are both ways to "make BERT lighter", but they lighten different things. DistilBERT removes layers, so inference becomes faster; ALBERT shares weights, so the number of parameters and memory decrease.

Rough guidelines for choosing:

  • Faster inference or running on devices: DistilBERT is a good fit. In the paper's measurements, CPU inference time dropped by about 40%.
  • Reducing memory or storage: ALBERT is a good fit, although inference does not get faster.
  • Accuracy is the top priority: use the original BERT or RoBERTa, which revisits training.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoTokenizer, DistilBertForSequenceClassification

"""
1. DistilBERT's pretraining loss (three losses), written following the paper and the official training code
2. Fine-tuning a pretrained DistilBERT for sentence classification
"""

def distil_loss(s_logits, t_logits, s_hidden, t_hidden, labels, attention_mask,
                T=2.0, a_ce=5.0, a_mlm=2.0, a_cos=1.0):
  """
  s_logits, t_logits: [B, n, vocab]   student/teacher word scores
  s_hidden, t_hidden: [B, n, 768]     student/teacher last-layer outputs
  labels:             [B, n]          original word id at masked positions, -100 elsewhere
  attention_mask:     [B, n]          0 at padding positions
  """
  m = attention_mask.bool()
  # L_ce: target the teacher's probabilities with a temperature-T softmax (same gradient when written as KL). Multiply by T^2 to keep the gradient scale
  loss_ce = F.kl_div(
    F.log_softmax(s_logits[m] / T, dim=-1),
    F.softmax(t_logits[m] / T, dim=-1),
    reduction="batchmean") * T ** 2
  # L_mlm: predict the masked words (temperature 1)
  loss_mlm = F.cross_entropy(s_logits.view(-1, s_logits.size(-1)), labels.view(-1), ignore_index=-100)
  # L_cos: align the directions of the last-layer outputs (1 - cos)
  target = torch.ones(int(m.sum()), device=s_hidden.device)
  loss_cos = F.cosine_embedding_loss(s_hidden[m], t_hidden[m], target)
  return a_ce * loss_ce + a_mlm * loss_mlm + a_cos * loss_cos

# Shape check only (in real training, compute the teacher inside torch.no_grad() with frozen weights)
B, n, V, H = 2, 8, 30522, 768
labels = torch.full((B, n), -100)
labels[:, 3] = 1000                                # Assume only the 4th position is masked
loss = distil_loss(torch.randn(B, n, V, requires_grad=True), torch.randn(B, n, V),
                   torch.randn(B, n, H, requires_grad=True), torch.randn(B, n, H),
                   labels, torch.ones(B, n, dtype=torch.long))
loss.backward()
print(loss.item())

# --- Fine-tune a pretrained DistilBERT ---
name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(name)   # Same WordPiece vocabulary as BERT-base
clf = DistilBertForSequenceClassification.from_pretrained(name, num_labels=2)
optimizer = torch.optim.AdamW(clf.parameters(), lr=5e-5)

batch = tokenizer(["I loved this movie.", "The plot was boring."],
                  padding=True, truncation=True, max_length=128, return_tensors="pt")
# DistilBERT does not take token_type_ids (the tokenizer does not return them)
labels = torch.tensor([1, 0])

clf.train()                                        # Enable dropout
out = clf(**batch, labels=labels)
out.loss.backward()
optimizer.step()
optimizer.zero_grad()

clf.eval()                                         # Disable dropout for inference
with torch.no_grad():
  print(clf(**batch).logits.softmax(dim=-1))

FAQ

Q. How much faster is DistilBERT, and how much performance does it lose?
A.

In the paper, parameters fell from 110M in BERT-base to 66M (a 40% reduction), and CPU inference became 60% faster. The GLUE validation score went from 79.5 to 77.0, retaining 97% of BERT-base. However, the gap is larger on small tasks such as RTE and CoLA.

Q. Why reduce the number of layers rather than the hidden size?
A.

Because the paper's investigation found that, for the same number of parameters, changing the number of layers affects computation speed more than changing the hidden size. Keeping the hidden size at 768, the same as the teacher, also has the advantage that the teacher's layer weights can be used directly to initialize the student.

Q. Which of the three losses used to train DistilBERT matters most?
A.

In the paper's experiments, the two distillation losses — LceL_{ce}, which imitates the teacher's probabilities, and LcosL_{cos}, which aligns hidden-state directions — accounted for most of the performance. Removing LceL_{ce} and LcosL_{cos} lowered the GLUE score by 2.96, while removing the masked language modeling loss LmlmL_{mlm} lowered it by only 0.31. Even more effective than any loss was initialization from the teacher's layers: random initialization lowered the score by 3.69.

References

  1. Sanh, V., Debut, L., Chaumond, J., & Wolf, T. (2019). DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter. 5th Workshop on Energy Efficient Machine Learning and Cognitive Computing (EMC²) @ NeurIPS 2019. arXiv:1910.01108.
  2. Hinton, G., Vinyals, O., & Dean, J. (2015). Distilling the Knowledge in a Neural Network. arXiv:1503.02531.
  3. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019. arXiv:1810.04805.
  4. Hugging Face. Distil* (official training code for DistilBERT, transformers examples/research_projects/distillation).
  5. Hugging Face. Transformers documentation: DistilBERT.