Title: BLOCKWISE SELF-ATTENTION FOR LONG DOCUMENT UNDERSTANDING

Abstract: We present BlockBERT, a lightweight and efficient BERT model that is designed to better modeling long-distance dependencies. Our model extends BERT by introducing sparse block structures into the attention matrix to reduce both memory consumption and training time, which also enables attention heads to capture either short-or long-range contextual information. We conduct experiments on several benchmark question answering datasets with various paragraph lengths. Results show that BlockBERT uses 18.7-36.1% less memory and reduces the training time by 12.0-25.1%, while having comparable and sometimes better prediction accuracy, compared to an advanced BERT-based model, RoBERTa.

1. INTRODUCTION:

Recent emergence of the pre-training and fine-tuning paradigm, exemplified by methods like ELMo (Peters et al., 2018) , GPT-2 (Radford et al., 2019) , BERT (Devlin et al., 2019) , XLNet (Yang et al., 2019) and RoBERTa (Liu et al., 2019) , has drastically reshaped the landscape of the natural language processing research. These methods first pre-train a deep model with language model objectives using a large corpus and then fine-tune the model using in-domain supervised data for target applications. Despite its conceptual simplicity, this paradigm has reestablished the new state-ofthe-art baselines across various tasks, such as question answering (Devlin et al., 2019) , coreference resolution (Joshi et al., 2019b) , relation extraction (Soares et al., 2019 ) and text retrieval (Lee et al., 2019; Nogueira & Cho, 2019) , to name a few.

Building such models in practice, however, is an extremely resource-intensive process. For instance, the training of BERT-family models is notoriously expensive. Devlin et al. (2019) report that it takes four days for pre-training BERT-Base/BERT-Large on 4/16 Cloud TPUs, respectively. In order to reduce the pre-training time of RoBERTa to 1 day, Liu et al. (2019) use 1,024 V100 GPUs. One crucial factor that contributes to the long training time is the memory consumption of these deep models, as it directly affects the batch size. Although the fine-tuning stage is relatively inexpensive, the memory issue still restricts the scenarios in which BERT can be used. For instance, "it is currently not possible to re-produce most of the BERT-Large results on the paper using a GPU with 12GB-16GB of RAM, because the maximum batch size that can fit in memory is too small.1 " Although one may think that model size is the main contributor to the large memory consumption, our analysis (Section 2.1) shows that one of the main bottlenecks is actually dot-product selfattention, operated in multiple layers of Transformers (Vaswani et al., 2017) , the building block of BERT. As the attention operation is quadratic to the sequence length, this fundamentally limits the maximum length of the input sequence, and thus restricts the model capacity in terms of capturing long-distance dependencies. As a result, downstream tasks have to either truncate their sequences to leading tokens (Nogueira & Cho, 2019) or split their sequences with a sliding window (Joshi et al., 2019a; b) . Ad-hoc handling of long sequences is also required in the pre-training stage, such as updating the model using only short sequences in the early stage (Devlin et al., 2019) .

Common strategies for reducing memory consumption, unfortunately, do not work. For instance, shrinking the model by lowering the number of layers L, attention heads A, or hidden units H leads to significant performance degradation (Vaswani et al., 2017; Devlin et al., 2019) and does not address the long sequence issue. Alternatively, general low-memory training techniques, such as microbatching (Huang et al., 2018) and gradient checkpointing (Chen et al., 2016) essentially trade off training time for memory consumption, prolongs the already lengthy training process.

In this work, we explore a different strategy, sparsifying the attention layers, intending to design a lightweight and effective BERT that can model long sequences in a memory-efficient way. Our BlockBERT extends BERT by introducing sparse block substructures into the attention matrix to reduce both memory consumption and the number of floating point operations (FLOPs), which also enables attention heads to capture either short-or long-range contextual information. Compared to the previous method that also enforces sparsity (e.g., Child et al. (2019) ), our approach is much simpler mathematically and very easy to implement. More importantly, the results of experiments conducted on several benchmark question answering datasets with various paragraph lengths show that BlockBERT performs comparably or even better than the original BERT-family models, while enjoying an 18.7-36.1% reduction in memory usage and 12.0-25.1% reduction in training time.

The rest of the paper is organized as follows. Section 2 gives a brief introduction of the BERT model, along with an in-depth analysis of its memory usage during training time. We describe our proposed model in Section 3 and contrast it with existing methods that aim for creating a lighter model. Section 4 presents the experimental results and ablation studies, followed by a short survey of other related work in Section 5 and the conclusion in Section 6.

2. BACKGROUND: MEMORY BOTTLENECK IN TRAINING BERT:

We briefly review BERT and introduce its memory profiling in this section. Following the paradigm of language model pre-training and down-stream task fine-tuning, BERT (Devlin et al., 2019) consists of multiple layers of bidirectional Transformers (Vaswani et al., 2017) , where each Transformer encoder has a multi-head self-attention layer and a position-wise feed-forward layer. Using the same notation as in (Devlin et al., 2019) , we denote the number of Transformer layers by L, the number of hidden units by H, the number of attention heads by A, the sequence length by N and the batch size by B. We also assume the feed-forward hidden unit size to be 4H.2 

2.1. MEMORY PROFILING:

Training BERT is a memory-intensive process. In order to identify the bottleneck, we follow the memory model proposed by Sohoni et al. (2019) , where the memory usage throughout neural network training is categorized into three main types: (1) Model Memory is used to store model parameters; (2) Optimizer Memory is the additional memory used by the specific learning algorithm during the process; (3) Activation Memory consists of the outputs of each layer, which are cached for reuse in backpropagation to compute gradients.

Take BERT-Base training as an example. The model has 110M parameters, so the model memory uses 0.2 GB if stored in half-precision floating-point format (FP16). For Adam (Kingma & Ba, 2014) , the optimizer needs additional memory to store the gradients, first moments, and second moments of model parameters. If stored using the same precision, the optimizer memory should be three times of model memory. 3 To calculate the exact size of activation memory is not trivial because it depends heavily on the implementation of the toolkit. Instead, we measure it empirically by training BERT-Base using Adam with a memory profiler (more details are provided in Appendix A.2).

We use 32 NVIDIA V100 GPUs for training. Each single GPU thus consumes a mini-batch of size b = B/32 = 8. Figure 1a shows the profiling result for a single GPU, where the model/optimizer/activation memory consumes 0.21/1.03/8.49 GB, resp. We can see that activation memory accounts for the vast majority of the total GPU memory (87.6%) and is clearly the bottleneck. Notice that although our analysis is done on BERT-Base, it can be easily generalized to BERT-Large and other models such as RoBERTa (Liu et al., 2019) and XLNet (Yang et al., 2019) . 

2.3. GENERAL TECHNIQUES FOR REDUCING MEMORY USAGE IN MODEL TRAINING:

Observing that activation memory is the bottleneck, we discuss the effectiveness of common memory reduction techniques for BERT training below.

Low Precision (Micikevicius et al., 2017) : Low precision is to use half-precision or mixed-precision for training neural networks. This technique has been widely used in Transformer training (Ott et al., 2019; Liu et al., 2019) . In this work, we already assume to use mixed-precision training by default, as indicated in the aforementioned analysis.

Microbatching (Huang et al., 2018) : Microbatching is to split a batch into small microbatches (which can be fit into memory), and then run forward and backward passes on them separately with gradients for each micro-batch accumulated. Because it runs forward/backward pass multiple times for a single batch, it trades off time for memory.

Gradient Checkpointing (Chen et al., 2016): Gradient checkpointing saves memory by only caching activations of a subset of layers. The un-cached activations will be recomputed during backpropagation from the latest checkpoint. This strategy trades off time for memory by repeating computations that require large memory and will obviously extend the model training time.

Knowledge Distillation (Hinton et al., 2015) : Knowledge distillation aims to compress and transfer knowledge from a teacher model to a simpler student model. However, knowledge distillation relies on a teacher model (which is still expensive in training time) and usually suffers from a certain degree of performance degradation.

As common techniques are limited in reducing both the training time and memory usage, we investigate how to optimize the dot-product attention layers and introduce our approach next.

3 MODEL: BLOCKBERT Following (Vaswani et al., 2017) , the dot-product attention in Transformer is defined as:

Attention(Q, K, V ) = softmax QK √ d V .

where Q, K, V ∈ R N ×d with N to be the sequence length and d to be a hidden dimension. As we can see, the inner product between Q and K consumes O(N 2 ) memory. One simple way to reduce memory consumption of attention is to sparsify the attention matrix. Suppose we have a masking matrix M ∈ {0, 1} N ×N . We define a masked version of attention as follows:

EQUATION

with operator defined by

(A M )ij = Aij if Mij = 1 -∞ if Mij = 0 .

In this work, we design M to be a sparse block matrix, which not only reduces memory and the number of floating point operations (FLOPs) but also benefits from efficient dense matrix support from deep learning frameworks, such as PyTorch and Tensorflow. More formally, we split the length-N input sequence into n partitions, with each partition of length N n . 4 The N × N attention matrix is then partitioned into n × n blocks, where each block matrix is of size N n × N n . A sparse block matrix M can be defined by a permutation π of {1, 2, • • • , n}:

EQUATION

By writing Q, K, V as be block matrices, such that

Q = [Q 1 • • • Q n ] , K = [K 1 • • • K n ] and V = [V 1 • • • V n ]

and pluging them into Equation 1, we can formally define Blockwise Attention as follows:

Blockwise-Attention(Q, K, V , M ) =        softmax Q 1 K π(1) √ d V π(1)

. . .

EQUATION

)

As a result, it only needs to compute and store

Q i K π(i) (i = 1, • • • n), each of which has size N n × N n .

In other words, BlockBERT reduces the corresponding O(N 2 ) memory consumption and FLOPs by a factor of n, since N n × N n × n = N ×N n .

3.1. BLOCKWISE MULTI-HEAD ATTENTION:

Analogous to Multi-head Attention (Vaswani et al., 2017) , we allow queries, keys, and values to be projected multiple times and perform blockwise attentions in parallel. Moreover, different blockwise attention heads can use different masking matrices. The outputs of multiple heads are then concatenated and aggregated with another linear projection. Let A be the number of attention heads and H the number of hidden units. Blockwise multi-head attention is formally defined by:

Blockwise-Multi-head-Attention(Q, K, V ) = Concat(head1, • • • headA)W O where headi = Blockwise-Attention(QW Q i , KW K i , V W V i , Mi), with d = H A , W Q i , W K i , W V i ∈ R

H×d and the projection matrix W O ∈ R H×H . Each masking matrix M i is determined by permutation π i according to Equation 2. In particular, we choose π from permutations generated by shifting one position: σ = (2, 3, • • • , n, 1), i.e., we select π ∈ {σ, σ 2 , • • • , σ n }. For example, with 12 attention heads (A = 12) and 2 blocks (n = 2), one configuration can be assigning 10 heads to permutation (1, 2) and the other 2 heads to permutation (2, 1). Figure 2 illustrates the blockwise multi-head attention with the block numbers n ∈ {2, 3}.

Blockwise sparsity captures both local and long-distance dependencies in a memory-efficiency way, which is crucial for long-document understanding tasks. For instance, the identity permutation, i.e., (1, 2, • • • , n), enables each token to attend its nearby tokens in self-attention. Tokens within the same local group attend a long-distance group of tokens together in other permutations. Our proposed BlockBERT essentially replaces the multi-head attention layers in Transformer/BERT with blockwise multi-head attention.

3.2. ANALYSIS OF MEMORY USAGE REDUCTION:

To validate our claim that BlockBERT with n×n blocks can reduce the O(N 2 ) memory use by a factor of n, we perform the same memory profiling as described in sections 2.1 and 2.2. Again, We fix the number of tokens in each GPU (b×N = 4096) and choose N from {128, 256, 512, 1024, 2048}. 5As we can see from Figure 3 and Table 1 , the empirical results align well with the theoretical values.

When we set block size to be 2 and 3 for BlockBERT, their estimated O(N 2 ) activation memory decreases to 1/2 and 1/3 of BERT's O(N 2 ) activation memory, resp. As shown in Table 2 , for the sequence length N = 512, BlockBERT with 2 / 3 blocks saves 18.7% / 23.8% overall memory, resp. The saving is more significant for longer sequences. When N = 1024, the overall memory reduction of BlockBERT with 2 / 3 blocks is 27.3% / 36.1%, resp.

4. EXPERIMENTS:

We evaluate the pre-training and fine-tuning performance of BlockBERT. In particular, when n = 2, we denote 10:2 to be the configuration which distributes 10 heads to permutation (1, 2) and 2 to permutation (2, 1); when n = 3, we denote 8:2:2 to be the configuration which assigns 8, 2, 2 heads to permutation (1, 2, 3), (2, 3, 1), and (3, 1, 2), resp. We compare BlockBERT with the following baselines:

Google BERT The pre-trained base model from Devlin et al. (2019) .

RoBERTa-2seq and RoBERTa-1seq We compare with two versions of RoBERTa (Liu et al., 2019) . RoBERTa-2seq is trained with both masked language model (MLM) task and next sentence prediction (NSP) task, while RoBERTa-1seq refers to the pre-training model with only MLM task.

SparseBERT We pre-train BERT models with its Transformer encoder replaced by a Sparse Transformer encoder (Child et al., 2019) . We set its sparsity hyper-parameters stride = 128 and expressivity c = 32. The attention masks used for Sparse Transformer encoder are illustrated in Figure 5 . 2 .

Besides memory saving, we also achieve a significant speedup. For example, when N = 1024, BlockBERT (n = 2) reduces the training time from RoBERTa's 9.7 days to 7.5 days.

4.2. FINE-TUNING TASKS:

We evaluate BlockBERT on several question answering tasks, including SQuAD 1.1/2.0 (Rajpurkar et al., 2018) and five other tasks from the MrQA shared task6 -HotpotQA (Yang et al., 2018) , NewsQA (Trischler et al., 2017) , SearchQA (Dunn et al., 2017) , TriviaQA (Joshi et al., 2017) and NaturalQA (Kwiatkowski et al., 2019) These QA datasets have different paragraph length distribution patterns and are thus ideal for testing the effectiveness of BlockBERT. For example, SQuAD, NaturalQA, and HotpotQA consist of mostly short paragraphs (shorter than 512), while paragraphs in SearchQA (average length 1,004) and TriviaQA (average length 934) have around 1,000 tokens. This means that for SearchQA and TriviaQA, a BERT model with sequence length N = 512 can only capture half of the context. The detailed paragraph length distributions can be found in Figure 6 .

For all the pre-trained models, we adopt the same fine-tuning QA setup from Devlin et al. (2019) .

The tokenized paragraph (p 1 , • • • , p s ) and question (q 1 , • • • , q t ) are concatenated to be a sequence

[CLS]q 1 • • • q t [SEP]p 1 • • • p s [SEP].

The sequence is then fed into the pre-trained model with two extra linear layers for predicting the start and end positions of the answer spans. The detailed fine-tuning setting is listed in Appendix A.4 . Table 3 and Table 4 report the experimental results.

4.3. ABLATION STUDY:

We fix the assignment of attention heads in above experiments. For example, BlockBERT with sequence length N = 512 and 2 blocks is trained with ten heads using permutation (1, 2) and the other two using permutation (2, 1). However, we know that there are other ways to partition twelve attention heads, e.g., seven heads for permutation (1, 2) and the other five for permutation (2, 1). It would be interesting to see how the assignment of heads affects model performance. In this section, we grid search attention head assignments and plot their best validation performance in 1.2M training steps. The results are shown in Figure 4 .

Our observations are threefold: (1) Identity permutations, i.e., (1, 2) and (1, 2, 3), are important. As shown in Figure 4 , all optimal solutions assign considerable attention heads to block diagonal matrices, since those matrices enable each token to attend to its nearby tokens;

(2) Non-identity permutations follow the rule of "vital few and trivial many." Although identity permutations are important, assigning all attention heads to them (corresponding to 12:0 and 12:0:0 in Figure 4 ) significantly hurts performance, since the model can not learn long-term dependencies with only identity permutation;

(3) Pre-training performance and fine-tuning performance are correlated but not always consistent. When n = 3, pre-training performance suggests 10:1:1 to be the best head assignment -ten heads for permutation (1, 2, 3), one head for (2, 3, 1) and one head for (3, 1, 2), but we observe that the configuration of 8:2:2 achieves better performance in fine-tuning tasks. 

5. RELATED WORK:

In this section, we review the related work of memory optimization for neural network training and recent efforts to simplify Transformer and BERT. In recent years, there is an increasing interest in training neural networks with low-memory (Sohoni et al., 2019) . Mainstream techniques include low-precision training (Micikevicius et al., 2017) , microbatching (Huang et al., 2018) , gradient checkpointing (Chen et al., 2016) . Another line of researches studies this problem from a theoretical perspective, including the recently proposed lottery ticket hypothesis (Frankle & Carbin, 2018) . Since the invention of Transformer (Vaswani et al., 2017; Dai et al., 2019) and its successful application on language model pre-training (Devlin et al., 2019; Radford et al., 2019; Yang et al., 2019; Liu et al., 2019) , there have been several studies attempted to simplify it from different perspectives. The first line of research focuses on attention matrix sparsification, such as Star Transformer (Guo et al., 2019) , Sparse Transformer (Child et al., 2019 ), Adaptive Sparse Transformer (Correia et al., 2019; Sukhbaatar et al., 2019) , Log-Sparse Transformer (Li et al., 2019) , etc. However, due to limited support for sparse tensor from current deep learning platforms, most of studies have to represent a sparse matrix using a dense matrix with a binary mask or rely on customized CUDA kernels (Gray et al., 2017) . The second line of research attempts to prune redundant heads in Transformer, such as Voita et al. (2019) and Michel et al. (2019) . The third line of research focuses on knowledge distillation, including DistilBERT7 which distills BERT using a smaller BERT and Tang et al. (2019) which distills BERT with BiLSTM (Hochreiter & Schmidhuber, 1997) .

6. CONCLUSION:

In this work, we study lightweight BERT model with the goal of achieving both efficiency and effectiveness. We profile and analyze the memory bottlenecks of BERT, and focus on optimize dotproduct self-attention, which consumes quadratic memory with respect to the sequence length. To reduce both training time and memory consumption, we present BlockBERT, which sparsifies the attention matrices to be sparse block matrices. The proposed model achieves time and memory saving without significant loss of performance. In the future, we would like to explore more applications of BlockBERT on NLP tasks involving long sequences such as coreference resolution (Joshi et al., 2019b ) and document-level machine translation (Miculicich et al., 2018) , and also non-NLP tasks such as protein sequence modeling (Rives et al., 2019) . 

B

:

https://github.com/google-research/bert

The default parameter settings for BERT-Base and BERT-Large can be found in Table5inAppendix A.1.

In the current PyTorch Adam implementation, the first and second moments are stored in single precision. Consequently, BERT's optimizer memory (1 GB) is five times of model memory (0.2 GB).

We assume N can be divided by n. If not, we pad the input sequence to make N divisible.

We use GPUs of 16 GB memory for profiling. BERT with N = 2048 fails due to an out-of-memory error.

https://mrqa.github.io

https://github.com/huggingface/pytorch-transformers/tree/master/examples/distillation

https://github.com/pytorch/fairseq/blob/master/fairseq/modules/sparse multihead attention.py.

https://github.com/huggingface/pytorch-transformers

https://github.com/huggingface/transformers/blob/master/examples/benchmarks.py

Figures and Tables:

PRE-TRAINING All the models follow the base setting, i.e., L = 12, H = 768, A = 12 and are trained on the same corpus -BooksCorpus and English Wikipedia with uncased word piece tokens. We fix the number of tokens per batch B × N = 131, 072, i.e., if sequence length N = 512 then batch size B = 256, if sequence length N = 1024 then batch size B = 128. The detailed pre-training configuration is listed in Table 6 in Appendix A.1. Moreover, the pre-training of SparseBERT and BlockBERT follows the RoBERTa-1seq setting, i.e., we drop the NSP (Next Sentence Prediction) task, and an input sequence is up to N tokens until it reaches a document boundary. A summary of the pretraining performance comparison between BlockBERT and RoBERTa-1seq is shown in Table

Figure 4: Ablation over blockwise attention heads assignment.

Pre-training Performance Analysis.

Table content: <table><tr><td>N</td><td>Model</td><td colspan="4">Training Time (day) Memory (per GPU, GB) Heads Config. Valid. ppl</td></tr><tr><td/><td>RoBERTa-1seq</td><td>6.62</td><td>9.73</td><td>-</td><td>3.58</td></tr><tr><td>512</td><td colspan="2">BlockBERT n=2 5.83 (-12.0%)</td><td>7.91 (-18.7%)</td><td>10:2</td><td>3.56</td></tr><tr><td/><td colspan="2">BlockBERT n=3 5.80 (-12.5%)</td><td>7.32 (-23.8%)</td><td>8:2:2</td><td>3.71</td></tr><tr><td/><td>RoBERTa-1seq</td><td>9.66</td><td>13.39</td><td>-</td><td>3.60</td></tr><tr><td>1024</td><td colspan="2">BlockBERT n=2 7.51 (-22.3%)</td><td>9.73 (-27.3%)</td><td>9:3</td><td>3.57</td></tr><tr><td/><td colspan="2">BlockBERT n=3 7.23 (-25.1%)</td><td>8.55 (-36.1%)</td><td>8:2:2</td><td>3.63</td></tr></table>

. Since MrQA does not have an official test set, we follow Joshi et al. (2019a) who split the development set evenly to build a new development set and test set.

Table content: <table/>

Test time statistics (sec) for different input size (Batch size × Sequence length). OOM indicates out-of-memory.

Table content: <table><tr><td>× N</td><td colspan="4">8×1024 16×1024 24×1024 32×1024</td></tr><tr><td>RoBERTa</td><td>0.1371</td><td>OOM</td><td>OOM</td><td>OOM</td></tr><tr><td colspan="2">BlockBERT n=2 0.0990</td><td>0.1869</td><td>OOM</td><td>OOM</td></tr><tr><td colspan="2">BlockBERT n=3 0.0954</td><td>0.1790</td><td>0.2634</td><td>OOM</td></tr></table>

Peer review (iclr2020):
The authors propose BlockBERT, a model that makes the attention matrix of Transformer models sparse by introducing block structure. This has the dual benefit of reducing memory and reducing training time. The authors show on various question answering tasks that their model is competitive with RoBERTa. 1. Can the authors add additional details about the training of their model in Section 4.1? It is not clear for example the vocabulary size - is that the RoBERTa vocabulary size of around 50k or the BERT vocabulary size that is smaller? I believe this will affect the memory and training speed. 2. For the datasets such as TriviaQA and SearchQA, how is RoBERTa finetuned on these tasks? By doing the window approach? 3. The authors compare to RoBERTa and Sparse BERT as baselines for the section on performance. However, can the authors also include metrics on training time and memory in Table 2 for Sparse BERT as well as other sparse attention transformer architectures proposed (for example the Correia paper or the Sukhbaatar paper)? It is not clear the savings from this architecture compared to sparse Transformers in general. 4. The analysis in Section 4.3 is quite unclear due to how compressed the description is and how tiny the graphs are. 5. The authors mention that attention heads can be sparsified due to the memory usage and quadratic time complexity. Other work has also shown that the attention heads are quite redundant and can be pruned away, so attention head dropout is effective. For example https://arxiv.org/abs/1905.09418