O N THE C ONNECTION BETWEEN L OCAL A TTENTION AND D YNAMIC D EPTH - WISE C ONVOLUTION
A BSTRACT
Vision Transformer (ViT) attains state-of-the-art performance in visual recognition, and the variant, Local Vision Transformer, makes further improvements.
The major component in Local Vision Transformer, local attention, performs the attention separately over small local windows.
We rephrase local attention as a channel-wise locally-connected layer and analyze it from two network regularization manners, sparse connectivity and weight sharing, as well as dynamic weight computation.
We point out that local attention resembles depth-wise convolution and its dynamic variants in sparse connectivity: there is no connection across channels, and each position is connected to the positions within a small local window.
The main differences lie in (i) weight sharing - depth-wise convolution shares connection weights (kernel weights) across spatial positions and attention shares the connection weights across channels, and (ii) dynamic weight computation manners - local attention is based on dot-products between pairwise positions in the local window, and dynamic convolution is based on linear projections conducted on the center representation or the globally pooled representation.
The connection between local attention and dynamic depth-wise convolution is empirically veriﬁed by the ablation study about weight sharing and dynamic weight computation in Local Vision Transformer and (dynamic) depth-wise convolution.
We empirically observe that the models based on depth-wise convolution and the dynamic variants with lower computation complexity perform on-par with or slightly better than Swin Transformer, an instance of Local Vision Transformer, for ImageNet classiﬁcation, COCO object detection and ADE semantic segmentation. Code is available at https://github.com/Atten4Vis/ DemystifyLocalViT .
I NTRODUCTION
Vision Transformer (Chu et al., 2021b; d’Ascoli et al., 2021; Dosovitskiy et al., 2021;
Guo et al., 2021; Han et al., 2020; Khan et al., 2021; Touvron et al., 2020; Wang et al., 2021b; Wu et al., 2021;
Xu et al., 2021; Yuan et al., 2021b) has shown promising performance in ImageNet classiﬁcation.
The improved variants, Local Vision Transformer (Chu et al., 2021a; Liu et al., 2021b; Vaswani et al., 2021), adopt the local attention mechanism, which partitions the image space into a set of small windows, and conducts the attention over the windows simultaneously.
Local attention leads to great improvement in memory and computation efﬁciency and makes the extension to downstream tasks easier and more efﬁcient, such as object detection and semantic segmentation.
We exploit the network regularization schemes (Goodfellow et al., 2016), sparse connectivity that controls the model complexity, and weight sharing that relaxes the requirement of increasing the training data scale and reduces the model parameters, as well as dynamic weight prediction that increases the model capability, to study the local attention mechanism.
We rephrase local attention as a channel-wise spatially-locally connected layer with dynamic connection weights.
The main properties are summarized as follows.
(i)
Sparse connectivity: there is no connection across channels, and each output position is only connected to the input positions within a local window.
(ii) Weight sharing: the connection weights are shared across channels or within each group of channels.
(iii)
Dynamic weight: the connection weights are dynamically predicted according to each image instance.
We connect local attention with depth-wise convolution (Chollet, 2017; Howard et al., 2017) and its dynamic variants that are also a channel-wise spatially-locally connected layer with optional dynamic connection weights.
They are similar in sparse connectivity.
The main differences lie in (i) weight sharing - depth-wise convolution shares connection weights (kernel weights) across spatial positions and attention shares the connection weights across channels, and (ii) dynamic weight computation manners - local attention is based on dot-products between pairwise positions in the local window, and dynamic convolution is based on linear projections conducted on the center representation or the globally pooled representation.
We further present the empirical veriﬁcation for the connection.
We take the recently-developed Local
Vision Transformer, Swin Transformer (Liu et al., 2021b), as an example, and study the empirical performance of local attention and (dynamic) depth-wise convolution in the same training settings as
Swin Transformer.
We replace the local attention layer with the (dynamic) depth-wise convolution layer, keeping the overall structure unchanged.
The results show that the (dynamic) depth-wise convolution-based approaches achieve comparable or slightly higher performance for ImageNet classiﬁcation and two downstream tasks, COCO object detection and ADE semantic segmentation, and (dynamic) depth-wise convolution takes lower computation complexity.
The ablation studies imply that weight sharing and dynamic weight improves the model capability.
Speciﬁcally, (i) for Swin Transformer, weight sharing across channels is beneﬁcial mainly for reducing the parameter (attention weight) complexity, and the attention-based dynamic weight scheme is advantageous in learning instance-speciﬁc weights and block-translation equivalent representations; (ii) for depth-wise convolution, weight sharing across positions is beneﬁcial for reducing the parameter complexity as well as learning translation equivalent representations, and the linear projection-based dynamic weight scheme learns instance-speciﬁc weights.
C ONNECTING L OCAL A TTENTION AND D EPTH -W ISE C ONVOLUTION 2. L OCAL A TTENTION
Vision Transformer (Dosovitskiy et al., 2021) forms a network by repeating the attention layer and the subsequent point-wise MLP (point-wise convolution).
The local Vision Transformer, such as
Swin Transformer (Liu et al., 2021b) and HaloNet (Vaswani et al., 2021), adopts the local attention layer, which partitions the space into a set of small windows and performs the attention operation within each window simultaneously, to improve the memory and computation efﬁciency.
The local attention mechanism forms the keys and values in a window that the query lies in.
The attention output for the query x i ∈ R D at the position i is the aggregation of the corresponding values in the local window, { x i 1 , x i 2 , . . .
, x iN k } , weighted by the corresponding attention weights { a i 1 , a i 2 , . .
. , a iN k } 1 :
[Equation]
where N k = K w × K h is the size of the local window.
The attention weight a ij is computed as the softmax normalization of the dot-product between the query x
i and the key x ij :
[Equation]
where Z i = (cid:88)
[Equation]
The multi-head version partitions the D -dimensional query, key and value vectors into M subvectors (each with DM dimensions), and conducts the attention process M times, each over the corresponding subvector.
The whole output is the concatenation of M outputs, y i =
[ y (cid:62) i 1 y (cid:62) i 2 . . .
y (cid:62) iM ] (cid:62) .
The m th output y im is calculated by
[Equation]
where x ijm is the m th value subvector and a ijm is the attention weight computed from the m th head in the same way as Equation 2.
(a)
S p a ti a l
C h a n n e l (b)
S p a ti a l
C h a n n e l (c)
S p a ti a l
C h a n n e l (d)
S p a ti a l
C h a n n e l (e)
S p a ti a l
C h a n n e l
2. S PARSE C ONNECTIVITY , W EIGHT S HARING , AND D YNAMIC W EIGHT
We give a brief introduction of two regularization forms, sparse connectivity and weight sharing, and dynamic weight, and their beneﬁts.
We will use the three forms to analyze local attention and connect it to dynamic depth-wise convolution.
Sparse connectivity means that there are no connections between some output neurons (variables) and some input neurons in a layer.
It reduces the model complexity without decreasing the number of neurons, e.g., the size of the (hidden) representations.
Weight sharing indicates that some connection weights are equal.
It lowers the number of model parameters and increases the network size without requiring a corresponding increase in training data (Goodfellow et al., 2016).
Dynamic weight refers to learning specialized connection weights for each instance.
It generally aims to increase the model capacity.
If regarding the learned connection weights as hidden variables, dynamic weight can be viewed as introducing second-order operations that increase the capability of the network.
The connection to Hopﬁeld networks is discussed in (Ramsauer et al., 2020).
2. A NALYZING LOCAL ATTENTION
We show that local attention is a channel-wise spatially-locally connected layer with dynamic weight computation, and discuss its properties.
Figure 1 (c) illustrates the connectivity pattern.
The aggregation processes (Equation 1 and Equation 3) for local attention can be rewritten equivalently in a form of element-wise multiplication:
[Equation]
where (cid:12) is the element-wise multiplication operator, and w ij ∈ R D is the weight vector formed from the attention weight a ij or { a ij 1 , a ij 2 , . . .
, a ijM } .
Sparse connectivity.
The local attention layer is spatially sparse: each position is connected to the N k positions in a small local window.
There are also no connections across channels.
The element-wise multiplication in Equation 4 indicates that given the attention weights, each output element, e.g., y id (the i th position for the d th channel), is only dependent on the corresponding input elements from the same channel in the window, { x i 1 d , x i 2 d , . . .
, x iN k d } , and not related to other channels.
Weight sharing.
The weights are shared with respect to channels.
In the single-head attention case, all the elements { w ij 1 , w ij 2 , . . . , w ijD } in the weight vector w ij are the same: w ijd = a ij , 1 (cid:54) d (cid:54) D .
In the multi-head attention case, the weight vector w ij is group-wise same: w ij is partitioned to M subvectors each corresponding to one attention head, { w ij 1 , w ij 2 , . . .
, w ijM } , and the elements in each subvector w ijm are the same and are equal to the m th attention weight, a ijm .
Dynamic weight.
The weights, { w i 1 , w i 2 , . . .
, w iN k } , are dynamically predicted from the query x
i and the keys { x i 1 , x i 2 , . . .
, x iN k } in the local window as shown in Equation 2.
We rewrite it as:
[Equation]
Each weight may obtain the information across all the channels in one head, and serves as a bridge to deliver the across-channel information to each output channel.
Translation equivalence.
Different from convolution which satisﬁes translation equivalence through sharing weights across positions, the equivalence to translation for local attention, depends if the keys/values are changed, i.e., the attention weights are changed, when the feature map is translated.
In the case of sparsely-sampled window (for run-time efﬁciency), e.g., (Hu et al., 2019; Liu et al., 2021b; Ramachandran et al., 2019; Vaswani et al., 2021), local attention is equivalent to block-wise translation, i.e., the translation is a block or multiple blocks with the block size same as the window size K w × K h , and otherwise not equivalent (as keys/values are changed).
In the case that the windows are densely sampled (e.g., (Zhao et al., 2020)), local attention is equivalent to translation.
Set representation.
The keys/values for one query are collected as a set with the spatial-order information lost.
This leads to that the spatial correspondence between the keys/values across windows is not exploited.
The order information loss is partially remedied by encoding the positions as embeddings (Dosovitskiy et al., 2021; Touvron et al., 2020), or learning a so-called relative position embedding (e.g., (Liu et al., 2021b)) in which the spatial-order information is preserved as the keys/values in a local window are collected as a vector.
2. C ONNECTION TO D YNAMIC D EPTH -W ISE C ONVOLUTION
Depth-wise convolution is a type of convolution that applies a single convolutional ﬁlter for each channel: ¯ X d = C d ⊗ X d , where X d and ¯ X d are the d th input and output channel maps, C d ∈ R N k is the corresponding kernel weight, and ⊗ is the convolution operation.
It can be equivalently written in the form of element-wise multiplication for each position:
[Equation]
Here, oﬀset( i, j ) is the relative offset, from the 2D coordinate of the position j to the 2D coordinate of the central position i .
The weights { w oﬀset( i,j ) ∈ R D ; j = 1 , 2 , . . . , N k } are reshaped from
C 1 , C 2 , . .
C D .
The N k weight vectors are model parameters and shared for all the positions.
We also consider two dynamic variants of depth-wise convolution: homogeneous and inhomogeneous 2 .
The homogeneous dynamic variant predicts the convolution weights using linear projections from a feature vector that is obtained by globally-pooling the feature maps:
[Equation]
Here, { x 1 , x 2 , . . .
, x N } are the image responses.
GAP() is the global average pooling operator.
g () is a function based on linear projection: a linear projection layer to reduce the channel dimension with BN and ReLU, followed by another linear projection to generate the connection weights.
The inhomogeneous dynamic variant predicts the convolution weights separately for each position from the feature vector
x i at the position (the center of the window):
[Equation]
This means that the weights are not shared across positions.
We share the weights across the channels in a way similar to the multi-head attention mechanism to reduce the complexity.
We describe the similarities and differences between (dynamic) depth-wise convolution and local attention.
Figure 1 (c) illustrates the connectivity patterns and Table 1 shows the properties between local attention and depth-wise convolution , and various other modules.
Similarity.
Depth-wise convolution resembles local attention in sparse connectivity .
There are no connections across channels.
Each position is only connected to the positions in a small local window for each channel.
Difference.
One main difference lies in weight sharing : depth-wise convolution shares the connection weights across spatial positions, while local attention shares the weights across channels or within each group of channels.
Local attention uses proper weight sharing across channels to get better performance.
Depth-wise convolution beneﬁts from the weight sharing across positions to reduce the parameter complexity and increase the network capability.
The second difference is that the connection weights for depth-wise convolution are static and learned as model parameters, while the connection weights for local attention are dynamic and predicted from each instance.
The dynamic variants of depth-wise convolution also beneﬁt from the dynamic weight.
[Table]
One more difference lies in window representation.
Local attention represents the positions in a window by utilizing a set form with spatial-order information lost.
It explores the spatial-order information implicitly using the positional embedding or explicitly using the learned so-called relative positional embedding.
Depth-wise convolution exploits a vector form: aggregate the representations within a local window with the weights indexed by the relative position (see Equation 6); keep spatial correspondence between the positions for different windows, thus exploring the spatial-order information explicitly.
E XPERIMENTAL S TUDY
We conduct empirical comparisons between local attention and depth-wise convolutions on three visual recognition tasks: ImageNet classiﬁcation, COCO object detection
[Table]
and ADE semantic segmentation.
We follow the structure of Swin Transformer to build the depth-wise convolutionbased networks.
We apply the same training and evaluation settings from Swin Transformer to our models.
In addition, we study the effects of weight sharing and dynamic weight in the two structures.
The results for large scale pre-training are given in the appendix.
3. A RCHITECTURES
We use the recently-developed Swin Transformer as the example of local attention-based networks and study the performance over the tiny and base networks: Swin-T and Swin-B, provided by the authors (Liu et al., 2021b)
We follow the tiny and base networks to build two depth-wise convolutionbased networks, DW-Conv.-T and DW-Conv.-B so that the overall architectures are the same, making the comparison fair.
We also build two dynamic versions, D-DW-Conv.
and I-D-DW-Conv., by predicting the dynamic weights as described in Section 2.4.
We simply replace local attention in Swin Transformer by depth-wise convolution of the same window size, where the pre- and postlinear projections over the values are replaced by 1 × 1 convolutions.
We adopt the convolutional network design pattern to append BN (Ioffe & Szegedy, 2015) and ReLU (Nair & Hinton, 2010) to the convolution.
The details are available in the Appendix.
In terms of parameter and computation complexity, the depth-wise convolution-based networks are lower (Table 2) because there are linear projections for keys and values in local attention.
3. D ATASETS AND I MPLEMENTATION D ETAILS
ImageNet classiﬁcation.
The ImageNet-1K recognition dataset (Deng et al., 2009) contains 1 .
28 M training images and 50 K validation images with totally 1,000 classes.
We use the exactly-same training setting as Swin Transformer (Liu et al., 2021b).
The AdamW (Loshchilov & Hutter, 2019) optimizer for 300 epochs is adopted, with a cosine decay learning rate scheduler and 20 epochs of linear warm-up.
The weight decay is 0 . 05 , and the initial learning rate is 0 .
The augmentation and regularization strategies include RandAugment (Cubuk et al., 2020), Mixup (Zhang et al., 2018a),
CutMix (Yun et al., 2019), stochastic depth (Huang et al., 2016), etc.
COCO object detection.
The COCO 2017 dataset (Lin et al., 2014) contains 118 K training and 5 K validation images.
We follow Swin Transformer to adopt Cascade Mask R-CNN (Cai & Vasconcelos, 2019) for comparing backbones.
We use the training and test settings from Swin Transformer: multi-scale training - resizing the input such that the shorter side is between 480 and 800 and the longer side is at most 1333 ; AdamW optimizer with the initial learning rate 0 . 0001 ; weight decay0 .
05 ; batch size - 16 ; and epochs - 36 .
ADE semantic segmentation.
The ADE20K (Zhou et al., 2017) dataset contains 25 K images, 20 K for training, 2 K for validation, and 3 K for testing, with 150 semantic categories.
The same setting
[Table]
as Swin Transformer (Liu et al., 2021b) is adopted.
UPerNet (Xiao et al., 2018) is used as the segmentation framework.
Details are provided in the Appendix.
3. R ESULTS
ImageNet classiﬁcation.
The comparison for ImageNet classiﬁcation is given in Table 2.
One can see that the local attention-based networks, Swin Transformer, and the depth-wise convolutionbased networks, perform on par (with a slight difference of 0 . 1 ) in terms of top- 1 accuracy and real accuracy (Beyer et al., 2020) for both tiny and base models.
In the tiny model case, the two dynamic depth-wise convolution-based networks perform higher.
In particular, the depth-wise convolutionbased networks are more efﬁcient in parameters and computation complexities.
In the tiny model case, the parameters and computation complexities are reduced by 14 . 2% and 15 .
5% , respectively.
Similarly, in the base model case, the two costs are reduced by 15 . 9% and 16 .
2% , respectively.
The homogeneous dynamic variant takes more parameters but with almost the same complexity efﬁciency, and the inhomogeneous dynamic variant take advantage of weight sharing across channels that reduce the model parameters.
COCO object detection.
The comparisons between local attention (Swin Transformer), depth-wise convolution, and two versions of dynamic depth-wise convolution are shown in Table 3.
Depth-wise convolution performs a little lower than local attention, and dynamic depth-wise convolution performs better than the static version and on par with local attention.
ADE semantic Segmentation.
The comparisons of single scale testing on ADE semantic segmentation are shown in Table 3.
In the tiny model case, (dynamic) depth-wise convolution is ~ 1 . 0% higher than local attention.
In the base model case, the performances are similar 3 .
score: [Table]
[Table]
3. E MPIRICAL A NALYSIS
Local and channel-separable connection has been shown to be helpful for visual recognition.
The empirical results in Table 2, e.g., local attention performs better than global attention (local connection) and depth-wise convolution performs better than convolution (channel-separable connection), also verify it.
In the following, we present empirical results for weight sharing and dynamic weight by taking the tiny models as examples.
Weight sharing.
We study how the performance is affected by the number of channels in each group across which the weights are shared (the numbers of attention heads at each stage are accordingly changed) for local attention and local MLP (learn the weights in each window as model parameters and not shared across windows).
Figure 2 shows the effect for (a) local MLP - static weights, and (b) local attention - dynamic weights.
One can see that for local attention, too many channels and too few channels in each group perform similarly, but do not lead to the best.
For local MLP, weight sharing signiﬁcantly reduces model parameters.
These indicate proper weight sharing across channels is helpful for both local attention and local MLP.
We further study the effect of combining the weight sharing pattern for local MLP and depth-wise convolution.
For local MLP, Weight sharing across positions means the connection weight is shared for different spatial blocks in local MLP.
For convolution, the scheme of sharing weights across channels is similar to the multi-head manner in local attention.
The results in Table 4 suggest that: (i) for local MLP, sharing weight across channels reduces the model parameters and sharing across spatial blocks do not have big impact; (ii) For depth-wise convolution, sharing weight across channels does not have big impact, but sharing weight across positions signiﬁcantly increase the performance.
The window sampling scheme for local MLP and depth-wise convolution is different: local MLP sparsely samples the windows using the way in Swin Transformer, for reducing the high memory cost, and depth-wise convolution densely sample the windows.
Weight sharing across positions in local
MLP is insufﬁcient for learning translation-equivalent representation, explaining why local MLP with weight sharing across both channels and positions performs lower than depth-wise convolution with additional weight sharing across channels.
Dynamic weight.
We study how dynamic weight in local attention affects performance.
As seen from Table 2, local MLP achieves, the static version, 80 .
3% and 82 .
2% for tiny and base models, lower than Swin, the dynamic version, 81 .
3% and 83 .
This implies that dynamic weight is helpful.
The improvements from dynamic weight are also observed for depth-wise convolution (Table 2).
We further study the effects of the attention scheme and the linear-projection scheme for dynamic weight computation.
The observations from in Table 5 include: the attention mechanism for shifted and sliding window sampling performs similarly; the inhomogeneous dynamic weight computation way is better than the attention mechanism ( 81 . 8 vs 81 . 4 ).
We think that the reasons for the latter observation include: for the attention mechanism the representation is only block translation equivalent other than any translation equivalent; the linear projection-based dynamic weight scheme
[Figure]
[Table]
(vector representation for the window) learns better weights than the attention-based scheme (set representation for the window).
We also observe that such inﬂuence is eliminated for large models and detection tasks.
Set representation.
Local attention represents the positions in a window as a set with the spatialorder information lost.
Swin Transformer learns relative positional embeddings where the positions in a window are actually described as a vector keeping the spatial-order information.
It is reported in (Liu et al., 2021b) that removing the relative positional embeddings leads to a 1 . 2% accuracy drop, indicating the spatial-order information is important.
Concurrent works.
We give the comparison between inhomogeneous dynamic depth-wise convolution (I-D-DW Conv.) and concurrent local attention-based works (Chu et al., 2021a;
Wang et al., 2021a; Huang et al., 2021; Xu et al., 2021) in Table 6.
We follow Shufﬂe Transformer and add an extra DW Conv.
before FFN in I-D-DW Conv, and the performance is improved by 0 .
The performance is on par with these concurrent works except the Twins-SVT (81.9%, 2.9G) which uses interleaved attention and additional depth-wise convolutions.
R ELATED W ORK
Sparse connectivity.
Sparse connection across channels is widely explored for removing redundancy in the channel domain.
The typical schemes are depth-wise convolution adopted by MobileNet (Howard et al., 2017; Sandler et al., 2018), ShufﬂeNetV2 (Ma et al., 2018) and IGCv3 (Sun et al., 2018), and group convolution adopted by ResNeXt (Xie et al., 2017), merge-and-run (Zhao et al., 2018), ShufﬂeNetV1 (Zhang et al., 2018b), and IGC (Zhang et al., 2017).
The self-attention unit 4 in Vision Transformer, its variants (Chen et al., 2020; Chu et al., 2021b;
Dosovitskiy et al., 2021; Han et al., 2021; Heo et al., 2021; Li et al., 2021; Liu et al., 2021b; Pan et al., 2021; Touvron et al., 2020; Vaswani et al., 2021; Wang et al., 2021b; Wu et al., 2021; Yuan et al., 2021a;b; Zhang et al., 2021;
Zhao et al., 2020;
Zhou et al., 2021), and the spatial information fusion unit (e.g., token-mixer in MLP-Mixer (Tolstikhin et al., 2021) and ResMLP (Touvron et al., 2021)) have no connections across channels.
1 × 1 (point-wise) convolution (in ShufﬂeNetV2 (Ma et al., 2018), MobileNet (Howard et al., 2017;
Sandler et al., 2018), IGC (Zhang et al., 2017), ViT (Dosovitskiy et al., 2021), local ViT (Liu et al., 2021b; Vaswani et al., 2021), MLP-Mixer (Tolstikhin et al., 2021), ResMLP (Touvron et al., 2021)) has no connections across spatial positions.
The convolutions with other kernel sizes and local attention (Zhao et al., 2020; Liu et al., 2021b; Vaswani et al., 2021) have connections between each position and the positions within a small local window, respectively.
[Table]
Weight sharing.
Weight sharing across spatial positions is mainly used in convolution, including normal convolution, depth-wise convolution and point-wise convolution.
Weight sharing across channels is adopted in the attention unit (Vaswani et al., 2017), its variants (Chu et al., 2021a;b;
Dosovitskiy et al., 2021;
Li et al., 2021; Liu et al., 2021b; Touvron et al., 2020; Vaswani et al., 2021; Wang et al., 2021b; Wu et al., 2021; Yuan et al., 2021b), and token-mixer MLP in MLPmixer (Tolstikhin et al., 2021) and ResMLP (Touvron et al., 2021).
Dynamic weight.
Predicting the connection weights is widely studied in convolutional networks.
There are basically two types.
One is to learn homogeneous connection weights, e.g., SENet (Hu et al., 2018b), dynamic convolution (Jia et al., 2016).
The other is to learn the weights for each region or each position (GENet (Hu et al., 2018a),
Lite-HRNet (Yu et al., 2021), Involution (Li et al., 2021)).
The attention unit in ViT or local ViT learns dynamic connection weights for each position.
Networks built with depth-wise separable convolutions.
There are many networks built upon depth-wise separable convolution or its variants, such as MobileNet (Howard et al., 2017; Sandler et al., 2018), ShufﬂeNet (Ma et al., 2018), IGC (Zhang et al., 2017), Xception (Chollet, 2017), and
EfﬁcientNet (Tan & Le, 2019; 2021).
In this paper, our goal is to connect dynamic depth-wise convolution with local attention.
Convolution vs Transformer.
The study in (Cordonnier et al., 2020) shows that a multi-head selfattention layer can simulate a convolutional layer by developing additional carefully-designed relative positional embeddings with the attention part dropped .
Differently, we connect (dynamic) depth-wise convolution and local self-attention by connecting the attention weights for self-attention and the dynamic weights for convolution (as well as studying weight sharing).
In (Andreoli, 2019), the mathematical connection (in terms of the tensor form) between convolution and attention is presented.
The opinion that convolution and attention are essentially about the model complexity control is similar to ours, and we make the detailed analysis and report empirical studies.
The concurrently-developed work in NLP (Tay et al., 2021) empirically compares lightweight depthwise convolution (Wu et al., 2019) to Transformer for NLP tasks, and reaches a conclusion similar to ours for vision tasks: convolution and Transformer obtain on-par results.
Differently, we attempt to understand why they perform on par from three perspectives: sparse connectivity, weight sharing and dynamic weight, and discuss their similarities and differences.
C ONCLUSION
The connections between local attention and dynamic depth-wise convolution are summarized as follows (i)
Same with dynamic depth-wise convolution, local attention beneﬁts from two sparse connectivity forms: local connection and no connection across channels.
(ii) Weight sharing across channels in local attention is helpful for reducing the parameter (attention weight) complexity and slightly boosting the performance, and weight sharing across positions in depth-wise convolution is helpful for reducing the parameter complexity and learning translation-equivalent representations and thus boosting the performance.
(iii)
The attention-based dynamic weight computation for local attention is beneﬁcial for learning image-dependent weights and block-translation equivalent representations, and the linear projection-based dynamic weight computation for (in)homogeneous dynamic depth-wise convolution is beneﬁcial for learning image-dependent weights.
Inhomogeneous dynamic depth-wise convolution is superior over local attention for ImageNet classiﬁcation and segmentation in the case of tiny models, and on par for larger models and detection tasks.
In addition, the better downstream performance for local attention and depth-wise convolution stems from the larger kernel size ( 7 × 7 vs 3 × 3 ), which is also observed in Yuan et al.
(2021d).
A PPENDIX A R ELATION G RAPH
We present a relation graph in Figure 3 to describe the relation between convolution, depth-wise separable convolution (depth-wise convolution + 1 × 1 convolution), Vision Transformer, Local
Vision Transformer, as well as multilayer perceptron (MLP), Separable MLP in terms of sparse connectivity, weight sharing, and dynamic weight.
Table
Multilayer perceptron (MLP) is a fully-connected layer: each neuron (an element at each position and each channel) in one layer is connected with all the neurons in the previous layer 5 .
Convolution and separable MLP are sparse versions of MLP.
The connection weights can be formulated as a tensor (e.g., 3 D tensor, two dimension for space and one dimension for channel) and the low-rank approximation of the tensor can be used to regularize the MLP.
Convolution is a locally-connected layer, formed by connecting each neuron to the neurons in a small local window with the weights shared across the spatial positions.
Depth-wise separable convolution is formed by decomposing the convolution into two components: one is point-wise 1 × 1 convolution, mixing the information across channels, and the other is depth-wise convolution, mixing the spatial information.
Other variants of convolution, such as bottleneck, multi-scale convolution or pyramid, can be regarded as low-rank variants.
Separable MLP (e.g., MLP-Mixer and ResMLP) reshapes the 3 D tensor into a 2 D format with the spatial dimension and channel dimension.
Separable MLP consists of two sparse MLP along the two dimensions separately, which are formed by separating the input neurons into groups.
Regarding channel sparsity, the neurons in the same channel form a group, and an MLP is performed over each group with the MLP parameters shared across groups, forming the ﬁrst sparse MLP (spatial/token mixing).
A similar process is done by viewing the neurons at the same position into a group, forming the second sparse MLP (channel mixing).
Vision Transformer is a dynamic version of separable MLP.
The weights in the ﬁrst sparse MLP (spatial/token mixing) are dynamically predicted from each instance.
Local Vision Transformer is a spatially-sparser version of Vision Transformer: each output neuron is connected to the input neurons in a local window.
PVT (Wang et al., 2021b) is a pyramid (spatial sampling/ low-rank) variant of
Vision Transformer.
Depth-wise separable convolution can also be regarded as a spatially-sparser version of separable MLP.
In the ﬁrst sparse MLP (spatial/token mixing), each output neuron is only dependent on the input neurons in a local window, forming depth-wise convolution.
In addition, the connection weights are shared across spatial positions, instead of across channels.
B M ATRIX F ORM E XPLANATION
We use the matrix form to explain sparsity connectivity in various layers and how they are obtained by modifying the MLP.
MLP.
The term MLP, Multilayer Perceptron, is used ambiguously, sometimes loosely to any feedforward neural network.
We adopt one of the common deﬁnitions, and use it to refer to fully-connected layers.
Our discussion is based on a single fully-connected layer, and can be easily generalized to two or more fully-connected layers.
One major component, except the nonlinear units and others, is a linear transformation:
[Equation]
where x represents the input neurons, y represents the output neurons, and W represents the connection weights, e.g., W ∈ R NC × NC , where N is the number of positions, and C is the number of channels.
Convolution.
Considering the 1 D case with a single channel (the 2 D case is similar), the connection weight matrix W ∈ R N × N is in the following sparse form, also known as the Toeplitz matrix
(We r e g u l a r
i z a t i o n
PyramidMSConv.
L o c a l i t y S e p .
D i m .
S e p .
L o c a li t y
S e p .
D i m .
S e p .
Sp a t i a l
S p a t i a l L R
C h a nn e l L R
ViT
MLP
Conv.
Sparse Connection Dynamic Weight
Low-Rank
Bottleneck
DW-S Conv.
Local ViT
Sep. MLP
LR MLP
D i m .
L R
D y n a m
i
c
PVT
L o c a li t y S e p .
Sp a t i a l L
R
Dynamic Local-S MLP
InhomogeneousVec.
Atten.
DynamicDW-SConv.
V e c .
A t t e n .
weight.
† Spatial-mixing MLP (channel-separable MLP) corresponds to token-mixer
MLP.
‡ 1 × 1 Conv. is also called point-wise (spatial-separable) MLP.
(cid:91)
The weights might be shared within each group of channels.
Please refer to Figure 1 for the connectivity pattern illustration.
Sparse between positions
Sparse between
Weight sharing across
Dynamic
[Table]
weight
[Table]
(cid:51) (cid:51) (cid:51) (cid:91)
[Table]
attention (cid:51) (cid:51) (cid:51) (cid:91) (cid:51)
[Table]
(cid:51) (cid:51) (cid:51)
[Table]
(cid:51) (cid:51) (cid:51) (cid:51)
[Table]
(cid:51) (cid:51)
[Table]
(cid:51) (cid:51) (cid:91) (cid:51)
[Table]
(cid:51) (cid:51)
[Table]
(cid:51) (cid:51) use the window size 3 as an example):
W =   aa 0 · · · aaaa0 · · ·  ... a  0 · · · aa  .
For the C -channel case, we organize the input into a vector channel by channel: [ x (cid:62) 1 x (cid:62) 2 . . .
x (cid:62) C ] (cid:62) , and accordingly the connection weight matrix channel by channel for the c o th output channel,
W c o =
[ W c o 1 W c
o 2 . . .
W c o C ] (the form of W c
o i is the same as Equation 10).
The whole form could be written as
[Equation]
Sep. MLP.
Sep. MLP, e.g., ResMLP and MLP-Mixer, is formed with two kinds of block-sparse matrices: one for channel-mixing and the other for spatial-mixing.
In the case that the input is organized channel by channel (the neurons in each channel form a group), x = [ x (cid:62) 1 x (cid:62) 2 . . .
x (cid:62) C ] (cid:62) , the connection weight matrix is in a block-sparse form: [Equation]
[Equation]
where the block matrices W c ∈ R N × N are shared across all the channels, and the sharing pattern can be modiﬁed to share weights within each group of channels.
The input can be reshaped position by position (the neurons at each position forms a group): x = [ x (cid:62) 1 x (cid:62) 2 . . .
x (cid:62) N ] (cid:62) , and similarly one more connection weight matrix can be formulated in a blocksparse form (it is essentially a 1 × 1 convolution, W p ∈ R C × C ):
[Equation]
The forms of block-sparsity are studied in interleaved group convolutions (Zhang et al., 2017) without sharing the weights across groups.
Sep. MLP can also be regarded as using Kronecker product to approximate the connection matrix,
[Equation]
Here, [Equation] =
[Equation]
(cid:62)
[Equation]
W p .
and ⊗ is the Kronecker product operator.
mat( x ) reshapes the vector x in a 2 D matrix form, while vec( x ) reshapes the 2 D matrix into a vector form.
In Sep.
MLP, the 2 D matrix, mat( x ) ∈ R C × N , is organized so that each row corresponds to one channel and each column corresponds to one spatial position.
CCNet (Huang et al., 2019b) and interlaced self-attention (Huang et al., 2019a) use Kronecker product to approximate the spatial connection: the former reshapes the vector in a 2 D matrix form along the x and y axes, and the latter reshapes the vector windows by windows.
Vision Transformer (ViT).
The matrix form is similar to Sep. MLP.
The difference is that the matrix
W c is predicted from each image instance.
The weight prediction manner in ViT has a beneﬁt: handle an arbitrary number of input neurons.
Depth-wise separable convolution.
There are two basic components: depth-wise convolution, and 1 × 1 convolution that is the same as channel-mixing MLP in Sep. MLP.
Depth-wise convolution can be written in the matrix form:
[Equation]
[Equation] where the form of W cc is the same as Equation 10.
Local ViT.
In the non-overlapping window partition case, local ViT simply repeats ViT over each window separately with the linear projections, applied to keys, values, and queries, shared across windows.
In the overlapping case, the form is a little complicated, but the intuition is the same.
In the extreme case, the partition is the same as convolution, and the form is as the following:
[Equation]

  
[Equation]
(16) where the dynamic weight matrix W d is like the form below:
[Equation]
Low-rank MLP.
Low-rank MLP approximates the connection weight matrix W ∈ R D
o × D i in
Equation 9 using the product of two low-rank matrix:
[Equation]
(18) where r is a number smaller than D i and D o
Pyramid.
The downsampling process in the pyramid networks can be regarded as spatial low rank: W ( ∈ R NC × NC ) → W (cid:48) ( ∈ R N (cid:48)
C × N (cid:48) C ) , where N (cid:48) is equal to N 4 in the case that the resolution is reduced by 12 .
If the numbers of input and output channels are different, it becomes
W (
[Equation]
(cid:48)
[Equation]
Multi-scale parallel convolution.
Multi-scale parallel convolution used in HRNet (Wang et al., 2020; Sun et al., 2019) can also be regarded as spatial low rank.
Consider the case with four scales, multi-scale parallel convolution can be formed as as the following,
[Equation]
) where C 1 , C 2 , C 3 , and C 4 are the numbers of the channels in four resolutions.
C L OCAL A TTENTION VS C ONVOLUTION : D YNAMIC W EIGHTS
We take the 1 D case with the window size 2 K + 1 as an example to illustrate the dynamic weight prediction manner.
Let { x
i − K , . . .
, x i , . . .
, x i + k } correspond to the (2 K + 1) positions in the i th window, and { w i − K , . .
w i , . .
. , w i + K } be the corresponding dynamic weights for updating the representation of the i th (center) position.
The discussion can be easily extended to multiple weights for each positions, like the M -head attention and updating the representations for other positions.
Inhomogeneous dynamic convolution.
We use the case using only a single linear projection to illustrate inhomogeneous dynamic convolution.
The properties we will discuss are similar for more linear projections.
The dynamic weights are predicted as the following:
[Equation]
It can be seen that dynamic convolution learns the weights for each position through the parameters that are different for different positions, e.g., θ k corresponds to w i + k .
It regards the positions in the window as the vector form, keeping the spatial order information.
Dot-product attention.
The dot-product attention mechanism in the single-head case predicts the weights as the following 6 :
[Equation]
Dot-product attention uses the same parameters P (cid:62) k P q for all the positions.
The weight depends on the features at the same position, e.g., w i − k corresponds to x i − k .
It in some sense regards the positions in the window as a set form, losing the spatial order information.
We rewrite it as the following
[Equation]
from which we can see that the parameters Θ d is dynamically predicted.
In other words, dot-product attention can be regarded as a two-level dynamic scheme.
Relative position embeddings is equivalent to adding static weights that keeps the spatial order information:
[Equation]
A straightforward variant is a combination of the static Θ and the dynamic Θ d :
[Equation]
[Equation]
Convolutional attention.
We introduce a convolutional attention framework so that it enjoys the beneﬁts of dynamic convolution and dot-product attention: keep the spatial order information and two-level dynamic weight prediction
The post-convolutional attention mechanism left-multiplies a matrix (with the kernel size being 3 ):
[Equation]

[Equation] [Equation]
This can be reviewed as a variant of relative positional embeddings (Equation 23).
In the simpliﬁed case that the left matrix is diagonal, it can be regarded as the product version of relative positional embeddings (Equation 23 is an addition version).
We can perform a convolution with the kernel size being 3 , the kernel weights shared across channels (it is also ﬁne not to share weights), and then do dot-product attention.
This is called pre-convolutional attention: perform convolutions on the representations.
The two processes are can be written as follows (omit BN and ReLU that follow the convolution),   w
[Equation]
 =   a
[Equation]
a
[Equation]
a [Equation] · · ·    a
[Equation]
a· · ·   ...
· · · aa    · · · aa
[Equation]
a
[Equation]

  
[Equation] [Equation]
x
[Equation]

[Equation]
a
[Equation]
a
[Equation]
a
[Equation]
  .
It can be generalized to using normal convolution:
[Equation]
 
[Equation]


[Equation]
Here, C ’ is a ( 2 K + 1 )-row
matrix and can be easily derived from the convolutional kernel C 3 .
The (2 K + 1) weights, { w i − 1 , w i , w i +1 } , correspond to the (2 K + 1) rows in C , respectively.
This means that the three positions are differentiated and the same position in each window corresponds to the same row.
This explains why the positional embeddings are not necessary when convolutions are adopted (Wu et al., 2021).
Using different pairs ( W q , W k ) leads to more weights for each position, e.g., M pairs correspond to M -head attention.
D A RCHITECTURE D ETAILS
Overall structures.
Following local vision transformer, Swin Transformer (Liu et al., 2021b), we build two depth-wise convolution-based networks, namely DW-Conv.-T and DW-Conv.-B. The corresponding dynamic versions are D-DW-Conv.-T, D-DW-Conv.-B, I-D-DW-Conv.-T, and
I-DDW-Conv.-B.
The depth-wise convolution-based networks follow the overall structure of Swin
Transformer.
We replace local self attention by depth-wise convolution with the same window size.
We use batch normalization (Ioffe & Szegedy, 2015) and ReLU (Nair & Hinton, 2010) instead of layer normalization (Ba et al., 2016) in the convolution blocks.
[Table]
Table 8 shows the architecture details of Swin Transformer and depth-wise convolution-based networks for the tiny model.
Normalizations are performed within the residual block, same as Swin
Transformer.
The base model is similarly built by following Swin Transformer to change the number of channels and the depth of the third stage.
Dynamic depth-wise convolution.
Dynamic depth-wise convolution generates the connection weights according to the instance.
As described in Section 2.4, for the homogeneous version, we conduct the global average pooling operation to get a vector, and adopt two linear projections: the ﬁrst one reduces the dimension by 1 / 4 , followed by BN and ReLU, and then generate the kernel weights and shared for all spatial positions.
Unlike SENet (Hu et al., 2018b), we currently do not use the
Sigmoid activation function for generating the weights.
For the inhomogeneous version, we generate unshared dynamic weight for each spatial position using the corresponding feature.
The connection weights are shared across channels to reduce the model parameters and computation complexity.
Speciﬁcally, we share 3 and 4 channels in each group of channels for tiny and base models.
Thus the number of model parameters and computation complexity are similar to Swin Transformer.
[Table] [Table]
Channel and spatial separable MLP, spatial separable MLP = point
[Table]
wise 1 × 1 convolution
Mixer-B/16 (Tolstikhin et al., 2021)
[Table]
[Table]
Mixer-L/
(Tolstikhin et al., 2021)
[Table]
[Table]
ResMLP-12 (Touvron et al., 2021)
[Table]
ResMLP-24 (Touvron et al., 2021)
[Table]
-36 (Touvron et al., 2021)
[Table]
-Ti (Liu et al., 2021a)
[Table]
gMLP-S (Liu et al., 2021a)
[Table]
gMLP-B (Liu et al., 2021a)
[Table]
Global attention: dynamic channel separable MLP + spatial separable MLP
ViT-B/16 (Dosovitskiy et al., 2021)
[Table]
ViT-L/16 (Dosovitskiy et al., 2021)
[Table]
[Table]
DeiT-S (Touvron et al., 2020)
[Table]
DeiT-B (Touvron et al., 2020)
[Table]
DeiT-B (Touvron et al., 2020)
[Table]
E S ETTING D ETAILS
ImageNet pretraining.
We use the identical training setting with Swin Transformer in ImageNet pretraining for fair comparison.
The default input size is 224 × 224 .
The AdamW optimizer (Loshchilov & Hutter, 2019), with the initial learning rate 0 .
001 and the weight decay 0 .
05 , is used for 300 epochs.
The learning rate is scheduled by a cosine decay schema and warm-up with linear schema for the ﬁrst 20 epochs.
We train the model on 8 GPUs with the total batch size 1024.
The augmentation and regularization strategies are same as Swin Transformer, which includes RandAugment (Cubuk et al., 2020), Mixup (Zhang et al., 2018a), CutMix (Yun et al., 2019), random erasing (Zhong et al., 2020) and stochastic depth (Huang et al., 2016).
The stochastic depth rate is employed as 0 . 2 and 0 .
5 for the tiny and base models, respectively, the same as Swin Transformer.
COCO object detection.
We follow Swin Transformer to adopt Cascade Mask R-CNN (Cai &
Vasconcelos, 2019) for comparing backbones.
We use the training and test settings from Swin
Transformer: multi-scale training - resizing the input such that the shorter side is between 480 and 800 and the longer side is at most 1333; AdamW optimizer with the initial learning rate 0.0001; weight decay - 0.05; batch size - 16; and epochs - 36.
ADE semantic segmentation.
Following Swin Transformer, we use UPerNet (Xiao et al., 2018) as the segmentation framework.
We use the same setting as the Swin Transformer: the AdamW optimizer with initial learning rate 0.00006; weight decay 0.01; linear learning rate decay; 160, iterations with warm-up for 1500 iterations; 8 GPUs with mini-batch 2 per GPU.
We use the same data augmentation as Swin Transformer based on MMSegmentation (Contributors, 2020).
The experimental results are reported as single scale testing.
Static version of Swin Transformer - Local MLP.
We remove the linear projections applied to keys and queries, accordingly dot production and softmax normalization.
The connection weights (corresponding to attention weights in the dynamic version) are set as static model parameters which are learnt during the training and shared for all the images.
Retraining on 384 × 384 .
We retrain the depth-wise convolution-based network on the ImageNet dataset with 384 × 384 input images from the model trained with 224 × 224 images.
We use learning rate 10 − 5 , weight decay 10 − 8 and stochastic depth ratio 0 .
1 for 30 epochs for both 7 × 7 and 12 ×windows.
F A DDITIONAL E XPERIMENTS AND A NALYSIS
More results on ImageNet classiﬁcation.
We give more experimental results with different sparse connection strategies, as shown in Table 9.
These results also verify that locality-based sparsity pattern (adopted in depth-wise convolution and local attention) besides sparsity between channels/spatial positions still facilitates the network training for ImageNet-1K.
Results on large scale pre-training.
Transformers (Liu et al., 2021b; Dosovitskiy et al., 2021) show higher performance compared with the previous convolutional networks with large scale pretraining.
We further study the performance on ImageNet-22K pre-training.
We ﬁrst train the model on ImageNet-22K dataset which has about 14.2 million images, and then ﬁne-tune the model on ImageNet-1K and downstream segmentation tasks. The ﬁne-tuning results in Table 10 indicate the (dynamic) depth-wise convolution based networks could get the performance comparable to Swin transformer on large scale pre-training. Cooperating with different normalization functions.
Transformers usually use the layer normalization to stabilize the training, while convolutional architectures adopt batch normalization.
We verify different combinations of backbones (Swin and DW Conv.) and normalization functions.
The popular used layer normalization (LN), batch normalization (BN), and the dynamic version of batch
[Table] [Table] [Table] normalization - centering calibrated batch normalization (Gao et al., 2021) (CC. BN) are veriﬁed in the experiments.
Table 11 shows the results on ImageNet classiﬁcation [Table]
Depth-wise convolution with other architectures.
We conduct experiments on other local attention designs, such as SVT (Chu et al., 2021a) and VOLO (Yuan et al., 2021c) whose implementations are publicly available.
SVT uses local self attention as a basic spatial feature fusion operation, while
VOLO proposes a new attention module named Vision Outlooker.
We replace the local self attention with depth-wise convolution in SVT same as the paper, and replace Vision Outlooker with 7 × 7 local self attention and 7 × 7 depth-wise convolution, respectively.
The remaining structures are unchanged and the same training setting is used as the original papers.
The experimental results are shown in
Tab 12 and the observations are the same as the Swin Transformer design.
Retraining on 384 × 384 images.
Similar to (Liu et al., 2021b), we study the performance of ﬁnetuning the models: ﬁrst learn with 224 × 224 images, then ﬁne-tune on large images of 384 × 384 .
We study two cases: (1) keep the window size 7 × 7 unchanged; and (2) upsample the kernel weights from 7 × 7 to 12 × 12 as done in (Liu et al., 2021b) for upsampling the relative positional embeddings.
The results are in Table 13 7 .
In the case of keeping the window size 7 × 7 unchanged, depth-wise convolution (DW) performs better.
When using a larger window size 12 × 12 , depth-wise convolution performs worse than 7 × 7 .
We suspect that this is because upsampling the kernel weights is not a good starting for ﬁne-tuning.
In Swin Transformer, using a larger window size improves the performance.
We believe that this is because the local attention mechanism is suitable for variable window sizes.
Cooperating with SE.
Squeeze-and-excitation (Hu et al., 2018b) (SE) is a parameter- and computation-efﬁcient dynamic module, initially designed for improving the ResNet performance.
The results in Table 14 show that depth-wise convolution (DW), a static module, beneﬁts from the SE module, while Swin Transformer, already a dynamic module, does not beneﬁt from dynamic module
SE.
The reason is still unclear, and might lie in the optimization.
G P OTENTIAL S TUDIES
Complexity balance between point-wise ( 1 × 1 ) convolution and depth-wise (spatial) convolution.
Depth-wise convolution takes only about 2% computation in the depth-wise convolution-based architecture.
The major computation complexity comes from 1 × 1 convolutions.
The solutions to [Table] [Table] this issue could be: group 1 × 1 convolution studied in IGC (Zhang et al., 2017; Sun et al., 2018), and channel-wise weighting (like SENet) studied in Lite-HRNet (Yu et al., 2021) and EfﬁcientNet (Tan &
Le, 2019; 2021), or simply add more depth-wise (spatial) convolutions.
Attention weights as channel maps.
Attention weights in attention can be regarded as channel maps.
The operations, such as convolution or simple weighting, can be applied to the attention weights.
The resT approach (Zhang & Yang, 2021) performs 1 × 1 convolutions over the attention weight maps.
Dynamic weights.
In Swin Transformer and our developed dynamic depth-wise convolution networks, only the spatial part, attention and depth-wise convolution, explores dynamic weights.
LiteHRNet instead studies dynamic weight for point-wise ( 1 × 1 ) convolution.
It is interesting to explore dynamic weight for both parts.
Convolution-style MLP weights.
The weights of the spatial-mixing MLP in MLP-Mixer and
ResMLP could be modiﬁed in the convolution-like style with more weights (some like the relative position embeddings used in local attention, larger than the image window size) so that it could be extended to larger images and downstream tasks with different image sizes.