Search

Search papers and lessons

DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter

Victor Sanh, Lysandre Debut, Julien Chaumond et al. · 2019

Sanh and colleagues shrink BERT to half its layers by training the small model to copy the big one's word probabilities, keeping 97 percent of its GLUE score while running about 60 percent faster.

On this page

  • Colour = topic mix
  • Neural network basics
  • Calculus
  • Discrete math
  • Probability
  • Linear algebra
  • Pre-training
  • ReadReady to readNot yet

TL;DR

DistilBERT is a small language model trained to imitate BERT, a larger one. It has the same general design as BERT but half as many layers, and it is trained with three losses at once: match the teacher's soft word probabilities, predict the masked words as usual, and align the direction of the hidden states with the teacher's.

The result has about 40 percent fewer parameters, runs about 60 percent faster at inference, and keeps about 97 percent of BERT's score on the GLUE benchmark.

Builds on: BERT: Pre-training of Deep Bidirectional Transformers, Knowledge Distillation · Leads to: smaller pre-trained encoders trained with distillation, and the on-device question answering the authors demonstrated

Why it mattered

Pre-trained transformers such as BERT became the default starting point for language tasks, but they are large and slow to run. The paper's question was whether a much smaller model could keep most of that quality when used the same way: pre-trained once, then fine-tuned on each task.

The authors built a general-purpose student, not a task-specific one, so a single distilled checkpoint can be fine-tuned for classification and question answering. They also ran a proof-of-concept on-device question-answering experiment, which the abstract reports as a demonstration rather than a benchmark.

The problem

BERT-base has 12 transformer layers and about 110 million parameters. Running it costs memory and time on each query, and that cost matters on phones and in any service with a tight latency budget. Simpler compression, such as training a small model from scratch on the same labels, loses a lot of accuracy, because the labels say only which word was hidden, not which other words were plausible.

Knowledge distillation addresses the second point. A teacher assigns a probability to every vocabulary word at each masked position, and that full distribution carries information about which words are close in meaning. The student learns from the whole distribution rather than from a single correct word. The paper's job was to apply this to pre-training, so the student is a general model, and to choose the student's architecture and starting point so it trains well.

How it works

Here is one tiny instance of the distillation signal. The teacher has three candidate words for a masked slot, with raw scores (logits) z=(2,1,0)z = (2, 1, 0). The student produces its own distribution from its own scores.

  1. Turn the teacher's scores into probabilities with a temperature T=2T = 2: divide each score by TT and apply the softmax. The scores become (1,0.5,0)(1, 0.5, 0).
  2. Exponentiate: e1=2.718e^1 = 2.718, e0.5=1.649e^{0.5} = 1.649, e0=1e^0 = 1. Sum: 5.3675.367.
  3. Divide: the teacher's soft targets are t=(0.506,0.307,0.186)t = (0.506, 0.307, 0.186). Check: they sum to 1.0001.000.
  4. Without the temperature the same scores give (0.665,0.245,0.090)(0.665, 0.245, 0.090), which is sharper. The temperature spreads probability onto the less likely words, which is the information the student needs.
  5. The student, at the same temperature, produces s=(0.4,0.4,0.2)s = (0.4, 0.4, 0.2). Its distillation loss is the cross-entropy between the two: −∑itilog⁡si≈1.045-\sum_i t_i \log s_i \approx 1.045. Training lowers this number by moving the student's probabilities toward tt.
  6. At inference the temperature is set to 1, which recovers the ordinary softmax. The student's output is then used as a normal classifier.
  7. The full objective adds two more terms, described in the math section, and the student's layers are initialised from the teacher's by taking one layer out of two.
flowchart LR
  T[BERT teacher, 12 layers] --> SOFT[Soft targets at temperature T]
  T --> HID[Teacher hidden states]
  S[DistilBERT student, 6 layers, initialised from every other teacher layer] --> SL[Student predictions at temperature T]
  S --> SH[Student hidden states]
  SOFT --> LCE[Distillation loss]
  SL --> LCE
  D[Masked text] --> LMLM[Masked language modelling loss]
  S --> LMLM
  HID --> LCOS[Cosine loss on hidden states]
  SH --> LCOS
  LCE --> TOT[Total loss]
  LMLM --> TOT
  LCOS --> TOT

The math

The softmax with temperature is

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

where ziz_i is the model's score for class ii and TT controls how smooth the output is. The same TT is used for the teacher and the student during training, and T=1T = 1 at inference.

The distillation loss

With teacher probabilities tit_i and student probabilities sis_i, the distillation loss is

Lce=−∑itilog⁡si.L_{ce} = -\sum_i t_i \log s_i.

This is the Cross-Entropy Loss between the teacher's distribution and the student's. It is minimised when si=tis_i = t_i for every word.

The masked language modelling loss

The student is also trained on the original task, predicting the hidden words. Its loss LmlmL_{mlm} is the usual Masked Language Modeling loss against the true words. The paper's ablation study finds that this term adds little on top of the two distillation losses, so the teacher's signal does most of the work.

The cosine loss and the total

The cosine loss pushes the direction of the student's hidden vector hsh_s toward the teacher's hth_t at each token. Writing cos⁡(hs,ht)\cos(h_s, h_t) for the Cosine Similarity of the two vectors, a loss that is zero when they point the same way is

Lcos=1−cos⁡(hs,ht).L_{cos} = 1 - \cos(h_s, h_t).

The final objective is a linear combination of the three terms,

L=λceLce+λmlmLmlm+λcosLcos,L = \lambda_{ce} L_{ce} + \lambda_{mlm} L_{mlm} + \lambda_{cos} L_{cos},

with weights chosen by the authors. Because the student uses Transformer layers, its hidden vectors have the same size as BERT's, which is what makes the direct comparison of hsh_s and hth_t possible.

Results

The headline results are from the abstract: the student has about 40 percent fewer parameters than BERT, keeps about 97 percent of BERT's score across the language understanding benchmark (GLUE), and runs about 60 percent faster at inference. The ratio of 97 percent is an average over tasks, so the per-task tables in the paper matter for any single use.

The main design evidence is the ablation study, which removes one training loss at a time. Removing the distillation loss hurts most, and the masked language modelling loss matters least. Read the paper's tables for the exact per-task and ablation numbers rather than relying on a summary.

Limits the paper states or implies:

  • The student is a general model, so its gains come from pre-training. A task-specific distillation step can reduce the gap further but adds training cost.
  • The 97 percent figure hides differences between tasks, so a team with one task should measure that task directly.
  • The speed numbers depend on the hardware and batch size, and the on-device result is one proof-of-concept app.

Reading guide

Read BERT: Pre-training of Deep Bidirectional Transformers first for the teacher's architecture and masked training, and Knowledge Distillation for the soft-target idea. Then read the paper in this order.

  • Introduction: the goal of a small general-purpose model. Needs Transformer.
  • Knowledge distillation section: the teacher, the student, and the soft-target loss. Needs Softmax Temperature and Cross-Entropy Loss.
  • DistilBERT section: the student architecture, its initialisation from the teacher, and the three losses. Needs Masked Language Modeling, Layer Normalization, Positional Encoding and Word Embedding.
  • Experiments, GLUE benchmark: the per-task table. Needs Fine-Tuning for how each task is trained on top of the pre-trained model.
  • Ablation study: which loss matters. Read it after the DistilBERT section.
  • Related work: other compression methods. Optional on a first read.

Check yourself

QuestionThe teacher's raw scores are (2, 1, 0). Using T = 2, which word gets the largest soft target, and roughly what probability does it get?Show answer

Dividing by T=2T = 2 gives (1,0.5,0)(1, 0.5, 0). Exponentials are 2.7182.718, 1.6491.649 and 11, which sum to 5.3675.367. The first word gets 2.718/5.367≈0.5062.718 / 5.367 \approx 0.506.

QuestionWhy does the paper use soft teacher probabilities rather than only the correct word as the training target?Show answer

The full distribution shows which other words the teacher considers plausible. Those small probabilities encode similarity between words, so the student learns more per example than from a one-hot label. The temperature makes these small probabilities larger, which is why it is used during training.

QuestionThe ablation study finds that dropping the masked language modelling loss changes results much less than dropping the distillation loss. What does that suggest about where the gain comes from?Show answer

Most of the gain comes from copying the teacher's output distribution, not from the original masked prediction objective. The masked loss still helps a little, but the teacher's soft targets carry most of the information the student uses.

QuestionSuppose a team needs a model for one task. The paper reports 97 percent of BERT's score as an average over tasks. What should they check before adopting DistilBERT?Show answer

They should measure DistilBERT on their own task rather than trust the average, since an average hides differences between tasks. They should also check the speed numbers on their own hardware and batch size, because the paper's 60 percent figure depends on that setup.

Sources

Read the full paper

Victor Sanh, Lysandre Debut, Julien Chaumond et al., 2019. arXiv:1910.01108