# TinyBERT: Distilling BERT for Natural Language Understanding

Distillation shrinks BERT into a small student that keeps most of its accuracy

Xiaoqi Jiao, Yichun Yin, Lifeng Shang, Xin Jiang, Xiao Chen, Linlin Li and 2 more · arXiv · 2019-9-23

- **Problem** BERT is too large and slow for phones and other edge devices. Earlier distillation methods act at only one stage, so part of the knowledge is lost.
- **Method** TinyBERT is a small student trained to copy a large BERT teacher. It matches embeddings, attention, hidden states and logits, first on general text and then on augmented task data.
- **Results** TinyBERT4 reaches 77.0 on the GLUE test set, against 79.5 for BERTBASE. It is 7.5x smaller and 9.4x faster.

## Why compress BERT and why distillation is harder here

Pre-trained language models such as BERT have raised scores on many NLP benchmarks, but their parameter count and inference time make them hard to run on phones and other edge hardware. The study aims to cut computation and model storage while keeping accuracy, and it chooses knowledge distillation, where a small student is trained to reproduce the behaviour of a large teacher, as the means.

BERT is used in two steps: pre-training on a large unlabelled corpus and then fine-tuning on a downstream task. Knowledge is present at both steps, so a distillation method that only works on the final task outputs leaves part of it behind. Earlier BERT distillation methods act mostly at one stage. DistilBERT distills at pre-training, while BERT-PKD extracts knowledge from intermediate layers at fine-tuning.

## What the student is asked to match

Both teacher and student are stacks of Transformer layers, each made of multi-head attention and a position-wise feed-forward network. Attention scores come from queries and keys scaled by the square root of the key dimension, and the output is a softmax-weighted sum of values. Written out, the attention matrix is \\( A = \\frac{QK^{T}}{\\sqrt{d\_k}} \\) and the attention output is \\( \\mathrm{Attention}(Q,K,V)=\\mathrm{softmax}(A)V \\).

The feed-forward sub-layer applies two linear maps with a ReLU between them.

The design rests on the observation that BERT attention weights carry linguistic information, including syntax and coreference, so matching them should pass that information from teacher to student. Because of this, the student is trained on several kinds of intermediate quantity rather than only on its final output, and the loss used for each student layer depends on which kind of layer it is.

The student layer m learns from teacher layer g(m), with the embedding layer taken as index 0 and the prediction layer as index M+1. The total objective sums the layer losses over these indices with a weight \\( \\lambda\_m \\) per layer.

The attention loss averages the mean squared error between each student head and the matching teacher head over the h heads: \\\[ L\_{attn}=\\frac{1}{h}\\sum\_{i=1}^{h}\\mathrm{MSE}(A^{S}\_{i},A^{T}\_{i}) \\\] The target is the unnormalized attention matrix rather than its softmax. The authors report that this setting converged faster and performed better in their experiments.

The hidden-state loss fits the teacher hidden states with a learnable linear map \\( W\_h \\) applied to the student states: \\\[ L\_{hidn}=\\mathrm{MSE}(H^{S}W\_{h},H^{T}) \\\] Here \\( d' \\) is smaller than \\( d \\), so \\( W\_h \\) lifts the student width into the teacher width. The embedding loss uses the same pattern with its own map \\( W\_e \\): \\\[ L\_{embd}=\\mathrm{MSE}(E^{S}W\_{e},E^{T}) \\\] The prediction loss is a soft cross-entropy between teacher and student logits at temperature t, written as \\( L\_{pred}=\\mathrm{CE}(z^{T}/t,\\,z^{S}/t) \\).

The paper finds that t = 1 works well. The layer loss selects one of these: the embedding loss at m = 0, the sum of hidden-state and attention losses for intermediate layers, and the prediction loss at m = M+1. \\\[ L\_{layer}=L\_{embd}\\ (m=0),\\quad L\_{hidn}+L\_{attn}\\ (M\\ge m\>0),\\quad L\_{pred}\\ (m=M+1) \\\]

## How the two training stages fit together

In general distillation, the teacher is the original BERT without fine-tuning, and the student learns from general-domain text through the Transformer distillation objectives. The prediction loss is left out at this stage. The result is a general TinyBERT that serves as the initialization for the next stage. A general TinyBERT performs generally worse than BERT because the hidden size, the embedding size and the layer count are all reduced.

The task stage needs more task examples than the training set holds. Data augmentation runs with BERT predicting replacements for single-piece words and with GloVe neighbours replacing multi-piece words. The augmentation loop draws candidate replacements with probability threshold pt, produces Na augmented copies per example, and uses a candidate set of size K.

The paper sets pt = 0.4, Na = 20 and K = 15 for all experiments.

Task-specific distillation uses the fine-tuned BERT as teacher and starts from the general TinyBERT. The authors argue that fine-tuned BERTs are over-parameterized for domain-specific tasks, so a smaller student can match them. The two stages are complementary: general distillation supplies the initialization, and task-specific distillation on the augmented data adds task knowledge.

## Student configurations and training budgets

TinyBERT4 has M = 4 layers, hidden size d' = 312, feed-forward size d'i = 1200 and h = 12 heads, for a total of 14.5M parameters. The teacher is BERTBASE with N = 12, d = 768, d'i = 3072 and h = 12, containing 109M parameters. TinyBERT4 uses g(m) = 3 x m, so it learns from every third layer of BERTBASE, and each layer weight λ is 1. TinyBERT6 uses M = 6, d' = 768 and d'i = 3072 to match the 6-layer baselines.

General distillation uses English Wikipedia, about 2,500M words, with maximum sequence length 128 for 3 epochs. The other hyper-parameters follow BERT pre-training. Task-specific intermediate-layer distillation runs 20 epochs with batch size 32 and learning rate 5e-5 on the augmented data, with 10 epochs for MNLI, QQP and QNLI and 50 for CoLA.

Prediction-layer distillation then runs 3 epochs, with batch size chosen from {16, 32} and learning rate from {1e-5, 2e-5, 3e-5} on the dev set. The maximum sequence length is 64 for single-sentence tasks and 128 for sentence-pair tasks.

Baselines include BERT-TINY, which is pre-trained directly with the original BERT recipe, and the 4-layer BERT4-PKD and DistilBERT4 models, which the authors train with released code. Evaluation uses the GLUE benchmark, whose tasks include CoLA, SST-2, MRPC, STS-B, QQP, MNLI, QNLI, RTE and WNLI.

## GLUE test results against the teacher and baselines

On the GLUE test set, TinyBERT4 averages 77.0, against 79.5 for BERTBASE and 70.2 for BERT-TINY. The paper describes this as more than 96.8% of the teacher's performance. TinyBERT4 is higher than BERT-TINY on every task in Table 1. Its average is about 6.8% higher, and its CoLA score is 44.1 against 19.5. Test predictions were submitted to the official GLUE evaluation server.

Against the 4-layer knowledge distillation baselines, TinyBERT4 is ahead of BERT4-PKD at 72.6 and DistilBERT4 at 71.9 on average, by at least 4.4%. The parameter and inference figures in the body are the authors' measurements, with inference speedup taken on a single NVIDIA K80 GPU.

TinyBERT4 reports 1.2B FLOPs in Table 1, against 3.1B for MobileBERTTINY.

The 6-layer baselines are taken from reported numbers or evaluated with released models. The authors also note that all 4-layer distilled models have large gaps to the teacher on CoLA, and TinyBERT4 narrows that gap more than the other 4-layer baselines.

Unlike PD and BERT-PKD, which initialize the student from pre-trained layers of BERT, TinyBERT initializes through general distillation, so its configuration is not tied to the teacher's width and depth.

## Which learning procedures matter

On the dev set, the full TinyBERT4 averages 75.6. Removing general distillation gives 72.5, removing task-specific distillation gives 68.5 and removing data augmentation gives 68.4. The dev tasks are MNLI-m, MNLI-mm, MRPC and CoLA, and every row is for TinyBERT4.

Removing general distillation gives 82.5 on MNLI-m, 84.1 on MRPC and 40.8 on CoLA, while removing task-specific distillation gives 80.6, 83.8 and 28.5 on the same tasks. Removing general distillation hurts most on CoLA. The authors conjecture that the linguistic generalization learned in general distillation matters most for judging acceptability.

The variant without task-specific distillation scores lower than the one without general distillation on the average and on CoLA, but not on every column. The text's statement that task-specific steps help more on every task is therefore supported only in the average and on CoLA.

## Which distillation objectives matter

The full TinyBERT4 averages 75.6 on dev. Removing embedding-layer distillation gives 74.1, removing prediction-layer distillation gives 73.5, removing attention distillation gives 71.0 and removing hidden-state distillation gives 72.9. Removing the whole Transformer-layer distillation gives 56.3, which is the largest drop in the objective ablation.

Under the w/o Trm setting, the embedding-layer distillation still runs at pre-training, and embedding- and prediction-layer distillation run at fine-tuning. The authors attribute the collapse to initialization. At pre-training, a good starting point matters for Transformer layers, and without Transformer-layer distillation no upper-layer signal updates those layers at that stage.

Attention-based distillation has a greater effect than hidden-state distillation in these runs, and the two are complementary, which the authors describe as making them the most important techniques for the model in their experiments.

## Which teacher layers each student layer imitates

On the dev set, the uniform mapping averages 75.6 for TinyBERT4, against 70.9 for top and 71.3 for bottom.

The top mapping beats the bottom mapping on both MNLI columns, with 81.7 against 80.6 on MNLI-m and 82.3 against 81.3 on MNLI-mm. It is worse on MRPC, with 83.6 against 84.6, and on CoLA, with 35.9 against 38.5. The authors take this as evidence that different tasks depend on knowledge from different BERT layers, and they state that the uniform strategy covers bottom to top layers and performs best on every task in the table.

## Limits of the evidence

The ablations are run only on TinyBERT4 and only on four dev tasks: MNLI-m, MNLI-mm, MRPC and CoLA. The headline GLUE comparison relies on test-set results for TinyBERT4 and TinyBERT6, and on baselines whose numbers are partly reported and partly self-trained.

The MobileBERTTINY comparison differs in depth, teacher and distillation strategy, so it does not isolate the effect of the method. Results on SQuAD v1.1 and v2.0 and on further baselines such as Poor Man's BERT, BERT-of-Theseus and MiniLM are presented in the appendix, outside the body text.

Adaptive selection of teacher layers for each task is left as future work, and so are wider and deeper teachers such as BERTLARGE and combining the method with quantization or pruning. A general TinyBERT is weaker than BERT before task-specific distillation, and the 4-layer model still has large gaps on CoLA.

## Paper info

- **Authors**: Xiaoqi Jiao, Yichun Yin, Lifeng Shang, Xin Jiang, Xiao Chen, Linlin Li, Fang Wang, Qun Liu
- **Venue**: arXiv · Preprint
- **First published**: 2019-9-23
- **Added**: 2026-11-12
- **Updated**: 2020-10-16
- **Version**: v5
- **arXiv**: 1909.10351
- **Category**: cs.CL · cs.AI · cs.LG
- **Original paper terms**: [arXiv non-exclusive 1.0](https://arxiv.org/licenses/nonexclusive-distrib/1.0/)
- **What we show**: Paper info and commentary

[Original paper ↗](https://arxiv.org/abs/1909.10351v5) · [PDF ↗](https://arxiv.org/pdf/1909.10351v5)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Xiaoqi Jiao, Yichun Yin, Lifeng Shang, Xin Jiang, Xiao Chen, Linlin Li, Fang Wang, Qun Liu (2019). TinyBERT: Distilling BERT for Natural Language Understanding. arXiv:1909.10351v5. https://arxiv.org/abs/1909.10351v5

**BibTeX**

```
@misc{jiao2019tinybert,
  title = {{TinyBERT: Distilling BERT for Natural Language Understanding}},
  author = {Xiaoqi Jiao and Yichun Yin and Lifeng Shang and Xin Jiang and Xiao Chen and Linlin Li and Fang Wang and Qun Liu},
  year = {2019},
  eprint = {1909.10351},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1909.10351v5}
}
```

## Other paper commentary

- [Generating Sentences from a Continuous Space](https://refivu.com/en/papers/921b1922-5f2e-49a8-80cd-9df917da7fe7-generating-sentences-from-a-continuous-space.md)
- [A Diversity-Promoting Objective Function for Neural Conversation Models](https://refivu.com/en/papers/a4f62a40-246e-47fd-bbb9-33f09731586c-a-diversity-promoting-objective-function-for-neural.md)
- [A Call for Clarity in Reporting BLEU Scores](https://refivu.com/en/papers/626061b1-f2e9-4997-a6e6-2f15df6f8b3f-a-call-for-clarity-in-reporting-bleu-scores.md)
- [MS MARCO: A Human Generated MAchine Reading COmprehension Dataset](https://refivu.com/en/papers/5bd254d7-7f81-466f-936c-2233b75bea95-ms-marco-a-human-generated-machine-reading-comprehension.md)
- [NLTK: The Natural Language Toolkit](https://refivu.com/en/papers/26e265b2-45d0-4d0e-b6a7-a161ecf1fe09-nltk-the-natural-language-toolkit.md)
- [EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks](https://refivu.com/en/papers/6bc7db3b-907c-40de-8993-2cc4b32ed04f-eda-easy-data-augmentation-techniques-for-boosting.md)
- [Self-Refine: Iterative Refinement with Self-Feedback](https://refivu.com/en/papers/f8f8d11b-268b-4988-84b8-c616a701e2ba-self-refine-iterative-refinement-with-self-feedback.md)
- [LIO-SAM: Tightly-coupled Lidar Inertial Odometry via Smoothing and Mapping](https://refivu.com/en/papers/8fa3265c-e57e-4469-8761-2a9bfc47279e-lio-sam-tightly-coupled-lidar-inertial-odometry-via.md)
- [Soft-NMS -- Improving Object Detection With One Line of Code](https://refivu.com/en/papers/d6a13a67-cb33-4ee3-8420-05da2f2b5960-soft-nms-improving-object-detection-with-one-line.md)
- [Identifying the Best Machine Learning Algorithms for Brain Tumor Segmentation, Progression Assessment, and Overall Survival Prediction in the BRATS Challenge](https://refivu.com/en/papers/a75a6487-afcf-4dd0-8b85-09a24d21da45-identifying-the-best-machine-learning-algorithms-for-brain.md)
- [SeqGAN: Sequence Generative Adversarial Nets with Policy Gradient](https://refivu.com/en/papers/29153239-a1df-4102-9df1-abd1ba2a9c96-seqgan-sequence-generative-adversarial-nets-with-policy.md)
- [Deep Learning for Person Re-identification: A Survey and Outlook](https://refivu.com/en/papers/d4bdc05a-ddac-43ad-93f5-95986e1858a4-deep-learning-for-person-re-identification-a-survey.md)

## Terms in this paper

- [BERT](https://refivu.com/en/terms/45b639a1d317-bert)
- [Data Augmentation](https://refivu.com/en/terms/cc5618231f4a-data-augmentation)
- [GloVe](https://refivu.com/en/terms/8a6b3410f3dd-glove)
- [GLUE](https://refivu.com/en/terms/9305114e7947-glue)
- [multi-head attention](https://refivu.com/en/terms/370ae5c971cd-multi-head-attention)
- [MNLI](https://refivu.com/en/terms/3187e3865499-mnli)
- [Speedup](https://refivu.com/en/terms/48c9c2eb8140-speedup)
- [English Wikipedia](https://refivu.com/en/terms/34ae8aa404c0-english-wikipedia)
- [CoLA](https://refivu.com/en/terms/8381ed275c42-cola)
- [BERTBASE](https://refivu.com/en/terms/73320a675f5a-bertbase)
- [MRPC](https://refivu.com/en/terms/54148d717308-mrpc)
- [Transformer layer](https://refivu.com/en/terms/60077cf08ed1-transformer-layer)
- [mapping function](https://refivu.com/en/terms/75f2f65a2859-mapping-function)
- [Position-wise Feed-Forward Network](https://refivu.com/en/terms/60eeedb9a5f0-position-wise-feed-forward-network)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/b5b68df2-5d79-42e6-8e82-c8fdbf0e3a3d-tinybert-distilling-bert-for-natural-language-understanding)
