Computer Science
Computer Science-2021.gz:143249
Computer Science
c8db5fd0bb1650d6f635983ae9b2176b14f712be
Armour: Generalizable Compact Self-Attention for Vision Transformers

Attention-based transformer networks have demonstrated promising potential as their applications extend from natural language processing to vision. However, despite the recent improvements, such as sub-quadratic attention approximation and various training enhancements, the compact vision transformers to date using the regular attention still fall short in comparison with its convnet counterparts, in terms of \textit{accuracy,} \textit{model size}, \textit{and} \textit{throughput}. This paper introduces a compact self-attention mechanism that is fundamental and highly generalizable. The proposed method reduces redundancy and improves efficiency on top of the existing attention optimizations. We show its drop-in applicability for both the regular attention mechanism and some most recent variants in vision transformers. As a result, we produced smaller and faster models with the same or better accuracies.


Introduction
The Transformer architecture [17] has been widely used in natural language processing (NLP) tasks and obtained dominating results. Recently, the Vision Transformer (ViT) [8] has demonstrated the state-of-the-art results for image classification by using exclusively the Transform architecture and the multi-head attention (MHA). However, as a proof-of-concept, ViT underperforms the convolutional neural networks (CNN) in accuracy unless a large private labeled image dataset (JFT-300M) is used. DeiT [16] first introduced some smaller variants of ViT by reducing the embedding dimension and the number of heads. Unfortunately, the smallest DeiT architecture still falls short when compared against the CNN counterpart, EfficientNet B0 [15], across all the key metrics (accuracy, model size, and latency.) Since then, several works [21,9] proposed hybrid architectures that reintroduce convolutions alongside the MHAs, as the desirable inductive biases built into the former are uniquely suited to solve vision tasks.
In this paper, we re-examine the fundamental design of self-attention for opportunities to further reduce model size and latency for vision transformers, while at least maintaining the same accuracy. We are especially interested in generalizable optimizations that can be easily applied on top of both the widely-used regular self-attention and its latest variants.
To achieve the goal, we first identify the redundancy in the linear transformations in self-attention that produce the query, key, value matrices. Then we propose a compact self-attention called Armour which reduces the number of transformations, therefore improving both model size and latency. The proposed method is compared against its variants, and shows preferable performance in accuracy and throughput. Next, we replace the regular self-attention with Armour in the smallest accurate ViT in [16], which yields a new model with the same accuracy, while achieving EfficientNet B0-level model size and throughput.
Since Armour targets the fundamental design redundancy of self-attention, it is highly generalizable and can be applied on top of most ViT optimizations. To demonstrate its drop-in applicability, we replace the evolved attention layers in a competitive hybrid ViT architecture [9] with two Armour variants. The resulting models achieve better accuracy and GPU/CPU throughputs with fewer parameters. Given the all-round advantages, the easy-to-implement Armour attention and its generalized forms should be considered in places where self-attention and its variants are used, especially for the rapidly evolving vision transformers.

Related Work
The attention mechanism was first introduced and used in conjunction with a recurrent network in [2] to help memorize long sequences in neural machine translation. The Transformer [17] further proposed the multi-head attention mechanism which performs multiple self-attention in parallel to achieve more effective learning at different scales. Recently, the Transformer architecture has extended its application from NLP to vision tasks, especially as ViT [8] has achieved the state-of-theart results for image classification with an architecture that closely resembles the initial NLP version.
The other examples of using the Transformer as a viable alternative to CNNs include object detection [3,7,14,28], video processing [24,26], image enhancement [4,22], etc. Due to the enormous computational and memory requirements of the transformer models, there has been increasing interest in transformer optimizations along several directions.
The regular transformer scales quadratically with the number of tokens N in the input sequence, which limits its usage in settings with limited resources. Several works [19,12,6,11] have proposed techniques to reduce the complexity from O(N 2 ) to as low as O(N ), yielding linear transformers. However, these techniques only outperform the regular method for very long sequences.
Another direction focuses on the sparsity in transformers. [5] exploits a factorized sparse representation of attention. [18] leverages token and head sparsities to reduce the attention computation and memory access for NLP tasks. For ViT, [27] is an early example that prunes channels according to the learnable importance scores. In our work, the reduction of the transformations in self-attention can be viewed as a fixed layer pruning scheme, which is unexplored by any of these works.
Evolving the Transformer architecture can also significantly improve performance. For ViTs, the evolutions can be categorized by how the key components are implemented, including positional encoding [9,21], token embedding [23], projection for attention [20], and model hierarchy [20,21,9]. Selecting deployment-friendly operators for non-linearity and normalization can also greatly improve inference latency. For example, [9] replaced the linear projection and LayerNorm [1] with 1×1 convolutions and BatchNorm [10], respectively, later of which can be fused into the preceding convolution at inference time. Our work introduces optimizations at the fundamental level of the self-attention mechanism. As a result, it is high generalizable and can be applied on top of most of the aforementioned techniques to achieve additional improvements in accuracy, model size, and throughput.

Compact Self-Attention
In this section, we first review the preliminaries associated with the regular attention mechanism, and raise the question of whether it should be adopted verbatim in the context of non auto-regressive tasks, such as the vision transformer. Then, we identify the redundancy in the linear transformations and propose the Armour attention to exploit it.

Preliminaries
The scaled dot-product attention is a mapping that accepts three matrices representing the packed vectors of query, key and value, respectively. Conventionally, these matrices are named as Q, K, V ∈ R L×d , where L is the length of the input token sequence, and d is the hidden dimension. Then scaled dot-product attention can be defined as: where the softmax function is applied row-wise for each token to compute the attention probabilities. When the Q, K, and V matrices are computed from the same input tensor x, i.e., Q = xW Q , K = xW K , V = xW V , it is regarded as a self-attention. Finally, a multi-head attention (MHA) performs Figure 1: Redundancies between W Q , W K , and W V in the regular self-attention.
h self-attentions in parallel over the attention heads, which collectively allow more effective learning at different scales.
The attention mechanism can be interpreted as a retrieval system in matrix form. The dot-product between Q and K T calculates the similarities between the query and key vectors, known as the attention scores. Then, the scores are normalized by the softmax function to produce the attention probabilities which indicate how much each token will be expressed at a given position. Finally, the probability matrix is multiplied with V to yield weighted value vectors which are summed up as the output for each position. Originally, the attention mechanism has been used mostly in auto-regressive models for NLP tasks, meaning that Q is not calculated from the same sequence as K and V . But for self-attention in ViTs, all three matrices are linearly transformed from the same input sequence. Do we still need all three linear transformations?

Armour Attention
We take a closer look at the linear transformations. Recall that Q = xW Q and K = xW K in QK T . Since Q and K are linearly transformed from the same input x, the weight matrices W Q and W K are entangled in gradient back-propagation. This is a fundamental redundancy in the regular self-attention mechanism. Figure 1 visualizes the pair-wise redundancies between W Q , W K , and W V in the first attention layer of DeiT-Ti [16]. We computed the magnitude of element-wise difference, e.g. , |W Q − W K |, and measured the percentage under a small threshold = 1e − 2. It is evident that the redundancy between W Q and W K is significantly higher than that between the other two pairs, as a result of the entanglement.
To exploit this fundamental redundancy, we propose the Armour self-attention by sharing the weights between Q and V . Therefore, its scaled dot-product attention becomes: A comparison between the regular self-attention and the Armour variant is illustrated in Figure 2.
The proposed method reduces the number of linear transformations from 3 to 2, yielding smaller and faster transformers. More importantly, by using W Q both before and after the softmax function, we break the entanglement between W Q and W K , forcing both to learn more efficient mappings. Since Armour exploits the fundamental redundancy in attention, it leads to optimized models with the same or better accuracies.
There are two other ways of weight sharing between Q, K and V : W Q = W K and W K = W V . Intuitively, W Q = W K seems more natural, since QK T is where the entanglement happens. In fact, this was accidentally discovered in Reformer [12] as a by-product of the locality-sensitive hashing (LSH) attention which requires Q and K to be equal. However, the authors realized in a W Q = W K formulation, the dot-product between a query vector and itself will almost always be greater than the dot-product with another vector, which undermines the capacity of self-attention. As a result, Reformer had to modify the masking to forbid a token from attention to itself, except in situations where a token has no other valid attention targets. This necessary but overly-simplified additional step incurs latency overhead during training and inference, and still reduces the capacity of the attention matrix along the diagonal. The other variant is W K = W V , which is sometimes used in auto-regressive transformers where Q is calculated from a different sequence than K and V . In this  , an extra tensor transpose is required between K T and V = K, which will lead to performance penalty.
In the first 4 rows of Table 1, we compared the Armour attention against the other variants denoted as W K = W V , W Q = W K diag, and W Q = W K . Among all cases, Armour yields the best ImagetNet accuracy and throughput. The two variants of W Q = W K with and without the diagonal post-processing both result in noticeable accuracy drops. The Armour-Ti is produced by replacing the regular self-attention in the baseline DeiT-Ti [16] with the Armour attention. The optimized model retains virtually the same accuracy while achieving a 7.8% decrease in model size and a 7.2% increase in GPU throughput. It is also worth noting that the new best compact ViT, Armour-Ti dist/ 1200, is now in range with EfficientNet-B0 in terms of model size and accuracy, and offers a slight advantage in GPU throughput. This confirms the redundancy even in the smallest DeiT model, and demonstrates Armour as a good replacement for the regular attention.

Generalized Compact Self-Attention
Since the Armour attention targets the fundamental redundancy in the regular self-attention. It is highly generalizable and can be applied orthogonally on top of most ViT optimizations, as long as transformations of some form are still applied. In this section, we use a highly-competitive hybrid ViT architecture, LeViT [9], as an example to show its drop-in applicability. We derive two variants of the new attention design by applying the generalized Armour mechanism. For the other works that also modify the regular self-attention, their generalized compact variants can be similarly derived.
There are two types of attention blocks in LeViT: the regular attention block depicted on the left in Figure 3, and the shrinking attention block. The latter accounts for only 2 out of 11 attention blocks  in the smallest architecture, and is not considered in this work. The regular attention block uses 1 × 1 convolutions for the linear transformations, and replaces the LayerNorm with BatchNorm. In an effort to reduce the computation of QK T , the size of Q and K matrices is reduced relative to V by half. Therefore, the shapes of Q, K, and V matrices are N × (D × HW ), N × (HW × D), and N × (HW × 2D), respectively, where D is the key dimension, N is the number of heads, and C × H × W is the traditional shape of activation maps in the BCHW format.
Despite the changes in transformations and dimensions, we use this evolved attention block as an example to demonstrate how the Armour attention can be easily generalized to provide additional optimizations. We derive two compact variants: one that reduces V by half, and the other that removes V completely. The first variant is depicted in the middle of Figure 3, where the size of V is changed to N × (HW × D), and is concatenated with Q to maintain the 2× ratio of V in the original design. The second variant is depicted on the right of Figure 3, where V is completely replaced by the concatenation of Q and K.
In Table 2, we show the results of applying the two variants to LeViT-128S: Armour-128S and Armour-128S+. The first variant introduces a small reduction of the number of parameters by 3.7%, and negligible improvement in GPU and CPU throughputs. However, we break the gradient entanglement between W Q and W K by concatenating Q into V and using W Q in both matrix multiplies. As a result, Armour-128S is 1.1% more accurate than LeViT-128S, as all three 1×1 convolutions are forced to learn better mappings. The second variant offers more moderate improvements and a 0.6% accuracy advantage compared to the baseline.
Note that we chose tensor concatenation as it is the simplest form of generalized Armour attention.
In the scenarios where Q, K, and V are generated by convolutions with different shapes, the typical efficient convolution tricks, such as grouped convolution [13] and shuffled grouped convolution [25] can also be considered. With this example, we have demonstrated how easily the Armour attention can be generalized to exploit the redundancy even in the smallest model of a highly-optimized hybrid ViT architecture.

Experiments
In this section, we present experimental results demonstrating the techniques introduced above. The experiments are conducted with simple modifications on top of DeiT [16] and LeViT [9], respectively. The ImageNet-2012 dataset is used for training and evaluation, which is made possible for ViT by the extensive data augmentation techniques in [16]. The training uses an 8x NVIDIA V100 GPU machine. The inference time is measured on one V100 GPU and on an Intel Xeon E5-2686 at 2.3GHz. The Armour models are trained with the same settings and hyper-parameters as their DeiT and LeViT counterparts, expect for a different learning rate of 1e-3 instead of 5e-4.

Armour Attention Experiments
In Table 1, the first 5 architectures are trained without distillation for 300 epochs. We were able to reproduce the reported accuracy for DeiT-Ti, 72.1% vs. 72.2%. Amour-Ti represents the same architecture of DeiT-Ti, expect that all the regular self-attentions are replaced by the Armour attentions. The optimized model achieves a 7.8% decrease in the number of parameters and a 7.2% increase in GPU throughput, while retaining virtually the same accuracy at 72.0%.
The next 3 architectures in Table 1 are trained with distillation. By training DeiT-Ti dist for 300 epochs, we observed an accuracy gap between the reproducible accuracy (73.8%) and the published accuracy (74.5%). Despite that, Armour-Ti dist achieves the same accuracy, while improving the model size by 6.8% and the GPU throughput by 6.4%. Because of the accuracy reproduction issue, the most accurate Armour-Ti dist/ 1200 is trained for 1200 epochs instead of 1000 as in DeiT, which yielded a nearly identical accuracy as the best DeiT-Ti with distillation (76.5% vs. 76.6%). This shows the Armour attention has indeed exploited the fundamental redundancy in the regular self-attention mechanism.
In Table 3, we measured the improvements in model size and throughput for the other DeiT architectures. Since we have verified the accuracy of the smallest optimized architecture in Table 1, we expect these larger variants to safely benefit from the improvements without significant accuracy degradation.

Generalized Armour Attention Experiments
In Table 2, all three architectures are trained with distillation for 500 epochs. The best published accuracy of the baseline LeViT-128S is 76.6%, which is produced by training with distillation for 1000 epochs. Compared to the locally reproduced baseline, both Armour variants achieved better accuracies as well as slightly improved GPU and CPU throughputs. In Table 4, we also calculated the improvements in model size and throughput for the larger LeViT architectures, if the generalize Armour attention is applied. Overall, the generalized Armour mechanism achieves good reduction of model size, and small to moderate throughput uplift.

Conclusion
In this paper, we re-examined the design of the widely-used self-attention and identified a fundamental redundancy. To exploit that, we proposed Armour, a compact self-attention that reduces the number of linear transformations. Armour is easy to implement and highly generalizable. By replacing the We have also demonstrated that the generalized Armour mechanism can be easily and orthogonally applied on top of the other transformer optimizations, even when the design of self-attention has evolved. Thanks to its drop-in applicability, we believe Armour should be considered as a replacement for both regular attention and its variants for better accuracy, model size, and throughput.

Broader Impact
The Transformer models have achieved remarkable success for many NLP tasks, and demonstrated promising potential for vision tasks. However, these models typically require enormous computation and memory capacities, which limits their usage in settings with limited resources, such as mobile and embedded devices. Our work focuses on the fundamental redundancy in the self-attention mechanism that is the widely-used by transformers. The proposed method can be easily generalized, therefore serving as "a raising tide that lifts all boats". By providing an easy-to-implement drop-in replacement, for self-attention, numerous transformer models across many application domains can be seamlessly improved in model size, power and latency. These optimized models can yield an immediate impact on real-life applications, especially in settings with resource constraints.