AI Logic

Model Compression

TinyBERT

Updated:

How TinyBERT works. Left: the layers of the student (4 layers) are mapped to those of the teacher BERT-base (12 layers), with a loss computed at the embedding layer, each Transformer layer, and the prediction layer. Right: two-stage learning that proceeds from general distillation on a large text corpus to task-specific distillation on augmented task data

Background and Overview

TinyBERT is a method that, when compressing BERT with knowledge distillation, matches the teacher not only at the final output but also at the embedding layer and at each layer's attention and hidden states, so that even a small 4-layer model reaches accuracy close to BERT-base. It was proposed in 2019 by Jiao, Yin, and colleagues at Huawei Noah's Ark Lab and Huazhong University of Science and Technology (Findings of EMNLP 2020).

Pre-trained language models such as BERT have many parameters and slow inference, which makes them hard to run on devices such as smartphones. Earlier work had already used knowledge distillation to build small students, but because BERT is built in two stages, "pre-training β†’ fine-tuning," the open question was at which stage, and how, to distill.

TinyBERT introduces two ideas.

  • Transformer distillation: The layers of the teacher and the student are paired, and the student is trained to match the teacher's embedding-layer output, the attention matrices of multi-head attention, the hidden states of each layer, and the logits of the prediction layer.
  • Two-stage learning: General-purpose distillation is performed at the pre-training stage, and at the fine-tuning stage the data are augmented and a second, task-specific distillation is performed.

According to the paper, the 4-layer TinyBERTβ‚„ is 7.5x smaller and 9.4x faster than the teacher BERT-base and retains more than 96.8% of the teacher's performance on GLUE. The 6-layer TinyBERT₆ performs almost on par with the teacher.

Theory (Transformer Distillation Loss)

Let the student have MM Transformer layers and the teacher NN. A mapping function n=g(m)n = g(m) determines which teacher layer the student's mm-th layer learns from. The embedding layer is numbered 0 and the prediction layer M+1M + 1, with g(0)=0g(0) = 0 and g(M+1)=N+1g(M + 1) = N + 1. The overall loss is a weighted sum of per-layer losses (Eq. (6) in the paper).

Lmodel=βˆ‘x∈Xβˆ‘m=0M+1Ξ»m Llayer ⁣(fmS(x),fg(m)T(x))\mathcal{L}_{\text{model}} = \sum_{x \in \mathcal{X}} \sum_{m=0}^{M+1} \lambda_m\, \mathcal{L}_{\text{layer}}\!\left(f_m^S(x), f_{g(m)}^T(x)\right)

The per-layer loss depends on the type of layer (Eq. (11) in the paper).

Llayer={Lembdm=0Lhidn+Lattn0<m≀MLpredm=M+1\mathcal{L}_{\text{layer}} = \begin{cases} \mathcal{L}_{\text{embd}} & m = 0 \\ \mathcal{L}_{\text{hidn}} + \mathcal{L}_{\text{attn}} & 0 < m \le M \\ \mathcal{L}_{\text{pred}} & m = M + 1 \end{cases}

The individual losses are as follows (Eqs. (7)–(10) in the paper).

  1. Attention loss: The mean squared error between per-head attention matrices Ai∈RlΓ—lA_i \in \mathbb{R}^{l \times l} (ll is the sequence length), averaged over the hh heads. AiA_i is the pre-softmax value QK⊀/dkQK^\top / \sqrt{d_k}, because it converged faster and performed better than the post-softmax value.
  2. Hidden-state loss: Compares the Transformer layer outputs HS∈RlΓ—dβ€²H^S \in \mathbb{R}^{l \times d'} and HT∈RlΓ—dH^T \in \mathbb{R}^{l \times d}. Since the student width dβ€²d' is smaller than the teacher width dd, the student's output is projected with a learnable matrix Wh∈Rdβ€²Γ—dW_h \in \mathbb{R}^{d' \times d} before comparison.
  3. Embedding-layer loss: The embeddings ESE^S and ETE^T are compared in the same way, after projection with a matrix WeW_e.
  4. Prediction-layer loss: The teacher and student logits zTz^T and zSz^S are divided by a temperature tt, and the soft cross-entropy is taken. The paper found t=1t = 1 to be sufficient.
Lattn=1hβˆ‘i=1hMSE(AiS,AiT),Lhidn=MSE(HSWh,HT),Lembd=MSE(ESWe,ET),Lpred=CE(zT/t,Β zS/t)\mathcal{L}_{\text{attn}} = \frac{1}{h} \sum_{i=1}^{h} \mathrm{MSE}(A_i^S, A_i^T), \quad \mathcal{L}_{\text{hidn}} = \mathrm{MSE}(H^S W_h, H^T), \quad \mathcal{L}_{\text{embd}} = \mathrm{MSE}(E^S W_e, E^T), \quad \mathcal{L}_{\text{pred}} = \mathrm{CE}(z^T / t,\ z^S / t)

TinyBERTβ‚„ maps one student layer to every third layer of the 12-layer teacher BERT-base (g(m)=3mg(m) = 3m). All layer weights Ξ»m\lambda_m are 1 (left side of the top figure).

The attention matrix has shape lΓ—ll \times l, so as long as the number of heads matches, it can be compared directly even when the student's width differs from the teacher's. The paper adds this loss based on prior work (Clark et al. 2019) showing that BERT's attention captures linguistic knowledge such as syntax and coreference.

Two-Stage Learning and Data Augmentation

Following the way BERT is built, TinyBERT distills twice (right side of the top figure).

  1. General distillation: Using a BERT that has only been pre-trained (not fine-tuned) as the teacher, Transformer distillation is performed on a large text corpus (English Wikipedia). The prediction layer is not distilled, both to focus on learning the structure of the intermediate layers and because adding it did not help in preliminary experiments. The resulting general TinyBERT serves as an initialization for any task.
  2. Data augmentation: The task's training data are expanded by generating sentences with words replaced.
  3. Task-specific distillation: Starting from the general TinyBERT and using a BERT fine-tuned on the task as the teacher, distillation is performed on the augmented data. The intermediate layers are distilled first, followed by the prediction layer.

The data augmentation procedure is as follows (Algorithm 1 in the paper). Each word in a sentence is replaced with a candidate word with probability pt=0.4p_t = 0.4. For single-piece words, candidates are drawn from the top K=15K = 15 words predicted by BERT with that position set to [MASK]; for words split into multiple pieces, candidates are the 15 nearest words by GloVe word vectors. This is repeated Na=20N_a = 20 times per sentence.

The two stages complement each other. General distillation provides an initialization with broad linguistic knowledge, and task-specific distillation packs in task knowledge using the augmented data. The paper notes reports that fine-tuned BERT is over-parameterized for individual tasks, leaving room for a small model to reach comparable accuracy.

Why It Retains Performance Despite Its Small Size

Sections 4.5 and 4.6 of the paper remove parts of the method and compare results on the GLUE dev sets (average of MNLI-m, MNLI-mm, MRPC, and CoLA).

Removed componentAverageDifference from TinyBERTβ‚„ (75.6)
General distillation72.5βˆ’3.1
Task-specific distillation68.5βˆ’7.1
Data augmentation68.4βˆ’7.2
Embedding-layer distillation74.1βˆ’1.5
Prediction-layer distillation73.5βˆ’2.1
Attention distillation71.0βˆ’4.6
Hidden-state distillation72.9βˆ’2.7
Transformer-layer distillation (both attention and hidden states)56.3βˆ’19.3
  • Every stage contributes (Table 2). Task-specific distillation and data augmentation have especially large effects, and general distillation stands out on CoLA, which judges grammatical acceptability.
  • Matching the intermediate layers matters most (Table 3). Removing Transformer-layer distillation drops the average from 75.6 to 56.3. Attention distillation is more effective than hidden-state distillation, and combining the two works better still.
  • Using the teacher's layers uniformly gives the best results (Table 4). Learning from every third layer (75.6) beats learning only from the top 4 layers (average 70.9) or the bottom 4 layers (71.3) on every task. Since different tasks benefit from different layers, the paper argues that learning uniformly from bottom to top works best.

In short, rather than imitating only the final answer, matching the teacher's intermediate reasoning (where attention goes and the intermediate representations) lets even a small student absorb much of the teacher's knowledge.

Experimental Results

Table 1 of the paper reports results on the GLUE test sets (evaluated on the official server). Inference speed was measured on a single NVIDIA K80 GPU.

ModelParametersSpeedupMNLI-m/mmSST-2CoLAAverage
BERT-base (teacher)109M1.0x83.9 / 83.493.452.879.5
BERT-Tiny (small BERT pre-trained directly)14.5M9.4x75.4 / 74.987.619.570.2
BERTβ‚„-PKD52.2M3.0x79.9 / 79.389.424.872.6
DistilBERTβ‚„52.2M3.0x78.9 / 78.091.432.871.9
TinyBERTβ‚„14.5M9.4x82.5 / 81.892.644.177.0
DistilBERT₆67.0M2.0x82.6 / 81.392.549.076.8
TinyBERT₆67.0M2.0x84.6 / 83.293.151.179.4

The average is taken over eight tasks: MNLI, QQP, QNLI, SST-2, CoLA, STS-B, MRPC, and RTE.

  • 6.8 points higher on average than BERT-Tiny of the same size: With the same architecture (4 layers, width 312), distillation is far better than direct pre-training.
  • At least 4.4 points higher than other 4-layer distillation methods: This is achieved with about 28% of their parameters and 3.1x faster inference.
  • On par with the teacher at 6 layers: TinyBERT₆'s average of 79.4 is almost the same as the teacher's 79.5 and exceeds DistilBERT₆ with the same architecture by 2.6 points.

TinyBERTβ‚„ has M=4M = 4 layers, width dβ€²=312d' = 312, a feed-forward width of 1,200, and 12 heads.

Practical Considerations

  • Training is more expensive. In addition to general distillation (3 epochs on Wikipedia), each task requires distilling the intermediate layers for 20 epochs (10 epochs for large datasets such as MNLI) on 20x augmented data, and the prediction layer for 3 epochs. A fine-tuned teacher is also needed for every task.
  • Start with a uniform layer mapping. Mapping to the teacher's layers uniformly (every third layer) gave the best results in the paper's comparison. Selecting layers per task is left as future work.
  • Match the number of heads to the teacher. The attention loss compares per-head attention matrices, so the student must have the same number of heads as the teacher (TinyBERTβ‚„ also has 12 heads).
  • The student's size can be chosen freely. BERT-PKD and DistilBERT initialize the student from a subset of the teacher's layers, so the student's width had to match the teacher's. Because TinyBERT is initialized by general distillation, its width and number of layers can be set freely.

Even TinyBERTβ‚„ still trails the teacher on CoLA, which judges grammatical acceptability: 44.1 versus the teacher's 52.8. The paper also notes that all 4-layer students show a large gap to the teacher on CoLA. For tasks that require fine-grained linguistic judgments, consider a larger student such as a 6-layer model.

Comparison with Other Methods

The table below compares representative distillation methods for compressing BERT along the same dimensions.

MethodDistillation stageWhat is matchedHow the student is built
BERT-PKDFine-tuningPredictions and intermediate-layer outputsInitialized from a subset of the teacher's layers
DistilBERTPre-trainingPrediction distribution and hidden-state directionsInitialized from a subset of the teacher's layers
MobileBERTPre-trainingLayer-wise knowledge transferred progressivelyFrom a bottlenecked BERT-large to a thin 24-layer model
TinyBERTBoth pre-training and fine-tuningEmbeddings, attention, hidden states, and predictionsInitialization built by general distillation

DistilBERT distills only once at the pre-training stage, so it can be applied easily to any task. TinyBERT spends extra effort distilling again for each task and, in return, achieves higher accuracy at the same size.

  • When a single task needs a model small and fast enough to run on a device, TinyBERT is a good fit.
  • When a small model that can be used easily across many tasks is needed, pre-training-only distillation such as DistilBERT is more convenient.
  • To make a model even lighter, a distilled model can be combined with quantization or pruning.

The basic idea of distillation (imitating the teacher's probability distribution via a softmax with temperature) is explained in the knowledge distillation article.

PyTorch example

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

# TinyBERT's Transformer distillation loss, written following Eqs. (7)-(11) of the paper.
# The teacher and student are assumed to return each layer's attention matrices (pre-softmax) and hidden states.

class TinyBERTDistillLoss(nn.Module):
    def __init__(self, d_student=312, d_teacher=768, mapping=lambda m: 3 * m):
        super().__init__()
        self.W_h = nn.Linear(d_student, d_teacher, bias=False)   # projection W_h for hidden states (learned)
        self.W_e = nn.Linear(d_student, d_teacher, bias=False)   # projection W_e for embeddings (learned)
        self.g = mapping                                         # student layer m -> teacher layer g(m)

    def forward(self, s, t, stage="intermediate", temperature=1.0):
        """s, t are dicts:
           "embd": (B, l, d), "hidden": [(B, l, d) for layers 1..M], "attn": [(B, h, l, l) for layers 1..M], "logits": (B, C)"""
        if stage == "prediction":
            # Prediction-layer distillation: soft cross-entropy CE(z^T/t, z^S/t) (Eq. (10))
            p_t = F.softmax(t["logits"] / temperature, dim=-1)
            return -(p_t * F.log_softmax(s["logits"] / temperature, dim=-1)).sum(-1).mean()

        # Embedding-layer distillation (m = 0, Eq. (9))
        loss = F.mse_loss(self.W_e(s["embd"]), t["embd"])
        for m in range(1, len(s["hidden"]) + 1):
            n = self.g(m)                                        # teacher layer index (1-based)
            # Attention distillation: mean of per-head MSE (Eq. (7); mse_loss averages over heads too)
            loss = loss + F.mse_loss(s["attn"][m - 1], t["attn"][n - 1])
            # Hidden-state distillation: MSE(H^S W_h, H^T) (Eq. (8))
            loss = loss + F.mse_loss(self.W_h(s["hidden"][m - 1]), t["hidden"][n - 1])
        return loss                                              # all layer weights lambda are 1


# Shape-only example (teacher: 12 layers, width 768; student: 4 layers, width 312; both 12 heads)
B, l, h, C = 2, 16, 12, 3
teacher = {"embd": torch.randn(B, l, 768),
           "hidden": [torch.randn(B, l, 768) for _ in range(12)],
           "attn": [torch.randn(B, h, l, l) for _ in range(12)],
           "logits": torch.randn(B, C)}
student = {"embd": torch.randn(B, l, 312, requires_grad=True),
           "hidden": [torch.randn(B, l, 312, requires_grad=True) for _ in range(4)],
           "attn": [torch.randn(B, h, l, l, requires_grad=True) for _ in range(4)],
           "logits": torch.randn(B, C, requires_grad=True)}

crit = TinyBERTDistillLoss()
loss_mid = crit(student, teacher, stage="intermediate")   # general distillation and first half of task-specific distillation
loss_pred = crit(student, teacher, stage="prediction")    # second half of task-specific distillation
(loss_mid + loss_pred).backward()
print(loss_mid.item(), loss_pred.item())

# Use the teacher without gradients and in model.eval() mode to disable dropout.
# With real models, extract hidden states with e.g. Hugging Face's BertModel(..., output_hidden_states=True),
# and modify the model so that pre-softmax attention scores can be retrieved.

FAQ

Q. How does TinyBERT differ from [DistilBERT](/architectures/distilbert)?
A.

DistilBERT distills only once, at the pre-training stage, and initializes the student from a subset of the teacher's layers. TinyBERT distills twice, at the pre-training stage and at the task fine-tuning stage, and matches the teacher down to the attention matrices and the hidden states of each layer. In the paper's GLUE comparison, with the same 6-layer, width-768 architecture, TinyBERT₆ averaged 2.6 points higher than DistilBERT₆.

Q. Why match the attention matrices before the softmax?
A.

In the paper's experiments, matching the pre-softmax values QK⊀/dkQK^\top / \sqrt{d_k} led to faster convergence and better performance than matching the post-softmax probabilities.

Q. Is data augmentation always necessary?
A.

In the paper's experiments, removing data augmentation dropped the dev-set average from 75.6 to 68.4, an impact as large as removing task-specific distillation. The task data are often too small for a small student to imitate the teacher's behavior well. It adds computational cost, but it is worth using when accuracy is the priority.

References

  1. X. Jiao, Y. Yin, L. Shang, X. Jiang, X. Chen, L. Li, F. Wang, and Q. Liu, "TinyBERT: Distilling BERT for Natural Language Understanding," Findings of EMNLP 2020, arXiv:1909.10351.
  2. G. Hinton, O. Vinyals, and J. Dean, "Distilling the Knowledge in a Neural Network," arXiv:1503.02531, 2015.
  3. huawei-noah/Pretrained-Language-Model (TinyBERT code and models, released by the paper's authors)