TernaryBERT: Distillation-aware Ultra-low Bit BERT

Wei Zhang, Lu Hou, Yichun Yin, Lifeng Shang, Xiao Chen, Xin Jiang, Qun Liu

Introduction

Transformer-based models have shown great power in various natural language processing (NLP) tasks. Pre-trained with gigabytes of unsupervised data, these models usually have hundreds of millions of parameters. For instance, the BERT-base model has 109M parameters, with the model size of 400+MB if represented in 32-bit floating-point format, which is both computation and memory expensive during inference. This poses great challenges for these models to run on resource-constrained devices like cellphones. To alleviate this problem, various methods are proposed to compress these models, like using low-rank approximation (Ma et al., 2019; Lan et al., 2020), weight-sharing (Dehghani et al., 2019; Lan et al., 2020), knowledge distillation (Sanh et al., 2019; Sun et al., 2019; Jiao et al., 2019), pruning (Michel et al., 2019; Voita et al., 2019; Fan et al., 2019), adaptive depth and/or width (Liu et al., 2020; Hou et al., 2020), and quantization (Zafrir et al., 2019; Shen et al., 2020; Fan et al., 2020).

Compared with other compression methods, quantization compresses a neural network by using lower bits for weight values without changing the model architecture, and is particularly useful for carefully-designed network architectures like Transformers. In addition to weight quantization, further quantizing activations can speed up inference with target hardware by turning floating-point operations into integer or bit operations. In (Prato et al., 2019; Zafrir et al., 2019), 8-bit quantization is successfully applied to Transformer-based models with comparable performance as the full-precision baseline. However, quantizing these models to ultra low bits (e.g., 1 or 2 bits) can be much more challenging due to significant reduction in model capacity. To avoid severe accuracy drop, more complex quantization methods, like mixed-precision quantization (Shen et al., 2020; Zadeh and Moshovos, 2020) and product quantization (PQ) Fan et al. (2020), are used. However, mixed-precision quantization is unfriendly to some hardwares, and PQ requires extra clustering operations.

Besides quantization, knowledge distillation (Hinton et al., 2015) which transfers knowledge learned in the prediction layer of a cumbersome teacher model to a smaller student model, is also widely used to compress BERT (Sanh et al., 2019; Sun et al., 2019; Jiao et al., 2019; Wang et al., 2020). Instead of directly being used to compress BERT, the distillation loss can also be used in combination with other compression methods (McCarley, 2019; Mao et al., 2020; Hou et al., 2020), to fully leverage the knowledge of teacher model.

In this work, we propose TernaryBERT, whose weights are restricted to {−1,0,+1}\{-1,0,+1\}. Instead of directly using knowledge distillation to compress a model, we use it to improve the performance of ternarized student model with the same size as the teacher model. In this way, we wish to transfer the knowledge from the highly-accurate teacher model to the ternarized student model with smaller capacity, and to fully explore the compactness by combining quantization and distillation. We investigate the ternarization granularity of different parts of the BERT model, and apply various distillation losses to improve the performance of TernaryBERT. Figure 1 summarizes the accuracy versus model size on MNLI, where our proposed method outperforms other BERT compression methods. More empirical results on the GLUE benchmark and SQuAD show that our proposed TernaryBERT outperforms other quantization methods, and even achieves comparable performance as the full-precision baseline, while being much smaller.

Related Work

Knowledge distillation is first proposed in (Hinton et al., 2015) to transfer knowledge in the logits from a large teacher model to a more compact student model without sacrificing too much performance. It has achieved remarkable performance in NLP (Kim and Rush, 2016; Jiao et al., 2019) recently. Besides the logits Hinton et al. (2015), knowledge from the intermediate representations (Romero et al., 2014; Jiao et al., 2019) and attentions (Jiao et al., 2019; Wang et al., 2020) are also used to guide the training of a smaller BERT.

Instead of directly being used for compression, knowledge distillation can also be used in combination with other compression methods like pruning (McCarley, 2019; Mao et al., 2020), low-rank approximation (Mao et al., 2020) and dynamic networks (Hou et al., 2020), to fully leverage the knowledge of the teacher BERT model. Although combining quantization and distillation has been explored in convolutional neural networks (CNNs) (Polino et al., 2018; Stock et al., 2020; Kim et al., 2019), using knowledge distillation to train quantized BERT has not been studied. Compared with CNNs which simply perform convolution in each layer, the BERT model is more complicated with each Transformer layer containing both a Multi-Head Attention mechanism and a position-wise Feed-forward Network. Thus the knowledge that can be distilled in a BERT model is also much richer (Jiao et al., 2019; Wang et al., 2020).

2 Quantization

Quantization has been extensively studied for CNNs. Popular ultra-low bit weight quantization methods for CNNs can be divided into two categories: approximation-based and loss-aware based. Approximation-based quantization (Rastegari et al., 2016; Li et al., 2016) aims at keeping the quantized weights close to the full-precision weights, while loss-aware based quantization (Hou et al., 2017; Hou and Kwok, 2018; Leng et al., 2018) directly optimizes for the quantized weights that minimize the training loss.

On Transformer-based models, 8-bit fixed-point quantization is successfully applied in fully-quantized Transformer (Prato et al., 2019) and Q8BERT (Zafrir et al., 2019). The use of lower bits is also investigated in (Shen et al., 2020; Fan et al., 2020; Zadeh and Moshovos, 2020). Specifically, In Q-BERT Shen et al. (2020) and GOBO (Zadeh and Moshovos, 2020), mixed-precision with 3 or more bits are used to avoid severe accuracy drop. However, mixed-precision quantization can be unfriendly to some hardwares. Fan et al. (2020) propose Quant-Noise which quantizes a subset of weights in each iteration to allow unbiased gradients to flow through the network. Despite the high compression rate achieved, the quantization noise rate needs to be tuned for good performance.

In this work, we extend both approximation-based and loss-aware ternarization methods to different granularities for different parts of the BERT model, i.e., word embedding and weights in Transformer layers. To avoid accuracy drop due to the reduced capacity caused by ternarization, various distillation losses are used to guide the training of the ternary model.

Approach

In this section, we elaborate on the method of using knowledge distillation to train TernaryBERT, the weights of which take values in {−1,0,+1}\{-1,0,+1\}.

Let the full-precision weight in the BERT model be w{\bf w}, where w=vec(W){\bf w}=\text{vec}({\bf W}) returns a vector by stacking all the columns of weight matrix W{\bf W}. The corresponding ternarized weight is denoted as w^=Qw(w)\hat{\bf{w}}=Q_{w}({\bf w}) where QwQ_{w} is the weight ternarization function. The whole framework, which we call Distillation-aware ternarization, is shown in Figure 2. Specifically, at the tt-th training iteration, we first ternarize the weights wt{\bf w}^{t} in the student BERT model to w^t\hat{\bf{w}}^{t}. Then we do the forward pass with the ternarized model. After that, the gradient of the distillation loss w.r.t. the quantized weights ∂L∂w^t\frac{\partial\mathcal{L}}{\partial\hat{\bf{w}}^{t}} is computed. As is shown in Courbariaux et al. (2016); Hou and Kwok (2018), it is important to keep the full-precision weight during training. Hence, we use the full-precision weight for parameter update: wt+1=UpdateParameter(wt,∂L∂w^t,ηt){\bf w}^{t+1}=\text{UpdateParameter}({\bf w}^{t},\frac{\partial\mathcal{L}}{\partial\hat{\bf{w}}^{t}},\eta^{t}), where ηt\eta^{t} is the learning rate at the tt-th iteration.

In the following, we will first introduce what and how to quantize in Section 3.1. Then in Section 3.2, we introduce the distillation loss used to improve the performance of the ternarized model.

The BERT model Devlin et al. (2019) is built with Transformer layers Vaswani et al. (2017). A standard Transformer layer includes two main sub-layers: Multi-Head Attention (MHA) module and Feed-Forward Network (FFN).

the softmax function is applied on the normalized scores to get the output as headh=Softmax(1dAh)HlWhV.\text{head}_{h}=\text{Softmax}(\frac{1}{\sqrt{d}}{\bf A}_{h}){\bf H}_{l}{\bf W}^{V}_{h}. Denote W∗=[W1∗,⋯ ,WNH∗]{\bf W}^{*}=[{\bf W}^{*}_{1},\cdots,{\bf W}^{*}_{N_{H}}] where ∗* can be Q,K,VQ,K,V. The output of the multi-head attention is:

Combining (2) and (3), the forward propagation for the ll-th Transformer layer can be written as

where LN is the layer normalization. The input to the first transformer layer

is the combination of the token embedding, segment embedding and position embedding. Here z{\bf z} is the input sequence, and WE,WS,WP{\bf W}^{E},{\bf W}^{S},{\bf W}^{P} are the learnable word embedding, segment embedding and position embedding, respectively.

For weight quantization, following Shen et al. (2020); Zafrir et al. (2019), we quantize the weights WQ,WK,WV,WO,W1,W2{\bf W}^{Q},{\bf W}^{K},{\bf W}^{V},{\bf W}^{O},{\bf W}^{1},{\bf W}^{2} in (2) and (3) from all Transformer layers, as well as the word embedding WE{\bf W}^{E} in (4). Besides these weights, we also quantize the inputs of all linear layers and matrix multiplication operations in the forward propagation. We do not quantize WS,WP{\bf W}^{S},{\bf W}^{P}, and the bias in linear layers because the parameters involved are negligible. Following Zafrir et al. (2019), we also do not quantize the softmax operation, layer normalization and the last task-specific layer because the parameters contained in these operations are negligible and quantizing them can bring significant accuracy degradation.

In the following, we discuss the choice of the weight ternarization function QwQ_{w} in Figure 2.

Weight ternarization is pioneered in ternary-connect Lin et al. (2016) where the ternarized values can take {−1,0,1}\{-1,0,1\} represented by 2 bits. By ternarization, most of the floating-point multiplications in the forward pass are turned into floating-point additions, which greatly reduces computation and memory. Later, by adding a scaling parameter, better results are obtained in Li et al. (2016). Thus in this work, to ternarize the weights of BERT, we use both approximation-based ternarization method TWN Li et al. (2016) and loss-aware ternarization LAT Hou and Kwok (2018), where the ternary weight w^\hat{\bf{w}} can be represented by the multiplication of a scaling parameter α>0\alpha>0 and a ternary vector b∈{−1,0,+1}n{\bf b}\in\{-1,0,+1\}^{n} as w^=αb\hat{\bf{w}}=\alpha{\bf b}. Here nn is the number of elements in w^\hat{\bf{w}}.

In the tt-th training iteration, TWN ternarizes the weights by minimizing the distance between the full-precision weight wt{\bf w}^{t} and ternarized weight w^t=αtbt\hat{\bf{w}}^{t}=\alpha^{t}{\bf b}^{t} with following optimization problem (Li et al., 2016)

Let IΔ(x){\bf I}_{\Delta}({\bf x}) be a thresholding function that [IΔ(x)]i ⁣ ⁣= ⁣ ⁣1[{\bf I}_{\Delta}({\bf x})]_{i}\!\!=\!\!1 if xi ⁣> ⁣ ⁣Δx_{i}\!>\!\!\Delta, −1-1 if xi ⁣ ⁣< ⁣ ⁣−Δx_{i}\!\!<\!\!-\Delta, and 0 otherwise, where Δ\Delta is a positive threshold. Let ⊙\odot be element-wise multiplication, the optimal solution of (5) satisfies Hou and Kwok (2018): bt=IΔt(wt){\bf b}^{t}={\bf I}_{\Delta^{t}}({\bf w}^{t}) and αt=∥bt⊙wt∥1∥bt∥1,\alpha^{t}=\frac{\|{\bf b}^{t}\odot{\bf w}^{t}\|_{1}}{\|{\bf b}^{t}\|_{1}}, where

The exact solution of Δt\Delta^{t} requires an expensive sorting operation (Hou et al., 2017). Thus in (Li et al., 2016), TWN approximates the threshold with Δt=0.7∥wt∥1n\Delta^{t}=\frac{0.7\|{\bf w}^{t}\|_{1}}{n}.

Unlike TWN, LAT directly searches for the ternary weights that minimize the training loss L\mathcal{L}. The ternary weights are obtained by solving the optimization problem:

For a vector x{\bf x}, let x\sqrt{{\bf x}} be the element-wise square root, Diag(x)\text{Diag}({\bf x}) returns a diagonal matrix with x{\bf x} on the diagonal, and ∥x∥Q2 ⁣ ⁣= ⁣ ⁣x⊤Qx\|{\bf x}\|_{Q}^{2}\!\!=\!\!{\bf x}^{\top}Q{\bf x}. Problem (6) can be reformulated as solving the following sub-problem at the tt-th iteration (Hou and Kwok, 2018)

where vt{\bf v}^{t} is a diagonal approximation of the Hessian of L\mathcal{L} readily available as the second moment of gradient in adaptive learning rate optimizers like Adam (Kingma and Ba, 2015). Empirically, we use the second moment in BertAdamhttps://github.com/huggingface/transformers/blob/v0.6.2/pytorch_pretrained_bert/optimization.py, which is a variant of Adam by fixing the weight decay (Loshchilov and Hutter, 2019) and removing the bias compensation (Kingma and Ba, 2015). For (7), both an expensive exact solution based on sorting operation, and an efficient approximate solution based on alternative optimization are provided in (Hou and Kwok, 2018). In this paper, we use the more efficient approximate solution.

In the original paper of TWN and LAT, one scaling parameter is used for each convolutional or fully-connected layer. In this work, we extend them to the following two granularities: (i) layer-wise ternarization which uses one scaling parameter for all elements in each weight matrix; and (ii) row-wise ternarization which uses one scaling parameter for each row in a weight matrix. With more scaling parameters, row-wise ternarization has finer granularity and smaller quantization error.

Activation Quantization.

To make the most expensive matrix multiplication operation faster, following Shen et al. (2020); Zafrir et al. (2019), we also quantize the activations (i.e., inputs of all linear layers and matrix multiplication) to 8 bits. There are two kinds of commonly used 8-bit quantization methods: symmetric and min-max 8-bit quantization. The quantized values of the symmetric 8-bit quantization distribute symmetrically in both sides of 0, while those of min-max 8-bit quantization distribute uniformly in a range determined by the minimum and maximum values.

We find that the distribution of hidden representations of the Transformer layers in BERT is skewed towards the negative values (Figure 3). This bias is more obvious for early layers (Appendix A). Thus we use min-max 8-bit quantization for activations as it gives finer resolution for non-symmetric distributions. Empirically, we also find that min-max 8-bit quantization outperforms symmetric quantization (Details are in Section 4.3).

Specifically, for one element xx in the activation x{\bf x}, denote xmax=max(x)x_{max}=\text{max}({\bf x}) and xmin=min(x)x_{min}=\text{min}({\bf x}), the min-max 8-bit quantization function is

where s=(xmax−xmin)/255,s=(x_{max}-x_{min})/255, is the scaling parameter. We use the straight-through estimator in (Courbariaux et al., 2016) to back propagate the gradients through the quantized activations.

2 Distillation-aware Ternarization

The quantized BERT uses low bits to represent the model parameters and activations. Therefore it results in relatively low capacity and worse performance compared with the full-precision counterpart. To alleviate this problem, we incorporate the technique of knowledge distillation to improve performance of the quantized BERT. In this teacher-student knowledge distillation framework, the quantized BERT acts as the student model, and learns to recover the behaviours of the full-precision teacher model over the Transformer layers and prediction layer.

Specifically, inspired by Jiao et al. (2019), the distillation objective for the Transformer layers Ltrm\mathcal{L}_{trm} consists of two parts. The first part is the distillation loss which distills knowledge in the embedding layer and the outputs of all Transformer layers of the full-precision teacher model to the quantized student model, by the mean squared error (MSE) loss: ∑l=1L+1MSE(HlS,HlT).\sum_{l=1}^{L+1}\text{MSE}({\bf H}_{l}^{S},{\bf H}_{l}^{T}). The second part is the distillation loss that distills knowledge from the teacher model’s attention scores from all heads AlT{\bf A}_{l}^{T} in each Transformer layer to the student model’s attention scores AlS{\bf A}_{l}^{S} as ∑l=1LMSE(AlS,AlT)\sum_{l=1}^{L}\text{MSE}({\bf A}_{l}^{S},{\bf A}_{l}^{T}). Thus the distillation for the Transformer layers Ltrm\mathcal{L}_{trm} is formulated as:

Besides the Transformer layers, we also distill knowledge in the prediction layer which makes the student model’s logits PS{\bf P}^{S} learn to fit PT{\bf P}^{T} from the teacher model by the soft cross-entropy (SCE) loss:

The overall objective of knowledge distillation in the training process of TernaryBERT is thus

We use the full-precision BERT fine-tuned on the downstream task to initialize our quantized model, and the data augmentation method in (Jiao et al., 2019) to boost the performance. The whole procedure, which will be called Distillation-aware ternarization, is shown in Algorithm 1.

Experiments

In this section, we evaluate the efficacy of the proposed TernaryBERT on both the GLUE benchmark Wang et al. (2018) and SQuAD Rajpurkar et al. (2016, 2018). The experimental code is modified from the huggingface transformer library.Given the superior performance of Huawei Ascend AI Processor and MindSpore computing framework, we are going to open source the code based on MindSpore (https://www.mindspore.cn/en) soon. We use both TWN and LAT to ternarize the weights. We use layer-wise ternarization for weights in Transformer layers while row-wise ternarization for the word embedding, because empirically finer granularity to word embedding improves performance (Details are in Section 4.3).

We compare our proposed method with Q-BERT (Shen et al., 2020) and Q8BERT (Zafrir et al., 2019) using their reported results. We also compare with a weight-ternarized BERT baseline Q2BERT by modifying the min-max 8-bit quantization to min-max ternarization using the released code of Q8BERT.https://github.com/NervanaSystems/nlp-architect.git For more direct comparison, we also evaluate the proposed method under the same 8-bit quantization settings as Q-BERT and Q8BERT. When the weights are quantized to 8-bit, we use layer-wise scaling for both the weights in Transformer layers and the word embedding as 8-bit quantization already has high resolution.

The GLUE benchmark is a collection of diverse natural language understanding tasks, including textual entailment (RTE), natural language inference (MNLI, QNLI), similarity and paraphrase (MRPC, QQP, STS-B), sentiment analysis (SST-2) and linguistic acceptability (CoLA). For MNLI, we experiment on both the matched (MNLI-m) and mismatched (MNLI-mm) sections. The performance metrics are Matthews correlation for CoLA, F1/accuracy for MRPC and QQP, Spearman correlation for STS-B, and accuracy for the other tasks.

The batch size is 16 for CoLA and 32 for the other tasks. The learning rate starts from 2×10−52\times 10^{-5} and decays linearly to 0 during 1 epoch if trained with the augmented data while 3 epochs if trained with the original data. The maximum sequence length is 64 for single-sentence tasks CoLA and SST-2, and 128 for the rest sentence-pair tasks. The dropout rate for hidden representations and the attention probabilities is 0.1. Since data augmentation does not improve the performance of STS-B, MNLI, and QQP, it is not used on these three tasks.

Results on BERT and TinyBERT.

Table 1 shows the development set results on the GLUE benchmark. From Table 1, we find that: 1) For ultra-low 2-bit weight, there is a big gap between the Q-BERT (or Q2BERT) and full-precision BERT due to the dramatic reduction in model capacity. TernaryBERT significantly outperforms Q-BERT and Q2BERT, even with fewer number of bits for word embedding. Meanwhile, TerneryBERT achieves comparable performance with the full-precision baseline with 14.9×14.9\times smaller size. 2) When the number of bits for weight increases to 8, the performance of all quantized models is greatly improved and is even comparable as the full-precision baseline, which indicates that the setting ‘8-8-8’ is not challenging for BERT. Our proposed method outperforms Q-BERT on both MNLI and SST-2 and outperforms Q8BERT in 7 out of 8 tasks. 3) TWN and LAT achieve similar results on all tasks, showing that both ternarization methods are competitive.

In Table 1, we also apply our proposed quantization method on a 6-layer TinyBERT Jiao et al. (2019) with hidden size of 768, which is trained using distillation. As can be seen, the quantized 8-bit TinyBERT and TernaryTinyBERT achieve comparable performance as the full-precision baseline.

Test set results are summarized in Table 2. The proposed TernaryBERT or TernaryTinyBERT achieves comparable scores as the full-precision baseline. Specially, the TernaryTinyBERT has only 1.6 point accuracy drop while being 23.2x smaller.

2 SQuAD

SQuAD v1.1 is a machine reading comprehension task. Given a question-passage pair, the task is to extract the answer span from the passage. SQuAD v2.0 is an updated version where the question might be unanswerable. The performance metrics are EM (exact match) and F1.

The learning rate decays from 2×10−52\times 10^{-5} linearly to 0 during 3 epochs. The batch size is 16, and the maximum sequence length is 384. The dropout rate for the hidden representations and attention probabilities is 0.1. Since Ltrm\mathcal{L}_{trm} is several magnitudes larger than Lpred\mathcal{L}_{pred} in this task, we separate the distillation-aware quantization into two stages, i.e., first using Ltrm\mathcal{L}_{trm} as the objective and then L\mathcal{L} in (8).

Results.

Table 3 shows the results on SQuAD v1.1 and v2.0. TernaryBERT significantly outperforms Q-BERT and Q2BERT, and is even comparable as the full-precision baseline. For this task, LAT performs slightly better than TWN.

3 Ablation Study

In this section, we perform ablation study on quantization, knowledge distillation, initialization, and data augmentation.

We evaluate the effects of different granularities (i.e., row-wise and layer-wise ternarization in Section 3.1) of TWN on the word embedding and weights in Transformer layers. The results are summarized in Table 4. There is a gain of using row-wise ternarization over layer-wise ternarization for word embedding. We speculate this is because word embedding requires finer granularity as each word contains different semantic information. For weights in the Transformer layers, layer-wise ternarization performs slightly better than row-wise quantization. We speculate this is due to high redundancy in the weight matrices, and using one scaling parameter per matrix already recovers most of the representation power of Transformer layers. Appendix E shows that the attention maps of TernaryBERT (with layer-wise ternarization for weights in Transformer layers) resemble the full-precision BERT. Thus empirically, we use row-wise ternarization for word embedding and layer-wise ternarization for weights in the Transformer layers.

Activation Quantization.

For activations, we experiment on both symmetric and min-max 8-bit quantization with SQuAD v1.1 in Table 5. The weights are ternarized using TWN. As can be seen, the performance of min-max quantization outperforms the symmetric quantization. As discussed in Section 3.1, this may because of the non-symmetric distributions of the hidden representation.

Knowledge Distillation.

In Table 6, we investigate the effect of distillation loss over Transformer layers (abbreviated as “Trm”) and final output logits (abbreviated as “logits”) in the training of TernaryBERTTWN\text{TernaryBERT}_{\text{TWN}}. As can be seen, without distillation over the Transformer layers, the performance drops by 3% or more on CoLA and RTE, and also slightly on MNLI. The accuracy of all tasks further decreases if distillation logits is also not used. In particular, the accuracy for CoLA, RTE and SQuAD v1.1 drops by over 5% by removing the distillation compared to the counterpart.

Initialization and Data Augmentation.

Table 7 demonstrates the effect of initialization from a fine-tuned BERT otherwise a pre-trained BERT, and the use of data augmentation in training TernaryBERT. As can be seen, both factors contribute positively to the performance and the improvements are more obvious on CoLA and RTE.

4 Comparison with Other Methods

In Figure 1 and Table 8, we compare the proposed TernaryBERT with (i) Other Quantization Methods: including mixed-precision Q-BERT Shen et al. (2020), post-training quantization GOBO Zadeh and Moshovos (2020), as well as Quant-Noise which uses product quantization Fan et al. (2020); and (ii) Other Compression Methods: including weight-sharing method ALBERT Lan et al. (2019), pruning method LayerDrop Fan et al. (2019), distillation methods DistilBERT and TinyBERT Sanh et al. (2019); Jiao et al. (2019). The result of DistilBERT is taken from Jiao et al. (2019). The results for the other methods are taken from their original paper. To compare with the other mixed-precision methods which use 3-bit weights, we also extend the proposed method to allow 3 bits (the corresponding model abbreviated as 3-bit BERT, and 3-bit TinyBERT) by replacing LAT with 3-bit Loss-aware Quantization (LAQ) Hou and Kwok (2018). The red markers in Figure 1 are our results with settings 1) 2-2-8 TernaryTinyBERT, 2) 3-3-8 3-bit TinyBERT and 3) 3-3-8 3-bit BERT.

In mixed precision Q-BERT, weights in Transformer layers with steeper curvature are quantized to 3-bit, otherwise 2-bit, while word embedding is quantized to 8-bit. From Table 8, our proposed method achieves better performance than mixed-precision Q-BERT on MNLI, using only 2 bits for both the word embedding and the weights in the Transformer layers. Similar observations are also made on SST-2 and SQuAD v1.1 (Appendix B).

In GOBO, activations are not quantized. From Table 8, even with quantized activations, our proposed TernaryBERT outperforms GOBO with 2-bit weights and is even comparable to GOBO with 3/4 bit mixed-precision weights.

Other Compression Methods.

From Table 8, compared to other popular BERT compression methods other than quantization, the proposed method achieves similar or better performance, while being much smaller.

Conclusion

In this paper, we proposed to use approximation-based and loss-aware ternarization to ternarize the weights in the BERT model, with different granularities for word embedding and weights in the Transformer layers. Distillation is also used to reduce the accuracy drop caused by lower capacity due to quantization. Empirical experiments show that the proposed TernaryBERT outperforms state-of-the-art BERT quantization methods and even performs comparably as the full-precision BERT.

References

APPENDIX

Appendix A Distributions of Hidden Representations on SQuAD v1.1

Figure 4 shows the distribution of hidden representations from the embedding layer and all Transformer layers on SQuAD v1.1. As can be seen, the hidden representations of early layers (e.g. embedding and transformer layers 1-8) are biased towards negative values while those of the rest layers are not.

Appendix B More Comparison between TernaryBERT and Q-BERT

We compare with reported results of Q-BERT on SST-2 and SQuAD v1.1 in Table 9. Similar to the observations for MNLI in Section 4.4, our proposed method achieves better performance than mixed-precision Q-BERT on SST-2 and SQuAD v1.1.

Appendix C Training Curve on MNLI

Figure 5 shows the training loss and validation accuracy of TernaryBERT and 8-bit BERT on MNLI-m. As can be seen, 8-bit BERT has smaller loss and higher accuracy than TernaryBERT. There is no significant difference between the learning curve of TernaryBERT using TWN and LAT.

Appendix D 3-bit BERT and TinyBERT

In Table 10, we extend the proposed method to allow 3 bits by replacing LAT with 3-bit Loss-aware Quantization (LAQ). Compared with TernaryBERTLAT\text{TernaryBERT}_{\text{LAT}}, 3-bit BERT performs lightly better on 7 out of 8 GLUE tasks, and the accuracy gap with the full-precision baseline is also smaller.

Appendix E Attention Pattern of BERT and TernaryBERT

In Figures 7-9, we compare the attention patterns of the fine-tuned full-precision BERT-base model and the ternarized TernaryBERTTWN\text{TernaryBERT}_{\text{TWN}} on CoLA and SST-2. CoLA is a task which predicts the grammatical acceptability of a given sentence, and SST-2 is a task of classifying the polarity of movie reviews. As can be seen, the attention patterns of TernaryBERT resemble those in the full-precision BERT.