In DistilBERT pretraining, the pretrained BERT-base is frozen as the teacher, and only the student is trained, as follows:
- Create inputs in which 15% of the tokens are masked (dynamic masking, re-sampled each time).
- 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).
- Compute the three losses and add them with weights.
- Update only the student's weights with the combined loss.
The three losses are:
- Distillation loss Lce: the cross-entropy of the student's probabilities si with the teacher's word probabilities ti as the target.
- Masked language modeling loss Lmlm: as in BERT, the loss for predicting the masked words correctly.
- Cosine loss Lcos: a loss that aligns the directions of the teacher's and student's hidden-state vectors.
The distillation loss is:
Lce=−i∑tilogsi
Both ti and si are computed with a softmax at the same temperature T:
pi=∑jexp(zj/T)exp(zi/T)
zi is the score (logit) of word i. A larger T flattens the distribution, so information in the probabilities the teacher assigns to "second and third most likely words" also reaches the student. At inference, T is set back to 1.
The final loss is the weighted sum of the three losses:
L=αceLce+αmlmLmlm+αcosLcos
The paper does not state the values of T or the weights, but in the official training code T=2 is the default, and the training example uses αce=5, αmlm=2 and αcos=1. In the official code, the cosine loss is 1−cos(ht,hs) 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.
| Item | Value |
|---|
| Teacher | BERT-base (pretrained, weights frozen) |
| Data | The same English Wikipedia and BooksCorpus as BERT |
| Batch | Very large batches of up to 4,000 examples via gradient accumulation |
| Masking | Dynamic masking (re-sampled each time) |
| Next sentence prediction | Not used |
| Hardware | About 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.