Symmetric Dot-Product Attention for Efficient Training of BERT Language Models (2024)

Abstract: Initially introduced as a machine translation model, the Transformer architecture has now become the foundation for modern deep learning architecture, with applications in a wide range of fields, from computer vision to natural language processing. Nowadays, to tackle increasingly more complex tasks, Transformerbased models are stretched to enormous sizes, requiring increasingly larger training datasets, and unsustainable amount of compute resources. The ubiquitous nature of the Transformer and its core component, the attention mechanism, are thus prime targets for efficiency research. In this work, we propose an alternative compatibility function for the selfattention mechanism introduced by the Transformer architecture. This compatibility function exploits an overlap in the learned representation of the traditional scaled dot-product attention, leading to a symmetric with pairwise coefficient dot-product attention. When applied to the pre-training of BERT-like models, this new symmetric attention mechanism reaches a score of 79.36 on the GLUE benchmark against 78.74 for the traditional implementation, leads to a reduction of 6% in the number of trainable parameters, and reduces the number of training steps required before convergence by half.

heading: 1 Introduction
text: Since its introduction in 2017, the Transformer architecture powered by its scaled dot-product attention mechanism (Vaswani et al., 2017) has become the core component of modern deep-learning architectures and has enabled researchers to achieve breakthroughs in both natural language processing (NLP) and computer vision tasks such as language modelling (Brown et al., 2020), machine translation (Raffel et al., 2019), speech processing (Radford et al., 2022), and image recognition (Dosovitskiy et al., 2020). One of the many successes of the Transformer lies in its ability to operate and
learn in an unsupervised setting from unstructured textual data, as well as its ability to handle complex and varied structures such as graphs, images, and sentences by increasing the model’s number of layers. However, this trend has led to the emergence of machine learning models so enormous that the gap between the amount of compute resources available to many research groups and the amount needed to stay competitive is increasing year after year (Togelius and Yannakakis, 2023), and by training larger and larger models, brought deep-learning’s energy consumption to unsustainable amounts (Thompson et al., 2021).
Efficient Transformer implementations are a popular area of research with many recent contributions on encoding and dense representation of tokens (Su et al., 2021), hardware-optimized implementation of attention (Dao et al., 2022), or implementations for long document processing (Beltagy et al., 2020). While the attention mechanism itself has been studied extensively (Niu et al., 2021), and several improvements to its computational complexity have been achieved (Kitaev et al., 2020; Zhou et al., 2020), it is still primarily computed via the dot-product between a query and a key (see Figure 1). Vaswani et al. (2017) highlight the difficulty of determining a proper compatibility function, and suggest that a more sophisticated compatibility function than dot product may be beneficial.
In this work, we propose alternative compatibility functions for the attention mechanism, i. e., the scaled dot-product attention mechanism. With this approach, we aim to improve the training efficiency of Transformer-based models and to reduce their resource consumption. We especially focus on the self-attention mechanism of BERT (Devlin et al., 2018), a Transformer-based encoder model.
Our contributions can be summarized as follows:
• We introduce an alternative formula to replace the scaled dot-product attention (Section 2)
8002
that takes advantage of the underlying symmetric structure of attention, in order to reduce the number of parameters and improve the computational efficiency of the model.
• We benchmark our approach by training several BERT models on three attention mechanism setups as well as two different model sizes (Section 3).
We demonstrate that our new attention formula reduces the number of parameters of the model by 6%, and achieves a reduction of the number of training steps required for model convergence by 50% without sacrificing accuracy (Section 4). Finally, we discuss the effects of our proposed compatibility function on training efficiency, and situate our approach within the context of research on efficient Transformer-based models (Section 5).

heading: 2 Improving the Attention Mechanism
text: Modern Transformer-based models are neural networks that rely on the scaled dot-product attention mechanism introduced by Vaswani et al. (2017). We propose two variations of this mechanism: a symmetric dot-product and a symmetric with pairwise factors dot-product, that lead to a reduction in the number of parameters of the self-attention layer.

heading: 2.1 Scaled Dot-Product Attention
text: The scaled dot-product attention given by the following equation (Equation 1) is an operator on three input matrices, queries Q, keys K and values V . We focus on the dot product QKT between queries Q and keys K, which is responsible for measuring the compatibility between tokens. The
compatibility A is an operator on two input tokens (x, y ∈ Rh), that computes the dot-product of the projections of x and y respectively through the operators Q and K:
Attn(Q,K, V ) = softmax ( QKT√
d
) V (1)
Given two linear operators Q : Rh → Rd and K : Rh → Rd, we define a compatibility operator A : Rh × Rh → R, such that:
A(x, y) = Q(x) ·K(y)T (2)
We challenge the necessity of using two different operators to compute the affinity of the selfattention encoder layer of the Transformer block. Since both Q and K are operators on the same token space, it is reasonable to assume that the representations they learn share some features. In that case, since the original expression (Equation 1) does not enforce any feature sharing, it may possess redundant parameters that will need to be learned twice.
We attempt to make this feature sharing property explicit in the compatibility operator expression, in order to remove redundant parameters, reduce overall model size, and improve convergence rate.

heading: 2.2 Symmetric Dot-Product attention
text: A simple way to make the feature sharing property explicit, is to enforce the following relation Q = K between the two operators. This ensures that Q and K share features and results in the symmetric compatibility operator:
Asym(x, y) = Q(x) ·Q(y)T (3)

heading: 2.3 Pairwise Dot-Product Attention
text: One aspect that needs to be considered is the amount of features shared between the two operators. Complete overlap in terms of features may be detrimental to the overall performance of the attention mechanism, e. g., it could prevent the model to learn asymmetric relationships. Thus, we suggest the following compatibility operator where the amount of feature sharing is learned during training. To achieve this, we start with an operator L that will be shared, and we define operators Q and K as a composition of L with a base change, resulting in the following compatibility operator (Equation 5):
Given a linear operator L : Rh → Rd and two square matrices Wq,Wk ∈ Rd×d, we define two linear operators Q : Rh → Rd and K : Rh → Rd, such that:
Q(x) = L(x) ·Wq K(x) = L(x) ·Wk
(4)
Let S ∈ Rd×d be the product S = Wq ·W Tk , we define a compatibility operator A : Rh ×Rh → R, such that:
A(x, y) = Q(x) ·K(y)T
A(x, y) = L(x) ·Wq ·W Tk · L(y)T A(x, y) = L(x) · S · L(y)T (5)
This operator can be interpreted as a weighted dotproduct whose weights are stored in S, a matrix of pairwise factors. To make the expression consistent with the previously established expressions (Equation 2 and Equation 3), we relabel the L operator with the letter Q, resulting in the following pairwise compatibility operator (Equation 6):
Apair(x, y) = Q(x) · S ·Q(y)T (6)

heading: 2.4 Parameter Count
text: For a Transformer block of n heads, with input size h and attention size d, we give the parameter count formula for a complete block (with parameters from Q, K and V ). We note that most Transformer implementations impose d = h/n.
As shown in Table 1, the symmetric compatibility operator uses two thirds of the original number of parameters. For the pairwise compatibility operator, the parameter count also depends on the number of attention heads, it converges towards 2/3 of the original number of parameters as the number of attention heads increases.
In this section, we introduced two alternative compatibility functions for the attention mechanism, a symmetric dot-product operator and a symmetric with pairwise factors dot-product operator.
In the following sections we will refer to them respectively as the symmetric operator and the pairwise operator, we will refer to the traditional scaled dot-product operator as the original operator.

heading: 3 Experiments
text: To evaluate the symmetric and pairwise operators against the original operator, we train and evaluate several Transformer-based encoder models, each using a different compatibility operator as part of the self-attention mechanism. The models are trained under the same conditions. First, we pre-train the models, because we want to measure the evaluation loss during training to see if our modifications have an impact on the training efficiency and the accuracy of the model. Then, we evaluate each model on the GLUE benchmark (Wang et al., 2019b) to evaluate the model’s accuracy on relevant downstream tasks, such as, sentence acceptability (Warstadt et al., 2018), sentiment analysis (Socher et al., 2013), sentence similarity (Cer et al., 2017), and natural language inference (Williams et al., 2018; Rajpurkar et al., 2016). Finally, we select model checkpoints during training and evaluate those checkpoints on GLUE to measure the models’ accuracy on downstream tasks during training.

heading: 3.1 Pre-Training Dataset
text: To pre-train our models, we select a subset of 30 million English documents from the OSCAR corpus (Abadji et al., 2022; Jansen et al., 2022) by applying content quality filters (see Appendix A). Using OSCAR data instead of the BookCorpus (Zhu et al., 2015) and Wikipedia dumps is recommended for training BERT models (Geiping and Goldstein, 2023) and ensures that the amount of
documents is large enough for single epoch training.
This training dataset is tokenized using the pretrained bert-base-uncased tokenizer (Devlin et al., 2018) and sentences are aggregated into groups of 512 tokens. After tokenization, the resulting dataset contains 137 million training samples, 70 billion tokens and 10,000 test samples.

heading: 3.2 Model Architectures
text: We prepare three variations of the BERT model (Devlin et al., 2018) using the original, the symmetric and the pairwise operators. We also train on two model sizes, bert-small and bert-base.
As shown in Table 2, the symmetric and pairwise operators lead to significant reduction in the number of parameters, 3.65% and 3.19% for the bert-small model, 6.47% and 5.93% for the bertbase model.
In the following sections, we refer to a bert-base model as BERTbase when it uses the original operator, BERTbase,sym or BERTbase,pair when it uses the symmetric or pairwise operator respectively.

heading: 3.3 Pre-Training Setup
text: We follow the pre-training setup described by Devlin et al. (2018). The models are trained on a pure masked language modeling task with masking probability of 0.15 and batch size of 256 samples per training steps. Models are trained on 200,000 steps with a linear learning rate of 10−4 and learning rate warm-up during the first 10,000 steps. For the optimizer, we use Adam (Kingma and Ba, 2014) with weight decay, β1 = 0.9, β2 = 0.999, ϵ = 10−12, resulting in models pre-trained on 26 billion tokens. We measure evaluation cross-entropy loss during training to assess the training efficiency of our models.

heading: 3.4 Benchmark Fine-Tuning Setup
text: After pre-training, the models are fine-tuned and benchmarked on the GLUE dataset (Wang et al., 2019b) to assess their natural language understanding (NLU) capabilities. Each model is fine-tuned on the provided downstream task training dataset for 5 epochs, with a batch size of 16 and a linear learning rate of 1 · 10−5. This benchmarking step is repeated on 5 downstream trials with different seeds. We measure individual task’s scores, benchmark average and standard deviation across all trials. For each model, we measure: the combined
F1 and accuracy on the Microsoft Research Paraphrase Corpus mrcp (Dolan and Brockett, 2005), Matthews correlation on the Corpus of Linguistic Acceptability cola (Warstadt et al., 2018), matched and mis-matched accuracy on the Multi-Genre Natural Language Inference Corpus mnli (Williams et al., 2018), accuracy on the Quora Question Pairs dataset qqp1, accuracy on the Recognizing Textual Entailment dataset rte (Dagan et al., 2006; Haim et al., 2006; Giampiccolo et al., 2007; Bentivogli et al., 2009), the combined Pearson and Spearman correlation on the Semantic Textual Similarity Benchmark stsb (Cer et al., 2017), accuracy on the Stanford Question Answering Dataset qnli (Rajpurkar et al., 2016), and accuracy on the Stanford Sentiment Treebank sst2 (Socher et al., 2013). The Winograd schema challenge wnli task has been excluded from the evaluation following the recommendation of Devlin et al. (2018).
Compared to the original BERT setup or more recent compute optimized fine-tuning setups (Geiping and Goldstein, 2023), we choose to fine-tune for a longer time (5 epochs instead of 3) and with a lower learning rate (1 · 10−5 instead of 4 · 10−5), to have a more stable fine-tuning experience and reduce the risk of lucky seeding. With this choice, we aim to have a fairer evaluation of the models.

heading: 3.5 Checkpoint Benchmarking
text: We want to evaluate how downstream accuracy evolves during pre-training. We extract checkpoints during training and evaluate them on the GLUE benchmark. Each checkpoint is fine-tuned and evaluated on GLUE using the previously established fine-tuning setup.

heading: 4 Results
text: In this section, we present the results of our experiments, the pre-training of our three variants (Figure 2), the scores they reach on the GLUE benchmark (Table 3) once fully trained and the evolution of the GLUE score during training (Figure 3).

heading: 4.1 Pre-Training Experiment
text: Figure 2b shows that the symmetric and pairwise variant converge much faster than the original variant for the BERTbase model. The evaluation loss of the original variant remains on the initial plateau until step 25,000, when it sharply decreases. The
1https://data.quora.com/ First-Quora-Dataset-Release-Question-Pairs
symmetric variant remains on the initial plateau until step 13,500 and the pairwise variant until step 12,000. We also note that the original and pairwise variants will eventually reach the same evaluation loss plateau, while the symmetric variant remains above the two other variants with an additional absolute error of 0.1.
Comparing Figures 2a and 2b, we observe the impact of model size on training efficiency. When the model size increases, the original variant’s initial plateau is expanded from step 12,000 to step 25,000, while the symmetric and pairwise variant were almost unaffected.

heading: 4.2 GLUE Benchmark Fine-Tuning
text: Table 3 shows that the pairwise variant performs better than the original variant with an increase of 0.6 points on the average GLUE score for both model sizes. The symmetric variant, however, is outperformed by the original variant in both cases, with a drop of 4 points on the average GLUE score. We also observe that both proposed variants have a lower standard deviation on the bert-base model.

heading: 4.3 GLUE Benchmarking Along Training Steps
text: Figure 3 shows that the improved training efficiency observed during pre-training translates to a faster convergence rate on the GLUE benchmark as well. The pairwise and original variants both reach a final average GLUE score of approximately 79. The pairwise variant achieves 95% (a score of 75) of its final value after 30,000 steps, the original variant reaches the same score after 65,000 steps.
0K 25K 50K 75K 100K 125K 150K 175K 200K
60
65
70
75
80
BERTbase, pair BERTbase, sym BERTbase
Steps
GL UE
a ve
ra ge
sc or
e
Figure 3: Average GLUE score over training steps. Checkpoints are sampled during training and evaluated on the GLUE benchmark. The red dashed line correspond to 95% of the final GLUE average score.
We also observe a smoother evolution of the accuracy for the pairwise variant compared to the original variant. The experiment also highlights the performance drop of the symmetric variant when compared to the original variant.

heading: 5 Discussion

heading: 5.1 Pre-training Efficiency
text: During the pre-training experiment, we observed that both variants BERTbase,sym and BERTbase,pair outperformed the original variant BERTbase in terms of convergence rate (they initiated the learning and reached their respective plateau faster), for a bert-base model the convergence rate seems to be two times faster.
However, BERTbase and BERTbase,pair ultimately met around the same evaluation loss, while BERTbase,sym performed a little worse.
One obvious explanation for the improved convergence rate can be found in the reuse of the Q operator, this can impact convergence rate in three way:
• The accumulation of two loss gradients per forward/backward pass instead of a single one, resulting in an effect similar (but not exactly equivalent) to doubling the learning rate for the parameters of the Q operator.
• The reduction in the number of parameters.
• Sharing representation for both Q and K operators. If they do learn a subset of the same features, then enforcing a shared representation for both of them will reduce the amount of learning required.
These effects explain why both BERTbase,sym and BERTbase,pair converge much faster than BERTbase.
While converging faster than BERTbase, BERTbase,sym did not reach the same evaluation loss. It is fair to assume that this is a modelling issue and not a size issue since BERTbase,pair outperformed BERTbase,sym with a similar number of parameters. Thus, we can conclude that symmetry is not a desired property of the compatibility function of the attention mechanism.

heading: 5.2 GLUE Benchmark
text: The evaluation of the three variants on the GLUE benchmark shows that BERTbase,pair is more accurate than BERTbase, reaching an average score of 79.39 against 78.74 respectively. The evaluation also shows that the standard deviation of the average score across five trials is lower for both
BERTbase,pair and BERTbase,sym, with a standard deviation of 0.37 and 0.36 against 0.63 for BERTbase.
This confirms that the training efficiency improvement observed on the pre-training task translates to the fine-tuning task and leads to improvement on the downstream task’s accuracy. With the added benefit of making the fine-tuning task more stable, as shown by the lower standard deviation.
We also note that the fairly small 0.1 difference in evaluation loss during training for BERTbase,sym has translated to a 4 points accuracy drop on the evaluation benchmark, echoing our remark on the need to model asymmetric relationships.
With these results, we experimentally prove that our pairwise operator improves the training efficiency of Transformer-based models, leading to a faster convergence rate and overall lower training loss. These improvements also translate to downstream task benchmarks. Models using the pairwise compatibility operator are indeed more accurate than the ones using the original compatibility operator.

heading: 5.3 GLUE Evaluation During Pre-Training
text: Running the benchmark evaluation on our three models at several steps of the pre-training experiment shows that the training efficiency we observed translates well into downstream accuracy. Our BERTbase,sym and BERTbase,pair converge faster towards their respective final values, similarly to the training loss observed on the pretraining task. BERTbase reaches 95% of its final value after 65,000 steps and BERTbase,pair after 30,000 steps. While BERTbase eventually catches up and improves on BERTbase,sym, BERTbase,pair is consistently the better model.
This final experiment highlights the improved
training efficiency induced by the pairwise compatibility operator. The faster convergence rate observed during pre-training is also observed on the downstream task evaluation, confirming the convergence rate improvement by a factor of two for the BERTbase,pair model.

heading: 6 Related Work
text: While the Transformer architecture (Vaswani et al., 2017) popularized the use of the attention mechanism, and contributed to its adoption in the field of NLP, the attention mechanism was first introduced to NLP with recurrent neural networks applied to machine translation (Bahdanau et al., 2016). In this setting, the compatibility operator is a simple multi-layer perceptron with non-linear activation operating on the concatenation of inputs encoded by the recurrent neural network. This definition of the attention mechanism was then extended to other compatibility operator: Luong et al. (2015) mention the use of the dot-product between the recurrent neural network’s hidden state, propose to explicitly integrate token positions into the compatibility operator, and even suggest the use of a general dot-product operator score(ht, hs) = hTt Whs. Those initial influences have also been documented by Galassi et al. (2020) and Niu et al. (2021), where the general dot-product appears as a weighted dot-product between query and keys f(q,K) = qTWK. Thus the pairwise compatibility operator we introduce is an evolution of the general dot-product, where we constrain it to a single and shared linear operator Q before applying the bilinear form of matrix S, resulting in the following operator A(x, y) = Q(x)SQ(y)T .
To the best of our knowledge, our work is the first application of the general dot-product with enforced symmetry to the self-attention mechanism of the Transformer architecture. While we focused on the compatibility operator, recent improvements have been made on other parts of the attention mechanism. Namely, He and Hofmann (2023) proposed to simplify the entire Transformer block by carefully removing components and achieved an impressive 15% weight reduction, while still relying on the traditional scaled dot-product.

heading: 7 Conclusions
text: In this work, we revisited the traditional scaled dot-product used in the Transformer self-attention mechanism. We challenged the use of two dis-
tinct operators to compute the dot-product between queries and keys, in favor of single shared operator and a weighted dot-product with pairwise factors. By doing so, we enforced a symmetric structure to the compatibility operator of the attention mechanism, reducing the number of parameters used in the Transformer layer by a third. As a result, when applied to BERT models, our pairwise compatibility operator reduces the overall number of parameters of the model by 6%, reduces the number of pre-training steps required by half and improves accuracy on the GLUE benchmark, making Transformer-based encoders more efficient, faster to train and lowering their resource requirements. We believe our work can be applied to other Transformer architectures like decoder and encoder-decoder models, as well as to other NLP tasks like machine translation and language modeling. And, more generally, to the concept of attention as a whole, where it would bring improvement in other fields such as computer vision.
For future work, we plan to evaluate the pairwise dot-product attention mechanism on larger models reaching into the billion parameters, and to evaluate our attention mechanism on other benchmarks, like SuperGLUE (Wang et al., 2019a) and SQuAD2.0 (Rajpurkar et al., 2018). We plan on implementing the pairwise compatibility operator for the crossattention mechanism, and evaluating it on decoder and encoder-decoder tasks like language modeling and machine translation. Finally, we want to evaluate our pairwise dot-product attention not only on natural language processing tasks, but also on tasks from other fields, computer vision, time series forecasting and reinforcement learning.
Limitations
Our work focuses only on the application and evaluation of alternative compatibility functions for the self-attention mechanism of Transformer-based encoder models, benchmarked on NLU tasks. While our work has shown positive results on this specific use case, we cannot draw any conclusion on its application to decoder models and pure language modeling tasks, or encoder-decoder model and machine translation tasks. Those use cases rely on the cross-attention mechanism for which the shared representation we exploit with our pairwise compatibility operator may not be appropriate.
While we suggest that the Q and K operators learn a shared representation, we did not perform
any analysis of the original scaled-dot product attention or of our pairwise dot-product attention. The parameter redundancy of multi-head attention models has been covered in Bian et al. (2021). However, to our knowledge the parameter redundancy between the query and the key operator of a single head has not been studied.
While our work showed positive improvements on the training efficiency of BERT-like models of fairly small sizes (100 million parameters), it is not enough to draw conclusions on its efficiency on very large models (e.g., 10 billion parameters).
We decided to benchmark our models on GLUE, as it is the most popular benchmark for NLU evaluation. However, this benchmark as been largely surpassed by modern machine learning models. For that reason, new benchmarks have been introduced, such as SuperGLUE (Wang et al., 2019a) or SQuAD2.0 (Rajpurkar et al., 2018).
Reproducibility Statement
All software related to our experiments with the attention mechanism is available online2. It uses the PyTorch (Paszke et al., 2017) and Hugging Face Transformer (Wolf et al., 2020) frameworks. The necessary steps to recreate the training dataset are documented3, the dataset used for training is available on Hugging Face4.

heading: Acknowledgements
text: The work presented in this paper has received funding from the German Federal Ministry for Economic Affairs and Climate Action (BMWK) through the project OpenGPT-X (project no. 68GX21007D), and has been supported by the German Federal Ministry of Education and Research as part of the project TRAILS.

heading: A OSCAR Filters
text: To ensure high quality of our training dataset, we filter OSCAR dumps with the following rules:
• From the UT1 Blocklists project5, we exclude the following categories:
– “agressif” – “adult” – “cryptojacking” – “dangerous_material” – “phishing” – “warez” – “ddos” – “hacking” – “malware” – “mixed_adult” – “sect”
• We exclude documents whose harmful perplexity score is below 5.0 and above 100,000.
• Following recommendation from Abadji et al. (2022), we exclude documents which have been flagged with quality warnings.
5http://dsi.ut-capitole.fr/blacklists/index_ en.php

heading: Future Work
text: For future work, we plan to evaluate the pairwise dot-product attention mechanism on larger models reaching into the billion parameters, and to evaluate our attention mechanism on other benchmarks, like SuperGLUE (Wang et al. , 2019a) and SQuAD2. 0 (Rajpurkar et al. , 2018). We plan on implementing the pairwise compatibility operator for the crossattention mechanism, and evaluating it on decoder and encoder-decoder tasks like language modeling and machine translation. Finally, we want to evaluate our pairwise dot-product attention not only on natural language processing tasks, but also on tasks from other fields, computer vision, time series forecasting and reinforcement learning. Limitations
Our work focuses only on the application and evaluation of alternative compatibility functions for the self-attention mechanism of Transformer-based encoder models, benchmarked on NLU tasks