COS F ORMER : R ETHINKING S OFTMAX IN A TTENTION
A BSTRACT
Transformer has shown great successes in natural language processing, computer vision, and audio processing.
As one of its core components, the softmax attention helps to capture long-range dependencies yet prohibits its scale-up due to the quadratic space and time complexity to the sequence length.
Kernel methods are often adopted to reduce the complexity by approximating the softmax operator.
Nevertheless, due to the approximation errors, their performances vary in different tasks/corpus and suffer crucial performance drop when comparing with the vanilla softmax attention.
In this paper, we propose a linear transformer called
COS F ORMER that can achieve comparable or better accuracy to the vanilla transformer in both casual and cross attentions.
COS F ORMER is based on two key properties of the softmax attention: i).
non-negativeness of the attention matrix; ii).
non-linear re-weighting scheme that can concentrate the distribution of the attention matrix.
As its linear substitute, COS F ORMER fulﬁlls these properties with a linear operator and a cosine -based distance re-weighting mechanism.
Extensive experiments on language modeling and text understanding tasks demonstrate the effectiveness of our method.
We further exam our method on long sequences and achieve state-of-the-art performance on the Long-Range Arena benchmark.
I NTRODUCTION
[Figure]
With years of development, the transformer model (Vaswani et al., 2017) and its variants (Zaheer et al., 2020; Wang et al., 2020; Tay et al., 2020a) have been successfully adapted to three most popular artiﬁcial intelligence (AI) ﬁelds: i.e., natural language processing (Devlin et al., 2019;
Liu et al., 2019), computer vision (Dosovitskiy et al., 2020; Carion et al., 2020;
Liu et al., 2021) and audio processing (Schneider et al., 2019; Baevski et al., 2020).
Compared with conventional recurrent (Hochreiter & Schmidhuber, 1997) and convolutional architectures (He et al., 2016), are and stronger in capturing global information with less inductive bias, thus excelling on many tasks.
Dot-product attention with softmax normalization is the cornerstone of the transformer to capture long-range dependencies.
However, its quadratic space and time complexity with regard to the length of the sequence make its computational overhead prohibitive, especially for long inputs.
To address this issue, numerous methods are proposed recently, such as the sparse attention matrix (Zaheer et al., 2020; Beltagy et al., 2020; Tay et al., 2020a; Kitaev et al., 2019; Child et al.
, 2019),lowrank representations (Wang et al., 2020) or kernel-based methods (Peng et al., 2020; Choromanski et al., 2020; Katharopoulos et al., 2020), among many others.
These methods achieve reduced computational complexity with comparable performances when compared with the vanilla attention architecture on several selected tasks or corpus.
However, the improved efﬁciency is usually achieved via introducing additional yet often impractical assumptions on the attention matrix (Wang et al., 2020) or with valid approximation of softmax operation only within constrained theoretical bounds (Choromanski et al., 2020; Peng et al., 2020)
Therefore, when their assumptions are unsatisﬁed or when approximation errors get accumulated, these methods may not always be advantageous over the vanilla architecture (Narang et al., 2021).
Consequently, performance deﬁciencies in a broad application spectrum are often observed in these transformer variants, especially those with linear complexity.
For example, the Performer (Choromanski et al., 2020), RFA (Peng et al., 2020) and Reformer (Kitaev et al., 2019) show less satisfactory performance on the GLUE benchmark (Wang et al., 2018) when compared with the vanilla architecture as suggested in our preliminary experiments (Tab. 2).
Furthermore, many of these aforementioned methods are not applicable to casual attentions, which are critical for auto-regressive training.
For example, techniques proposed in Linformer (Wang et al., 2020) and BigBird (Zaheer et al., 2020) are speciﬁc to cross attentions.
Since the softmax operator appears to be the main hurdle while efﬁcient yet accurate approximation to softmax is difﬁcult to achieve, one question naturally arises: “ Can we replace the softmax operator with a linear function instead, while maintaining its key properties? ”.
By digging into the softmax attention, we ﬁnd two key properties that affect its empirical performance: (i) elements in the attention matrix are non-negative (Tsai et al., 2019; Katharopoulos et al., 2020); (ii) the non-linear re-weighting scheme acts as a stabilizer for the attention weights (Titsias, 2016; Gao & Pavel, 2017;
Jang et al., 2016).
These ﬁndings reveal some new insights of the current approaches.
For example, the linear transformer (Katharopoulos et al., 2020) achieves property (i) using an exponential linear unit (Clevert et al., 2016) activation function.
However, due to lack of the re-weighting scheme, it underperforms other efﬁcient transformer variants on the Long-Range Arena benchmark as shown in Figure 1 as well as the language modeling task (Table 2) based on our controlled experiments.
In this paper, we propose a new variant of linear transformer called COS F ORMER that satisﬁes both of the above properties.
Speciﬁcally, we enforce the non-negative property by passing the features to a ReLU (Agarap, 2018) activation function before computing the similarity scores.
In this way, we encourage the model to avoid aggregating negatively-correlated contextual information.
Further, we adopt a cos re-weighting scheme to stabilize the attention weights.
This helps the model to amplify local correlations, which usually contain more relevant information for natural language tasks.
Thanks to the Ptolemy’s theorem, our attention can be exactly decomposed into a linear form.
We perform extensive experiments on both autoregressive language models and bidirectional models on ﬁve public benchmarks, including WikiText-103 (Merity et al., 2017), GLUE (Wang et al., 2018),
IMDB (Maas et al., 2011), AMAZON (Ni et al., 2019) and
Long-Range Arena benchmark (Tay et al., 2020b).
Our model shows much better inference speed and smaller memory footprint, while achieving on par performance with the vanilla transformer.
It is noteworthy that our method ranks 1 st on the Long-Range Arena benchmark, showing favorable performance than other competitors, which well demonstrates its strong capacity in modeling long sequence inputs.
O UR M ETHOD
In this section, we provide technique details of our linear transformer called COS F ORMER .
The key insight of the COS F ORMER is to replace the non-decomposable non-linear softmax operation by a linear operation with decomposable non-linear re-weighting mechanism.
Our model is applicable to both casual and cross attentions with a linear time and space complexity with regard to the input sequence length, thus exhibiting strong capacity in modeling long-range dependencies.
2. T HE G ENERAL FORM OF T RANSFORMER
Given an input sequence x with length of N , we ﬁrst represent it in the embedding space x ∈ R N × d with feature dimension of d .
A transformer block T : R N × d → R N × d with input x is deﬁned as:
[Equation]
where F is a feedforward network that contains a residual connection; A is the self-attention function that computes the attention matrix A , which has quadratic space and time complexity with respect to N , thus becoming the computation bottleneck of T on long inputs.
There are three key components in A , namely, query ( Q ), key ( K ), value ( V ) computed through three learnable linear matrices W Q , W K , W V : Q = xW Q ,
K = xW K , V = xW V .
We use M i to represent the i-th row of a matrix M , then the output O ∈ R N × d of A ( x ) can be computed as:
[Equation]
where S ( · ) measures the similarity between queries.
If S ( Q, K ) = exp( QK T ) , the Eq.
2 becomes the dot-product attention with softmax normalization.
In this case, the space and time complexity to compute one row of the output
O i is O ( N ) .
Therefore, the total space and time complexity for computing O grows quadratically with respect to the input length.
2. L INEARIZATION OF S ELF - ATTENTION
According to Eq. 2, we can select any similarity functions to compute the attention matrix.
In order to maintain a linear computation budget, one solution is to adopt a decomposable similarity function such that:
[Equation]
where φ is a kernel function that maps the queries and keys to their hidden representations.
Then one can rewrite Eq.
2 in the form of kernel functions as:
[Equation]
After that, attention operation in linear complexity is achieved via the matrix product property:
[Equation]
In this form (Eq. 5), instead of explicitly computing the attention matrix A =
QK T ∈ R N × N , we calculate the
φ ( K ) T V ∈ R
d × d ﬁrst, and then multiplying φ ( Q ) ∈ R N × d .
By using this trick, we only incurs a computation complexity of O ( Nd 2 ) .
Note that in typical natural language tasks, the feature dimension of one head d is always much smaller than the input sequence length N ( d (cid:28) N ), so we can safely omit d and achieve computation complexity of O ( N ) , as illustrated in Figure 2.
Previous Solutions As aforementioned, the key to the linear attentions is to ﬁnd a decomposable similarity function S ( · ) that generalizes well to different tasks.
Most existing linear transformers are trying to ﬁnd an unbiased estimation of the softmax attention.
For example, RFA (Peng et al., 2020) approximates the softmax operation with random feature maps using theorem of random fourier features (Rahimi & Recht, 2008) and the Performer (Choromanski et al., 2020) utilizes positive random features to approximate it.
However, we empirically ﬁnd that these methods are sensitive to the selection of sampling rate and becomes unstable if the sampling rate gets too high.
Also, to accommodate recency bias, gating mechanisms are employed to better exploit more recent context.
Another group of works attempt to directly replace the softmax with a linear operation.
For example, the linear transformer (Katharopoulos et al., 2020) model replaces the softmax similarity function with a pure dot product S =
QK T , and use a non-linear activation function φ ( · )
= elu( · ) + 1 to model the pairwise relation between features.
However, our controlled experiments show that their solution does not necessarily generalize well on many downstream tasks (Tab. 2) or
the Long-Range
Arena benchmark (Tab. 4).
In this paper, we propose a new replacement of softmax that not only achieves comparable or better performance than the softmax attention in a wide range of tasks, but also enjoys linear space and time complexity.
d x d
Q’
K’ T
V
O(Nd 2 )
O(Nd 2 + Nd 2 ) ≈ O(N)
O(Nd 2 )
N x N
Q
K T
V d x N N x d
O(N 2 d)
O(N 2 d + N 2 d)
≈ O(N 2 )
Softmax
O(N 2 d)
Vanilla self attention
Linearized self attention
N x d
N x d
N x d d x N
N x d
N x d
2. A NALYSIS OF S OFTMAX A TTENTION
In the vanilla transformer architecture, when S ( Q, K ) = exp( QK T ) , the softmax operation is applied to obtain row-wise normalization on the attention matrix A ∈ R N × N as shown in the Eq. 2.
In other words, we normalize the relations of each element in the input sequence to all other elements in order to obtain a weighted aggregation of contextual information.
However, apart from the good empirical performance of softmax attention, what are the crucial and necessary characteristics of it remain only loosely determined in the original transformer paper and follow-up works.
Loss
[Table]
LeakyReLU
[Table]
In this work, we empirically identify two key properties of the softmax operation that may play important roles for its performance: 1) it ensures all values in the attention matrix
A to be non-negative; 2) it provides a non-linear reweighting mechanism to concentrates the distribution of attention connections and stabilizes the training(Titsias, 2016; Gao & Pavel, 2017;
Jang et al., 2016).
To validate these assumptions, we design the following preliminary studies as shown in Table 1.
First, to validate the importance of nonnegativity, we compare three instantiations of the function φ in equation 3: an identify mapping φ
I = I that does not preserve the non-negativity, and the other variant φ ReLU( · )
= ReLU( · ) that retains only positive input values while replacing negative values to zeros.
We also add the φ LeakyReLU( · ) =
LeakyReLU( · ) variant as it does not have the non-negativity as well but have the same non-linearly as the ReLU one.
Second, to demonstrate the effect of non-linear re-weighting, we compare the models using only φ ReLU( · ) without any re-weighting and those with softmax operations.
From Table 1, the superior results of φ ReLU over φ I and φ LeakyReLU demonstrate the beneﬁt of retaining non-negative values.
Our conjecture is that by retaining only positive values in the similarity matrices, the model ignores features with negative correlations, thus effectively avoiding aggregating irrelevant contextual information.
By comparing the results of φ ReLU with the softmax, we observe that models with softmax re-weighting converge faster and generalize better to downstream tasks.
This might be explained as softmax normalization ampliﬁes the correlated pairs, which might be useful to identify useful patterns.
2. COS F ORMER
Based on the observations above, we propose our model COS F ORMER , which discards entirely the softmax normalization while still features the non-negativity and re-weighting mechanism.
Our
COS F ORMER consists two main components: a linear projection kernel φ linear and a cos -Based Reweighting mechanism.
Below we describe details of each components:
Linear projection kernel φ linear
Recall the general form of the attention in Eq. 2, let us deﬁne a linear similarity as:
[Equation]
where φ linear is the transformation function that map queries Q and keys K to our desired representations Q (cid:48) and K (cid:48) , and s is a function that can be linearly decomposed to measure the similarity between Q (cid:48) and K (cid:48) .
Speciﬁcally, in order to ensure a full positive attention matrix A and avoid
[Figure]
aggregating negatively-correlated information, we adopt ReLU( · ) as the transformation functions and therefore effectively eliminate negative values:
[Equation]
As Q (cid:48) and K (cid:48) contain only non-negative values, we directly take their dot-product s ( x, y ) =
xy T , x, y ∈ R 1 × d followed by a row-wise normalization to compute attention matrices:
[Equation]
Based on Eq.
4, we rearrange the order of dot-product and obtain the formulation of the proposed attention in linear complexity as:
[Equation] [Equation]
cos-
Based Re-weighting Mechanism
The non-linear re-weighting mechanism introduced by the softmax attention can concentrate the distribution of the attention weights and therefore stabilize the training process (Titsias, 2016; Gao & Pavel, 2017; Jang et al., 2016).
We also empirically ﬁnd that it can punish far-away connections and enforce locality in some cases.
In fact, such locality bias, i.e., a large portion of contextual dependencies are from neighboring tokens, is commonly observed on downstream NLP tasks (Clark et al., 2019; Kovaleva et al., 2019), as shown in Figure 3 (1).
Based on the assumption above, what we need to fulﬁll the second property of softmax may be a decomposable re-weighting mechanism that can introduce recency bias to the attention matrix.
Here, we propose a cos -based re-weighting mechanism as it perfectly ﬁt our purpose: 1).
the Ptolemy’s theorem ensures the cos weights can be decomposed into two summations; 2).
as shown in Figure 3 (4), the cos will put more weights on the neighbouring tokens and therefore enforces locality.
Also, by comparing the attention matrices in Figure 3 (2) and (3), the COS F ORMER enforces more locality than the one without the re-weighting mechanism.
Speciﬁcally, by combining with Eq 6, the model with cosine re-weighting is deﬁned as:
[Equation]
By leveraging the Ptolemy’s theorem, we decompose this formulation as:
[Equation]
T where i, j = 1 , ..., N, M ≥ N , and Q (cid:48)
=
ReLU( Q ) , K (cid:48)
=
ReLU( K ) .
Let Q cos i = Q (cid:48)
i cos (cid:0) πi 2 M (cid:1) ,
Q sin i = Q
[Equation]
i sin
[Equation] [Equation]
, the output of the proposed attention module can be expressed as:
[Equation]
[Figure]
where O i is the output at the i th position of the sequence from the attention module.
Detailed derivation are included in the Appendix.
Without losing the generality, our method achieves a linear complexity as:
[Equation]
Relation to positional encoding
COS F ORMER can be seen as a new way of introducing the relative positional bias to the efﬁcient transformer.
Compared with the Rotary Position Embedding (Su et al., 2021), they use a more complex position embedding strategy and did not enforce the nonnegativity to the similarity scores as ours.
Also, since they only change the position embedding on the numerator while keeping the denominator unchanged, the summation of their attention scores is not equal to 1.
For Stochastic Positional Encoding (Liutkus et al., 2021), they use a sampling strategy to approximate the softmax, and introduce relative positional encoding to linear transformers.
E XPERIMENTS
In this section, we experimentally validate the effectiveness of the proposed method in multiple settings.
The purposes of the experiments are three-fold.
First, we validate the capacity of COS F ORMER in language modeling through autoregressive (Sec. 3.1) and bidirectional (Sec. 3.2) setups using
WikiText-103 (Merity et al., 2017).
In this way, we validate the effectiveness of the proposed linear attention module in both causal and non-causal cases.
Second, we investigate the generalization ability of COS F ORMER on downstream tasks by comparisons with other existing transformer variants.
This is achieved by performing comparative ﬁnetuning experiments on ﬁve datasets, including
GLUE (QQP, SST-2, MNLI)
(Wang et al., 2018), IMDB (Maas et al., 2011) and AMAZON (Ni et al., 2019)
(Sec. 3.3).
We further compare COS F ORMER with other transformer variants on the long-range-arena benchmark (Tay et al., 2020b) to understand its ability in modeling long-range dependencies (Sec. 3.4) and show comparative analysis into model efﬁciency (Sec. 3.5).
Third, we conduct ablation studies to understand each component in COS F ORMER (Sec. 3.6).
3. A UTOREGRESSIVE LANGUAGE MODELING
In autoregressive or left-to-right language modeling, we estimate the probability distribution of a token given its previous tokens.
We use (Baevski & Auli, 2018) as our baseline model.
Speciﬁcally, we adopt their large model which has 16 cascaded layers with a projected dimensions of 1024, and replace the self-attention module with our proposed linear attention module.
We train our model on 8 Nvidia Tesla A100 GPUs with a sequence length of 512 for 150K updates on the WikiText- (Merity et al., 2017) and report perplexity on the validation and test splits in Table 2.
[Table]
We observe that although the baseline model is a powerful standard transformer which requires quadratic computation complexity, COSF ORMER outperforms it with a clear margin in linear computation complexity.
Besides, we achieve comparable perplexity to other methods on the validation set, and signiﬁcantly outperform all competing methods on the test set by a clear gap, which further demonstrates the effectiveness of COS F ORMER .
[Table] [Table]
[Table]
B IDIRECTIONAL L ANGUAGE M ODEL
For bidirectional language modeling
[Table]
we adopt RoBERTa
(Liu et al., 2019) as the baseline model.
Similarly, we replace the self-attention module in the RoBERTa by the proposed linear attention module, and keep other structures unchanged.
We train this bidirectional task on 2 Nvidia Tesla
A100 GPUs for 50K iterations with a input sequence length 512.
As shown in Figure 4, COSF ORMER converges faster than vanilla transformer on both training and validation sets with a comparable or smaller loss values, despite it only consumes linear space and time computation complexity.
In addition, the COS F ORMER variant with re-weighting mechanism has both notably better converge speed and ﬁnal results over the counterpart without re-weighting, which further validates the effectiveness of our cos -based distance matrix and also demonstrates the effectiveness of recency bias on natural language data.
3. D OWNSTREAM FINE - TUNING TASKS
In this section, we ﬁne-tune the pre-trained model on downstream tasks to demonstrate the generalization ability of COS F ORMER on downstream tasks.
We use the pre-trained bidirectional model and ﬁne-tune it on three downstream text classiﬁcation tasks: GLUE (QQP, SST-2, MNLi) (Wang et al., 2018), IMDB (Maas et al., 2011) and AMAZON (Ni et al., 2019).
For fair comparison, we ﬁrst pre-train all the competing efﬁcient transformer variants for the same 50K iterations on WikiText103 (Merity et al., 2017) under the same setting, then we follow the same ﬁne-tuning protocol as
RoBERTa (Liu et al., 2019) to ﬁne-tune these methods on the downstream tasks.
From Table 3, we can see that COS F ORMER outperforms baseline (Liu et al., 2019) on three out of ﬁve datasets, and achieves either best or secondary place on all ﬁve downstream datasets compared to competing efﬁcient transformers.
It is worth noting that despite Longformer (Beltagy et al., 2020) achieves better results on MNLI than COS F ORMER , it requires a computation complexity of O ( Nw ) , where w is window size.
As shown in Figure 1, Longformer is slower and requires more memory overhead than
COS F ORMER .
Other competing methods(Peng et al., 2020; Choromanski et al., 2020; Kitaev et al., 2019) are all based on kernel functions and have substantial performance gaps compared with our model.
This validates the effectiveness of the proposed COS F ORMER model compared with other efﬁcient transformer variants.
3. R ESULTS ON L ONG - RANGE - ARENA B ENCHMARK
To further evaluate the generalization ability of the proposed method, we train our model from scratch on Long-range-arena benchmark 2020b.
Long-range-arena (Tay et al., 2020b) is a benchmark speciﬁcally designed for efﬁcient transformers with long input sequences, thus serving as a suitable testbed to assess the quality of efﬁcient transformer variants comparatively.
To ensure fair comparison, we ﬁrst implement our method on Jax (Bradbury et al., 2018), then carefully follow their preprocessing, data split, model structure and training protocol.
We evaluate our method on a variety of tasks including Long sequence ListOps (Nangia & Bowman, 2018), Byte-level text classiﬁcation (Maas et al., 2011), document retrieval using the ACL Anthology Network (Radev et al., 2013), image classiﬁcation on sequence of pixels on CIFAR-10 (Krizhevsky & Hinton, 2009), and
Pathﬁnder (Linsley et al., 2018).
As shown in Table 4, COS F ORMER overall achieves competitive results across all the tasks while achieving best performance on ListOps and Document Retrieval.
For the Pathﬁnder task, since the distance between the two points can be very far from each other, our introduced locality bias would have negative impact to this task and show a bit lags to other
SOTA methods, despite that the performance gap between our method and the vanilla transformer is small It is worth mentioning that COS F ORMER achieves the best overall scores on Long-range-arena benchmark, being one of the only two models that surpass vanilla transformer architecture.
[Table] [Table]
3. E FFICIENCY C OMPARISON
In this section, we compare the efﬁciency of COS F ORMER with other models, with a focus on long sequences as inputs.
With the proposed linear attention module, we expect that COS F ORMER scales comparably with other linear variants while signiﬁcantly surpassing the vanilla transformer architecture.
For a fair and comprehensive comparison, we implement our method and competing methods on Jax (Bradbury et al., 2018).
We use the byte-level text classiﬁcation benchmark and report runtime speed during both training and inference under different sequence lengths (1k-4k).
We conduct experiments on one Nvidia A6000 GPU and also report the corresponding inferencetime memory foot prints as shown in Figure 1.
As shown in Table 5 and Figure 1, most pattern based methods (Beltagy et al., 2020; Zaheer et al., 2020; Tay et al., 2020a; 2021) and vanilla transformer (Vaswani et al., 2017) are much slower and require greater memory than COS F ORMER prevents them from extending to longer sequence.
Further, the kernel based methods like (Narang et al., 2021; Choromanski et al., 2020; Tay et al., 2020a) have comparable speed and memory overheads, but their performances are less satisfactory compared to COS F ORMER across above metrics.
In summary, our model COS F ORMER achieves overall better efﬁciency than other linear variants while maintain superior modeling and generalization ability.
3. A BLATION : cos - BASED R E - WEIGHTING
with and without cos -based re-weighting ( φ ReLU ).
We evaluate on two compositive metrics.
Bidirectional ﬁnetune avg : average score across 5 datasets reported in Table 3.
LRA avg : average score across 5 tasks reported in Table 4.
[Table]
By introducing cos -based re-weighting, we provide a non-linear mechanism to concentrate the distribution of attention connections and stabilizes the training.
In this way, we encourage the model to better take into account the locality inductive biases commonly observed on many natural language tasks.
In particular, we investigate the effect of the cos -based re-weighting in two aspects.
First, as shown in Figure 4, by adding cos -based re-weighting, we obtain both notably better converge speed and ﬁnal results in autoregressive language modeling.
Further, in Table 6, we present a comparison between COS F ORMER models with and without re-weighting mechanism.
We use two composite metrics which comprehensively include 10 different datasets from bidirectional downstream ﬁne-tuning tasks and long-range-arena (Tay et al., 2020b).
COS F ORMER achieves overall better results over the counterpart without reweighting, improving the average scores on bidirectional ﬁnetuning and long-range-arena by a clear margin.
This veriﬁes that the proposed re-weighting effectively incorporates the locality inductive biases for natural language tasks.
R ELATED WORK
This section will introduce the existing works on improving the efﬁciency of Transformers, they can be broadly divided into two categories, Pattern based methods and Kernel based methods .
Pattern based method Pattern based methods sparsify the attention matrix with handcrafted or learnable patterns.
As an early approach, Lee et al.
(2019) leverages the inducing points from the sparse Gaussian process to reduce the quadratic complexities of a transformer.
Child et al.
(2019) reduces the complexity by applying combination of strided pattern and local pattern to the vanilla attention matrix.
Longformer (Beltagy et al., 2020) designs ﬁxed diagonal sliding windows combined with global window, and the sliding window pattern can also be extended with dilation to enlarge the receptive ﬁeld.
Zaheer et al.
(2020) presents a more powerful and expressive sparse attention mechanism, which combines multiple types of attention patterns and gives a thorough study of sparse attention mechanism.
Instead of ﬁxed patterns, Kitaev et al.
and Daras et al.
(2020) group the attention computation process into buckets by local sensitive hashing, while Roy et al.
(2020) uses mini-batch spherical k -means.
Nevertheless, Pattern based methods can only cope with sequences up to a certain length, and the computational complexity still grows rapidly when the input sequence becomes longer.
Kernel based method When faced with longer input sequences, it is more efﬁcient to directly reduce the complexity of the theoretical calculation method.
Kernel based methods speed up selfattention by reducing the computation complexity of self-attention from quadratic to linear.
Vyas et al.
(2020) approximate the full attention with a ﬁxed number of cluster attention groups by assuming neighbouring queries in Euclidean space should have similar attention distributions.
Peng et al.
(2020) chooses to use the production of Gaussian kernel functions to approximate Softmax , changing the order of scale dot product calculation, thus reducing the theoretical time to linear complexity and Choromanski et al.
(2020) uses Haar measurement based kernel instead.
Wang et al.
(2020) imports the low-rank prior for attention matrix and approximate softmax with SVD decomposition manner.
Xiong et al.
(2021) utilizes the Nystr ¨ om method with segment-means to generate a lowrank approximation of the Softmax matrix.
Katharopoulos et al.
(2020) formalizes the transformer layer as a recurrent neural network.
In this paper, we demonstrate that the approximation to Softmax is unneccessary for Linearization of self-attention module.
We instead propose a new method to replace Softmax with a linear operation with a re-weighting mechanism, which reduces both time complexity and space complexity to O ( N ) while maintaining the accuracy.
C ONCLUSION
We presented COS F ORMER , a new efﬁcient transformer that has linear time and space complexity.
Our COS F ORMER is based on two key properties of the original softmax attention: (i) every element in the attention matrix are non-negative, such that negatively-correlated information are not included for contextual information aggregation; (ii) the non-linear re-weighting scheme concentrates the distribution of the attention matrix, in order to better exploit the locality inductive biases on sequence modeling.
To fulﬁll these properties in our COS F ORMER , we utilized the RuLU function as our linear operation to ensure the non-negative property; a new cos -based re-weighting mechanism was proposed to enforce the locality bias in the original softmax attention.
Since our COS F ORMER is naturally decomposable, it does not suffer the accumulated approximation error that usually happens in previous linear transformers.
On causal pre-training, bidirectional pre-training, and multiple downstream text understanding tasks, COS F ORMER achieves comparable or even better performances than the vanilla transformer.
On long sequence benchmark, COS F ORMER achieved state-of-the-art performance over ﬁve different tasks.
Further, COS F ORMER obtains a signiﬁcant overall advantage in terms of time and memory efﬁciency over all existing efﬁcient transformers, facilitating the transformers to easily scale to longer input sequence.
A A PPENDIX A. M ATHEMATICAL D ERIVATION OF cos - BASED R E - WEIGHTING
Following Equation
[Equation]
we give a detailed deviation of how to obtain output at position i th position:
[Equation]
T (13) where i, j = 1 , ..., N, M ≥ N , and Q (cid:48) =
ReLU( Q ) , K (cid:48)
=
ReLU( K ) .
Let Q cos i = Q (cid:48)
i cos (cid:0) πi 2 M (cid:1) ,
Q cos i = Q (cid:48)
i cos (cid:0) πi 2 M (cid:1) , K cos j = K (cid:48) j cos (cid:0) πj 2 M (cid:1) , K sin j = K (cid:48)
j sin (cid:0) πj 2 M (cid:1) .
It presents that the output of the proposed COS F ORMER attention can be obtained in a linear manner.
A. P SEUDO C ODE OF COS F ORMER Algorithm 1 describe the way to compute COS F ORMER attention Algorithm 1 COS F ORMER attention
Input: Q ∈ R N × d 1 , K ∈ R M × d 1 , V ∈ R M × d 2 ;
Output: O ∈ R N × d 2 ;
Use M i to represent the i -th row of matrix M ;
Initialize A [ i ] =
πi 2 N , O
[ i ][ j ] = 0 , i = 1 , . . .
, N, j = 1 , . .
, d 2 ;
Initialize S cos
[ i ][ j ] = 0 , S sin [ i ][ j ] = 0 , T cos
[ i ] = 0 , T sin [ i ] = 0 , i = 1 , . . .
, d 1 , j = 1 , . . .
, d 2 ; for i in 1 , . . .
, M do :
K cos i = K i cos (cid:0)
πi 2 M (cid:1) , K sin i =
K i sin (cid:0)
πi 2 M (cid:1) ;
S cos += ( K cos i ) T V i ;
S sin += (cid:0) K sin i (cid:1) T V i ;
T cos += K
cos i ;
T sin += K sin i ; end for for i in 1 , . . .
, N do :
[Equation]
end for
A. A LGORITHM TO VISUALIZE ATTENTION MATRIX
Algorithm 2 describe the way to visualize attention matrix as Figure
Input: M k
; threshold
Output:
Initialize M [ i ][ j ] = 0 , i ∈
, d, j ∈ 1 , . . .
, d ; for k in 1 , . . . , n do : for i in 1 , . . .
, d do : index = argsort ( M k
[ i ]) ( descending order) p
=for j in 1 , . . .
, d do : l = index[ j ] p += M k
[ i ][ l ]
M [ i ][ l ] +=if p > threshold then : break end if end for end for end for
A. I NTRODUCTION OF D ATASET
We train both models on autoregressive language modeling and bidirectional modeling by Wikitext103 dataset, it is split by tokens and its statistics as Table 7.Then we ﬁne-tune the pre-trained bidirectional modeling on several text classiﬁcation tasks.
QQP dataset contain thousands of sentence pair from community question-answering website
Quora.
Network need to determine pairs of question are semantically equivalent.
SST-2 and IMDB are collections of movie reviews.
The task is to determine whether a review is positive or not.
AMAZON dataset contains millions of product reviews from Amazon.
The requirement of this task is to infer the scoring of the product from the review text.
MNLI is a crow-source collections of sentence pairs.
The network must distinguish which of the three categories entailment, contradiction and neutral the given sentences belong to.
The long-range-aren benchmark contains 5 different datasets.
ListOps contains some designed clever mathematical problem to clarify the parsing ability of neural models.
IMDB is also used in this benchmark to examine the text classiﬁcation ability of neural models.
CIFAR-10 is a image collection of various of object, this task require models capture 2D spatial relations between ﬂatten pixels.
In pathﬁnder task, models need to determine the connection of two points in the picture, so as to examine the model’s ability to acquire 2D spatial relationships.
AAN dataset is used to evaluate the ability for models to encode and store compressed representations for retrieving
[Table]
A. Q UALITATIVE R ESULTS OF LRA
We provide our qualitative results of the ListOps and Document Retrieval tasks on Long-RangeArena benchmark (Tay et al., 2020b) with a comparison to the vanilla transformer.
ListOps is a ten-way classiﬁcation task which aims to prediction the results of a sequence with a hierarchical structure and operators MAX, MEAN, MEDIAN and SUM MOD that are enclosed by delimiters (brackets).
The network needs to access all tokens and model the logical structure of the inputs in order to make a prediction.
Document Retrieval task is to decide whether the two input long documents are similar or not with a binary label.
This task evaluates a model’s ability to encode and store compressed representations that are useful for matching and retrieval.
Since the samples in LRA are too long, We substantially shorten some selected samples and display them as below:
Listops:
Listing 1: Examples of LisOps
Byte level document retrieval:
Introduction
Recent advances in Statistical Machine Translation (SMT) are widely centred around two concepts: (a) hierarchical translation processes, frequently employing Synchronous Context Free Grammars (SCFGs) and (b) transduction or synchronous rewrite processes over a linguistic ......
Automatic Grammatical Error Correction (GEC) for non-native English language learners has attracted more and more attention with the development of natural language processing , machine learning and big-data techniques. ?
The CoNLL2013 shared task focuses on the problem of GEC in five different error types including determiner, preposition, noun number......
4 5 Our
output: False
Transformer output
True
Ground-truth
False
Listing 2: Examples of Document Retrieval