On the Relationship between Self-Attention and Convolutional Layers

  • 2019-11-08 23:48:38
  • Jean-Baptiste Cordonnier, Andreas Loukas, Martin Jaggi
  • 29


Recent trends of incorporating attention mechanisms in vision have ledresearchers to reconsider the supremacy of convolutional layers as a primarybuilding block. Beyond helping CNNs to handle long-range dependencies,Ramachandran et al. (2019) showed that attention can completely replaceconvolution and achieve state-of-the-art performance on vision tasks. Thisraises the question: do learned attention layers operate similarly toconvolutional layers? This work provides evidence that attention layers canperform convolution and, indeed, they often learn to do so in practice.Specifically, we prove that a multi-head self-attention layer with sufficientnumber of heads is at least as powerful as any convolutional layer. Ournumerical experiments then show that the phenomenon also occurs in practice,corroborating our analysis. Our code is publicly available.


Quick Read (beta)

On the Relationship between Self-Attention and Convolutional Layers

Jean-Baptiste Cordonnier, Andreas Loukas & Martin Jaggi
École Polytechnique Fédérale de Lausanne (EPFL)

Recent trends of incorporating attention mechanisms in vision have led researchers to reconsider the supremacy of convolutional layers as a primary building block. Beyond helping CNNs to handle long-range dependencies, Ramachandran et al. (2019) showed that attention can completely replace convolution and achieve state-of-the-art performance on vision tasks. This raises the question: do learned attention layers operate similarly to convolutional layers? This work provides evidence that attention layers can perform convolution and, indeed, they often learn to do so in practice. Specifically, we prove that a multi-head self-attention layer with sufficient number of heads is at least as expressive as any convolutional layer. Our numerical experiments then show that the phenomenon also occurs in practice, corroborating our analysis. Our code is publicly available11 1 https://github.com/epfml/attention-cnn/tree/arxiv-v1 .



On the Relationship between Self-Attention and Convolutional Layers

Jean-Baptiste Cordonnier, Andreas Loukas & Martin Jaggi
École Polytechnique Fédérale de Lausanne (EPFL)

1 Introduction

Recent advances in Natural Language Processing (NLP) are largely attributed to the rise of the transformer (Vaswani et al., 2017). Pre-trained to solve an unsupervised task on large corpora of text, transformer-based architectures, such as GPT-2 (Radford et al., 2018), BERT (Devlin et al., 2018) and Transformer-XL (Dai et al., 2019), seem to possess the capacity to learn the underlying structure of text and, as a consequence, to learn representations that generalize across tasks. The key difference between transformers and previous methods, such as recurrent neural networks (Hochreiter & Schmidhuber, 1997) and convolutional neural networks (CNN), is that the former can simultaneously attend to every word of their input sequence. This is made possible thanks to the attention mechanism—originally introduced in Neural Machine Translation to better handle long-range dependencies (Bahdanau et al., 2015). With self-attention in particular, the similarity of two words in a sequence is captured by an attention score measuring the distance of their representations. The representation of each word is then updated based on those words whose attention score is highest.

Inspired by its capacity to learn meaningful inter-dependencies between words, researchers have recently considered utilizing self-attention in vision tasks. Self-attention was first added to CNN by either using channel-based attention (Hu et al., 2018) or non-local relationships across the image (Wang et al., 2018). More recently, Bello et al. (2019) augmented CNNs by replacing some convolutional layers with self-attention layers, leading to improvements on image classification and object detection tasks. Interestingly, Ramachandran et al. (2019) noticed that, even though state-of-the art results are reached when attention and convolutional features are combined, under same computation and model size constraints, self-attention-only architectures also reach competitive image classification accuracy.

These findings raise the question, do self-attention layers process images in a similar manner to convolutional layers? From a theoretical perspective, one could argue that transfomers have the capacity to simulate any function—including a CNN. Indeed, Pérez et al. (2019) showed that a multi-layer attention-based architecture with additive positional encodings is Turing complete under some strong theoretical assumptions, such as unbounded precision arithmetic. Unfortunately, universality results do not reveal how a machine solves a task, only that it has the capacity to do so. Thus, the question of how self-attention layers actually process images remains open.


In this work, we put forth theoretical and empirical evidence that self-attention layers can (and do) learn to behave similar to convolutional layers:

  • I.

    From a theoretical perspective, we provide a constructive proof showing that self-attention layers can express any convolutional layers.

Specifically, we show that a single multi-head self-attention layer using relative positional encoding can be re-parametrized to express any convolutional layer. Our insights lead to a relative positional encoding, that we refer to as quadratic encoding, that is very efficient in terms of size.

  • II.

    Our experiments show that the first few layers of attention-only architectures (Ramachandran et al., 2019) do learn to attend on grid-like pattern around each query pixel, similar to our theoretical construction.

Strikingly, this behavior is confirmed both for our quadratic encoding, but also for relative encoding that is learned during training. Our results seem to suggest that localized convolution is the right inductive bias for the first few layers of an image classifying network. For deeper layers, on the other hand, long-range as well as horizontally-symmetric inter-dependencies become more relevant.

For reproducibility purposes, our code is publicly available on GitHub22 2 https://github.com/epfml/attention-cnn/tree/arxiv-v1 .

2 Background on Attention Mechanisms for Vision

We here recall the mathematical formulation of self-attention layers and emphasize the role of positional encodings.

2.1 The Multi-Head Self-Attention Layer

Let 𝑿T×D𝑖𝑛 be an input matrix consisting of T tokens in of D𝑖𝑛 dimensions each. While in NLP each token corresponds to a word in a sentence, the same formalism can be applied to any sequence of T discrete objects, e.g. pixels. A self-attention layer maps any query token t[T] from D𝑖𝑛 to D𝑜𝑢𝑡 dimensions as follows:

Self-Attention(𝑿)t,: :=softmax(𝑨t,:)𝑿𝑾𝑣𝑎𝑙, (1)

where we refer to the elements of the T×T matrix

𝑨 :=𝑿𝑾𝑞𝑟𝑦𝑾𝑘𝑒𝑦𝑿 (2)

as attention scores and the softmax output33 3 softmax(𝑨t,:)k=exp(𝑨t,k)/pexp(𝑨t,p) as attention probabilities. The layer is parametrized by a query matrix 𝑾𝑞𝑟𝑦D𝑖𝑛×Dk, a key matrix 𝑾𝑘𝑒𝑦D𝑖𝑛×Dk and a value matrix 𝑾𝑣𝑎𝑙D𝑖𝑛×D𝑜𝑢𝑡.For simplicity, we exclude any residual connections, batch normalization and constant factors.

A key property of the self-attention model described above is that it is equivariant to reordering, that is, it gives the same output independently of how the T input tokens are shuffled. This is problematic for cases we expect the order of things to matter. To alleviate the limitation, a positional encoding is learned for each token in the sequence (or pixel in an image), and added to the representation of the token itself before applying self-attention

𝑨 :=(𝑿+𝑷)𝑾𝑞𝑟𝑦𝑾𝑘𝑒𝑦(𝑿+𝑷), (3)

where 𝑷T×D𝑖𝑛 contains the embedding vectors for each position. More generally, 𝑷 may be substituted by any function that returns a vector representation of the position.

It has been found beneficial in practice to replicate this self-attention mechanism into multiple heads, each being able to focus on different parts of the input by using different query, key and value matrices. In multi-head self-attention, the output of the Nh heads of output dimension Dh are concatenated and projected to dimension D𝑜𝑢𝑡 as follows:

MHSA(𝑿):=concath[Nh][Self-Attentionh(𝑿)]𝑾𝑜𝑢𝑡+𝒃𝑜𝑢𝑡 (4)

and two new parameters are introduced: the projection matrix 𝑾𝑜𝑢𝑡NhDh×D𝑜𝑢𝑡 and a bias term 𝒃𝑜𝑢𝑡D𝑜𝑢𝑡.

2.2 Attention for Images

Convolutional layers are the de facto choice for building neural networks that operate on images. We recall that, given an image tensor 𝑿W×H×D𝑖𝑛 of width W, height H and D𝑖𝑛 channels, the output of a convolutional layer for pixel (i,j) is given by

Conv(𝑿)i,j,::=(δ1,δ2)ΔΔK𝑾δ1,δ2,:,:𝑿i+δ1,j+δ2,:+𝒃, (5)

where 𝑾 is the K×K×D𝑜𝑢𝑡×D𝑖𝑛 weight tensor 44 4 To simplify notation, we index the first two dimensions of the tensor from -K/2 to K/2., 𝒃D𝑜𝑢𝑡 is the bias vector and the set


contains all possible shifts appearing when convolving the image with a K×K kernel.

In the following, we review how self-attention can be adapted from 1D sequences to images.

With images, rather than tokens, we have query and key pixels 𝒒,𝒌[W]×[H]. Accordingly, the input is a tensor 𝑿 of dimension W×H×D𝑖𝑛 and each attention score associates a query and a key pixel.

To keep the formulas consistent with the 1D case, we abuse notation and slice tensors by using a 2D index vector: if 𝒑=(i,j), we write 𝑿𝒑,: and 𝑨𝒑,: to mean 𝑿i,j,: and 𝑨i,j,:,:, respectively. With this notation in place, the multi-head self attention layer output at pixel 𝒒 can be expressed as follows:

Self-Attention(𝑿)𝒒,: =𝒌softmax(𝑨𝒒,:)𝒌𝑿𝒌,:𝑾𝑣𝑎𝑙 (6)

and accordingly for the multi-head case.

2.3 Positional Encoding for Images

There are two types of positional encoding that has been used in transformer-based architectures: the absolute and relative encoding (see also creftypecap 1 in the Appendix).

With absolute encodings, a (fixed or learned) vector 𝑷𝒑,: is assigned to each pixel 𝒑. The computation of the attention scores we saw in creftype 2 can then be decomposed as follows:

𝑨𝒒,𝒌abs =(𝑿𝒒,:+𝑷𝒒,:)𝑾𝑞𝑟𝑦𝑾𝑘𝑒𝑦(𝑿𝒌,:+𝑷𝒌,:)
=𝑿𝒒,:𝑾𝑞𝑟𝑦𝑾𝑘𝑒𝑦𝑿𝒌,:+𝑿𝒒,:𝑾𝑞𝑟𝑦𝑾𝑘𝑒𝑦𝑷𝒌,:+𝑷𝒒,:𝑾𝑞𝑟𝑦𝑾𝑘𝑒𝑦𝑿𝒌,:+𝑷𝒒,:𝑾𝑞𝑟𝑦𝑾𝑘𝑒𝑦𝑷𝒌,: (7)

where 𝒒 and 𝒌 correspond to the query and key pixels, respectively.

The relative positional encoding was introduced by Dai et al. (2019). The main idea is to only consider the position difference between the query pixel (pixel we compute the representation of) and the key pixel (pixel we attend) instead of the absolute position of the key pixel:

𝑨𝒒,𝒌rel :=𝑿𝒒,:𝑾𝑞𝑟𝑦𝑾𝑘𝑒𝑦𝑿𝒌,:+𝑿𝒒,:𝑾𝑞𝑟𝑦𝑾^𝑘𝑒𝑦𝒓𝜹+𝒖𝑾𝑘𝑒𝑦𝑿𝒌,:+𝒗𝑾^𝑘𝑒𝑦𝒓𝜹 (8)

In this manner, the attention scores only depend on the shift 𝜹:=𝒒-𝒌. Above, the learnable vectors 𝒖 and 𝒗 are unique for each head, whereas for every shift 𝜹 the relative positional encoding 𝒓𝜹Dp is shared by all layers and heads. Moreover, now the key weights are split into two types: 𝑾𝑘𝑒𝑦 pertain to the input and 𝑾^𝑘𝑒𝑦 to the relative position of pixels.

3 Self-Attention as a Convolutional Layer

This section derives sufficient conditions such that a multi-head self-attention layer can simulate a convolutional layer. Our main result is the following:

Theorem 1.

A multi-head self-attention layer with Nh heads of dimension Dh, output dimension D𝑜𝑢𝑡 and a relative positional encoding of dimension Dp3 can express any convolutional layer of kernel size Nh×Nh and min(Dh,D𝑜𝑢𝑡) output channels.

The theorem is proven constructively by selecting the parameters of the multi-head self-attention layer so that the latter acts like a convolutional layer. In the proposed construction, the attention scores of each self-attention head should attend to a different relative shift within the set ΔΔK={-K/2,,K/2}2 of all pixel shifts in a K×K kernel. The exact condition can be found in the statement of Lemma 1.

Then, Lemma 2 shows that the aforementioned condition is satisfied for the relative positional encoding that we refer to as the quadratic encoding:

𝒗(h):=-α(h)(1,-2𝚫1(h),-2𝚫2(h))𝒓𝜹 :=(𝜹2,𝜹1,𝜹2)𝑾𝑞𝑟𝑦=𝑾𝑘𝑒𝑦:=𝟎𝑾𝑘𝑒𝑦^:=𝑰 (9)

The learned parameters 𝚫(h)=(𝚫1(h),𝚫2(h)) and α(h) determine the center and width of attention of each head, respectively. On the other hand, 𝜹=(𝜹1,𝜹2) is fixed and expresses the relative shift between query and key pixels.

It is important to stress that the above encoding is not the only one for which the conditions of Lemma 1 are satisfied. In fact, in our experiments, the relative encoding learned by the neural network also matched the conditions of the lemma (despite being different from the quadratic encoding). Nevertheless, the encoding defined above is very efficient in terms of size, as only Dp=3 dimensions suffice to encode the relative position of pixels, while also reaching similar or better empirical performance (than the learned one). Though we lack a formal proof, we conjecture that every encoding that satisfies Lemma 1 should have at least three dimensions.

Remark for the 1D case.

Convolutional layers acting on sequences are commonly used in the literature for text (Kim, 2014), as well as audio (van den Oord et al., 2016) and time series (Franceschi et al., 2019). Theorem 1 can be straightforwardly extended to show that multi-head self-attention with Nh heads can also simulate a 1D convolutional layer with a kernel of size K=Nh with min(Dh,D𝑜𝑢𝑡) output channels using a positional encoding of dimension Dp2. Since we have not tested empirically if the preceding construction matches the behavior of 1D self-attention in practice, we cannot claim that it actually learns to convolve an input sequence—only that it has the capacity to do so.

3.1 Proof of Main Theorem

Figure 1: Illustration of a Multi-Head Self-Attention layer applied to a tensor image 𝑿. Each head h attends pixel values around shift 𝚫(h) and learn a filter matrix 𝑾𝑣𝑎𝑙(h). We show attention maps computed for a query pixel at position 𝒒.

The proof follows directly from Lemmas 1 and 2 stated below:

Lemma 1.

Consider a multi-head self-attention layer consisting of Nh=K2 heads, DhD𝑜𝑢𝑡 and let 𝐟:[Nh]ΔΔK be a bijective mapping of heads onto shifts. Further, suppose that for every head the following holds:

softmax(𝑨𝒒,:(h))𝒌={1 if 𝒇(h)=𝒒-𝒌0 otherwise. (10)

Then, for any convolutional layer with a K×K kernel and D𝑜𝑢𝑡 output channels, there exists {𝐖𝑣𝑎𝑙(h)}h[Nh] such that MHSA(𝐗)=Conv(𝐗) for every 𝐗RW×H×D𝑖𝑛.


Our first step will be to rework the expression of the Multi-Head Self-Attention operator from equation (1) and equation (4) such that the effect of the multiple heads becomes more transparent:

MHSA(𝑿) =𝒃𝑜𝑢𝑡+h[Nh]softmax(𝑨(h))𝑿𝑾𝑣𝑎𝑙(h)𝑾𝑜𝑢𝑡[(h-1)Dh+1:hDh+1]𝑾(h) (11)

Note that each head’s value matrix 𝑾𝑣𝑎𝑙(h)D𝑖𝑛×Dh and each block of the projection matrix 𝑾𝑜𝑢𝑡 of dimension Dh×D𝑜𝑢𝑡 are learned. Assuming that DhD𝑜𝑢𝑡, we can replace each pair of matrices by a learned matrix 𝑾(h) for each head. We consider one output pixel of the multi-head self-attention:

MHSA(𝑿)𝒒,:=h[Nh](𝒌softmax(𝑨𝒒,:(h))𝒌𝑿𝒌,:)𝑾(h)+𝒃𝑜𝑢𝑡 (12)

Due to the conditions of the Lemma, for the h-th attention head the attention probability is one when 𝒌=𝒒-𝒇(h) and zero otherwise. The layer’s output at pixel 𝒒 is thus equal to

MHSA(𝑿)𝒒 =h[Nh]𝑿𝒒-𝒇(h),:𝑾(h)+𝒃𝑜𝑢𝑡 (13)

For K=Nh, the above can be seen to be equivalent to a convolutional layer expressed in eq. 5: there is a one to one mapping (implied by map 𝒇) between the matrices 𝑾(h) for h=[Nh] and the matrices 𝑾k1,k2,:,: for all (k1,k2)[K]2.

Remark about Dh and D𝑜𝑢𝑡.

It is frequent in transformer-based architectures to set Dh=D𝑜𝑢𝑡/Nh, hence Dh<D𝑜𝑢𝑡. In that case, 𝑾(h) can be seen to be of rank D𝑜𝑢𝑡-Dh, which does not suffice to express every convolutional layer with D𝑜𝑢𝑡 channels. Nevertheless, it can be seen that any Dh out of D𝑜𝑢𝑡 outputs of MHSA(𝑿) can express the output of any convolutional layer with Dh output channels. To cover both cases, in the statement of the main theorem we assert that the output channels of the convolutional layer should be min(Dh,D𝑜𝑢𝑡). In practice, we advise to concatenate heads of dimension Dh=D𝑜𝑢𝑡 instead of splitting the D𝑜𝑢𝑡 dimensions among heads to have exact re-parametrization and no “unused” channels.

Lemma 2.

There exists a relative encoding scheme {𝐫𝛅RDp}𝛅Z2 with Dp3 and parameters 𝐖𝑞𝑟𝑦,𝐖𝑘𝑒𝑦,𝐖^𝑘𝑒𝑦,𝐮 with DpDk such that, for every ΔΔΔK there exists some vector 𝐯 (conditioned on Δ) yielding softmax(𝑨𝐪,:)𝐤=1 if 𝐪-𝐤=Δ and zero, otherwise.


We show by construction the existence of a Dp=3 dimensional relative encoding scheme yielding the required attention probabilities.

As the attention probabilities are independent of the input tensor 𝑿, we set 𝑾𝑘𝑒𝑦=𝑾𝑞𝑟𝑦=𝟎 which leaves only the last term of creftype 8. Setting 𝑾^𝑘𝑒𝑦Dk×Dp to the identity matrix (with appropriate row padding), yields 𝑨𝒒,𝒌=𝒗𝒓𝜹 where 𝜹:=𝒒-𝒌. Above, we have assumed that DpDk such that no information from 𝒓𝜹 is lost.

Now, suppose that we could write:

𝑨𝒒,𝒌=-α(𝜹-𝚫2+c) (14)

for some constant c. In the above expression, the maximum attention score over 𝑨𝒒,: is -αc and it is reached for 𝑨𝒒,𝒌 with 𝜹=𝚫. On the other hand, the α coefficient can be used to scale arbitrarily the difference between 𝑨𝒒,𝚫 and the other attention scores.

In this way, for 𝜹=𝚫, we have

limαsoftmax(𝑨𝒒,:)𝒌 =limαe-α(𝜹-𝚫2+c)𝒌e-α((𝒒-𝒌)-𝚫2+c)

and for 𝜹𝚫, the equation becomes limαsoftmax(𝑨𝒒,:)𝒌=0, exactly as needed to satisfy the lemma statement.

What remains is to prove that there exist 𝒗 and {𝒓𝜹}𝜹𝒵2 for which creftype 14 holds. Expanding the rhs of the equation, we have -α(𝜹-𝚫2+c)=-α(𝜹2+𝚫2-2𝜹,𝚫+c). Now if we set 𝒗=-α(1,-2𝚫1,-2𝚫2) and 𝒓𝜹=(𝜹2,𝜹1,𝜹2), then


which matches creftype 14 with c=-𝚫2 and the proof is concluded. ∎

4 Experiments

The aim of this section is to validate the applicability of our theoretical results—which state that self-attention can perform convolution—and to examine whether self-attention layers in practice do actually learn to operate like convolutional layers, when being trained on standard image classification tasks. In particular, we study the relationship between self-attention and convolution with quadratic and learned relative positional encodings. We find that for both cases, the attention probabilities learned tend to respect the conditions of Lemma 1, corroborating our hypothesis.

4.1 Implementation Details

We study a fully attentional model consisting of six multi-head self-attention layers. As it has already been shown by Bello et al. (2019) that combining attention features with convolutional features improves performance on Cifar-100 and ImageNet, we do not focus on attaining state-of-the-art performance. Nevertheless, to validate that our model learns a meaningful classifier we compare it to the standard ResNet18 (He et al., 2015) on the CIFAR-10 dataset (Krizhevsky et al., ). In all experiments, we use a 2×2 invertible down-sampling (Jacobsen et al., 2018) on the input to reduce the size of the image as storing the attention coefficient tensor requires a large amount of GPU memory. The fixed size representation of the input image is computed as the average pooling of the last layer representations and given to a linear classifier.

We used the PyTorch library (Paszke et al., 2017) and based our implementation on PyTorch Transformers55 5 https://github.com/huggingface/pytorch-transformers. We release our code on Github66 6 https://github.com/epfml/attention-cnn/tree/arxiv-v1 and all hyper-parameters are in creftypecap 2 in the Appendix.

4.2 Quadratic Encoding

As a first step, we aim to verify that, with the relative position encoding introduced in equation (9), attention layers learn to behave like convolutional layers. We train nine attention heads at each layer to be on par with the 3×3 kernels used predominantly by the ResNet architecture. The center of attention of each head h is initialized to Δ(h)𝒩(𝟎,2𝑰2).

creftypecap 2 shows how the initial positions of the heads (different colors) at layer 4 changed during training. We can see that after optimization, the heads attend on specific pixel of the image forming a grid around the query pixel. Our intuition that Self-Attention applied to images learn convolutional filter around the queried pixel is then confirmed.

Figure 2: Centers of attention of each attention head (different colors) at layer 4 during the training. Use quadratic relative positional encoding. The central black square is the query pixel, whereas solid and dotted circles represent the 50% and 90% percentiles of each Gaussian, respectively.

creftypecap 3 displays all attention head at each layer of the model at the end of the training. It can be seen that in the first few layers the heads tend to focus on local patterns (layers 1 and 2), while deeper layers (layers 3-6) also attend to larger patterns by positioning the center of attention further from the queried pixel position. We also include in the Appendix a plot of the attention positions for a higher number of heads (Nh=16), creftypecap 10 displays both local patterns similar to CNN and long range dependencies. Interestingly, attention heads do not overlap and seem to take an arrangement maximizing the coverage of the input space.

Figure 3: Centers of attention of each attention head (different colors) for the 6 self-attention layers using quadratic positional encoding. The central black square is the query pixel, whereas solid and dotted circles represent the 50% and 90% percentiles of each Gaussian, respectively.

To verify that our self-attention model performs equally well as a small ResNet (creftypecap 5), in creftypecap 6 we display the evolution of the test accuracy on CIFAR-10 over the 300 epochs of training. The ResNet is faster to converge, but we cannot ascertain whether this corresponds to an inherent property of the architecture or an artifact of the adopted optimization procedures. Our implementation could be optimized to exploit the locality of Gaussian attention probabilities and reduce significantly the number of FLOPS.

Figure 4: Test accuracy on CIFAR-10.
Models accuracy # of params # of FLOPS
ResNet18 0.938 11.2M 1.1B
SA quadratic 0.938 12.1M 6.2B
SA learned 0.918 12.3M 6.2B
Figure 5: Test accuracy on CIFAR-10 and model sizes. SA stands for Self-Attention.

4.3 Learned Relative Positional Encoding

We move on to study the positional encoding used in practice by fully-attentional models on images.

Figure 6: Attention maps of each head (column) at each layer (row) using learned relative positional encoding. The central black square is the query pixel. We reordered the heads for visualization.

We implemented the 2D relative positional encoding scheme used by (Ramachandran et al., 2019; Bello et al., 2019): we learn a Dp/2 position encoding vector for each row and each column pixel shift. Hence the relative positional encoding of a key pixel at position 𝒌 with a query pixel at position 𝒒 is the concatenation of the row shift embedding 𝜹1 and the column shift embedding 𝜹2 (where 𝜹=𝒌-𝒒). We chose Dp=D𝑜𝑢𝑡=400 in the experiment. We differ from the (unpublished) implementation described by Ramachandran et al. (2019) in the following points: (i) we do not use convolution stem and ResNet bottlenecks for downsampling, but only a 2×2 invertible downsampling layer (Jacobsen et al., 2018) at input, (ii) we use Dh=D𝑜𝑢𝑡 instead of Dh=D𝑜𝑢𝑡/Nh backed from our theory that the effective number of learned filters is min(Dh,D𝑜𝑢𝑡), (iii) the attention scores are computed using only the relative positions of the pixels and not the data. As seen in creftypecap 5, our implementation achieves accuracy close to that of ResNet18.

The attention probabilities of each head at each layer are displayed on creftypecap 6. The figure confirms our hypothesis for the first two layers and partially for the third: even when left to learn the encoding from the data, certain self-attention heads (depicted on the left) learn to attend to individual pixels, closely matching the condition of Lemma 1 and thus Theorem 1. At the same time, other heads pay attention to horizontally-symmetric but non-localized patterns, as well as to long-range pixel inter-dependencies. The phenomenon is particularly prominent for layers four to six, where the behavior of self-attention can be seen to deviate from that of convolution. We also notice that vertical symmetry is much more rare in the learned attention probabilities of high layers. This matches the intuition that, for image classification, distinguishing between what is above or below something is more crucial than what is left or right. Finally, the fact that some of the heads in the last two layers seem to be redundant, likely indicating that the computational and space complexity of the model could be amenable to further reduction, for example by pruning.

5 Conclusion

We showed that self-attention layers applied to images can express any convolutional layer (given sufficiently many heads) and that learned fully-attentional models do behave similar to CNN in practice. More generally, fully-attentional models seem to learn a generalization of CNNs where the kernel pattern is learned at the same time as the filters—similar to deformable convolutions (Dai et al., 2017; Zampieri, 2019). Interesting directions for future work include translating existing insights from the rich CNNs literature back to transformers on various data modalities, including images, text and time series. Also, though we currently lack the computational resources to do so, we would be interested to test whether our findings are replicated for datasets of larger-scale, such as ImageNet and COCO.


  • Bahdanau et al. (2015) Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. In 3rd International Conference on Learning Representations, ICLR 2015, San Diego, CA, USA, May 7-9, 2015, Conference Track Proceedings, 2015.
  • Bello et al. (2019) Irwan Bello, Barret Zoph, Ashish Vaswani, Jonathon Shlens, and Quoc V. Le. Attention Augmented Convolutional Networks. arXiv:1904.09925 [cs], April 2019.
  • Dai et al. (2017) Jifeng Dai, Haozhi Qi, Yuwen Xiong, Yi Li, Guodong Zhang, Han Hu, and Yichen Wei. Deformable convolutional networks. CoRR, abs/1703.06211, 2017.
  • Dai et al. (2019) Zihang Dai, Zhilin Yang, Yiming Yang, Jaime G. Carbonell, Quoc V. Le, and Ruslan Salakhutdinov. Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. CoRR, abs/1901.02860, 2019.
  • Devlin et al. (2018) Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: pre-training of deep bidirectional transformers for language understanding. CoRR, abs/1810.04805, 2018.
  • Franceschi et al. (2019) Jean-Yves Franceschi, Aymeric Dieuleveut, and Martin Jaggi. Unsupervised scalable representation learning for multivariate time series. In NeurIPS 2019, 2019.
  • He et al. (2015) Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. CoRR, abs/1512.03385, 2015.
  • Hochreiter & Schmidhuber (1997) Sepp Hochreiter and Jürgen Schmidhuber. Long short-term memory. Neural Computation, 9(8):1735–1780, 1997.
  • Hu et al. (2018) Jie Hu, Li Shen, and Gang Sun. Squeeze-and-excitation networks. In 2018 IEEE Conference on Computer Vision and Pattern Recognition, CVPR 2018, Salt Lake City, UT, USA, June 18-22, 2018, pp. 7132–7141, 2018.
  • Jacobsen et al. (2018) Jörn-Henrik Jacobsen, Arnold W.M. Smeulders, and Edouard Oyallon. i-revnet: Deep invertible networks. In International Conference on Learning Representations, 2018.
  • Kim (2014) Yoon Kim. Convolutional neural networks for sentence classification. arXiv preprint arXiv:1408.5882, 2014.
  • (12) Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton. Cifar-10 (canadian institute for advanced research).
  • Paszke et al. (2017) Adam Paszke, Sam Gross, Soumith Chintala, Gregory Chanan, Edward Yang, Zachary DeVito, Zeming Lin, Alban Desmaison, Luca Antiga, and Adam Lerer. Automatic differentiation in PyTorch. In NIPS Autodiff Workshop, 2017.
  • Pérez et al. (2019) Jorge Pérez, Javier Marinkovic, and Pablo Barceló. On the turing completeness of modern neural network architectures. CoRR, abs/1901.03429, 2019.
  • Radford et al. (2018) Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. 2018.
  • Ramachandran et al. (2019) Prajit Ramachandran, Niki Parmar, Ashish Vaswani, Irwan Bello, Anselm Levskaya, and Jonathon Shlens. Stand-alone self-attention in vision models. CoRR, abs/1906.05909, 2019.
  • van den Oord et al. (2016) Aäron van den Oord, Sander Dieleman, Heiga Zen, Karen Simonyan, Oriol Vinyals, Alexander Graves, Nal Kalchbrenner, Andrew Senior, and Koray Kavukcuoglu. Wavenet: A generative model for raw audio. arXiv preprint arXiv:1609.03499, 2016.
  • Vaswani et al. (2017) Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. Attention is all you need. CoRR, abs/1706.03762, 2017.
  • Wang et al. (2018) Xiaolong Wang, Ross B. Girshick, Abhinav Gupta, and Kaiming He. Non-local neural networks. In 2018 IEEE Conference on Computer Vision and Pattern Recognition, CVPR 2018, Salt Lake City, UT, USA, June 18-22, 2018, pp. 7794–7803, 2018.
  • Yang et al. (2019) Zhilin Yang, Zihang Dai, Yiming Yang, Jaime G. Carbonell, Ruslan Salakhutdinov, and Quoc V. Le. Xlnet: Generalized autoregressive pretraining for language understanding. CoRR, abs/1906.08237, 2019.
  • Zampieri (2019) Luca Zampieri. Geometric deep learning for volumetric computational fluid dynamics. pp.  67, 2019.

Appendix A Appendix

A.1 Generalized Quadratic Positional Encoding

We noticed the similarity of the attention probabilities in the quadratic positional encoding (creftypecap 3) to isotropic bivariate Gaussian distributions with bounded support:

softmax(𝑨𝒒,:)𝒌=e-α(𝒌-𝒒)-𝚫2𝒌[W]×[H]e-α(𝒌-𝒒)-𝚫2. (15)

Building on this observation, we further extended our attention mechanism to non-isotropic Gaussian distribution over pixel positions. Each head is parametrized by a center of attention 𝚫 and a covariance matrix 𝚺 to obtain the following attention scores,

𝑨𝒒,𝒌=-12(𝜹-𝚫)𝚺-1(𝜹-𝚫)=-12𝜹𝚺-1𝜹+𝜹𝚺-1𝚫-12𝚫𝚺-1𝚫, (16)

where, once more, 𝜹=𝒌-𝒒. The last term can be discarded because the softmax is shift invariant and we rewrite the attention coefficient as a dot product between the head target vector 𝒗 and the relative position encoding 𝒓𝜹 (consisting of the first and second order combinations of the shift in pixels 𝜹):

𝒗=12(2(𝚺-1𝚫)1,2(𝚺-1𝚫)2,-𝚺1,1-1,-𝚺2,2-1,-2𝚺1,2-1) and 𝒓𝜹=(𝜹1,𝜹2,𝜹12,𝜹22,𝜹1𝜹2).


We trained our model using this generalized quadratic relative position encoding. We were curious to see if, using the above encoding the self-attention model would learn to attend to non-isotropic groups of pixels—thus forming unseen patterns in CNNs. Each head was parametrized by 𝚫2 and 𝚺-1/22×2 to ensure that the covariance matrix remained positive semi-definite. We initialized the center of attention to 𝚫(h)𝒩(𝟎,2𝑰2) and 𝚺-1/2=𝑰2+𝒩(𝟎,0.01𝑰2) so that initial attention probabilities were close to an isotropic Gaussian. creftypecap 7 shows that the network did learn non-isotropic attention probability patterns, especially in high layers. Nevertheless, the fact that we do not obtain any performance improvement seems to suggest that attention non-isotropy is not particularly helpful in practice—the quadratic positional encoding suffices.

Figure 7: Centers of attention of each attention head (different colors) for the 6 self-attention layers using non-isotropic Gaussian parametrization. The central black square is the query pixel, whereas solid and dotted circles represent the 50% and 90% percentiles of each Gaussian, respectively.

Pruning degenerated heads.

We noticed that certain non-isotropic attention heads attended on “non-intuitive” patches of pixels: either attending a very thin stripe of pixels, when 𝚺-1 was almost singular, or attending all pixels uniformly, when 𝚺-1 was close to 𝟎 (i.e. constant attention scores). We asked ourselves, are such attention patterns indeed useful for the model or are these heads degenerated and unused? To find out, we pruned all heads having largest eigen-values smaller than 10-5 or condition number (ratio of the biggest and smallest eigen-values) greater than 105. Specifically in our model with 6-layer and 9-heads each, we pruned [2,4,1,2,6,0] heads from the first to the last layer. This means that these layers cannot express a 3×3 kernel anymore. As shown in yellow on creftype 5, this ablation initially hurts a bit the performance, probably due to off biases, but after a few epochs of continued training with a smaller learning rate (divided by 10) the accuracy recovers its unpruned value. Hence, without sacrificing performance, we reduce the size of the parameters and the number of FLOPS by a fourth.

Figure 8: Evolution of test accuracy on CIFAR-10. Pruned model (yellow) is continued training of the non-isotropic model (orange).
Models accuracy # of params # of FLOPS
ResNet18 0.938 11.2M 1.1B
SA quadratic 0.938 12.1M 6.2B
SA quadratic generalized 0.934 12.1M 6.2B
SA quadratic generalized pruned 0.934 9.7M 4.9B
SA learned 0.918 12.3M 6.2B
Figure 9: Number of parameters and accuracy on CIFAR-10 per model. SA stands for Self-Attention.

A.2 Increasing the Number of Heads

For completeness, we also tested increasing the number of heads of our architecture from 9 to 16.

Figure 10: Centers of attention for 16 attention heads (different colors) for the 6 self-attention layers using quadratic positional encoding. The central black square is the query pixel, whereas solid and dotted circles represent the 50% and 90% percentiles of each Gaussian, respectively.

Similar to Figure 3, we see that the network distinguishes two main types of attention patterns. Localized heads (i.e., those that attend to nearly individual pixels) appear more frequently in the first few layers. The self-attention layer uses these heads to act in a manner similar to how convolutional layers do. Heads with less-localized attention become more common at higher layers.

A.3 Positional Encoding References

Model type of positional encoding relative
sinusoids learned quadratic
Vaswani et al. (2017)
Radford et al. (2018)
Devlin et al. (2018)
Dai et al. (2019)
Yang et al. (2019)
Bello et al. (2019)
Ramachandran et al. (2019)
Our work
Table 1: Types of positional encoding used by transformers models applied to text (top) and images (bottom). When multiple encoding types have been tried, we report the one advised by the authors.

A.4 Hyper-parameters Used in Our Experiments

number of layers 6
number of heads 9
hidden dimension 400
intermediate dimension 512
invertible pooling width 2
dropout probability 0.1
layer normalization epsilon 10-12
number of epochs 300
batch size 100
learning rate 0.1
weight decay 0.0001
momentum 0.9
cosine decay
linear warm up ratio 0.05
Table 2: Self-attention network parameters