ARE TRANSFORMERS UNIVERSAL APPROXIMATORS OF SEQUENCE-TO-SEQUENCE FUNCTIONS?
Year: 2020

Abstract:
Despite the widespread adoption of Transformer models for NLP tasks, the expressive power of these models is not well-understood. In this paper, we establish that Transformer models are universal approximators of continuous permutation equivariant sequence-to-sequence functions with compact support, which is quite surprising given the amount of shared parameters in these models. Furthermore, using positional encodings, we circumvent the restriction of permutation equivariance, and show that Transformer models can universally approximate arbitrary continuous sequence-to-sequence functions on a compact domain. Interestingly, our proof techniques clearly highlight the different roles of the self-attention and the feed-forward layers in Transformers. In particular, we prove that fixed width self-attention layers can compute contextual mappings of the input sequences, playing a key role in the universal approximation property of Transformers. Based on this insight from our analysis, we consider other simpler alternatives to selfattention layers and empirically evaluate them.

heading: 1 INTRODUCTION
text: Self-attention based Transformer networks (Vaswani et al., 2017) have been at the center of the recent progress on various natural language processing (NLP) tasks, including machine translation (Vaswani et al., 2017), language modeling (Radford et al., 2018; 2019), and question answering (Devlin et al., 2018; Yang et al., 2019; Liu et al., 2019). All these tasks involve learning models that map an input sequence of tokens to an output sequence of tokens. Transformers make it feasible to train large models to approximate these sequence-to-sequence functions due to their ability to process the input tokens in a parallel way, as opposed to the sequential nature of RNNs and LSTMs.
A Transformer block consists of two kinds of layers: a self-attention layer and a token-wise feedforward layer, with skip connections present in both layers. The self-attention layer transforms each input token embedding using a weighted combination of the embeddings of all tokens in the input sequence, where weights are generated by pairwise dot-products among the input token embeddings. The token-wise feed-forward layer then independently processes each of these modified input token embeddings without any interaction among them. Notably, Transformers employ parameter reuse across tokens, as both layers use the same parameters to process each token. Moreover, Transformers have to rely solely on the pairwise dot-products to capture interaction between the input tokens.
Given the parameter sharing and limited interactions between tokens, it is natural to wonder: what class of sequence-to-sequence functions can the Transformer networks represent? Also, what is the role of the two different kinds of layers? Are both layers needed to obtain the representation power of Transformers? In the existing literature, the advantage of Transformers has often been attributed to their capability of computing contextual embeddings/mappings of the input, as opposed to fixed word embeddings as in word2vec (Mikolov et al., 2013). Is it possible to formalize the notion of
∗Based on work performed at Google Research New York
contextual mappings? If yes, can Transformers actually compute such mappings? Such questions still remain elusive.
In this paper, we provide a mathematical definition of contextual mappings and show that multi-head self-attention layers can indeed compute contextual mappings of the input sequences. We further show that this ability to compute contextual mappings coupled with the value mapping ability of the feed-forward layers makes Transformers universal approximators of any permutation equivariant sequence-to-sequence function. We also improve this result using positional encodings, and show that Transformers can represent any sequence-to-sequence function; i.e., the restriction of permutation equivariance can be removed by positional encodings.
These results on universal approximation of sequence-to-sequence functions raise a natural question: is it possible to have a more efficient architecture to compute contextual mappings, consequently, preserving the ability to universally approximate sequence-to-sequence functions? Towards this, we explore other architectures that can implement contextual mappings (to some extent), and experimentally evaluate their performance. In our experiments, we notice that the models that combine these simpler architectures with Transformers have better performance, compared to the standalone Transformers. We conclude the paper by presenting more discussion and interesting future research directions along these lines.

heading: 1.1 SUMMARY OF OUR CONTRIBUTIONS
text: • We prove that Transformers are universal approximators of continuous and permutation equivariant sequence-to-sequence functions with compact support (Theorem 2). We also show that, if Transformers have trainable positional encodings added to the input, then they are universal approximators of continuous sequence-to-sequence functions on a compact domain (Theorem 3).
• We formalize the notion of contextual mappings and show that the attention layers can compute contextual mappings, where each unique context is mapped to a unique vector (Lemma 6).
• We experimentally evaluate other simpler layers that can compute contextual mappings to some extent, such as bi-linear projections and separable convolutions, and show that substituting some of the self-attention layers with these layers can result in better performance (Section 5).

heading: 1.2 RELATED WORKS & NOTATION
text: Analysis of attention-based models. Given the popularity of Transformers, there have been numerous works trying to understand the role of attention layers in natural language processing models. One such line of work focuses on probing the output of attention layers to understand the attention mechanism and internal language representation (Hewitt & Manning, 2019; Clark et al., 2019; Coenen et al., 2019; Vig & Belinkov, 2019). Although these results give valuable insights, a consistent theoretical analysis corroborating these findings is missing.
Universal approximation theorems. Universal approximation theorems are classical results in neural network theory, dating back many decades (Cybenko, 1989; Hornik, 1991). These results show that given unbounded width, a one-hidden-layer neural network can approximate arbitrary continuous function with compact support, up to any accuracy. Other results focusing on depth appeared more recently (Lu et al., 2017; Hanin & Sellke, 2017; Lin & Jegelka, 2018). In particular, Lu et al. (2017); Hanin & Sellke (2017) consider fully-connected ReLU networks whose input dimension is d, and show that networks with width d + 1 and unbounded depth are universal approximators of scalar-valued continuous functions. Lin & Jegelka (2018) show that a residual network with one hidden neuron per residual block is a universal approximator of scalar-valued functions, given unbounded depth. Although Transformer networks do have residual connections, due to their heavy parameter sharing, the existing analyses for residual networks do not extend to Transformers. Sannai et al. (2019) consider universally approximating permutation invariant/equivariant functions using fully-connected ReLU networks.
Turing completeness results on Transformers. Recently, Pérez et al. (2019) have shown that Transformers with infinite precision are Turing complete, which is not the case in finite precision setting (Dehghani et al., 2018). We note that Turing completeness deals with computation on formal languages (thus discrete objects), while universal approximation focuses on functions on a continuum. In other words, these are two different concepts; and one does not imply another.
Notation. We use the following notation in the paper. Given a matrix A, let Ai,j , Ai,:, and A:,j denote its (i, j)-th entry, i-th row, and j-th column, respectively. We use ‖A‖p to denote the entrywise `p norm of A. Let σ[·] be the softmax operator, which takes a matrix as input and applies softmax operation to each column of the matrix, which results in a column stochastic matrix, i.e., a matrix that has non-negative entries with each column summing to 1. We similarly define σH[·] to be the hardmax operator, which outputs the one-hot representation of the arg max entry for each column of the input matrix. If there are k arg max entries, then the output is 1/k for such entries. We use 1n to denote a vector of length n whose entries are all 1. We denote the 0-1 indicator function by 1 {·}. We use d and n to denote the embedding dimension and the sequence length, respectively. We assume throughout that n ≥ 2, as the Transformers reduce to residual networks when n = 1.

heading: 2 TRANSFORMER NETWORKS
text: A Transformer block is a sequence-to-sequence function mapping Rd×n to Rd×n. It consists of two layers: a self-attention layer and a token-wise feed-forward layer, with both layers having a skip connection. More concretely, for an input X ∈ Rd×n consisting of d-dimensional embeddings of n tokens, a Transformer block with multiplicative or dot-product attention (Luong et al., 2015) consists of the following two layers1:
Attn(X) = X + ∑h
i=1 W iOW i VX · σ[(W iKX)TW iQX], (1)
FF(X) = Attn(X) + W2 · ReLU(W1 ·Attn(X) + b11Tn ) + b21Tn , (2)
where W iO ∈ Rd×m, W iV ,W iK ,W iQ ∈ Rm×d, W2 ∈ Rd×r,W1 ∈ Rr×d, b2 ∈ Rd, b1 ∈ Rr, and FF(X) is the output of the Transformer block. The number of heads h and the head size m are two main parameters of the attention layer; and r denotes the hidden layer size of the feed-forward layer.
Here, we would like to point out that our definition of the self-attention layer (1) is an equivalent reformulation of (Vaswani et al., 2017), where they concatenate attention heads and multiply a matrix WO ∈ Rd×mh to the concatenation. One difference in our setup is the absence of layer normalization, which simplies our analysis while preserving the basic architecture of the Transformer.
We define the Transformer networks as the composition of Transformer blocks. The family of the sequence-to-sequence functions corresponding to the Transformers can be defined as:
T h,m,r := {g : Rd×n → Rd×n | g is a composition of Transformer blocks th,m,r’s}.
where th,m,r : Rd×n → Rd×n denotes a Transformer block defined by an attention layer with h heads of size m each, and a feed-forward layer with r hidden nodes.
We say that a function f : Rd×n → Rd×n is permutation equivariant if for any permutation matrix P , we have f(XP ) = f(X)P ; i.e., if we permute the columns of X , then the columns of f(X) are permuted in the same way. A Transformer block is permutation equivariant, which we formally prove in Section A. This consequently establishes the permutation equivariance of the class T h,m,r. Claim 1. A Transformer block th,m,r defines a permutation equivariant map from Rd×n to Rd×n.
As seen in above, both layers (cf. (1) and (2)) of a Transformer block employ parameter reuse/sharing, because each token/column undergoes the same transformations (e.g., W iQ, W i K , or W1) regardless of its position. Moreover, interactions between tokens can only be captured through pairwise dot-products in the softmax operator σ[·] (cf. (1)). Given such limitations in a single Transformer block’s representation power, it is not obvious what kinds of sequence-to-sequence functions T h,m,r can approximate; we provide the answer to this question in the next section.

heading: 3 TRANSFORMERS ARE UNIVERSAL APPROXIMATORS OF SEQUENCE-TO-SEQUENCE FUNCTIONS
text: In this section, we present our theorems showing that the Transformer networks are universal approximators of sequence-to-sequence functions. Let us start by defining the target function class FPE, which consists of all continuous permutation equivariant functions with compact support that
1In our proof we use bias vectors biQ for query projections in attention layers. We omit them here for brevity.
map Rd×n to Rd×n. Here, continuity is defined with respect to any entry-wise `p norm, 1 ≤ p <∞. Given two functions f1, f2 : Rd×n → Rd×n, for 1 ≤ p <∞, we define a distance between them as
dp(f1, f2) := (∫ ‖f1(X)− f2(X)‖pp dX )1/p .
The following result shows that a Transformer network with a constant number of heads h, head size m, and hidden layer of size r can approximate any function in FPE. Theorem 2. Let 1 ≤ p < ∞ and > 0, then for any given f ∈ FPE, there exists a Transformer network g ∈ T 2,1,4, such that dp(f, g) ≤ .
Next, we present our theorem on Transformers with positional encodings. In order to endow the Transformer networks with the ability to capture the information about the position of tokens in the input sequence, it is a common practice to add positional encodings E ∈ Rd×n to the input sequence before feeding it to the Transformer network (Vaswani et al., 2017; Devlin et al., 2018). Consider the functions represented by Transformers with positional encodings:
T h,m,rP := {gP(X) = g(X + E) | g ∈ T h,m,r and E ∈ Rd×n}.
Here we show that if E is trainable, these positional encodings are sufficient to remove the permutation equivariance restriction of the Transformers. Towards this, we define FCD to be the set of all continuous functions that map a compact domain in Rd×n to Rd×n. Note that FCD does not have the restriction of permutation equivariance as in FPE, but any f ∈ FCD is defined on a compact domain instead of the whole Rd×n. The following result states that, equipped with the trainable positional encodings, Transformers can approximate any sequence-to-sequence function in FCD. Theorem 3. Let 1 ≤ p < ∞ and > 0, then for any given f ∈ FCD, there exists a Transformer network g ∈ T 2,1,4P such that we have dp(f, g) ≤ .
Theorems 2 and 3 provide an interesting characterization of the representation power of fixed-width Transformer networks. Since the function classes T h,m,r and T h,m,rP become richer as we increase the values of (h,m, r), our results establish that general Transformer networks are also universal approximators of sequence-to-sequence functions. Remarkably, none of the parameters (h,m, r) depend on the input sequence length n or embedding dimension d.
Here, we would like to again point out that Theorems 2 and 3 appear quite surprising at a first glance, given the parameter sharing across all the tokens in a sequence, e.g., feed-forward layers are applied token-wise and the projection matrices in the self-attention layers are the same across different tokens. Furthermore, attention layers can only capture pairwise interaction between different tokens in the sequence. In the next subsection, we briefly describe one of our key steps in overcoming the aforementioned restrictions and proving universal approximation power of Transformers.

heading: 3.1 A KEY STEP: SELF-ATTENTION LAYERS CAN IMPLEMENT CONTEXTUAL MAPPINGS
text: Let us consider a setting where we are interested in embedding two sentences: 1) I am happy; and 2) I am Bob. These sentences are fed to a sequence-to-sequence model as
X = [X:,1,X:,2,X:,3] = [vI,vam,vhappy] and X̃ = [X̃:,1, X̃:,2, X̃:,3] = [vI,vam,vBob],
where vI,vam,vhappy, and vBob denote d-dimensional embedding for the tokens ‘I’, ‘am’, ‘happy’, and ‘Bob’, respectively. Since the word ‘I’ occurs in different contexts in these sentences, in order to implement arbitrary sequence-to-sequence functions, the sequence-to-sequence model should map the two occurrences of ‘I’ to different values. We formally define this requirement below.
Definition 3.1 (Contextual mapping). Consider a finite set L ⊂ Rd×n. A map q : L → R1×n defines a contextual mapping if the map satisfies the following:
1. For any L ∈ L, the n entries in q(L) are all distinct. 2. For any L,L′ ∈ L, with L 6= L′, all entries of q(L) and q(L′) are distinct.
In other words, a contextual mapping maps each token (column) of L ∈ L to a unique value which depends on the entire L; as a result, capturing the precise context of L. This allows the subsequent
token-wise function (e.g., defined by the feed-forward layers in case of Transformer networks) to realize the outputs of any arbitrary sequence-to-sequence functions.
At the first thought, we can consider getting a contextual mapping by simply averaging all the tokens, because this can capture the one-word difference (e.g., “happy” vs. “Bob”) in two different contexts. However, if there are multiple words that are different, it is not guaranteed that the average will be different. Indeed, requiring unique mappings for all the tokens for any change in any number of tokens, is a steep requirement.
While the self-attention layer does consider pair-wise interactions among different input tokens, it is not clear if this weak form of pair-wise interaction with shared projection weights is sufficient to extract the underlying context. The following result, which we sketch here, shows that self-attention layers can implement a permutation equivariant contextual mapping over almost all elements of a grid in [0, 1]d×n. We defer the full statement to Section 4.2. Lemma 6 (informal). Consider the grid Gδ := {0, δ, . . . , 1 − δ}d×n. Then, there exist a function gc : Rd×n → Rd×n composed of δ−d + 1 self-attention layers (h = 2,m = 1) and a vector u ∈ Rd such that q(L) := uT gc(L) satisfies the following properties, for a subset G̃δ ⊂ Gδ that contains almost all elements of Gδ:
1. For any L ∈ G̃δ , the entries of q(L) are all distinct. 2. For any L,L′∈G̃δ such that L is not a permutation of L′, all entries of q(L), q(L′) are distinct.
Lemma 6 shows that a series of self-attention layers can implement contextual mappings, despite the apparent restriction that each of them can only capture pair-wise interaction. However, the restriction of permutation equivarance still exists because attention layers are inherently permutation equivariant. Coupled with the ability of token-wise feed-forward layers to map different values in q(L) to arbitrary output values, we can prove universal approximation capability of Transformers.

heading: 3.2 PROOF OF THE UNIVERSAL APPROXIMATION THEOREM (THEOREM 2)
text: Next, we outline the proof of Theorem 2 in greater detail. We refer the reader to Section C for the proof of Theorem 3, since it is a modification of Theorem 2. Even though Theorems 2 and 3 do not specifically mention the required depth for approximation, our proof techniques do characterize it, and we show that our construction is tight in the number of parameters. We defer the discussion of depth to Section 4.4.
Recall that we want to show that given a function f ∈ FPE, we can find a Transformer network g ∈ T 2,1,4 such that dp(f, g) ≤ . Without loss of generality, we can assume that the compact support of f is contained in [0, 1]d×n. We achieve our desired objective in three key steps: Step 1. Approximate FPE with piece-wise constant functions. We first use (a variant of) the classical result that any continuous function can be approximated up to arbitrary accuracy by piecewise constant functions. For δ > 0, we define the following class of piece-wise constant functions.
FPE(δ) := { f : X 7→ ∑ L∈Gδ AL1 {X ∈ SL} | f is permutation equivariant, AL ∈ Rd×n } ,
where Gδ := {0, δ, . . . , 1 − δ}d×n and, for a grid point L ∈ Gδ , SL := ∏d j=1 ∏n k=1[Lj,k, Lj,k + δ) ⊂ [0, 1]d×n denotes the associated cube of width δ. Let f ∈ FPE(δ) be such that dp(f, f) ≤ /3. Step 2. Approximate FPE(δ) with modified Transformers. We then consider a slightly modified architecture for Transformer networks, where the softmax operator σ[·] and ReLU(·) are replaced by the hardmax operator σH[·] and an activation function φ ∈ Φ, respectively. Here, the set of allowed activations Φ consists of all piece-wise linear functions with at most three pieces, where at least one piece is constant. Let T h,m,r denote the function class corresponding to the sequence-to-sequence functions defined by the modified Transformer networks. The following result establishes that the modified Transformer networks in T 2,1,1 can closely approximate functions in FPE(δ).
Proposition 4. For each f ∈ FPE(δ) and 1 ≤ p <∞, ∃ g ∈ T 2,1,1 such that dp(f, g) = O(δd/p).
Step 3. Approximate modified Transformers with (original) Transformers. Finally, we show that g ∈ T 2,1,1 can be approximated by T 2,1,4. Let g ∈ T 2,1,4 be such that dp(g, g) ≤ /3.
Theorem 2 now follows from these three steps, because we have
dp(f, g) ≤ dp(f, f) + dp(f, g) + dp(g, g) ≤ 2 /3 +O(δd/p).
Choosing δ small enough ensures that dp(f, g) ≤ . We refer the reader to Sections B.1 and B.2 in the supplementary material for the formal statements and proofs of Steps 1 and 3, respectively. As for Step 2, which is the most critical step in establishing the universal approximation property of Transformers, we provide a sketch of the proof of Proposition 4 in the next section, and refer the reader to Section B.3 for the complete proof.

heading: 4 PROOF SKETCH OF PROPOSITION 4: DIFFERENT ROLES OF TWO LAYERS
text: As mentioned earlier, the heavy parameter sharing in Transformers makes the goal of universally approximating sequence-to-sequence functions seemingly difficult. Both the self-attention and the feed-forward layer weights inside a Transformer block are fixed across n tokens. In this section, we show that Transformers are able to overcome this architectural constraint, and compute contextual mappings of the entire input sequence just based on the pair-wise interactions. The token-wise feedforward layers then transform these contextual mappings to the desired output sequence.
We highlight these inner workings of Transformers en route to proving Proposition 4. We want to show that given a piece-wise constant function f ∈ FPE(δ), there exists a modified Transformer network g ∈ T 2,1,1 that closely approximates f . We achieve this goal by establishing the following three claims, which correspond to Lemmas 5, 6, and 7.
1. Given an input X ∈ Rd×n, a series of feed-forward layers in the modified Transformer network can quantize X to an element L on the extended grid G+δ := {−δ−nd, 0, δ, . . . , 1− δ}d×n.
2. Next, a series of self-attention layers in the modified Transformer network can take the input L and implement a contextual mapping q such that, for L and L′ that are not permutation of each other, all the elements in q(L) and q(L′) are distinct.
3. Finally, a series of feed-forward layers in the modified Transformer network can map elements of the contextual embedding q(L) to the desired output value of f ∈ FPE at the input X .
Before discussing these three claims in detail, we note that even though a Transformer network stacks self-attention and feed-forward layers in an alternate manner, the skip connections enable these networks to employ a composition of multiple self-attention or feed-forward layers. Furthermore, as alluded earlier, these three steps clearly highlight the different roles that self-attention and feed-forward layers play in realizing the ability to universally approximate sequence-to-sequence functions: 1) self-attention layers compute precise contextual maps; and 2) feed-forward layers then assign the results of these contextual maps to the desired output values.

heading: 4.1 QUANTIZATION BY FEED-FORWARD LAYERS
text: Since our objective in Proposition 4 is to approximate the function f ∈ FPE(δ), which takes a constant value on the cubes SL’s, the (modified) Transformer network approximating f first quantizes the input X according to these cubes. In particular, we want each input X ∈ SL to be mapped to the point L. The following result shows that a modified Transformer network can indeed implement this quantization map with a composition of multiple feed-forward layers.
Lemma 5. Consider a scalar quantization map gentq : R→ {−δ−nd, 0, δ, . . . , 1− δ}:
gentq (t) = { kδ if kδ ≤ t < (k + 1)δ, k = 0, . . . , 1/δ − 1, −δ−nd otherwise.
There exists a function gq : Rd×n 7→ G+δ composed of d δ + d token-wise feed-forward layers with r = 1 and activations in Φ, which employs the scalar quantization gentq to each entry of its input.
As desired, the function gq maps any X ∈ SL to L. Furthermore, if any element of X is not in [0, 1], the element is mapped to −δ−nd, indicating that X is outside the compact support of f ∈ FPE(δ).

heading: 4.2 CONTEXTUAL MAPPING BY SELF-ATTENTION LAYERS
text: In this subsection, we show that the (modified) Transformer network can compute contextual mappings (cf. Definition 3.1) from the output L ∈ G+δ of the map gq (cf. Section 4.1) by using a composition of self-attention layers. The following lemma, sketched earlier in Section 3.1, shows that the (modified) Transformer networks can implement a permutation equivariant contextual mapping over almost all elements of Gδ , while mapping the rest of elements in G+δ to a disjoint set. Lemma 6. Consider the following subset of Gδ = {0, δ, . . . , 1− δ}d×n:
G̃δ := {L ∈ Gδ | L:,i 6= L:,j for all i 6= j}. Assume that n ≥ 2 and δ−1 ≥ 2. Then, there exist a function gc : Rd×n → Rd×n composed of δ−d + 1 self-attention layers (h = 2,m = 1) that employ the σH operator, a vector u ∈ Rd, constants tl, tr ∈ R (0 < tl < tr), such that q(L) := uT gc(L) satisfies the following properties:
1. For any L ∈ G̃δ , the entries of q(L) are all distinct. 2. For any L,L′∈G̃δ such that L is not a permutation of L′, all entries of q(L), q(L′) are distinct. 3. For any L ∈ G̃δ , all the entries of q(L) are in [tl, tr]. 4. For any L ∈ G+δ \ G̃δ , all the entries of q(L) are outside [tl, tr].
At this point, a few remarks about the result in Lemma 6 are in order. First, since the Transformer networks are bound to implement permutation invariant maps, we require the Property 6.2 to hold for the pair of sequences that cannot be mapped to each other via permutation of columns. Furthermore, the self-attention layers implement the desirable contextual map for only G̃δ ⊆ Gδ , where all columns of L are distinct. Note that for small δ, Gδ \ G̃δ constitutes a negligible fraction of Gδ because |Gδ \ G̃δ| = O(δd|Gδ|). The function q in Lemma 6 maps the elements of G+δ \ G̃δ outside [tl, tr]—the interval where the outputs of the contextual mapping for G̃δ reside.

heading: 4.2.1 PROOF SKETCH OF LEMMA 6
text: Since Lemma 6 is one of the major technical contributions of this paper, we provide a short sketch of its proof. The complete proof is presented in Section B.5. For simplicity, we consider the case d = 1, so the input L ∈ G+δ is a row vector of length n. The key idea of the proof is that, using two attention heads of size 1, one can implement a selfattention layer that shifts up input entries that are in a specific interval, while leaving all other entries intact. We call this the selective shift operation. Since the entries in L are quantized, we apply the selective shift operation to 0, δ, . . . , 1 − δ using 1/δ attention layers. Interestingly, the value of the largest output entry after these operations is unique for each L ∈ G̃δ up to permutations. Using the largest entry, one can add one last layer that shifts up the entire matrix and outputs q(L) that satisfies Properties 6.1 and 6.2 of the lemma.
More concretely, the following function Ψ : R1×n → R1×n, parametrized by b, b′ ∈ R satisfying b < b′, can be implemented with two attention heads of size 1 with the hardmax (σH) operator:
Ψ(Z; b, b′)1,j = { maxk Z1,k −mink Z1,k if b < Z1,j < b′, 0 if Z1,j < b or Z1,j > b′.
If we define an attention layer of the form Z 7→ Z + Ψ(Z; b, b′), then any entry Z1,j in (b, b′) is shifted up by maxk Z1,k −mink Z1,k, while all the other entries stay untouched. We can choose b and b′ to selectively shift certain entries, hence the name selective shift operation.
We stack 1/δ self-attention layers, with attention parts δ−1Ψ(·; l − δ/2, l + δ/2) for each l ∈ {0, δ, . . . , 1 − δ}, in increasing order of l. With these layers, we can apply the selective shift operations to input entries of values 0, δ, . . . , 1 − δ. To see how the shift operations modify the input, now consider n = 2 for simplicity, and let L = [l1 l2] ∈ G̃δ . Without loss of generality, we can assume l1 < l2. The selective shift operation is applied to l1 first, shifting it by δ−1(maxL − minL) = δ−1(l2 − l1), resulting in l̃1 = l1 + δ−1(l2 − l1) > l2. After that, the operation on l2 shifts it up by δ−1(l̃1 − l2). Thus, the first 1/δ layers map L = [l1 l2] (l1 < l2) to
L̃ = [ l̃1 l̃2 ] := [ l1 + δ −1(l2 − l1) l2 + (δ−2 − δ−1)(l2 − l1) ] .
We can show that the map from [l1 l2] ∈ {L ∈ G̃δ | l1 < l2} to l̃2 is one-to-one, and that 0 < l̃1 < l̃2 < δ
−2. We then add one last layer that shifts all positive entries of L̃ by δ−3 max L̃ = δ−3 l̃2, whose output we denote by q(L) = [ δ−3 l̃2 + l̃1 δ −3 l̃2 + l̃2 ] . All entries of q(L) are in [δ−3 l̃2, δ −3 l̃2 + δ
−2), and this interval is disjoint for different L’s because L 7→ l̃2 is one-to-one. Thus, q(L) satisfies Properties 6.1 and 6.2 of the lemma. The remaining details are in Section B.5.

heading: 4.3 FUNCTION VALUE MAPPING BY FEED-FORWARD LAYERS
text: This brings us to the final step, which demonstrates the key utility of the feed-forward layers. After the contextual mapping by self-attention layers, each token captures the entire context available in the input sequence. The following result shows that token-wise application of a composition of feed-forward layers can map these tokens to the desired output values required by the function f .
Lemma 7. Let gc : Rd×n → Rd×n be the function from Lemma 6. Then, there exists a function gv : Rd×n → Rd×n composed of O(n( 1δ )
dn/n!) token-wise feed-forward layers (r = 1) with activations in Φ such that gv is defined by a token-wise function gtknv : Rd → Rd on each column,
gv(Z) = [ gtknv (Z:,1) · · · gtknv (Z:,n) ] ,
where for all j ∈ {1, . . . , n},
gtknv (gc(L):,j) = { (AL):,j if L ∈ G̃δ, 0d if L ∈ G+δ \ G̃δ.

heading: 4.4 TIGHTNESS OF CONSTRUCTIONS
text: We showed in this section that Theorem 2 requires O(n(1/δ)dn/n!) Transformer blocks for approximation, where δ is the width of the cubes. Each transformer block is of constant width, so it has O(d) parameters; this means that the total number of parameters is O(dn(1/δ)dn/n!). We note that this exponential dependence cannot be avoided in the worse case. If we assume continuity without any additional smoothness, quantizing the domain to cubes and approximating the function with constants require memorizing (output dim) × (num cubes)/n! real numbers, where the factor of 1/n! is due to permutation equivariance. Thus, Theorem 2 is optimal in the order of parameters.
If we compare with the residual network result (Lin & Jegelka, 2018), we can consider “flattening” X into a dn-dimensional vector and fitting the function. The proof technique in (Lin & Jegelka, 2018) requires O((1/δ)dn) layers, where each layer has O(dn) parameters: the total parameter requirement isO(dn(1/δ)dn). This shows that Transformers can approximate permutation equivariant functions in a more efficient way than residual networks.
In Section C, our proof of Theorem 3 shows that we requireO(n(1/δ)dn) layers to approximate continuous (not permutation equivariant) sequence-to-sequence functions. As seen from the argument above, this construction is also optimal in the order of parameters.

heading: 5 DISCUSSION AND EXPERIMENTS
text: As detailed in Section 4, the ability of the self-attention layers to compute contextual mappings plays a crucial role in the universal approximation property. Interestingly, our analysis shows that replacing the dot-product attention in Transformers with any other component capable of computing contextual mappings should preserve this universal approximation property. This leads naturally to questions about the alternative architectures that realize certain kinds of contextual mappings at different computational and memory costs. We explore and discuss some examples of such alternatives in this section. Our preliminary empirical study demonstrates their practical utility.

heading: 5.1 BI-LINEAR PROJECTION
text: Given token embeddings X as input, the bi-linear projection layer computes the following update.
BProj(X) = X + WO ·X ·WP .
The bi-linear projection layer (Gong et al., 2013) is motivated from the ability of random (Gaussian) matrices to map sparse differences to dense vectors (Ailon & Chazelle, 2009). If there are two input
contexts X1 and X2 that differ in one token, their difference X1 −X2 is sparse; however, after random projection, the difference (X1 −X2)WP will be dense, and the numbers are distinct with high probability, implementing a form “pair-wise contextual mapping,”2 although different from the contextual mapping in Definition 3.1.
This layer advantageously incurs smaller number of matrix multiplications as compared to the dotproduct attention. That said, the number of parameters in this layer depend on the sequence length, making it harder to reuse the model across tasks with different input sequence lengths. Moreover, the weights used to compute the contextual embeddings (WP ) are independent of the inputs (X), whereas in self-attention the weights (σ[(W iKX)
TW iQX]) depend on X . The first drawback can be addressed by replacing the linear projection with a depth-wise separable convolution layer, which is discussed in the next subsection.

heading: 5.2 DEPTH-WISE SEPARABLE CONVOLUTIONS
text: A depth-wise convolution layer (Sifre & Mallat, 2014; Chollet, 2017; Kaiser et al., 2017) involves convolving each dimension of X with a corresponding convolution filter of size k:
SepConv(X) = X + WO (X ∗WC) ,
where WC ∈ Rd×k and (X ∗WC)i,: := Xi,: ∗ (WC)i,:. Unlike bi-linear projection, this layer can be used across tasks with different input sequence lengths as the number of parameters are independent of the sequence length. While a single layer is unable to compute contextual mappings when the filter size is small, stacking multiple such layers can potentially provide a cheaper way to compute contextual mappings. In fact, based on depth-wise separable convolutions, Wu et al. (2019) proposed a light-weight dynamic convolution architecture that performs competitively with Transformers on machine translation.

heading: 5.3 EXPERIMENTS
text: We now present our experiments with these other architectures, with the goal of understanding the extent to which computing contextual mappings can capture the performance of Transformers. As discussed earlier, BProj and SepConv do not implement contextual mappings (cf. Definition 3.1), so we do not expect that either BProj or SepConv based models to have the same performance as the expensive Transformers. These models do not use input dependent weights to compute attention, and hence have weaker representation power. Instead, our goal is to see if we can use these cheaper layers to replace (some of) the expensive self-attention layers.
2This guarantee only holds for a finite set (can be exponential in n) of fixed vectors in Rn.
We follow the experimental setting from Devlin et al. (2018) to train the Transformers, with the masked language model pre-training followed by a task specific fine-tuning, and work with a 12 layer architecture based on BERTBASE. We present our results on a question answering task (SQuAD) (Rajpurkar et al., 2016) and a sentence entailment task (MNLI) (Williams et al., 2018). In our first set of experiments we train models that employ BProj and SepConv layers, instead of the selfattention layer in eq.(1). We notice that, as expected, these simpler models have weaker performance than the self-attention layer. See Table 1 in Section D for a comparison of these models on MNLI.
Next, we swap a varying number of the first few self-attention layers in BERTBASE with SepConv, implemented with filter reuse across dimensions (Wu et al., 2019)3. Fig. 1 illustrates the performance of these hybrid models. Interestingly, models with 1 or 2 convolution layers and rest the self-attention layers, perform better than models with only the self-attention layers. Note that, replacing self-attention layer with SepConv also reduces the computational cost and the number of parameters. One explanation we have is that the first few attention layers tend to attend broadly to the whole sequence (as empirically observed in (Clark et al., 2019)), and the cheaper convolution layers can perform this job more efficiently. A detailed evaluation of such hybrid architectures will be interesting future research.
Our experiments also call for a deeper understanding of the exact nature of the embeddings computed by practical attention models. Since Transformers in practice have fixed depth, we believe that they might not be able to exactly implement contextual mappings as we defined in Definition 3.1. However, there is some preliminary empirical evidence that Transformers do implement some sort of “contextual mappings.” For example, Fig. 4 of Coenen et al. (2019) presents visualizations of embeddings of a single word in different contexts (sentences). They experimentally notice that Transformers, in addition to computing contextual mappings, also map a word into semantic clusters. Formalizing and evaluating this property of Transformers is an interesting direction for future work. We again note that Wu et al. (2019) have proposed an alternative way to compute such embeddings based on dynamic convolution layers. Evaluating the mappings computed by these models should shed more light on the workings of attention models and inspire efficient and better performing architectures.

heading: A PROOF OF CLAIM 1
text: Suppose XP was given as input, where P is a permutation matrix. First note that
(W iKXP ) T (W iQXP ) = P T (W iKX) T (W iQX)P
After the softmax operation, we get
σ[P T (W iKX) T (W iQX)P ] = P Tσ[(W iKX) T (W iQX)]P .
Then,
Attn(XP ) = XP + h∑ i=1 W iO(W i VXP ) · P Tσ[(W iKX)T (W iQX)]P = Attn(X)P ,
where we used PP T = I . Permutation equivariance of the token-wise feed-forward layer can be shown similarly:
FF(XP ) = Attn(X)P + W2 · ReLU(W1 ·Attn(X)P + b11TnP ) + b21TnP = Attn(X)P + W2 · ReLU(W1 ·Attn(X) + b11Tn )P + b21TnP = FF(X)P ,
where ReLU(XP ) = ReLU(X)P was used. This analysis shows that the function class T h,m,r(·) is restricted to permutation equivariant functions.

heading: B PROOF DETAILS OF THEOREM 2
text: We first define some additional notation. For a, b ∈ N where a ≤ b, let [a] = {1, . . . , a} and [a : b] = {a, a + 1, . . . , b − 1, b}. For a, b, c ∈ R where b − a > 0 is an integer multiple of c > 0, we write [a : c : b] := {a, a+ c, a+ 2c, . . . , b− c, b}.
B.1 APPROXIMATING FPE WITH FPE(δ)
Lemma 8. For any given f ∈ FPE and 1 ≤ p <∞, one can find a δ∗ > 0 such that ∃ f ∈ FPE(δ∗) which satisfies dp(f, f) ≤ /3.
Proof Since f : Rd×n → Rd×n is a continuous function with compact support, the function is uniformly continuous. Since continuity is defined using entry-wise `p norm, and entry-wise `p norm is equivalent to entry-wise `∞ norm when the number of entries are finite, uniform continuity implies that
∀ > 0,∃δ > 0 such that ∀X,Y , ‖X − Y ‖∞ < δ =⇒ ‖f(X)− f(Y )‖p < .
This means that given any /3 > 0, we have such a δ > 0. Using this δ, we can create a grid Gδ and corresponding cubes SL, as described in the main text. For any L ∈ Gδ , we define CL ∈ SL to be the center point of the cube SL. Then, we can define a piece-wise constant approximation f(X) = ∑ L∈Gδ f(CL)1 {X ∈ SL}. Note that, for any X ∈ SL, we have ‖X −CL‖∞ < δ, so
by uniform continuity, we have ∥∥f(X)− f(X)∥∥
p = ‖f(X)− f(CL)‖p < /3. This proves that
dp(f, f) < /3.
As for permutation equivariance, since f is permutation equivariant, we have f(CLP ) = f(CL)P for any permutation matrix P . For any X ∈ SL, we have XP ∈ SLP , so
f(XP ) = f(CLP ) = f(CLP ) = f(CL)P = f(X)P .
Thus, the approximation f is also permutation equivariant. This proves the lemma.
B.2 APPROXIMATING T 2,1,1 WITH T 2,1,4
Lemma 9. For each g ∈ T 2,1,1 and 1 ≤ p <∞, ∃ g ∈ T 2,1,4 such that dp(g, g) ≤ /3.
Proof Recall that Th,m,r refers to the class of functions representable with composition of Transformer blocks with h heads of size m in self-attention layers and r hidden nodes in feed-forward layers. The same notation holds for the modified Transformers T h,m,r. Note that the softmax operator on a matrix A can be made arbitrarily close to hardmax by scaling up A. That is, σ[λA]→ σH[A] as λ→∞. This means that by scaling up parameters inside σ, we can approximate σH arbitrarily closely. Thus, the modified self-attention layers can be approximated with the original self-attention layers of the same number of heads h and head size m.
Also, any arbitrary (possibly discontinuous) piecewise linear function φ ∈ Φ can be approximated arbitrarily closely by four ReLU’s. Note that φ ∈ Φ as at most three pieces, and at least one of the pieces is constant. For example, consider the following function φ ∈ Φ:
φ(t) =  b1 if t < c1, a2t+ b2 if c1 ≤ t < c2, a3t+ b3 if c2 ≤ t.
This function can be approximated by four ReLU’s, as claimed by the lemma:
φ̃(t) = b1 + a2c1 + b2 − b1 ReLU(t− c1 + ) + ( a2 − a2c1 + b2 − b1 ) ReLU(t− c1)
+
( a3c2 + b3 − a2(c2 − )− b2
− a2 ) ReLU(t− c2 + )
+ ( a3 − a3c2 + b3 − a2(c2 − )− b2 ) ReLU(t− c2)
=  b1 if t < c1 − , a2c1+b2−b1 (t− c1) + a2c1 + b2 if c1 − ≤ t < c1, a2t+ b2 if c1 ≤ t < c2 − , a3c2+b3−a2(c2− )−b2
(t− c2) + a3c2 + b3 if c2 − ≤ t < c2, a3t+ b3 if c2 ≤ t.
Also, as we make → 0, we can approximate φ as closely as possible using φ̃. The cases where the second or third piece is constant can be shown similarly. This means that the modified feed-forward layers (whose activation is φ ∈ Φ) with single hidden node can be approximated with the original feed-forward layers (ReLU) with four hidden nodes.
Thus, given any g ∈ T 2,1,1, there exists a function g ∈ T 2,1,4 arbitrarily close to g, by appropriately choosing the parameters to be large enough. This finishes the proof.

heading: B.3 FINISHING PROOF OF PROPOSITION 4
text: As we have already discussed in Section 4, we establish Proposition 4 in three steps:
1. Given an input X , a group of feed-forward layers in the modified Transformer network can quantize X to an element L on the extended grid G+δ := {−δ−nd, 0, δ, . . . , 1− δ}d×n.
2. Next, a group of self-attention layers in the modified Transformer network can take the input L and produce desirable contextual mappings q(L) such that, for L and L̃, that are not permutation of each other, all the elements in q(L) and q(L̃) are distinct.
3. Finally, a group of feed-forward layers in the modified Transformer network can map elements of the contextual embedding q(L) to the desirable values, i.e., the output of f ∈ FPE on the input X .
These steps are formally stated in Lemmas 5, 6, and 7 in the main text. We present the proofs of these lemmas in the subsequent sections.
With the results established in these lemmas, we are now equipped with all the tools necessary to complete the proof of Proposition 4. Let us recall the functions gq, gc, and gv from Lemma 5, 6, and 7, respectively. We now show that the (modified) Transformer network g = gv ◦ gc ◦ gq approximates the underlying peicewise constant function f ∈ FPE over all points in its support except for a set of of measure O(δd).
Consider a point X ∈ SL ⊂ [0, 1]d×n, where L ∈ G̃δ . By Lemma 5, we have that gq(X) = L. Thus, it follows from Lemmas 6 and 7 that
gv ◦ gc ◦ gq(X) = gv ◦ gc(L) = [ gtknv (gc(L)·,1) g tkn v (gc(L)·,2) · · · gtknv (gc(L)·,n) ] = AL.
On the other hand, any point X ∈ ⋃
L∈Gδ\G̃δ SL ∪ (R d×n \ [0, 1]d×n) is mapped by gq to L ∈
G+δ \ G̃δ; as a result, we get gv ◦ gc ◦ gq(X) = gv ◦ gc(L) = 0. Therefore, we have g(X) = gv◦gc◦gq(X) = AL = f(X) for X ∈ ⋃
L∈G̃δ SL, and 0 everywhere else. Recall that f has its compact support in [0, 1]d, thus bounded; i.e., there exists B ≥ 0 such that ‖f(X)‖p ≤ B. The modified Transformer network g takes the same value as f on all points in [0, 1]d except for a set ⋃ L∈Gδ\G̃δ SL that has measure O(δ
d). This implies that dp(f, g) ≤ (Bpδd)1/p = O(δd/p).

heading: B.4 PROOF OF LEMMA 5
text: The proof strategy is simple; using 1δ + 1 token-wise feed-forward layers, we implement the quantization function gentq that works on the first row of the input. Then stack another 1 δ + 1 layers that quantizes the second row, and so on.
Given input X , we first start by clipping X1,: in the set (−∞, 0)∪[1,+∞) and mapping the intervals to −δ−nd. This can be done by the following layer:
Z 7→ Z + e(1)φ((e(1))TZ), φ(t) = { −t− δ−nd if t < 0 or t ≥ 1, 0 otherwise.
Next, add 1/δ layers of the following form, for k = 0, δ, . . . , 1− δ. Z 7→ Z + e(1)φ((e(1))TZ − kδ1Tn ), φ(t) = {
0 t < 0 or t ≥ δ −t 0 ≤ t < δ.
Each layer quantizes X1,: in [kδ, kδ + δ) to kδ, without modifying other intervals.
Note that both φ’s used in this construction are piecewise linear functions with three pieces, and at least one of them are constant. Thus, both φ’s are in Φ. We can repeat the same thing for the other rows, and at the end we will get a map from Rd×n to G+δ .

heading: B.5 PROOF OF LEMMA 6
text: Selective shift operation. Before starting the proof, we first describe the key component of our proof, which we refer to the selective shift operation. Consider the following function, which can be expressed with a multiplicative attention head, with head size m = 1 and hardmax σH:
ψ(Z; bQ) = e (1)uTZσH[(u TZ)T (uTZ − bQ1Tn )]
where u ∈ Rd is a vector that we will choose later, and e(1) = (1, 0, 0, . . . , 0) ∈ Rd is the standard basis vector.
To see what this function computes, first consider the j-th column of the attention score matrix: (uTZ)T (uTZ:,j − bQ). Note that, if uTZ:,j > bQ, σH will calculate arg max of uTZ, whereas if uTZ:,j < bQ, it will calculate arg min. Therefore, the (1, j)-th entry of ψ(Z; bQ) ∈ Rd×n can be written as
ψ(Z; bQ)1,j = u TZσH[(u TZ)T (uTZ:,j − bQ)] = { maxk u TZ:,k if uTZ:,j > bQ,
mink u TZ:,k if uTZ:,j < bQ,
for j ∈ [n]. Note that due to e(1), all rows of ψ(Z; bQ) except the first row are zero. From this observation, one can define a function parametrized by bQ and b′Q, where bQ < b ′ Q, which consists of two attention heads:
Ψ(Z; bQ, b ′ Q) := ψ(Z; bQ)− ψ(Z; b′Q),
Ψ(Z; bQ, b ′ Q)1,j =
{ maxk u
TZ:,k −mink uTZ:,k if bQ < uTZ:,j < b′Q, 0 if uTZ:,j < bQ or uTZ:,j > b′Q.
What this means is that, if we define an attention layer of the form Z 7→ Z + Ψ(Z; bQ, b′Q), then any column Z:,j satisfying uTZ:,j ∈ (bQ, b′Q) is shifted up in its first coordinate Z1,j by maxk u
TZ:,k − mink uTZ:,k, while all the other coordinates stay untouched. We call this the selective shift operation, because we can choose bQ and b′Q to selectively shift certain entries of the input.
Bijective column id mapping. Recall that the input to this step is from the range of gq (Lemma 5), which is G+δ = {−δ−nd, 0, δ, . . . , 1 − δ}d×n. Now consider L ∈ G + δ and u = (1, δ−1, δ−2, . . . , δ−d+1).
For any j ∈ [n], it is easy to check two following facts:
1. If Li,j 6= −δ−nd for all i ∈ [d], i.e., L:,j ∈ {0, δ, . . . , 1 − δ}d, then uTL:,j ∈ [0 : δ : δ−d+1 − δ], and the map L:,j 7→ uTL:,j from {0, δ, . . . , 1− δ}d to [0 : δ : δ−d+1 − δ] is a bijection.
2. If there exists i ∈ [d] such that Li,j = −δ−nd, then uTL:,j ≤ −δ−nd + δ−d+1 − 1 < 0.
Therefore, one can say that uTL:,j gives the “column id” for each possible value of L:,j ∈ {0, δ, . . . , 1− δ}d. The rough idea of the construction is to apply the selective shift operation to each column id, by setting u in the definition of Ψ(·) to be (1, δ−1, δ−2, . . . , δ−d+1) and choosing bQ = l − δ/2 and b′Q = l + δ/2 for each l ∈ [0 : δ : δ−d+1 − δ]. More concretely, we stack (1/δ)d attention layers, with attention parts δ−dΨ(·; l− δ/2, l+ δ/2) for each l ∈ [0 : δ : δ−d+1− δ], in increasing order of l. After that, we add an extra single-head attention layer with attention part δ−(n+1)dψ(·; 0).
We now divide possible input values L ∈ G+δ into three disjoint categories, and show how these layers change the input values at the end of all the layers. Recall the hierarchy G̃δ ⊂ Gδ ⊂ G+δ . The categories are defined as follows:
1. L ∈ G̃δ . All entries are between 0 and 1− δ, and all columns are unique. 2. L ∈ Gδ \ G̃δ . All entries are between 0 and 1− δ, but there are duplicate columns. 3. L ∈ G+δ \Gδ . The point has at least one entry that equals to −δ−nd.

heading: B.5.1 CATEGORY 1
text: In Category 1, we have L ∈ G̃δ . Let lj := uTL:,j . Due to permutation equivariance, we can assume without loss of generality that lj’s are in increasing order: l1 < l2 < · · · < ln. The first (1/δ)d layers sweep the set [0 : δ : δ−d+1 − δ] and apply selective shift operation on each element in the set. This means that selective shift operation will be applied to l1 first, then l2, and then l3, and so on, regardless of the specific values of lj’s.
First shift operation. In the first selective shift operation, the (1, 1)-th entry of L (L1,1) is shifted by the operation, while the other entries are left untouched. The updated value L̃1,1 is
L̃1,1 = L1,1 + δ −d(maxk u TL:,k −mink uTL:,k) = L1,1 + δ−d(ln − l1). Therefore, after the operation, the output of the layer is [ L̃:,1 L:,2 . . . L:,n ] , and the new value
of the first column L̃:,1 results in
uT L̃:,1 = L̃1,1 + d∑ i=2 δ−i+1Li,1 = L1,1 + δ −d(ln − l1) + d∑ i=2 δ−i+1Li,1 = l1 + δ −d(ln − l1).
Let us denote the updated “column id” uT L̃:,1 as l̃1. We can show that ln < l̃1, because
l̃1 := l1 + δ −d(ln − l1) ≥ 0 + δ−d · δ = δ−d+1 > ln.
Therefore, after updating, maxuT [ L̃:,1 L:,2 . . . L:,n ] = max{l̃1, l2, . . . , ln} = l̃1,
and the new minimum is l2.
Second shift operation. The second selective shift operation is applied to l2, by which only one entry L1,2 will be shifted. The updated value L̃1,2 is
L̃1,2 = L1,2 + δ −d(l̃1 − l2) = L1,2 + δ−d(l1 − l2) + δ−2d(ln − l1).
After updating, the new inner product of u and L̃:,2 results in
l̃2 := u T L̃:,2 = l2 + δ −d(l1 − l2) + δ−2d(ln − l1).
We can show that l̃1 < l̃2, because l1 + δ
−d(ln − l1) < l2 + δ−d(l1 − l2) + δ−2d(ln − l1) ⇔ (δ−d − 1)(l2 − l1) < δ−d(δ−d − 1)(ln − l1),
and the last inequality is true because δ−d > 1 and ln > l2. Since we have l̃1 < l̃2, and the new maximum in uT [ L̃:,1 L̃:,2 L:,3 . . . L:,n ] is now l̃2, and the new minimum is l3.
Repeating the process. More generally, we can repeat this process, and show that the j-th shift operation shifts L1,j by δ−d(l̃j−1 − lj), and results in the new column id
l̃j := u T L̃:,j = lj + j−1∑ k=1 δ−kd(lj−k − lj−k+1) + δ−jd(ln − l1).
In the general case, l̃j−1 < l̃j holds j = [2 : n], because
l̃j−1 = lj−1 + j−1∑ k=2 δ−kd+d(lj−k − lj−k+1) + δ−(j−1)d(ln − l1)
< l̃j = lj + j−1∑ k=1 δ−kd(lj−k − lj−k+1) + δ−jd(ln − l1)
⇔ j−1∑ k=1 δ−kd+d(δ−d − 1)(lj−k+1 − lj−k) < δ−(j−1)d(δ−d − 1)(ln − l1),
and the last inequality holds because
δ−(j−1)d(ln − l1) > δ−(j−1)d j−1∑ k=1 (lj−k+1 − lj−k) > j−1∑ k=1 δ−kd+d(lj−k+1 − lj−k).
Therefore, after the j-th selective shift operation, l̃j is the new maximum among {l̃1, . . . , l̃j , lj+1, . . . , ln} and lj+1 is the new minimum, which makes us possible to continue the process until the n-th operation.
After n shift operations. As a result, after the whole sweep from 0 to δ−d+1 − δ by the first (1/δ)d layers, a total of n shift operations are applied, and the input L is mapped to a new point L̃, where uT L̃ = [ l̃1 l̃2 . . . l̃n ] and l̃1 < l̃2 < · · · < l̃n.
We can now prove the following technical lemma, whose proof is deferred to Appendix B.5.4:
Lemma 10. After n shift operations, l̃n = uT L̃:,n satisfies the following bounds:
δ−(n−1)d+1(δ−d − 1) ≤ l̃n ≤ δ−nd+1(δ−d − 1)− δ(δ−d − 1)2.
Also, the map from [l1 l2 · · · ln] ∈ [0 : δ : δ−d+1 − δ] (where l1 < l2 < · · · < ln) to l̃n is one-to-one.
Global shifting by the last layer. As mentioned earlier, after this sweep, there is another attention layer with attention part δ−(n+1)dψ(·; 0). Since 0 < l̃1 < · · · < l̃n, what it does to L̃ is that it adds δ−(n+1)d maxk u T L̃:,k = δ −(n+1)d l̃n to each entry in the first row of L̃. The output of this layer is defined to be the function gc(L).
Now, in summary, for any L ∈ G̃δ , i ∈ [d], and j ∈ [n], we have
gc(L)i,j =
{ L1,j + ∑j−1 k=1 δ
−kd(lj−k − lj−k+1) + δ−jd(ln − l1) + δ−(n+1)d l̃n if i = 1, Li,j if i ∈ [2, d],
and for any L ∈ G̃δ and j ∈ [n],
uT gc(L):,j = l̃j + δ −(n+1)d l̃n.
Checking Properties 6.1 and 6.2. Given this result so far, it is now left to check if the constructed network is really a permutation equivariant contextual mapping, i.e., if it satisfies Properties 6.1 and 6.2 in Lemma 6.
First, for any L ∈ G̃δ , Property 6.1 holds because we already know l̃1 < l̃2 < · · · < l̃n, so they are all distinct. As for Property 6.2, note that the upper bound on l̃n from Lemma 10 also holds for other l̃j’s, so
uT gc(L):,j ∈ [δ−(n+1)d l̃n, δ−(n+1)d l̃n + δ−(n+1)d+1),
for all j ∈ [n]. Now, from Lemma 10, two L,L′ ∈ G̃δ (that are not permutations of each other) map to different l̃n and l̃′n, and they differ at least by δ. This means that two intervals [δ−(n+1)d l̃n, δ −(n+1)d l̃n+δ −(n+1)d+1) and [δ−(n+1)d l̃′n, δ −(n+1)d l̃′n+δ −(n+1)d+1) are guaranteed to be disjoint, so the entries of uT gc(L) and uT gc(L′) are all distinct. This proves Property 6.2.
Therefore, we finished showing that the map gc(·) we constructed using (1/δ)d + 1 attention layers implements a permutation equivariant contextual mapping on G̃δ .
Checking Property 6.3. It is now left to check if the map gc satisfies the other properties. At this point, we can check Property 6.3. From uT gc(L):,j ∈ [δ−(n+1)d l̃n, δ−(n+1)d l̃n + δ−(n+1)d+1) and Lemma 10, we can show that for any L ∈ G̃δ , we have
δ−2nd+1(δ−d − 1) ≤ uT gc(L):,j < δ−(n+1)d(δ−nd+1(δ−d − 1)− δ(δ−d − 1)2) + δ−(n+1)d+1
≤ δ−(2n+1)d+1(δ−d − 1),
where we used δ−1 ≥ 2. This proves that all uT gc(L):,j are between tl = δ−2nd+1(δ−d − 1) and tr = δ
−(2n+1)d+1(δ−d − 1). For the remaining input points L ∈ G+δ \ G̃δ , we will check that uT gc(L):,j is outside the interval [tl, tr] (Property 6.4).

heading: B.5.2 CATEGORY 2
text: In Category 2, we have L ∈ Gδ\G̃δ . Here, all entries are between 0 and 1−δ, but there are duplicate columns. Again, let lj := uTL:,j , and assume without loss of generality that l1 ≤ l2 ≤ · · · ≤ ln.
For the input L in Category 2, there exist some j, j′ ∈ [n], j 6= j′, such that lj = lj′ . This means that when the input passes through the attention layer δ−dΨ(·; lj − δ/2, lj + δ/2), the selective shift operation for lj is applied to both j-th and j′-th columns; the two columns are coupled together. More generally, suppose we have n′ < n distinct columns.
If n′ = 1. In the extreme case of n′ = 1, we have maxj lj = minj lj , so the selective shift operation applied at lj does not shift the entry at all; therefore, at the end of the first (1/δ)d attention layers, L̃ = L.
If 1 < n′ ≤ n− 1. When 1 < n′ ≤ n− 1, let the n′ distinct values of lj’s be l′1, . . . , l′n′ . The shift operation is applied n′ times, to l′1, . . . , l ′ n′ , and shifts one or more entries at a time. After the first (1/δ)d layers, the output L̃ has n′ distinct l̃j = uT L̃:,j , 0 ≤ l̃1 ≤ l̃2 ≤ · · · ≤ l̃n, whose distinct values are the same as the numbers we get when we apply shift operations to a length-n′ sequence [l′1 . . . l ′ n′ ]. Then, applying the same calculations from Category 1 shows that
l̃n = u T L̃:,n = l ′ n′ + n′−1∑ k=1 δ−kd(l′n′−k − l′n′−k+1) + δ−n ′d(l′n′ − l′1),
and it follows from the upper bound in Lemma 10 that
l̃n ≤ δ−n ′d+1(δ−d − 1)− δ(δ−d − 1)2 < δ−(n−1)d+1(δ−d − 1).
Note that the RHS matches the lower bound in Lemma 10. This implies that the value of l̃n calculated from the input L ∈ Gδ \ G̃δ (Category 2) is always strictly less (by at least δ) than that calculated from L ∈ G̃δ (Category 1).
Checking Property 6.4. After the global shifting by the last layer with attention part δ−(n+1)dψ(·; 0), we get the output gc(L) which satisfies
uT gc(L):,j = l̃j + δ −(n+1)d l̃n ≤ (δ−(n+1)d + 1)(δ−(n−1)d+1(δ−d − 1)− δ(δ−d − 1)2)
< δ−2nd+1(δ−d − 1) =: tl.
where the RHS is a lower bound on possible values of uT gc(L):,j for L ∈ G̃δ (Category 1). This means that the entries of uT gc(L) for Category 2 are outside [tl, tr], which satisfies Property 6.4.

heading: B.5.3 CATEGORY 3
text: In Category 3, we have L ∈ G+δ \ Gδ; the point L has at least one entry that equals to −δ−nd. Let lj := u
TL:,j , and recall that whenever a column L:,j has an entry that equals to −δ−nd, we have lj = u TL:,j ≤ −δ−nd+δ−d+1−1 < 0. Assume without loss of generality that l1 ≤ l2 ≤ · · · ≤ ln.
Recall that the selective shift operation is applied to each element of [0 : δ : δ−d+1 − δ], not to negative values. In case of Category 3, we have mink uTL:,k = l1 < 0, and l1 never gets shifted upwards, so it remains as the minimum for the whole time.
If all lj’s are negative. In case where all lj’s are negative, selective shift operation never changes the input L, so we get L̃ = L. Since we have uT L̃ < 0Tn (entry-wise), the last layer with attention part δ−(n+1)dψ(·; 0) adds δ−(n+1)d mink uT L̃:,k < 0 to each entry in the first row of L̃, further pushing it to the negative side. Therefore, the final output gc(L) satisfies uT gc(L) < 0Tn < tl1 T n .
If not all lj’s are negative. Now consider the case where at least one lj is positive. Let i be the index that satisfies li−1 < 0 ≤ li. Then, selective shift operation does not affect l1, . . . , li−1, and then it shifts li by
δ−d(max k uTL:,k −min k uTL:,k) = δ −d(ln − l1) ≥ δ−d(0 + δ−nd − δ−d+1 + 1) ≥ δ−(n+1)d+1,
where we used δ−1 ≥ 2 at the last inequality. The next shift operations shift li+1, . . . , ln by even larger amount, so at the end of the first (1/δ)d layers, we have δ−(n+1)d+1 ≤ l̃i ≤ · · · ≤ l̃n, while l̃j = lj < 0 for j ∈ [i− 1].
Shifts by the last layer. Here, the last layer with attention part δ−(n+1)dψ(·; 0) acts differently for negative and positive l̃j’s. For negative l̃j’s, it adds δ−(n+1)d mink l̃k = δ−(n+1)dl1 < 0 to l̃1, . . . , l̃i−1, pushing them further to the negative side. For positive l̃j’s, the layer adds δ−(n+1)d maxk l̃k = δ
−(n+1)d l̃n ≥ δ−(2n+2)d+1 to l̃i, . . . , l̃n, so that they are all greater than or equal to δ−(2n+2)d+1. Note that δ−(2n+2)d+1 > tr.
Checking Property 6.4. Therefore, in both cases, we can see that the final output gc(L) satisfies uT gc(L):,j /∈ [tl, tr], for all j ∈ [n]. This completes the verification of Property 6.4.

heading: B.5.4 PROOF OF LEMMA 10
text: Proof of lower and upper bounds on l̃n are straightforward:
l̃n := ln + n−1∑ k=1 δ−kd(ln−k − ln−k+1) + δ−nd(ln − l1)
≥ δ−(n−1)d n−1∑ k=1 (ln−k − ln−k+1) + δ−nd(ln − l1) = (δ−nd − δ−(n−1)d)(ln − l1) ≥ δ−(n−1)d+1(δ−d − 1),
l̃n ≤ ln + δ−d(l1 − ln) + δ−nd(ln − l1) ≤ δ−d+1 − δ + (δ−nd − δ−d)(δ−d+1 − δ) = δ−nd+1(δ−d − 1)− δ(δ−2d − 2δ−d + 1) = δ−nd+1(δ−d − 1)− δ(δ−d − 1)2.
For one-to-one property of the map, consider [l1 l2 · · · ln] and [l′1 l′2 · · · l′n] with increasing entries, which are mapped to l̃n and l̃′n, respectively. Suppose l̃n = l̃ ′ n. By definition,
l̃n − l̃′n =(ln − l′n) + δ−d(ln−1 − ln − l′n−1 + l′n) + δ−2d(ln−2 − ln−1 − l′n−2 + l′n−1) + . . . + δ−(n−1)d(l1 − l2 − l′1 + l′2) + δ−nd(ln − l1 − l′n + l′1) = 0.
Now assume for contradiction that ln 6= l′n. Then, we have −δ−d+1 + δ ≤ ln − l′n ≤ δ−d+1 − δ. However, the remaining terms have “coarse resolution”, and they can never cancel ln − l′n and make the sum zero, because for example, δ−d(ln−1 − ln − l′n−1 + l′n) can only have values 0, δ−d+1,−δ−d+1, 2δ−d+1,−2δ−d+1, . . . . Thus, ln = l′n must hold and the first term must be zero.
Similarly, assume that ln−1 6= l′n−1. Then, the second term is in the interval [−δ−2d+1 + δ−d+1, δ−2d+1 − δ−d+1]. Again, the remaining terms cannot cancel the second term, hence ln−1 = l ′ n−1 must hold. We can proceed this way, and show that lj = l ′ j must hold for all j ∈ [n], hence proving that the map is one-to-one.

heading: B.6 PROOF OF LEMMA 7
text: Note that |G+δ | = ( 1 δ + 1) dn, so the image of gc(G+δ ) (from Lemma 6) has finite number of distinct real numbers. Let M be the maximum over all these numbers. By construction of gc, we know that M > 0.
To construct a function gtknv that satisfies the statement of the lemma, we first implement the second part: gtknv (gc(L):,j) = 0d if L ∈ G+δ \ G̃δ . Note from Lemma 6 that, for any L ∈ G̃δ , we have uT gc(L):,j ∈ [tl, tr] for all j, and for any L ∈ G+δ \ G̃δ , uT gc(L):,j /∈ [tl, tr] for all j. Using this, we add the following feed-forward layer:
Z 7→ Z − (M + 1)1nφ(uTZ), φ(t) = {
0 if t ∈ [tl, tr] 1 if t /∈ [tl, tr].
Input to this layer is gc(L). If L ∈ G̃δ , then φ(uT gc(L)) = 0Tn , so the output stays the same as the input. If L ∈ G+δ \ G̃δ , then φ(uT gc(L)) = 1Tn , so all the entries of the input are shifted by −M − 1, and become strictly negative.
Recall that by definition of G̃δ , all the entries of gc(L) for L ∈ G̃δ are nonnegative. So the next thing to do is mapping all strictly negative entries to zero. This can be done in a similar way as Lemma 5. For i ∈ [d], add the following layer:
Z 7→ Z + e(i)φ((e(i))TZ), φ(t) = { −t if t < 0 0 if t ≥ 0.
After these d layers, the output for L ∈ G+δ \ G̃δ is a zero matrix, while the output for L ∈ G̃δ is gc(L).
Now, it is left to map gc(L) to AL, for L ∈ G̃δ . Up to permutation equivariance, each different context L maps to n unique numbers uT gc(L), which are at least δ apart from each other. The idea of value mapping is to map each unique number to the corresponding output column.
More precisely, choose any L ∈ G̃δ . For each value of uT gc(L):,j , j ∈ [n], we add one feedforward layer
Z 7→ Z + ((AL):,j − gc(L):,j)φ(u TZ − uT gc(L):,j1Tn ), φ(t) = { 0 t < −δ/2 or t ≥ δ/2, 1 −δ/2 ≤ t < δ/2.
If the input Z is a zero matrix, which is the case for L ∈ G+δ \ G̃δ , uTZ = 0Tn . Since tl is much larger than 0, activation is all zero. Thus, zero input matrix remains the same at the output.
If the input Z is gc(L), where L ∈ G̃δ is not a permutation of L, then
φ(uT gc(L)− uT gc(L):,j1Tn ) = 0Tn ,
so gc(L) is left untouched.
If some other L is a permutation of L, and L:,i = L:,j , then
φ(uT gc(L)− uT gc(L):,j1Tn ) = (e(i))T ,
so i-th column of gc(L) will turn to
gc(L):,i 7→ gc(L):,i + ((AL):,j − gc(L):,j) = gc(L):,i + ((AL):,i − gc(L):,i) = (AL):,i,
which is the desired output. In conclusion, this layer maps the column gc(L):,j to (AL):,j , without affecting any other columns.
As seen above, we need one layer per each unique value of uT gc(L):,j for each L ∈ G̃δ . Note that there are O(n(1/δ)dn/n!) such numbers, so we can use O(n(1/δ)dn/n!) layers to finish our construction.

heading: C PROOF OF THEOREM 3
text: Proof of Theorem 3 can be done in a similar way as Theorem 2. As in the proof of Theorem 2, there are three parts: Lemma 8, Proposition 4, and Lemma 9. The statement and proof of Lemmas 8 and 9 can be done in almost the same way, this time without permutation equivariance.
For the proof of the second part, which corresponds to Proposition 4, we construct the network in a similar way. Recall that we can assume without loss of generality that X ∈ [0, 1]d×n. Choose
E =  0 1 2 · · · n− 1 0 1 2 · · · n− 1 ... ... ...
... 0 1 2 · · · n− 1  . Then, the first column of X + E is in [0, 1]d, second is in [1, 2]d, and so on; this means that for all rows, the coordinates are monotonically increasing. So we can use the same technique as the proof of Proposition 4 to divide the input values into cubes, quantize them to L, apply contextual mapping, and then value mapping. We describe each step in the following.

heading: C.1 QUANTIZATION BY FEED-FORWARD LAYERS
text: In a similar way as Lemma 5, the goal of this step is to quantize the input in [0, 1]d × [1, 2]d × · · · × [n− 1, n]d to its discrete version:
[0 : δ : 1− δ]d × [1 : δ : 2− δ]d × · · · × [n− 1 : δ : n− δ]d.
This can be done by dn/δ feed-forward layers. We add dn/δ layers of the following form, for k = 0, δ, . . . , n− δ and i = 1, . . . , d:
Z 7→ Z + e(i)φ((e(i))TZ − kδ1Tn ), φ(t) = {
0 t < 0 or t ≥ δ −t 0 ≤ t < δ.
After dn/δ layers, any input entry of X + E in [kδ, kδ + δ) is quantized to kδ.

heading: C.2 CONTEXTUAL MAPPING BY ATTENTION LAYERS
text: By Step 1, we quantized any input X + E to its quantized version. We call this quantized version L: L ∈ [0 : δ : 1− δ]d × [1 : δ : 2− δ]d × · · · × [n− 1 : δ : n− δ]d. As done in Lemma 6, we define u := (1, δ−1, . . . , δ−d+1) and lj := uTL:,j , for all j ∈ [n]. Note that, because L:,j ∈ [j − 1 : δ : j − δ]d, we have
(j − 1)(1 + δ−1 + · · ·+ δ−d+1) ≤ lj ≤ (j − 1)(1 + δ−1 + · · ·+ δ−d+1) + δ−d+1 − δ,
and l1 < l2 < · · · < ln. Notice that this corresponds to the Category 1 in the proof of Lemma 6. For simplicity of notation, let sj = (j − 1) ∑d−1 k=0 δ
−k. We stack n(1/δ)d attention layers, with attention parts δ−dΨ(·; l − δ/2, l + δ/2) for each l ∈ ⋃n j=1[sj : δ : sj + δ
−d+1 − δ], in increasing order of l.
These n(1/δ)d attention layers perform selective shift operations on lj’s, in increasing order of j. As seen in Appendix B.5.1, shift operations result in l̃1 < l̃2 < · · · < l̃n. Also, the map from L to l̃n is one-to-one, which can be shown in the same way as Appendix B.5.4. Since the range of lj’s are a bit different, we have a different upper bound on l̃n:
l̃n := ln + n−1∑ k=1 δ−kd(ln−k − ln−k+1) + δ−nd(ln − l1)
≤ ln + δ−d(l1 − ln) + δ−nd(ln − l1) ≤ sn + δ−d+1 − δ + (δ−nd − δ−d)(sn + δ−d+1 − δ) = (δ−nd − δ−d + 1) (
(n− 1)δ −d − 1 δ−1 − 1
+ δ−d+1 − δ )
≤ (δ−nd − δ−d + 1)(δ−d − 1)(n− 1 + δ) < nδ−(n+1)d.
Finally, we add an extra single-head attention layer with attention part nδ−(n+1)d−1ψ(·; 0). We define the output of this layer as gc(L). In a similar way as Appendix B.5.1, this layer shifts all the layers by nδ−(n+1)d−1 l̃n, thus making the intervals corresponding to different values of l̃n disjoint from each other. This ensures that different contexts L are mapped to distinct numbers in uT gc(L), thus implementing a contextual mapping.

heading: C.3 FUNCTION VALUE MAPPING BY FEED-FORWARD LAYERS
text: Now, it is left to map gc(L) to the desired output. As seen in the last step, each different context L maps to n unique numbers uT gc(L), which are at least δ apart from each other. The value mapping step can be done in a similar way as Lemma 7. The construction now requires O(n(1/δ)dn) layers because there is no permutation equivariance.

heading: D EXPERIMENTAL SETUP
text: For our experiments we follow the same setting as in BERT (Devlin et al., 2018). We first pre-train the models on the masked language modeling task and the next sentence prediction task. We use English Wikipedia corpus and BooksCorpus dataset (Zhu et al., 2015) for this pre-training. We use BERTBASE, a 12 layer Transformer model as the baseline. This model uses an embedding size of 768 and has 12 head self-attention layers and 3072 wide feed forward layers. We train it with the Adam optimizer, with .01 dropout and weight decay. We do pre-training for 250k steps with a batch size of 1024 and a max sequence length of 512. Pre-training takes around 2 days on 16 TPUv3 chips. We take the pre-train models and finetune them on the MNLI and SQuAD datasets separately using the same hyper-parameters as in Devlin et al. (2018). MNLI is a sentence entailment task in which, given a premise sentence, requires us to classify a hypothesis sentence into neutral, contradiction or entailment classes. We report the classification accuracy on this task. SQuAD is a question answering task, in which given a paragraph and a question, requires us to identify the answer as a span of the words in the paragraph. For this task we report both the F1 score and the Exact Match (EM) percentage. The metrics are reported on the dev sets of these datasets.
For our experiments with the depth-wise separable convolution layers, we follow the implementation in (Wu et al., 2019). We first use a GLU layer followed by the convolution layer. We use 16 separable convolution filters, of filter length 128, and reuse them, with each filter operating on 48 of the 768 dimensions of the input. This layer also has a skip connection and the output is normalized using layer normalization, similar to the self-attention layer. In our experiments, we replace the selfattention layers of the Transformers, in the lower layers, with this convolution layer. We keep the feed forward layer of the Transformer block the same.
For the experiments performed in this paper, one might consider an alternate explanation that the tasks considered maybe are easy, and do not require any advanced architecture to solve them, and even a simple architecture (bi-linear projection or separable convolution) might solve these tasks. To rule out this case we consider an even simpler architecture, namely average attention, as a baseline for our experiments.
Average attention. An average attention layer replaces the self-attention layer, and just computes the average of projections of all the other tokens. That is, we replace σ[(W iKX)
TW iQX] in (1) with a matrix full of 1/n. The model still has the skip connections and the feed-forward layers like Transformer.

Review summaries:
C1. Transformers (without positional encodings and without layer normalization), with 2 attention heads of dimension 1 and feed-forward layers (FFN) with 4 hidden nodes, are universal approximators of continuous permutation-equivariant functions f of compact support, relative to any Lp metric (1 <= p < \infty). (Thm. 2, p. 3). (Without positional encodings, a function f computed by a Transformer is permutation equivariant: f(P(X)) = P(f(X)) for any permutation P of the columns of X, which are the vector encodings of the input tokens.)

This paper tries to analyse the Transformer, widely applied building block of a neural network component, to improve understanding of the internals of the model. The analysis starts showing that the transformer blocks generate permutation equivalent maps and then shows that the transformer can approximate any permutation equivalent map in a compact domain with arbitrary precision. Three key steps are developed and used to prove the universal approximation of arbitrary permutation equivalent map: 1) quantization of input via feed-forward layers, 2) contextual mapping via attention layers, and 3) value mapping via feed-forward layers. By introducing positional embeddings, the paper relaxes the restriction on permutation equivalence and proves that the Transformer is a universal approximator of any sequence to sequence function.