Formal Language Recognition by Hard Attention Transformers: Perspectives from Circuit Complexity
Yiding Hao, Dana Angluin, Robert Frank
Introduction
The Transformer architecture for neural networks (Vaswani et al., 2017) has yielded remarkable advances in performance on a variety of benchmark tasks in natural language processing. These advances have spurred considerable interest in understanding the capabilities and limitations of the Transformer architecture. While Transformer networks are extremely complex when deployed at scale, theoretical studies such as those of Pérez et al. (2019), Yun et al. (2020), Hahn (2020), and Merrill et al. (2022) have uncovered meaningful insights about the expressive power of Transformers by formulating abstract models of the self-attention mechanism and analyzing their computational power.
In this work, we analyze three restricted models of self-attention based on their ability to recognize formal languages. All three models use hard attention—meaning that each attention head attends only to the position or positions with the highest attention score, with no attention paid to any of the other positions—but differ in how they behave in the case of ties in the maximum attention value. In the first two models we study, the attention mechanism returns the value at exactly one position (for example, the leftmost) in case several positions tie for the maximum attention value. The first such model, which we call generalized unique hard attention Transformers (GUHAT) and was defined by Hahn (2020), imposes no restrictions on the nature of activation values or the functions the network uses to compute them. The second model, unique hard attention Transformers (UHAT), was defined and studied by Yao et al. (2021) and is a more concrete version of GUHAT that incorporates restrictions on the nature of activation values and computations. In the third model, which we call averaging hard attention Transformers (AHAT), the attention mechanism returns the uniform average of the values at positions with the maximum attention value. This is the definition of hard attention used by Pérez et al. (2019), Yun et al. (2020), and Merrill et al. (2022).Merrill et al. (2022) call it saturated hard attention.
Our main contribution is to prove that GUHAT and UHAT can only recognize formal languages in AC0, the class of formal languages recognized by a family of Boolean circuits of constant depth and polynomial size, whereas AHAT can recognize formal languages outside of AC0. More formally, we prove that any formal language recognized using a GUHAT is also recognized by a family of Boolean circuits of constant depth and polynomial size, establishing AC0 as an upper bound on the expressiveness of UHAT and GUHAT. We also show that every UHAT can be simulated by an AHAT, establishing UHAT as a subclass of AHAT. Based on the classical results of Furst et al. (1984), our upper bound subsumes Hahn’s (2020) results that GUHAT cannot recognize the DYCK languages or the PARITY language, neither of which belongs to AC0. Furthermore, our result combines with Pérez et al.’s (2019) AHAT implementation of the MAJORITY language and Bhattamishra et al.’s (2020) AHAT implementation of DYCK- (neither of which is in AC0) to show that AHAT can recognize languages that GUHAT cannot. Recently, Merrill et al. (2022) have given an upper bound on the power of AHAT: namely, that every formal language recognizable using averaging hard attention is recognizable using a family of circuits of constant depth and polynomial size with Boolean and majority gates; that is, a family of circuits in the complexity class TC0, known to be a strict superset of AC0. Taken together, our paper establishes the following relationships between the three models we consider of hard-attention Transformers.
Preliminaries
Let be a fixed finite alphabet of symbols, and let \\Sigma\Sigman\Sigma^{n}\Sigma\Sigma^{*}\Sigma\Sigma^{*}$.
Circuit Complexity
Our analysis of UHAT and GUHAT is carried out within the framework of circuit complexity, in which the complexity of a computational system is measured by the size, depth, and types of gates of a Boolean circuit implementing that system. In this section we review the basic concepts, definitions, and results of circuit complexity used by our analysis. A detailed overview is provided in Chapter 6 of Arora and Barak (2009).
Boolean circuits are a formal model of computational systems based on logic gates. Roughly speaking, a Boolean circuit consists of binary-valued input and output layers, with feedforward connectionsWe consider only acyclic circuits. to one another via intermediate gates that implement logical operations. We use the following definition of Boolean circuits.
A Boolean circuit with inputs and outputs is a labeled directed acyclic graph satisfying the following conditions. There are distinguished input vertices labeled with the variables . Each input vertex has fan-in . The rest of the vertices are gates, each having a label from Constant-0, Constant-1, NOT, AND, or OR. The Constant-0 and Constant-1 gates have fan-in , NOT gates have fan-in , and AND and OR gates have unbounded fan-in. Finally, the labels are applied to some (not necessarily distinct) vertices; these are the outputs.
We refer to the edges of a Boolean circuit as wires. The size of a circuit is the number of wires it contains, and the depth of a circuit is the maximum length of a directed path of wires from an input vertex to an output. A Boolean circuit computes a Boolean function from to ; we denote its output on input by .
Observe that a Boolean circuit has a fixed number of input vertices, and therefore can only take as input bit strings of a fixed length. We would like to define circuit computation for a map defined on all of . To that end, we allow different circuits for inputs of different lengths.
A family of circuits is a sequence , where for each integer , is a Boolean circuit with inputs and one output. A map from to is computed by a family of circuits if and only if for all and all , .
The class AC0 is defined by setting restrictions on the size and depth of circuits within a family of Boolean circuits.
A family of circuits is of constant depth if there exists a constant such that the depth of is bounded by for all . A family of circuits is of polynomial size if there exists a constant such that the size of is bounded by for all . The set AC0 is the set of families of Boolean circuits of both constant depth and polynomial size.
2 Non-AC0 Languages
Having defined the class AC0, we present some examples of languages not belonging to this class. First, the following three languages were shown by Furst et al. (1984) to fall outside AC0.
We define the following languages over the alphabet . The language PARITY is the set of all strings containing an even number of s; MAJORITY is the set of strings with at least as many s as s; and EQUALITY is the set of strings with exactly as many s as s.
Additionally, we show later in this paper (Corollary 3) that DYCK- also falls outside AC0.
The language DYCK- is the set of strings over an alphabet of types of pairs of brackets that are correctly nested and matched. For example, DYCK- over the alphabet can be described by a context free grammar with productions , , , and . The language DYCK- is the set of strings in DYCK- in which the depth of nesting of brackets never exceeds . The language SHUFFLE- is the shuffle (arbitrary interleaving) of strings from versions of DYCK- each using a different type of bracket pair.
Finally, we define PALINDROMES, a language shown in Section 5 to be in GUHAT.
The language PALINDROMES is the set of strings equal to their reverses, which can be described by the context free grammar with productions , , and for each alphabet symbol .
Hard Attention Transformers
We now define the three kinds of hard attention Transformers studied in this paper: GUHAT, UHAT, and AHAT. These formalisms are models of computation inspired by the encoder portion of the Transformer architecture. They conceptualize Transformers as cascading layers of feature extractors that convert a sequence of embeddings into increasingly higher-level representations.
We begin by presenting a general framework that subsumes the three hard attention Transformer models. Formally, a generalized Transformer is a device that maps a string x\in\Sigma^{*}\1x$ is accepted or rejected, respectively. Each such device is parameterized by a collection of functions described as follows.
A generalized Transformer with layers and attention heads is a tuple where
is the set of activation values,
is the activation function for layer , and
is the model output function.
On input where x_{n}=\y^{(0)}_{1}y^{(0)}_{2}\dots y^{(0)}_{n}\in\mathcal{A}^{n}$ of initial activation values is given by
for all . Each layer then produces a string of activation values from the previous activation values as follows. First, each attention head produces an matrix of attention scores given by
for all positions of the input string. Next, the pooling function converts each row of attention scores into an activation value based on :
Finally, the layer output is computed using the layer’s activation function:
When has been computed for all , the final output of the generalized Transformer is computed by applying the model output function to the last symbol of ; that is,
If , we say that accepts ; otherwise, we say that rejects . The language recognized by , denoted , is the set of strings such that accepts x\$.
The formalism we have presented above is fully generalized in the sense that we have placed no restrictions on the activation values or the functions , , , , or , other than to specify their domains and co-domains. The three hard attention Transformer models are derived by placing restrictions upon these elements.
2 Unique and Averaging Hard Attention
The first restriction we consider is on the form of the pooling function. We consider two types of pooling functions: the unique hard attention function, used in GUHAT and UHAT, and the averaging hard attention function, used in AHAT.
In unique hard attention, the pooling function simply selects the activation value from the previous layer corresponding to the argmax of the row of attention scores. In case of a tie, the leftmost activation value is selected.
Averaging hard attention is similar to unique hard attention, except that in the case of a tie, the selected activation values are averaged.
The GUHAT model is defined as the class of generalized Transformers that use unique hard attention.
A generalized unique hard attention Transformer is a generalized Transformer whose pooling function is . We use the term GUHAT to refer to the class of generalized unique hard attention Transformers, and also to the class of languages they recognize.
The GUHAT model mostly follows the definitions of Hahn (2020). It is slightly generalized in allowing the input function to depend on the input length , and in allowing the activation function to depend on the layer , but these generalizations are immaterial. In particular, it is not necessary to assume that the input length is provided to the input function: if the input function were , the subsequent layer could direct attention at every position to position (because it uniquely contains the end-of-sequence symbol \n$ is available at every position.
3 Restricted Models: UHAT and AHAT
GUHAT allows the activation values and the functions , , , and to take on any arbitrary mathematical value. In practical applications of Transformer networks, however, these components are restricted in specific ways. Many variations of hard attention Transformers attempt to incorporate these restrictions into theoretical models, though they do not entirely agree on the details of these restrictions.
The UHAT and AHAT models adopt many of these restrictions, largely following the definitions of Yao et al. (2021). For the sake of computability, we require activation values to be vectors of rational numbers. Following Pérez et al. (2019), we restrict scalars to be rational as well. Next, we assume that the input function is decomposed into a token embedding function and a position embedding function. Mirroring the more familiar description of attention functions in terms of query, key, and value matrices, we use a bilinear form for attention functions proposed in Luong et al. (2015). In addition to the unique and averaging hard attention mechanisms, we allow the pooling function to be future-masked (where for position only those positions with are considered in the attention computation) or past-masked (similarly for ). Finally, we assume that activation functions and the model output function are computed by feedforward neural networks with ReLU activation. These restrictions are summarized below.
the pooling function may be future-masked or past-masked;
each activation function is computed by a feedforward neural network with ReLU activation;
the output function is computed by a feedforward neural network with ReLU activation followed by a softmax layer, with if and only if the output of the network on input is greater than or equal to .
Because is finite, we may assume that the token embedding function is given by a table lookup. Our formulation of position embedding is somewhat more general than the definition of Yao et al. (2021), who take the position embedding to be a scalar defined as that occupies one position of the initial activation vector.
The UHAT and AHAT models are defined to be restricted Transformers that satisfy the above conditions and use unique and averaging hard attention, respectively.
A unique hard attention Transformer is a restricted Transformer whose pooling function is or a future- or past-masked version thereof. An averaging hard attention Transformer is a restricted Transformer whose pooling function is or a future-or past-masked version thereof. We use the terms UHAT and AHAT, respectively, for these classes of Transformers, and also for the classes of languages they recognize.
UHAT is clearly a subclass of GUHAT because the former imposes restrictions on the form of the input, attention, activation, and output functions. We suspect, but do not prove, that this inclusion is proper. Moreover, we briefly argue below that UHAT is properly contained in AHAT.
Since AHAT recognizes non-AC0 languages (Pérez et al., 2019; Bhattamishra et al., 2020), it suffices to show that . Let be a UHAT of dimension recognizing . We define a UHAT of dimension recognizing that has no ties in its attention values. Since the pooling functions used in UHAT and used in AHAT are identical in the absence of ties, replacing the pooling function of with gives us an AHAT recognizing .
Let be a sufficiently large integer depending on , specified below. Each activation value in is from with two additional constant components, set to and by the input function. The attention function computes using the original attention function and activation values, subtracting the value . This is achievable with a bilinear map.
4 Prior Results for These Models
Hahn (2020) shows that the languages and are in GUHAT, and the languages PARITY and DYCK- for all are not in GUHAT. Pérez et al. (2019) show that even without positional information, the language MAJORITY is in AHAT. Bhattamishra et al. (2020) show that SHUFFLE- is in AHAT, which implies that DYCK- is in AHAT. Yao et al. (2021) show that the language DYCK- is in UHAT. The latter two results use positional masking, but no other positional information.
PALINDROMES in GUHAT
Let us now illustrate how a GUHAT computes by way of example. In this section, we describe a GUHAT with layers and head that recognizes the language PALINDROMES over the alphabet . Broadly speaking, this Transformer works as follows. The first layer is responsible for comparing each symbol of the input string with the corresponding symbol on the opposite side of the string, and marking whether the two symbols match. The second layer reads these markings, searching for a mismatch identified by the first layer. If one is found, the model output function returns ; otherwise, it returns . For intuition, we simultaneously illustrate the Transformer’s computation on the input abcca\$, which should be rejected.
The input function is defined as for each and . For our example input, the initial (layer ) activation values are shown in the first row of Figure 1. These activation values are not rational-valued vectors, of course, but the GUHAT model imposes no restriction on the form these values can take.
We define the attention function for layer , , to be . For each position , this selects the activation at the correct corresponding position, . For position , it selects the activation at position .
We define the activation function for layer as
The layer activation values for our example input are shown in the second row of Figure 1. This indicates that positions and found mismatched symbols, and positions , , and did not.
Layer gathers the relevant information from layer into the last position. The layer attention function is defined by . This directs the attention at every position to the leftmost activation value from layer such that . In our example, the leftmost such position is , with its activation of . If the input sequence had instead been a valid palindrome, none of the positions would have been marked with by layer . In this case, the leftmost position with would have been the final position , which has the activation value of .
We define the layer activation function as . For our example input, the activation values for layer are shown in the third row of Figure 1. The activation value at position will be if and only if no earlier position found a symbol mismatch, so the model output function is simply . With the input sequence abcca\62(6,2)abcba\$62(6,6)1\Sigma$, we have the following.
For any finite alphabet , the language PALINDROMES over is in GUHAT.
A Normal Form for GUHAT
Despite the abstractness and generality of the GUHAT model, we can define a normal form representation and show that every Transformer in GUHAT is equivalent to a Transformer in GUHAT in this normal form with the same number of layers and heads. The key idea is to preserve in the activation values all the information from previous layers that has been used to compute them, by requiring that the input and activation functions just return the tuple of their arguments. We also require that attention values be integers in the smallest relevant range.
A GUHAT with layers and heads is in informative normal form if and only if the following conditions are satisfied.
The input function is .
For each layer , the activation values are -tuples of activation values at layer , and the activation function is defined by
For each layer and attention head , the attention function returns an integer in , where is the total number of possible ordered pairs of activation values at layer .
For any Transformer , there exists a Transformer in informative normal form such that . Moreover, has the same number of layers and heads as .
Let be a GUHAT with layers and heads, with input alphabet , input function , attention functions , activation functions , and output function . We describe how to construct functions for an equivalent Transformer in GUHAT in informative normal form, which also has layers and heads. We assume that is the input length.
For the input function is defined to return the triple . Note that there are at most possible initial activation values. We also define a function that translates initial activation values for into initial activation values for by .
Now, we induct on the layers of and . Assume that we have defined attention and activation functions for for layers before (where the initial activation values are treated as “layer ”), and a translation function that translates all possible activation values for from the previous layer into activation values for from the previous layer. To define the attention function for for layer for head , we enumerate all the possible pairs and of activation values of at layer , and determine the corresponding attention values of , which we denote by . We make a list of all the distinct resulting values and sort them into increasing order. Then we define to be the rank of in this sorted list. The activation function for for layer is, by definition,
The translation function for layer is defined by
that is, we translate each of the component activation values using and then apply the activation function of .
Finally, the output function for is defined by , that is, we translate the layer activation value of to the layer activation value of , and apply the output function of .
By construction, is in informative normal form, and it has layers and heads. It is not difficult to see that for any input , the translations of the activation values of are equal to the corresponding activation values of , and the outputs are equal as well. Thus, . ∎
To illustrate the construction of in the proof of Lemma 1, we briefly show how an informative normal form version of the Transformer for PALINDROMES from Section 5 would process the input x=abcca\1$, their translation is simplified.
The initial activation values and layer attention function are the same as in the example. The resulting layer activation sequence, consisting of a sequence of paired initial activations and attention values, is
The translation maps to if and if . When applied to the above activation sequence, this yields the previous example’s layer activation sequence.
The layer translation function maps a layer activation value
to . For layer and position the activation value for this input is
which is mapped to by . The previous example’s output function compares and and returns , rejecting the input .
From GUHAT to Circuits
In this section we show that for every language , we can construct a family of Boolean circuits of constant depth and polynomial size that also recognizes . This will prove the following, which is our main result.
Every language in GUHAT is recognized by a family of circuits in AC0.
Let be a language over that is in GUHAT. By Lemma 1, we may assume that is recognized by GUHAT Transformer in informative normal form. Assume has layers and heads.
The key step of the proof is to bound the number of bits needed to represent attention and activation values for an input sequence of length by , where the suppressed constants depend on and .
It is worth observing that the bounds provided by Lemma 2 do not hold in the case of AHAT. Attention scores may be the result of the average of an arbitrary subset of the possible inputs, which means that there are exponentially more possible activation values at each layer.
The following elementary facts about Boolean circuits will be useful.
An arbitrary Boolean function of inputs and outputs can be computed by a depth circuit of size at most .
Express each output of as a disjunctive normal form (DNF) formula of at most terms, each with at most literals. Convert each DNF formula to a circuit with one OR gate with inputs from an AND gate for each term, each of whose inputs is either an input to the function, or the result of applying a NOT gate to an input. In each such circuit, the OR gate has at most input wires, each AND gate has at most input wires, and each of at most NOT gates has one input wire, for a total size bounded by . The final circuit consists of these separate circuits computing in parallel, and its size is at most times the size of each one. The longest possible path to an output from an input is through a NOT, an AND, and the OR gate, for a depth of at most . ∎
If a Boolean function has at most inputs and at most outputs, then it may be computed by a Boolean circuit of depth and size at most .
With the bound on the number of bits to represent activation and attention values, Lemma 2 yields circuits of constant depth and size polynomial in for the input, attention, activation, and output functions. Additional circuitry is necessary to implement the comparison of attention scores and selection of the activation value to attend to for each position, layer, and head.
We next describe the circuit that implements the pooling function . For each pair , there is a circuit whose inputs are the outputs of and and whose output is a single wire with a value of if and otherwise. Because of the bounds on the number of inputs and outputs, each of these circuits can have depth and size polynomial in by Corollary 1. These circuits all compute in parallel.In fact, comparison of two -bit integers can be done with a Boolean circuit of constant depth and size polynomial in , but that is not necessary for the present purpose. Then for each position , whether maximizes can be computed by an AND gate whose inputs are for all . Let the output of this AND gate be denoted . Then if and only if the position maximizes . This increases the depth by .
For each , an indicator is computed by an AND gate whose inputs are and for all . Thus, if and only if is the leftmost position that maximizes . This increases the depth by .
Finally, these indicator values are used to combine the layer activation values in a selection circuit, yielding the representation of the activation value such that . In general, such a selection circuit takes as input selector bits , where exactly one , and input values , where each consists of bits. It outputs bits representing the selected (for which ). Letting denote bit of , the computation can be described as for and , which can be computed by one layer of AND gates in parallel. Then the bits of the output are for , which can be computed by one layer of OR gates in parallel. Thus, the selection circuit adds to the depth, and a polynomial in to the size.
Because each activation function for a GUHAT in informative normal form simply returns its arguments, no further computation is needed for the activation values. The representation of the activation value is just the sequence of wires representing followed by those representing , through .
To produce the output of the circuit, we note that the representation of has bits and the output of is a single bit, so can be implemented by a Boolean circuit of constant depth and size polynomial in , by Corollary 1. This concludes the proof of Theorem 1.
Furst et al. (1984) prove that the PARITY, EQUALITY, and MAJORITY languages are not in AC0, which immediately implies the following.
GUHAT does not contain the languages PARITY, MAJORITY, or EQUALITY.
To see that the DYCK- languages are also not in AC0, we reduce from the EQUALITY language.
For all , the language DYCK- is not in AC0, and is therefore not in GUHAT.
It suffices to prove this for . Assume that there is a family of Boolean circuits in AC0 that recognizes DYCK-. We may assume that the binary symbol encoding is and . We show how to use this to construct a family of Boolean circuits in AC0 that recognizes the EQUALITY language, a contradiction.
is constructed from as follows. If the inputs to are , then consists of with its first inputs set to the constant , its middle inputs set to , and its last inputs set to the constant .
Let be any element of . If the number of occurrences of is not equal to the number of occurrences of in , then the input to has unequal numbers of and symbols, which is not in DYCK- and is rejected. If the number of occurrences of is equal to the number of occurrences of in , then in any prefix of the input to , the number of occurrences of is less than or equal to the number of occurrences of . At the end of the input, the number of occurrences of is equal to the number of occurrences of , so the input to is in DYCK- and is accepted. Thus is a family of Boolean circuits in AC0 that recognizes the language EQUALITY, a contradiction. ∎
Discussion and Conclusions
We have defined formal language recognition by the encoder portion of a Transformer network using generalized unique hard attention (GUHAT), unique hard attention (UHAT), and averaging hard attention (AHAT), and shown that languages in UHAT and GUHAT are recognizable by constant depth, polynomial size families of circuits, that is, families of circuits in the complexity class AC0. This strengthens the negative result of Hahn (2020) that the languages PARITY and DYCK- are not in GUHAT, and provides a simpler and more general proof. Combined with prior results of Pérez et al. (2019) showing that the language MAJORITY is in AHAT, or Bhattamishra et al. (2020) showing that the language DYCK- is in AHAT, this shows that AHAT contains languages that are not in GUHAT or UHAT.
Many intriguing open questions remain. What classical closure properties hold for the classes of languages GUHAT, UHAT, and AHAT? Closure under complement just requires complementing the output function , and closure under pairwise union and intersection should be straightforward using a parallel approach; but what about closure under homomorphism, inverse homomorphism, concatenation, or Kleene star? We briefly observe that GUHAT and UHAT cannot be closed under both Kleene star and concatentation lest they contain all regular languages, including PARITY.
Existing formal models and indeed practical implementations of Transformers vary in their representation of position information, whether as an absolute representation of position, a ratio (e.g., position in a sequence of length as ), through angle information (e.g., position by the pair where ), or as an arbitrary learned embedding. In the UHAT and AHAT models, the choice of positional encoding can facilitate positional comparison (e.g., an angle-based encoding allows for equality testing via dot products) or make it uncomputable (e.g., if positional encodings enumerate Turing machines that halt on their own encodings). It remains to be understood what effect such differences in position representation have on the expressive power of a model.
More generally, is it possible to prove that soft attention, which we have not addressed here, is strictly more powerful than even averaging hard attention? Yao et al. (2021, Theorem B.3) present a construction for a soft attention Transformer that recognizes DYCK-. This construction crucially employs specialized encodings of position and layer normalization, whose formal power remains to be understood.
Finally, given the success that Transformers have had as models of natural language, it is perhaps surprising that these models’ expressive power seems to be best characterized (or at least bounded) in terms of circuit complexity. Mathematical explorations of natural language have most commonly employed the approach to language complexity afforded by the Chomsky hierarchy and its refinements, which is based on automata and formal grammars. The apparent incomparability of these approaches suggests that the exploration of different types of Transformer models might offer a new approach to the study of the formal properties of natural language.
Acknowledgements
We thank the reviewers and the action editor for their work in reviewing this paper.