November 01, 2023
As transformers have gained prominence in natural language processing, some researchers have investigated theoretically what problems they can and cannot solve, by treating problems as formal languages. Exploring such questions can help clarify the power of transformers relative to other models of computation, their fundamental capabilities and limits, and the impact of architectural choices. Work in this subarea has made considerable progress in recent years. Here, we undertake a comprehensive survey of this work, documenting the diverse assumptions that underlie different results and providing a unified framework for harmonizing seemingly contradictory findings.
Transformers [1] have gained prominence in natural language processing (NLP), both in direct applications like machine translation and in pretrained models like BERT [2] and GPT [3]–[5]. Consequently, some researchers have sought to investigate their theoretical properties. Such studies can broadly be divided into studies of expressivity and trainability. While trainability is very important and the focus of much study [6], [7], here we focus on expressivity, which is a prerequisite for trainability.
Studies of expressivity could be further divided into those from the perspectives of approximation theory and of formal language theory. The former [8], [9], investigates transformers as approximators of various classes of functions, along the lines of the universal approximation theorem for feedforward neural networks [10], [11]. The latter, which is the subject of this survey, investigates transformers as recognizers or generators of formal languages – that is, the inputs or outputs are treated as sequences of discrete symbols from a finite alphabet, and crucially as sequences of unbounded length.
The core research question in this subarea is: How can we characterize the expressivity of transformers in relation to various formal models, such as automata, boolean circuits or formal logic? Applications of this subarea, which are not addressed by the papers surveyed here but could be by future work, would hopefully answer questions like:
What new transformer variants are suggested by formal models?
Do failure cases anticipated from formal models occur in practice?
What insights into the complexity of human language are offered by a characterization of transformer expressivity?
This paper provides a comprehensive survey of research in this subarea. Compared to the surveys of [12] and [13], [14], which cover convolutional neural networks (CNNs), RNNs, and transformers, this is a narrower, but deeper, survey on transformers only.
Interpreting theoretical transformer results is complex due to diverse assumptions. Many variants of transformers exist in practice, and even more have been proposed in theory. This diversity leads to varied, even seemingly contradictory, results. We set up a unified framework for talking about transformer variants (4), and discuss how some of these variants compare to one another in expressivity.
We then provide background on various formal models that transformers have been compared with (5). Then, in 6, we systematically survey current results in this literature, documenting their assumptions and claims in terms of the definitions of [bg:transformers] [sec:targets].
1 summarizes the results surveyed here. One way to classify them is into lower bounds (what transformers can do) and upper bounds (what transformers can’t do).
Much work on lower bounds has looked at automata like finite automata, counter machines, and Turing machines, all of which had been successfully related to RNNs before [15], [16]. This wide diversity of machines is due to different variants of transformers, especially whether a transformer decoder is allowed to take a number of intermediate steps before outputting a decision (4.3.4), which dramatically increases its power (6.1).
By contrast, investigation of upper bounds has mainly focused on circuit complexity (5.2), which had been successfully related to feedforward networks before [17]–[20]. This line of research began with restricted models of transformer encoders and progressed to increasingly realistic variants and tighter bounds. One way to restrict transformers is by discretizing the attention mechanism (4.2.1); another is to limit the precision of number representations (4.4).
More recent work has turned to formal logic (5.3) as a way of characterizing the expressive power of transformers. The finer control afforded by logics opens the possibility for them to be used as upper bounds, lower bounds, or both.
We denote by \(\mathbb{N}_0=\{0,1,2,\ldots\}\) and \(\mathbb{N}=\mathbb{N}_0\setminus\{0\}\) the set of natural numbers with and without \(0\), respectively. We write \([n] = \{0,1,2,\ldots,n-1\}\) for any \(n\in\mathbb{N}\). We write \(\Sigma\) for a finite alphabet, which, in NLP applications, is the set of words or subwords known to the model.
We use \(d\), \(d'\), etc., for dimensionalities of vector spaces, lowercase bold letters (\(\mathbf{x}, \mathbf{y}, \dots\)) for vectors, and uppercase bold letters (\(\mathbf{X}, \mathbf{Y}, \dots\)) for matrices. For any vector \(\mathbf{x} \in \mathbb{R}^d\), we number its elements starting from \(0\). For \(i \in [d]\), we write \(\mathbf{x}_i\) or \([\mathbf{x}]_i\) (not \(x_i\)) for the \(i\)-th component of \(\mathbf{x}\).
For any set \(A\), we write \({A}^*\) for the set of all finite sequences over \(A\). We write the length of a sequence \(s \in {A}^*\) as \(|s|\) and number its elements starting from 0; thus, \(s = s_0 s_1 \cdots s_{|s|-1}\). We use the variable \(w\) for a string in \({\Sigma}^*\) and \(n\) for the length of \(w\). For sequences in \({\mathbb{R}}^*\), we use lowercase bold letters (\(\mathbf{x}, \mathbf{y}, \ldots\)), and for sequences in \({{(\mathbb{R}^{d})}^*}\), we use the variable \(X\).
A function \(f\colon{A}^*\rightarrow {B}^*\) is length-preserving if \(|f(w)|=|w|\) for all \(w\in {A}^*\). For every function \(g \colon A \rightarrow B\), we denote its extension to sequences by \(g\) as well. That is, \(g\colon{A}^*\rightarrow{B}^*\) is defined as follows: for all \(s\in{A}^*\) and \(i\in[|s|]\), \(g(s)_i = g(s_i)\).
An affine transformation is a function \(L\colon\mathbb{R}^{d_\text{in}}\rightarrow\mathbb{R}^{d_\text{out}}\) parameterized by weights \(\mathbf{W}_L\in\mathbb{R}^{{d_\text{out}}\times {d_\text{in}}}\) and bias \(\mathbf{b}_L\in\mathbb{R}^{d_\text{out}}\) such that for every \(\mathbf{x}\in\mathbb{R}^{d_\text{in}}\), \(L(\mathbf{x}) = \mathbf{W}_L \mathbf{x} + \mathbf{b}_L\). We say that \(L\) is linear if \(\mathbf{b}_L = \mathbf{0}\).
The activation functions we use are the rectified linear unit (ReLU) \(\mathcal{R}(x) = \max (x,0)\) and the logistic sigmoid function \(\mathcal{\sigma}(x) = 1/(1+e^{-x})\).
The softmax function \(\mathcal{S}\colon {\mathbb{R}}^* \rightarrow {\mathbb{R}}^*\) converts any sequence of reals into a probability distribution: \[\begin{align} \mathcal{S}(\mathbf{x})_i&=\frac{e^{\mathbf{x}_i}}{\sum_{i\in[|\mathbf{x}|]} e^{\mathbf{x}_i}} \qquad \forall i \in [|\mathbf{x}|]. \end{align}\]
In this section, we define transformers and relevant variants, and how transformers are used to describe formal languages. For additional background on transformers (not in relation to formal languages), [21] give a lucid commentary on the original paper, [22] give formal definitions and pseudocode, and [23] survey many variants of transformers.
Transformers are composed of an input layer (4.1), one or more hidden layers (4.2), and an output layer (4.3). The inputs and outputs of the layers are sequences of vectors, which we treat as members of \({{(\mathbb{R}^{d})}^*}\).1
Strings are initially mapped to sequences of vectors using a length-preserving function \(e\colon\Sigma^*\rightarrow{{(\mathbb{R}^{d})}^*}\), which is the sum of a word embedding \(\text{WE} \colon \Sigma \rightarrow\mathbb{R}^d\) and a position(al) embedding or encoding \(\text{PE}_n\colon [n] \rightarrow\mathbb{R}^d\) for \(n \in \mathbb{N}\): \[\begin{align} e(w_0\cdots w_{n-1})_i &= \text{WE}(w_i) + \text{PE}_n(i). \end{align}\]
In theoretical constructions, the word embedding can be any computable function. The original transformer paper [1] introduced the following position embedding: \[[\text{PE}_n(i)]_j = \begin{cases} \sin (10000^{-j/d} \cdot i) & \text{if j even} \\ \cos (10000^{-(j-1)/d} \cdot i) & \text{if j odd.} \end{cases}\] Theoretical papers have explored other position embeddings, including \(i\) itself [24], \(i/n\) [25], [26], and \(1/i\) or \(1/i^2\) [24].
A transformer layer is a length-preserving function \(\mathcal{L}\colon {{(\mathbb{R}^{d})}^*}\rightarrow {{(\mathbb{R}^{d})}^*}\). There are two variants. The post-norm variant [1] is \[\begin{align} X' &= \mathcal{N}_1(X+ \mathcal{A}(X))\\ \mathcal{L}(X) &= \mathcal{N}_2(X' + \mathcal{F}(X')) \addtocounter{equation}{1}\label{eq:postnorm} \end{align}\tag{1}\] and the pre-norm variant [27] is \[\begin{align} X' &= X+ \mathcal{A}(\mathcal{N}_1(X))\\ \mathcal{L}(X) &= X' + \mathcal{F}(\mathcal{N}_2(X')) \addtocounter{equation}{1}\label{eq:prenorm} \end{align}\tag{2}\] where
\(\mathcal{A}\) is a multi-head self-attention with \(d\) input/output dimensions, \(H\) heads, and \({d_\text{kv}}\) key/value dimensions per head
\(\mathcal{F}\) is a feed-forward network (4.2.2) with \(d\) input/output dimensions and \({d_\text{ff}}\) hidden dimensions
\(\mathcal{N}_1\) and \(\mathcal{N}_2\) are layernorms with \(d\) dimensions. We define each of these components below.
Attention was initially developed to facilitate retrieval of previously processed data from a variable-length history [28]. Transformers use a simple variant of attention known as scaled dot-product attention.
Scaled dot-product attention with \(d\) input/output dimensions and \({d_\text{kv}}\) key/value dimensions is a function \({\mathrm{A}}\colon \mathbb{R}^{d} \times {{(\mathbb{R}^{d})}^*} \rightarrow\mathbb{R}^{d}\) parameterized by linear transformations \[\begin{align} W_{\mathrm{A}}^\text{\kern 0.5pt Q},W_{\mathrm{A}}^\text{K},W_{\mathrm{A}}^\text{V}\colon\mathbb{R}^{d}&\rightarrow\mathbb{R}^{{d_\text{kv}}} &W_{\mathrm{A}}^\text{O}\colon\mathbb{R}^{{d_\text{kv}}}&\rightarrow\mathbb{R}^{d} \end{align}\] and defined for every \(\mathbf{z}\in \mathbb{R}^{d}\), \(X\in{{(\mathbb{R}^{d})}^*}\) (with \(|X| = n\)), and \(j \in [n]\) as \[\begin{align} \mathbf{s}(\mathbf{z}, X)_j &= \frac{W_{\mathrm{A}}^\text{\kern 0.5pt Q}(\mathbf{z}) \cdot W_{\mathrm{A}}^\text{K}(X_j)}{\sqrt{d_\text{kv}}} \tag{3} \\ \alpha(\mathbf{z}, X) &= \mathcal{S}(\mathbf{s}(\mathbf{z}, X)) \tag{4} \\ {\mathrm{A}}(\mathbf{z}, X) &= W_{\mathrm{A}}^\text{O}\Bigl( \sum_{j\in[n]} \alpha(\mathbf{z}, X)_j \, W_{\mathrm{A}}^\text{V}(X_j) \Bigr). \notag \end{align}\] Typically, \({\mathrm{A}}\) is extended to a function \({\mathrm{A}}\colon {{(\mathbb{R}^{d})}^*} \times {{(\mathbb{R}^{d})}^*} \rightarrow{{(\mathbb{R}^{d})}^*}\) that is length-preserving in its first argument. In cross-attention, \(\mathbf{z}\) is computed by the decoder while \(X\) is computed by the encoder. In self-attention, the two arguments are identical: \[\begin{align} {\mathrm{SA}}\colon {{(\mathbb{R}^{d})}^*}&\rightarrow{{(\mathbb{R}^{d})}^*} \\ {\mathrm{SA}}(X) &= {\mathrm{A}}(X, X). \end{align}\]
In future masked (also known as causally masked) self attention, a term \(m(i,j)\) is added to 3 to force every position to attend only to preceding positions: \[m(i,j) = \begin{cases} 0 & \text{if j \le i} \\ -\infty & \text{otherwise.} \end{cases}\] Some papers use strict future masking, that is, \(m(i,j) = 0\) iff \(j<i\), and occasionally past masking (\(j \ge i\)) and strict past masking (\(j>i\)).
Multi-head attention with \({d_\text{kv}}\) key/value dimensions per head is the sum of \(H\) attentions with \({d_\text{kv}}\) key/value dimensions: \[\mathcal{A}(\mathbf{z},X)= \sum_{h\in[H]}{\mathrm{A}}_h(\mathbf{z},X).\] Multi-head self attention is defined analogously. This is equivalent to the original formulation, which concatenated the outputs of the heads and passed the result through a shared, larger, \(W_{\mathrm{A}}^\text{O}\).
Some theoretical analyses simplify attention by replacing the softmax with variants that focus attention only on the position(s) with the maximum value, breaking ties in various ways. For any \(\mathbf{s}\in {\mathbb{R}}^*\), let \(M(\mathbf{s}) = \{ i \in [|\mathbf{s}|] \mid \forall j \in [|\mathbf{s}|], \mathbf{s}_j \le \mathbf{s}_i \}\) be the set of indices of the maximal elements of \(\mathbf{s}\). In leftmost-argmax, the leftmost maximal element is used: \[\begin{align} [\mathcal{S}_{\text{h}}(\mathbf{s})]_i &= \mathbb{I}[i = \min M(\mathbf{s})] \\ \intertext{whereas in \emph{average-argmax} the maximal elements share weight equally:} [\mathcal{S}_{\text{a}}(\mathbf{s})]_i &= \frac{\mathbb{I}[i \in M(\mathbf{s})]}{|M(\mathbf{s})|}. \end{align}\] If softmax is thought of as a Boltzmann distribution, then average-argmax is its low-temperature limit.
By substituting \(\mathcal{S}_{\text{h}}\) or \(\mathcal{S}_{\text{a}}\) for \(\mathcal{S}\) in 4 , we get leftmost-hard and average-hard attention, respectively. Leftmost-hard attention was previously called hard attention by [29] and unique hard attention by [30]. One may also consider rightmost-hard attention, in which the rightmost maximal element is used. Average-hard attention was also called hard attention by [24] and saturated attention by [31], and has been argued to be a realistic approximation to how trained transformers behave in practice [32].
Although feed-forward networks can take many forms, in the context of transformers, we use the following definition. A feed-forward network (FFN) with \(d\) input/output dimensions and \({d_\text{ff}}\) hidden dimensions is a function \(\mathcal{F}\colon \mathbb{R}^d\rightarrow \mathbb{R}^d\) parameterized by two affine transformations, \(L_\mathcal{F}^1\colon \mathbb{R}^d\to \mathbb{R}^{d_\text{ff}}\) and \(L_\mathcal{F}^2\colon \mathbb{R}^{d_\text{ff}}\to \mathbb{R}^d\), such that \[\begin{align} \mathcal{F}(\mathbf{x}) &= L_\mathcal{F}^2(\mathcal{R}(L_\mathcal{F}^1(\mathbf{x}))) \end{align}\] where \(\mathcal{R}\) is applied component-wise.
A \(d\)-dimensional layer normalization [33], or layernorm for short, is a function \(\mathcal{N}\colon \mathbb{R}^d \rightarrow \mathbb{R}^d\) parameterized by vectors \(\gamma_\mathcal{N},\beta_\mathcal{N}\in\mathbb{R}^d\) and scalar \(\varepsilon_\mathcal{N}\ge 0\): \[\mathcal{N}(\mathbf{x}) = \gamma_\mathcal{N}\odot \frac{ \mathbf{x} - \bar{\mathbf{x}}}{\sqrt{\mathrm{var}(\mathbf{x})+\varepsilon_\mathcal{N}}}+\beta_\mathcal{N}\] where \(\odot\) is component-wise multiplication and \[\bar{\mathbf{x}} = \frac{1}{d} \sum_{i\in[d]}\mathbf{x}_i \qquad \mathrm{var}(\mathbf{x}) = \frac{1}{d}\sum_{i \in [d]}(\mathbf{x}_i-\bar{\mathbf{x}})^2.\]
The original definition of layernorm [33] sets \(\varepsilon_\mathcal{N}= 0\), but, for numerical stability, all implementations we are aware of set \(\varepsilon_\mathcal{N}> 0\). Observe that \(\mathcal{N}\) is Lipschitz-continuous iff \(\varepsilon_\mathcal{N}> 0\).
Some transformer analyses omit \(\mathcal{N}\) for simplicity [24], while others set \(\varepsilon_\mathcal{N}\) to achieve various effects [26], [29].
We now define a complete transformer network.
A transformer encoder is a length-preserving function \(\mathcal{T}\colon{\Sigma}^*\to{{(\mathbb{R}^{d})}^*}\) parameterized by the weights of an input layer \(e\) and \(D\) transformer layers \(\mathcal{L}_1,\ldots,\mathcal{L}_D\). A post-norm transformer encoder is: \[\mathcal{T}(w) = \mathcal{L}_{D} \circ \cdots \circ \mathcal{L}_2 \circ \mathcal{L}_1 \circ e(w)\] where each \(\mathcal{L}_l\) is a post-norm layer and \(\circ\) is function composition. A pre-norm transformer encoder is additionally parameterized by the weights of a final layernorm \(\mathcal{N}\) and is defined as: \[\mathcal{T}(w) = \mathcal{N}\circ \mathcal{L}_{D} \circ \cdots \circ \mathcal{L}_2 \circ \mathcal{L}_1 \circ e(w)\] where each \(\mathcal{L}_l\) is a pre-norm layer .
The encoder’s output is a sequence of vectors in \({{(\mathbb{R}^{d})}^*}\). To use it as a language recognizer, we add an output layer that converts \(\mathcal{T}(w)\) to a probability \[\hat{p} = \mathcal{\sigma}(\mathbf{w}\cdot[\mathcal{T}(w)]_i + b)\] where \(\mathbf{w} \in \mathbb{R}^d\), \(b \in \mathbb{R}\), and \(i\) is a distinguished position. The encoder accepts iff \(\hat{p} \ge \frac{1}{2}\). [26] also consider a requirement that an encoder accepts/rejects strings with bounded cross-entropy. That is, we say that an encoder recognizes a language \(L\) with cross-entropy at most \(\eta\) iff for all strings \(w\), if \(w \in L\) then \(-\log \hat{p} \le \eta\), and if \(w \not\in L\) then \(-\log (1-\hat{p}) \le \eta\).
We are aware of two choices for the distinguished position \(i\). Most papers use the last position (\(i = n-1\)), but some [26], [34], inspired by binary classifiers based on BERT
[2], prepend a special symbol CLS at position \(0\) and use \(i=0\). While this is a minor difference, it should be noted that the guarantee of exactly one occurrence of \(\texttt{CLS}\) in the input can be useful in some constructions.
A transformer decoder is a transformer encoder \(\mathcal{T}\) with future masking in its attention, typically used to generate rather than recognize strings. The input is the prefix of previously-generated symbols, \(w_{{}<t}= w_0 \cdots w_{t-1}\), and the output is a probability distribution \(\hat{p}(w_t \mid w_{{}<t})\) over the next symbol, \[\hat{p}(\cdot \mid w_{{}<t}) = \mathcal{S}(\mathbf{W}\,[\mathcal{T}(w_{{}<t})]_{t-1} + \mathbf{b})\] where \(\mathbf{W} \in \mathbb{R}^{|\Sigma| \times d}\) and \(\mathbf{b} \in \mathbb{R}^{|\Sigma|}\). We assume \(w_0 = \texttt{BOS}\) and every string ends with \(\texttt{EOS}\), where \(\texttt{BOS}\) and \(\texttt{EOS}\) are special symbols that do not occur anywhere else. To sample a string, we first sample \(w_1\) from \(\hat{p}(w_1 \mid \texttt{BOS})\), then, for each time step \(t>1\), sample \(w_t\) from \(\hat{p}(w_t \mid w_{{}<t})\). The process stops when \(w_t = \texttt{EOS}\). Because each sampled output symbol becomes part of the input at the next time step, this kind of model is called autoregressive.
While a decoder can be used to recognize strings similarly to an encoder, it can also be used to generate the entire string; at least two definitions have been given for this.
First, [29] considers a weighted language as a distribution over strings \(p(w)\). For any length \(t\), the KL divergence (relative entropy) of the model \(\hat{p}(w)\) from the true distribution \(p(w)\), for predicting \(w_t\) conditioned on all previous words, is \[\Delta_t[\hat{p}\mathbin\|p] = \sum_{w_{{}<t}} \sum_{w_t} p(w_{{}<t}w_t) \log \frac{p(w_t \mid w_{{}<t})}{\hat{p}(w_t \mid w_{{}<t})}.\] As [29]’s results are negative, he does not spell out a positive criterion, but he seems to implicitly require that this divergence vanish at infinity: \[\lim_{t\rightarrow\infty} \Delta_t[\hat{p}\mathbin\|p] = 0. \label{eq:optimal95crossentropy}\tag{5}\]
Second, let us say that a transformer decoder \(\varepsilon\)-generates \(L\) iff \[L = \{ w \mid \forall t \in [|w|], \hat{p}(w_t \mid w_{{}<t}) \ge \varepsilon\}.\] Then [25], following [35], say that a transformer decoder \(T\) generates a language \(L\) iff there exists an \(\varepsilon> 0\) such that \(T\) \(\varepsilon\)-generates \(L\). (This means that a transformer decoder may generate more than one language, depending on the \(\varepsilon\) chosen.) They also show that any \(\varepsilon\)-generator can be converted into a recognizer.
While not focusing on transformers, [36] demonstrate limitations of autoregressive models for generation; for example, that there is a language \(L \in \mathsf{P}\) that cannot be \(\varepsilon\)-generated in polynomial time for any \(\varepsilon> 0\) if \(\mathsf{P} \neq \mathsf{NP}\).
A transformer encoder–decoder combines a transformer encoder and decoder, adding to each layer of the decoder an additional attention sublayer, known as cross attention, which attends to the output of the encoder. In the literature surveyed here, only the construction of [24] and related constructions [37], [38] employ an encoder–decoder.
When a transformer decoder or encoder–decoder is run as a language recognizer, it allows for the possibility of inserting a number of intermediate time steps between the end of the input string and the decision. The encoder–decoder models above do this, as do some decoder-only models [39], [40]. As we will see (6.1), intermediate steps vastly increase the model’s power, which has also been observed in practice in the form of a “scratchpad” [41] or “chain of thought” [42].
Although meaningful theoretical claims can be made about transformers for fixed-length strings [8], it is crucial when examining transformers as language recognizers to allow for unbounded string length. Fixing a maximum length makes all languages finite, collapsing many language classes into one.
It might be objected that considering unbounded lengths is too abstract, because in practice one can always fix a maximum length. But this maximum length, driven by practical needs, is growing steadily: for example, GPT-4 Turbo uses 128,000 tokens of context. At the same time, some theoretical findings surveyed here seem to have practical consequences for modest string lengths. For example, we will see that there are reasons to think that in theory, transformers cannot recognize Parity; in practice, they fail to learn Parity for strings with lengths in \([2,50]\) [43].
Some theoretical studies of transformers do allow them to depend on the input length \(n\). To borrow a term from circuit complexity (5.2), they allow certain kinds of non-uniformity. As we have seen, some position embeddings (4.1) depend on \(n\). We discuss some other instances below.
Transformers operate, in principle, on real numbers. While hard attention transformers could be defined using only rational numbers, even rational numbers can represent an arbitrary amount of information. With RNNs, the use of real or rational numbers has led to results that make them appear more powerful in theory than in practice [15], [44], [45].
Consequently, many studies use limited-precision numbers. Some studies limit number representations to have \(O(1)\) bits, as floating-point numbers do in practice [34]. But [46] argue that in \(O(1)\) precision, attention cannot attend uniformly to a string of sufficient length \(n\), as the attention weights (\(\alpha\)) would all round down to zero. So \(O(\log n)\) bits of precision is a common choice [25], [46], [47]. Other choices are possible as well: [47] use the set \(\mathbb{F} = \{a/2^b \mid a \in \mathbb{Z}, b \in \mathbb{N}\}\).
Restricting intermediate activations to limited precision introduces many decisions about when and how rounding should take place, which can potentially affect expressivity. For example, when summing \(n\) numbers, one could round after each addition or only at the end of the summation. Better formalizing these decisions and their impact on expressivity is an area for future research.
A few constructions allow the parameters themselves to depend on \(n\), which we consider to be a stronger dependence, because if these transformers were to be learned from data, different transformers would have to be learned for different maximum lengths. Finally, a few papers construct transformers in which \(d\), and therefore the number of parameters, depends on \(n\), which we consider to be stronger still.
In summary, transformers can vary in at least the following ways, any of which could a priori impact theoretical claims:
Architecture: encoder-only, decoder-only, or encoder–decoder
For encoders: definition of recognition
For decoders and encoder–decoders: definition of generation and how many intermediate steps
Position embedding (PE)
Attention pattern: leftmost-hard, rightmost-hard, average-hard, or softmax
Attention masking: none, future, or past
Layernorm: inclusion or omission, value of \(\varepsilon_\mathcal{N}\)
Residual connections: pre-norm or post-norm
Precision: infinite, \(O(\log n)\), \(O(1)\)
Uniformity: whether parameter values or number of parameters depend on \(n\).
Next, we present various formal models that transformers are compared to in the literature surveyed.
We assume familiarity with finite automata and Turing machines; for definitions, please see the textbook by [48]. Counter machines are automata with integer-valued registers [49]; they have been studied extensively in connection with LSTM RNNs [16], [45], [50], [51].
The language classes \(\mathsf{L}\) (languages decidable in \(O(\log n)\) space) and \(\mathsf{P}\) (languages decidable in polynomial time) are defined using deterministic Turing machines (with a read-only input tape and a read/write work tape). The class \(\mathsf{NL}\) (languages decidable in nondeterministic \(O(\log n)\) space) uses nondeterministic Turing machines. The class \(\mathsf{DLOGTIME}\) (languages decidable in \(O(\log n)\) time) uses random-access Turing machines [52]. It is known that \[\mathsf{L} \subseteq \mathsf{NL} \subseteq \mathsf{P}\] but none of these inclusions are known to be strict.
Circuits are a model of parallel computation particularly relevant to transformers. For more details, please see the textbook by [53].
Circuits operate on binary values. If we choose a fixed-length encoding of the symbols of \(\Sigma\) as strings of \(b = \lceil \log_2 |\Sigma| \rceil\) bits, then a circuit can simulate input alphabet \(\Sigma\) by encoding the value of the \(i\)-th input symbol into positions \(ib\) to \(ib+(b-1)\). For the rest of this section, we assume \(\Sigma = \{0,1\}\).
A circuit \(C\) with input length \(n\) is a directed acyclic graph with \(n\) input vertices \(s_1, \ldots, s_n\) and zero or more gate vertices, each labeled with a type NOT, AND, or OR. Input vertices have fan-in (in-degree) zero, NOT gates have fan-in one, and the fan-in of AND and OR gates can be either two or unbounded. One (input or gate) vertex \(t\) is designated the output of the circuit.
Given an input string \(w \in \{0,1\}^n\), each input vertex \(s_i\) is assigned the value \(w_i\), and each gate vertex is assigned the value computed by applying the logical function corresponding to its type to the values assigned to its in-neighbors. The circuit computes the boolean function \(C \colon \{0,1\}^n \rightarrow \{0,1\}\), mapping each input string to the value assigned to \(t\). The depth of \(C\), denoted \(D(C)\), is the length of the longest directed path from any \(s_i\) to \(t\). The size of \(C\), denoted \(|C|\), is the number of vertices in \(C\).
A circuit family is a sequence \(\mathcal{C} = \{C_n\}_{n\in\mathbb{N}}\) such that for each \(n\), \(C_n\) is a circuit with input length \(n\). We treat \(\mathcal{C}\) as a function on \(\{0,1\}^*\) as follows: for every \(w\in \{0,1\}^*\), \(\mathcal{C}(w) = C_{|w|}(w)\). Then \(\mathcal{C}\) defines the language \(L(\mathcal{C}) = \{w\in \{0,1\}^* \mid \mathcal{C}(w)=1 \}\), and we say that \(\mathcal{C}\) recognizes \(L(\mathcal{C})\). The depth and size of \(\mathcal{C}\) are the functions \(n \mapsto D(C_n)\) and \(n \mapsto |C_n|\).
As defined, a circuit family contains a different circuit for each length \(n\), with no constraint on the relationship between the circuits. For example, let \(L\) be any unary language: \(L \subseteq \{1\}^*\). For \(n \in\mathbb{N}\), if \(1^n \not\in L\), define \(C_n\) to be a circuit for the constant \(0\) function (an OR gate with fan-in \(0\)), and if \(1^n \in L\), define \(C_n\) to be a circuit for the AND of all the inputs. Thus, every unary language, even an undecidable one, is recognized by a circuit family of size \(O(n)\) and depth \(O(1)\).
A uniformity restriction on a circuit family \(\{C_n\}_{n\in\mathbb{N}}\) requires that the task of constructing a description of the circuit \(C_n\) given input \(n\) be computable within some specified resource bound as a function of \(n\), potentially making it comparable with classes defined by bounds on Turing machine time or space. Two such uniformity bounds are used in the work here: \(\mathsf{L}\) and \(\mathsf{DLOGTIME}\). Because these bounds are very restrictive, a special representation of the circuit \(C_n\) is used, namely, the ability to answer queries of the type of a gate and whether the output of one gate is an input to another gate.
We assume that the vertices of the circuit \(C_n\) are numbered from \(0\) to \(|C_n|-1\). The direct connection language of a family of circuits \(\cal{C}\) is the set of all tuples \(\langle f, i, j, \texttt{1}^n\rangle\) such that in \(C_n\), vertex \(i\) has type \(f\) and there is an edge from vertex \(i\) to vertex \(j\) [52]. Given a computable function bounding the size of \(\cal{C}\) and access to a membership oracle for the direct connection language, for any \(n\) it is straightforward to write out the list of vertices, edges, and types in \(C_n\).
Then a circuit family \(\cal{C}\) is \(\mathsf{L}\)-uniform (resp., \(\mathsf{DLOGTIME}\)-uniform) if there is a Turing machine that runs in logarithmic space (resp., deterministic logarithmic time) to decide membership in the direct connection language of \(\cal{C}\).
Circuit complexity classes classify circuit families and the languages they recognize based on uniformity, depth, size, fan-in bound, and the allowed gates. Since transformers have constant depth, circuit classes with constant depth are of particular interest; the classes that are used in the work we survey are:
\(\mathsf{AC}^0\) contains those languages that can be recognized by families of circuits with unbounded fan-in, constant depth, and polynomial size.
\(\mathsf{ACC}^0\) is like \(\mathsf{AC}^0\), but also has gates that output 1 iff the inputs sum to \(0\) modulo some constant.
\(\mathsf{TC}^0\) is like \(\mathsf{AC}^0\), but also allows MAJORITY gates, which have unbounded fan-in and output \(1\) iff at least half of their inputs are \(1\).
\(\mathsf{NC}^1\) is like \(\mathsf{AC}^0\), but with fan-in at most 2 and depth in \(O(\log n)\). The known relationships between these classes are: \[\mathsf{AC}^0 \subsetneq \mathsf{ACC}^0 \subseteq \mathsf{TC}^0 \subseteq \mathsf{NC}^1\] in the \(\mathsf{DLOGTIME}\)-uniform, \(\mathsf{L}\)-uniform, and non-uniform settings; moreover, \(\mathsf{L}\)-uniform \(\mathsf{NC}^1 \subseteq \mathsf{L}\).
A formal language can also be defined as a set of finite strings that satisfy a closed formula of a logic. For more details, refer to [54] or [55].
In the first-order logic of strings, or \(\mathsf{FO}\), the formulas are the smallest set containing:
Variables \(x, y\), and so on.
Atomic formulas \(Q_a(x)\), \(x=y\), \(x < y\), where \(a \in \Sigma\) is a symbol and \(x, y\) are variables.
\(\phi_1 \land \phi_2\), \(\phi_1 \lor \phi_2\), \(\phi_1 \rightarrow \phi_2\), \(\neg \phi_1\), where \(\phi_1\) and \(\phi_2\) are formulas.
\(\forall x. \phi\), \(\exists x. \phi\), where \(x\) is a variable and \(\phi\) is a formula. Under the intended interpretation, variables stand for positions of a finite string \(w\), and \(Q_a(x)\) is true iff \(w_x = a\). For example, if \(\Sigma=\{a,b\}\), \(\forall x. \forall y. Q_a(x) \land Q_b(y) \rightarrow x < y\) defines the regular language \(a^\ast b^\ast\). The language defined by a closed formula \(\phi\) consists of those strings that satisfy \(\phi\).
The languages definable in \(\mathsf{FO}\) are exactly the star-free languages [56]. Other variants add more quantifiers:
\(\mathsf{FOC}\) adds counting quantifiers \(\exists^{=x}y.\phi\), which hold iff there are exactly \(x\) values of \(y\) that make \(\phi\) true [52].
\(\mathsf{FOM}\) adds majority quantifiers \(\mathsf{M}x. \phi\), which hold iff at least half of the values of \(x\) make \(\phi\) true [52]. We are also interested in various sets of predicates:
Modular predicates \(\mathsf{MOD}^r_m(x)\), which hold iff \(x \equiv r \pmod{m}\) [57].
\(\mathsf{BIT}(x,y)\), which holds iff the \(y\)-th bit of \(x\) is \(1\).
\(\mathsf{Mon}\), the set of all predicates on one position, possibly depending on \(n\).2
\(\mathsf{ARB}\), the set of all predicates on one or more positions. A logic extended with predicates is conventionally written with the predicates in square brackets; for example, we write \(\mathsf{FO}[\mathsf{BIT}]\) for first-order logic with the \(\mathsf{BIT}\) predicate.
In linear temporal logic or LTL [60], every formula implicitly depends on a single time (or position). There are atomic formulas \(Q_a\) for every \(a \in \Sigma\), the connectives \(\land\), \(\lor\), and \(\neg\), as well as operators \(\boldsymbol{since}\) and \(\boldsymbol{until}\). The formula \(\alpha \mathrel{\boldsymbol{since}} \beta\) is true iff \(\alpha\) was true at some past time \(i\) and \(\beta\) was true from \(i\) to now (exclusive). LTL is equivalent to \(\mathsf{FO}\) [60].
1, which depicts the relationships between the language classes defined above, shows that the classes defined by circuits/logics cut across the (perhaps more familiar) Chomsky hierarchy. In this figure and in this section, all circuit classes are understood to be \(\mathsf{DLOGTIME}\)-uniform unless specified otherwise.
The classic examples of languages not in \(\mathsf{AC}^0\) are \(\mathrm{\small Parity}\) and \(\mathrm{\small Majority}\). The language \(\mathrm{\small Parity} \subseteq \{\texttt{0},\texttt{1}\}^*\) contains all bit strings containing an odd number of \(\texttt{1}\)’s, and \(\mathrm{\small Majority} \subseteq \{\texttt{0},\texttt{1}\}^*\) consists of all bit strings in which more than half of the bits are \(\texttt{1}\)’s. Other problems in \(\mathsf{TC}^0\) but not \(\mathsf{AC}^0\) include sorting, integer multiplication [61], and integer division [62].
The language \(\mathrm{\small Dyck-}k\) for \(k>0\) is the language of strings over \(k\) pairs of parentheses that are correctly balanced and nested. If we write the \(i\)-th parenthesis pair as \(\texttt{(}_{i}\;\texttt{)}_{i}\) for each \(i \in [k]\), then \(\mathrm{\small Dyck-}k\) is generated by the context-free grammar \(\{ S \rightarrow \texttt{(}_{i} S \texttt{)}_{i} S \mid i \in [k] \} \cup \{ S \rightarrow \varepsilon\}\). These languages are of interest because any context-free language can be obtained by applying a string homomorphism to the intersection of a Dyck language with a regular language [63].
Some papers surveyed here consider variations on Dyck languages. The language Dyck-\((k,D)\) for \(D>0\) is the subset of Dyck-\(k\) consisting of strings with maximum nesting depth \(D\); it is a star-free regular language (and therefore in \(\mathsf{AC}^0\)).
The language Shuffle-Dyck-\(k\) is the set of strings over \(k\) pairs of parentheses in which, for each parenthesis pair, erasing the other types of parentheses leaves a correctly balanced and nested string. For example, \([(()])\) is in Shuffle-Dyck-2. If \(k > 1\), Shuffle-Dyck-\(k\) is not context free.
As we will see (6.3.2), some transformer variants lie within \(\mathsf{TC}^0\). What problems lie beyond?
A permutation of \([k]\) is a bijection \(\pi \colon [k] \rightarrow [k]\), and \(S_k\) is the set of all permutations of \([k]\). Treating \(S_k\) as an alphabet and compositions of permutations as strings, we can define the language \(\mathrm{\small W}(S_k)\) of compositions of permutations of \([k]\) that equal the identity permutation. For example, in \(S_3\), the permutation \((120)\) maps \(0 \mapsto 1\), \(1 \mapsto 2\), and \(2 \mapsto 0\), so that \(\mathrm{\small W}(S_3)\) contains \((120)\circ(120)\circ(120)\) but not \((120)\circ(120)\). These languages are easy for finite automata to recognize, but difficult with only fixed computation depth. Indeed, \(\mathrm{\small W}(S_5)\) is complete for \(\mathsf{NC}^1\) under \(\mathsf{AC}^0\) reductions [64], so it is not in \(\mathsf{TC}^0\), assuming that \(\mathsf{TC}^0 \subsetneq \mathsf{NC}^1\) (as is widely believed). This makes it an example of a regular language that transformer encoders probably cannot recognize.
The languages \(\mathrm{\small W}(S_k)\) have some relevance to natural language: they resemble expressions like the child of the enemy of Ann where the interpretation of the child of is (roughly) a permutation of possible referents [65], and problems that have been used to benchmark transformers’ state-tracking abilities [66].
Other languages that are widely believed to be not in \(\mathsf{TC}^0\) include:
The language of closed Boolean formulas that are true (BFVP) is context-free but complete for \(\mathsf{NC}^1\) under \(\mathsf{DLOGTIME}\) reductions [67], so it is outside \(\mathsf{TC}^0\) if \(\mathsf{TC}^0 \subsetneq \mathsf{NC}^1\).
Undirected graph connectivity is \(\mathsf{L}\)-complete under \(\mathsf{L}\)-uniform \(\mathsf{NC}^1\) reductions [68], [69], so it is outside \(\mathsf{L}\)-uniform \(\mathsf{NC}^1\) (and therefore outside \(\mathsf{TC}^0\)) if \(\text{\mathsf{L}-uniform \mathsf{NC}^1} \subsetneq \mathsf{L}\).
There is a context-free language \(L_P\) that is \(\mathsf{NL}\)-complete under \(\mathsf{L}\) reductions [70], so it is outside \(\mathsf{L}\) (and therefore outside \(\mathsf{NC}^1\) and \(\mathsf{TC}^0\)) if \(\mathsf{L}\subsetneq \mathsf{NL}\).
Solving systems of linear equalities and universal context-free grammar recognition are \(\mathsf{P}\)-complete under \(\mathsf{L}\) reductions [71], [72], so they are outside \(\mathsf{TC}^0\) if \(\mathsf{L}\subsetneq \mathsf{P}\).
Matrix permanent is known to be outside of \(\mathsf{TC}^0\) [73].
\(\mathsf{DLOGTIME}\)-uniform \(\mathsf{AC}^0\) and \(\mathsf{TC}^0\) are equivalent to \(\mathsf{FO}[\mathsf{BIT}]\) and \(\mathsf{FOM}[\mathsf{BIT}]\), respectively. There are many such equivalences between circuit classes and logics. As a rule of thumb, adding unbounded fan-in gates to a circuit family correlates with adding quantifiers to the corresponding logic, and increasing the degree of non-uniformity of a circuit family correlates with adding numerical predicates to the corresponding logic [74]. For example, making \(\mathsf{AC}^0\) and \(\mathsf{TC}^0\) completely non-uniform corresponds to adding arbitrary numerical predicates \((\mathsf{ARB})\) to \(\mathsf{FO}\) and \(\mathsf{FOM}\), respectively [52], [75].
As we will see below, circuits and logics have their advantages and disadvantages for capturing the expressivity of transformers. An advantage of the circuit approach is that they have a more transparent resemblance to transformers. Transformers are computations with bounded depth, so it’s not hard to see that they should be computable by circuit families with bounded depth (\(\mathsf{AC}^0\) or \(\mathsf{TC}^0\)). On the other hand, an advantage of the logical approach is that if we seek an exact characterization of transformers, it can be easier in a logic to add or remove quantifiers or predicates, to limit quantifier depth or number of variables, to partition terms into different sorts, and so on, than to make adjustments to a circuit family.
| Lower bound | Source | PE | Attention | Notes |
|---|---|---|---|---|
| \(\ni \prob{Majority}\) | [76] | none | ||
| \(\ni \prob{Shuffle-Dyck-}k\) | [43] | none | , future mask | |
| \(\supseteq \text{SSCMs}\) | [43] | none | , future mask | |
| \(\ni \text{\prob{Dyck}-k}\) | [25] | \(i/n\), \(i/n^3\), \(n\) | & | |
| \(\supseteq \probclass{P}\) | [24] | \(i, 1/i, 1/{i^2}\) | \(\poly(n)\) steps | |
| \(\ni \prob{Parity}\) | [26] | \(i/n\), \((-1)^i\) | ||
| \(\supseteq \probclass{FOC[MOD;\mathord+]}\) | [34] | sinusoidal | ||
| \(\supseteq \FO[\textsf{Mon}]\) | [59] | arbitrary | ||
| \(\supseteq \textsf{LTL+C}[\textsf{Mon}]\) | [59] | arbitrary | ||
| Upper bound | Source | Precision | Attention | Notes |
| \(\not\ni \prob{Parity}, \text{\prob{Dyck}-1}\) | [29] | \(\real\) | ||
| \(\not\ni \prob{Parity}, \text{\prob{Dyck}-2}\) | [29] | \(\real\) | , future mask | \(\varepsilon_\layernorm>0\), vanishing KL |
| \(\subseteq \AC^0\) | [30] | \(\mathbb{Q}\) | ||
| \(\subseteq \TC^0\) | [31] | \(\mathbb{F}\) | ||
| \(\subseteq \probclass{FOC[MOD;\mathord+]}\) | [34] | \(O(1)\) | ||
| \(\subseteq \text{\probclass{L}-uniform~$\TC^0$}\) | \(O(\log n)\) | |||
| \(\subseteq \FOM\) | \(O(\log n)\) | |||
| \(\subseteq \text{\probclass{L}-uniform~$\TC^0$}\) | [77] | \(\mathbb{F}\) | ||
| Equivalent | Source | PE | Attention | Notes |
| \(= \probclass{RE}\) | [24] | \(i, 1/i, 1/{i^2}\) | unbounded steps | |
| \(= \FO\) | [78] | none | , strict future mask | |
| \(= \FO[\textsf{MOD}]\) | [78] | sinusoidal | , strict future mask | |
| \(= \FO[\textsf{Mon}]\) | [78] | arbitrary | , strict future mask | |
| \(= \probclass{P}\) | none | , future mask | \(\poly(n)\) steps |
While this area of research still has many unresolved questions, the emerging picture has three levels of expressivity. At the upper end are decoders or encoder–decoders with intermediate steps; these are equivalent to Turing machines (6.1). At the lower end are encoders with leftmost-hard or rightmost-hard attention; these can recognize only languages in \(\mathsf{AC}^0\) (6.2). In the middle are encoders with average-hard or softmax attention, which are the least well-understood but appear to lie between \(\mathsf{AC}^0\) and \(\mathsf{TC}^0\) (6.3).
In this section, “transformer” refers to a transformer encoder unless otherwise indicated.
[24] consider transformer encoder–decoders with several modifications:
The PE includes components \(i\), \(1/i\), and \(1/i^2\).
In self attention, 3 takes the negative absolute value of the dot-product, and 4 uses average-hard attention.
The FFNs use sigmoids instead of ReLUs. As described above (4.3.3), the decoder is allowed to run for arbitrarily many time steps until an acceptance criterion is met. Under these assumptions, transformer encoder–decoders can recognize any recursively enumerable language.3 This result uses arbitrary precision, but as a corollary, they show that a \(T(n)\)-time-bounded Turing machine can be simulated in a transformer using \(O(\log T(n))\) precision and \(O(T(n))\) intermediate steps.
[37] provide a simpler proof of [24]’s result by reducing to an RNN and appealing to the construction of [15]. They do this for two sets of assumptions. First,
The PE includes only \(i\).
The self attention sublayers are as above.
The FFNs use saturated linear activation functions: \(\sigma(x) = \max (0, \min (1, x))\). Second, they show the same with no PE and standard dot-product attention with future masking.
[38] define a notion of statistically-meaningful (SM) approximation and show that transformer encoder–decoders SM-approximate Turing machines. Both the decoder and Turing machine are limited to \(N\) time steps; additionally,
The PE can be an arbitrary computable function on \([N]\).
Attention is average-hard.
The FFNs have three ReLU layers.
[39] observe that the problems of evaluating arithmetic expressions or solving linear equations over \(\mathbb{Z}_p\) are \(\mathsf{NC}^1\)-hard under \(\mathsf{DLOGTIME}\) reductions, so (if \(\mathsf{TC}^0 \subsetneq \mathsf{NC}^1\)) they cannot be solved by \(O(\log n)\)-precision transformer decoders without intermediate steps.4 Similarly, the universal recognition problem for CFGs is \(\mathsf{P}\)-complete, so (if \(\mathsf{L}\subsetneq \mathsf{P}\)) it cannot be solved by \(O(\log n)\)-precision transformer decoders without intermediate steps.
However, these problems can be solved by a transformer decoder using (a polynomial number of) intermediate steps. The decoder has GELU activations [79] and PE including \(i\) and (for linear equation solving) \(m^2 \sin \frac{2i\pi}{m}\) and \(m^2 \cos\frac{2i\pi}{m}\) where \(m\) is the number of variables. More generally, they define a class of dynamic-programming algorithms that these transformers can solve using intermediate steps. All these decoders have parameters that depend on \(n\).
[40] show that a transformer decoder with \(O(\log(n+T(n)))\) precision and \(O(T(n))\) intermediate steps can simulate a Turing machine for \(T(n)\) steps, and in particular, decoders with a polynomial number of intermediate steps recognize exactly the languages in \(\mathsf{P}\). The proof is similar to that of [24], but uses a standard definition of transformers without PEs, relying only on the mild assumption that the input string begins with \(\texttt{BOS}\).
[29] shows that leftmost-hard attention transformers cannot recognize Parity or Dyck-1, using a variant of [80]’s random restriction method for proving that Parity is outside of \(\mathsf{AC}^0\).
[30] show more generally that any language recognized by a transformer with leftmost-hard attention is in \(\mathsf{AC}^0\). The proof gives a normal form for transformers with leftmost-hard attention and uses it to construct an \(\mathsf{AC}^0\) circuit family. It uses the fact that only \(O(\log n)\) bits of information are needed per position.
[59] give a lower bound on leftmost-hard-attention transformers with arbitrary PEs depending on a single position \(i\) and length \(n\), including \(i\), \(\tfrac{1}{i+1}\), \((-1)^i\), \(\cos \frac{\pi(1-2^{-i})}{10}\), and \(\sin \frac{\pi(1-2^{-i})}{10}\). They show that these transformers can recognize any language definable in \(\mathsf{FO}[\textsf{Mon}]\). Their proof converts a \(\mathsf{FO}[\textsf{Mon}]\) formula to LTL (5.3), which is simulated in a transformer.
[78] exactly characterize rightmost-hard-attention transformers with strict future masking. Without PEs, these transformers recognize exactly the class of star-free languages, that is, languages definable in \(\mathsf{FO}\). With periodic PEs, they are exactly equivalent to \(\mathsf{FO}[\mathsf{MOD}]\), and with arbitrary PEs, they are exactly equivalent to \(\mathsf{FO}[\mathsf{Mon}]\). Strict masking is important, as nonstrict masking is less expressive. They give two proofs of the star-free to transformer direction, one which goes through LTL (5.3) and one which uses Krohn-Rhodes theory. These proofs use a Boolean-valued version of RASP [81] as an intermediate representation.
Theoretical results on average-hard and softmax attention transformers have not yet clearly separated the two, so we treat them together. Both kinds of attention enable counting, which can be used to solve problems like Majority that are outside \(\mathsf{AC}^0\). But these transformers are no more powerful than \(\mathsf{DLOGTIME}\)-uniform \(\mathsf{TC}^0\), implying that they likely cannot solve problems complete for \(\mathsf{NC}^1\), \(\mathsf L\), and other classes believed to be above \(\mathsf{TC}^0\) (5.4).
The languages Majority, Dyck-\(k\), and Parity are all not in \(\mathsf{AC}^0\), so are interesting test cases.
[76] prove that a transformer encoder–decoder with a trivial decoder and without any PE recognizes Majority; [31] prove the same for transformer encoders.
[43] prove that \(\mathrm{\small Shuffle-Dyck-}k\) (which equals \(\mathrm{\small Dyck-}1\) when \(k = 1\)) is recognizable by a soft-attention transformer with future masking, no PE, no layernorm, and no residual connections. [25] show that a transformer decoder can generate Dyck-\(k\) using \(O(\log n)\) precision, softmax and leftmost-hard attention, future masking, and a PE including \(i/n\), \(i/n^3\), and \(n\). They also give constructions for Dyck-\((k,D)\).
[26] show that transformers whose PE includes \(i/n\) and \((-1)^i = \cos i \pi\) can recognize Parity.
On the other hand, [29] shows that softmax attention transformers cannot generate Parity or Dyck-2 under the following two conditions:
all position-wise functions are Lipschitz-continuous, and
generation is defined using the KL divergence criterion in 5 .
The apparent contradiction is resolved by considering the different assumptions underlying each result. [26] address this by giving two constructions corresponding to Hahn’s two conditions. The first has Lipschitz-continuous position-wise functions, but has high cross-entropy (4.3.1); as a generator, it would not meet criterion . The second construction uses layernorm with \(\varepsilon_\mathcal{N}= 0\), which is not Lipschitz-continuous, but it has arbitrarily low cross-entropy.
A number of authors have tested empirically whether transformers can learn the above languages. [82] find that they are
competitive with LSTMs at learning Dyck-\(2\) and Dyck-\(4\), and that prepending a BOS symbol helps.
[43] train transformers with future masking and no PE on Dyck-\(1\) and Shuffle-Dyck-\(k\), finding near-perfect learning and length generalization. For the languages Dyck-\((1,D)\) with learned or sinusoidal PEs, they find that the models do not generalize well for \(D>1\). [25] then investigate Dyck-\((k,D)\) for several values of \(k\) and \(D\) and several PEs. They report strong generalization only when using \(i/n\) for the PE, and posit that this is the key. It is hard, however, to directly compare the two results: [43] require correct prediction of the possible next symbols at each string prefix, while [25] average over predictions of right brackets.
[83] study experimentally how well transformers (and other networks) learn tasks at various levels of the Chomsky hierarchy, including generalization to longer strings. They find that transformers learn Majority, but not \(\mathrm{\small Parity}\).
[31] prove an upper bound analogous to that of [30], but for average-hard-attention transformers. They show that an average-hard-attention transformer with activations in \(\mathbb{F}\) can be simulated in \(\mathsf{TC}^0\). [77] tightens this bound to \(\mathsf{L}\)-uniform \(\mathsf{TC}^0\).
Furthermore, [47] show that softmax attention, \(O(\log n)\)-precision transformers are in \(\mathsf{L}\)-uniform \(\mathsf{TC}^0\), and then tighten this bound to \(\mathsf{DLOGTIME}\)-uniform \(\mathsf{TC}^0\) [46]. The proof constructs subroutines to answer queries about the types of nodes and connectivity of pairs of nodes in the computation graph of a transformer, and shows that these queries can be translated to queries for a \(\mathsf{TC}^0\) circuit family with \(O(\log n)\) time overhead.
An upper bound of \(\mathsf{DLOGTIME}\)-uniform \(\mathsf{TC}^0\) immediately implies an upper bound of \(\mathsf{FOM}[\mathsf{BIT}]\) [46]. [34] prove a tighter upper bound using a logic called \(\mathsf{FOC[MOD;\mathord+]}\), but on transformers with \(O(1)\) precision. This result is discussed below.
In addition to explicit constructions for particular languages mentioned above, various lower bounds have been proven, which are quite diverse.
[43], following [84], define a subclass of counter machines called simplified and stateless \(k\)-counter machines (SSCMs). These can update each counter based on the current input symbol, but have no state and cannot read the counters until the end of the string. They show that any SSCM can be converted to an equivalent transformer with future masking and no residual connections.
[85] study the ability of transformers with future masked attention to simulate deterministic finite automata (DFAs), in the sense of computing not only the same acceptance decision but also the same state sequence. Although a transformer with depth \(N\) can simulate a DFA for \(N\) timesteps, [85] show how to construct lower-depth shortcuts for subclasses roughly corresponding to classes of regular languages in 1. Though the parameters of these constructions depend on \(N\), in the context of this survey, a noteworthy finding is that any regular language in \(\mathsf{ACC}^0\) can be recognized up to length \(N\) by a transformer whose FFNs use sine activations and whose number of parameters is independent of \(N\).
[34] obtain both an upper and a lower bound by defining a logic \(\mathsf{FOC[MOD;\mathord+]}\), which is first-order logic with counting quantifiers, using two sorts for positions and counts [86], where positions have the \(\mathsf{MOD}\) predicate (but not \(<\) or \(=\)), and counts have \(<\), \(+\), and \(=\), capturing the fact that transformers can add and compare activations, but not positions. They show that this logic is intermediate in expressivity between \(O(1)\)-precision and infinite-precision transformers. The lower-bound proof uses a normal form that eliminates quantifiers over counts and makes quantifiers over positions have depth 1; a perhaps surprising consequence is that \(O(1)\)-precision transformers are no more powerful than 2-layer uniform-attention transformers.
[59] show that average-hard-attention transformers with arbitrary PEs depending on a single position \(i\) and length \(n\), including \(i\), \(\tfrac{1}{i+1}\), \((-1)^i\), \(\cos \frac{\pi(1-2^{-i})}{10}\), and \(\sin \frac{\pi(1-2^{-i})}{10}\), can recognize any language definable in LTL with counting operators, Presburger arithmetic on counts, and predicates in \(\mathsf{Mon}\).
[81] introduce the RASP (Restricted Access Sequence Processing) language as an abstraction of transformers, discussing how its components relate to the transformer architecture. However, they do not prove any relationship.
[87] present Tracr, a compiler from RASP programs to transformers. To do so, they impose some restrictions: a maximum input length, given at compile time; a mandatory \(\texttt{BOS}\) token; and the removal of selector composition, a RASP operation with no clear parallel in transformers. They rewrite several programs from [81] without this operation. In the other direction, [88] define a restricted class of transformers that can be learned and decompiled into RASP. Finally, [78] use a version of RASP restricted to Boolean values, and [89] use a restricted version of RASP to explore length generalization.
Out of the large body of research surveyed above, we highlight several conclusions:
Transformer decoders can use intermediate steps to simulate Turing machines; with unbounded steps, they are Turing-complete.
Regarding the expressivity of transformer encoders, circuit complexity and logic are especially promising frameworks.
Leftmost-hard-attention transformer encoders are in \(\mathsf{AC}^0\) and cannot solve some intuitively easy problems, like Parity and Majority.
Softmax and average-hard attention give transformer encoders the ability to count. Still, they lie within \(\mathsf{TC}^0\) and likely cannot solve problems like evaluating closed Boolean formulas. Some open questions that we think should be priorities for future research are:
Some variants (PEs, average-hard vs. softmax attention, pre-norm vs. post-norm, the presence of BOS/EOS/CLS) appear to be instrumental in proofs reviewed here; can their effect on expressivity be clarified?
Can the expressivity of softmax-attention transformers be characterized more tightly or even exactly in terms of some logic?
Given the current practical importance of decoder-only transformers and chain-of-thought, what further insights can circuits or logic provide into transformer decoders? We hope this paper can serve as a valuable resource for researchers pursuing these and other questions.
We would like to thank Frank Drewes, Jon Rawski, Ashish Sabharwal, and the anonymous reviewers for their valuable comments on earlier versions of this paper.
This differs from the original paper [1], which treats them as matrices in \(\mathbb{R}^{n \times d}\). Our notation aligns better with notation for formal languages and emphasizes the variability of the sequence length.↩︎
Although [58] define \(\textsf{Mon}\) to be the collection of all monadic predicates without dependence on \(n\), [59] do allow them to depend on \(n\).↩︎
[24] define both Turing machines and encoder–decoders to halt only when accepting. The construction could easily be modified to capture decidable languages.↩︎
This uses the result of [46], which would have to be adapted to transformer decoders, but this should be straightforward.↩︎