The Counting Power of Transformers
Abstract
Counting properties (e.g. determining whether certain tokens occur more than other tokens in a given input text) have played a significant role in the study of expressiveness of transformers. In this paper, we provide a formal framework for investigating the counting power of transformers. We argue that all existing results demonstrate transformers’ expressivity only for (semi-)linear counting properties, i.e., which are expressible as a boolean combination of linear inequalities. Our main result is that transformers can express counting properties that are highly nonlinear. More precisely, we prove that transformers can capture all semialgebraic counting properties, i.e., expressible as a boolean combination of arbitrary multivariate polynomials (of any degree). Among others, these generalize the counting properties that can be captured by C-RASP softmax transformers, which capture only linear counting properties.
To complement this result, we exhibit a natural subclass of (softmax) transformers that completely characterizes semialgebraic counting properties. Through connections with the Hilbert’s tenth problem, this expressivity of transformers also yields a new undecidability result for analyzing an extremely simple transformer model — surprisingly with neither positional encodings (i.e. NoPE-transformers) nor masking. We also experimentally validate trainability of such counting properties.
1 Introduction
Transformers (Vaswani et al., 2017) have emerged in recent years as a powerful model with a plethora of successful applications including (among others) natural language processing, computer vision, and speech recognition. Despite the success of transformers, the question of what transformers can express is still not well-understood and has in recent years featured in a rich body of research works (e.g. Strobl et al. (2024); Hahn (2020); Pérez et al. (2021); Hao et al. (2022)). In particular, formal language theory provides a formal framework in understanding expressivity issues for sequential models like transformers and Recurrent Neural Networks (RNNs).
One recurring theme when studying the expressibility of transformers is the counting power of transformers. Intuitively, counting amounts to asserting an arithmetic relationship between the numbers of occurrences of various tokens in a given text. Counting properties are essentially the class of properties for textual data under consideration in the well-known Vector Space Model (VSM) (cf. Salton et al. (1975); Wong et al. (1985); Shawe-Taylor and Cristianini (2004)), or the similar Bag-of-Words (BoW) model (Harris, 1954), which are known from the information retrieval community to be surprisingly powerful in measuring text similarity (e.g. see Shahmirzadi et al. (2019); Shawe-Taylor and Cristianini (2004)). A simple example of a counting property can be found in a sentiment analysis application111https://medium.com/data-science/sentiment-analysis-with-text-mining-13dd2b33de27 : the number of positive words exceeds the number of negative words in a text. In the formal language theory, such a counting property can be formalized as the following language
| (1) |
which is often referred to as majority. Here, (resp. ) refers to the number of occurrences of (resp. ) in the string . For example, but . Note that “tokens” in NLP are synonymous to “letters” in formal language theory. Another counting property that plays an important role in the theory of expressibility of transformers is parity language:
| (2) |
Multiple theoretical and empirical results (e.g. Hahn and Rofin (2024); Chiang and Cholak (2022); Huang et al. (2025); Hahn (2020); Hao et al. (2022); Bhattamishra et al. (2020); Anil et al. (2022); Delétang et al. (2023)) have shown that, while transformers can be efficiently trained for , this is not the case for . Several theoretical explanations have been offered, e.g., sensitivity by Hahn and Rofin (2024) and length generalization admitted by limit transformers by Huang et al. (2025)).
Thus far, existing results have touched only upon semilinear counting properties. For example, defining requires only a linear inequality (i.e. ). In fact, logical languages, which were devised by Barceló et al. (2024); Yang and Chiang (2024); Huang et al. (2025) epitomizing languages expressible by transformers, permit only linear expressions (e.g. ). However, polynomial expressions (cf. Shawe-Taylor and Cristianini (2004)) are also used to express co-occurrence of terms/tokens in a text. For example, using a higher-degree monomial such as
where counts the number of occurrences of a word in the text, one can emphasize the co-occurrence of “nvidia”, “intel” and “deal” in a text. This motivates the following question:
Research Question.
What counting properties are expressible on transformers? Can they express nonlinear counting properties?
The main contribution of this paper is the following result.
Theorem 1.1.
Transformers can capture all semialgebraic counting properties, i.e., those expressible as a boolean combination of inequalities between multivariate polynomials, where each variable counts the number of occurrences of a specific token in the text.
This means that transformers can capture expressions involving higher-degree polynomials like , or boolean combinations (i.e. unions/intersections) of similar polynomial expressions. Consequently, by the Weierstrass theorem it follows that the set of polynomials can also approximate any continuous function on the number of occurrences of tokens. We prove this theorem (using softmax transformers) — requiring the use of neither positional encodings nor positional masking — and experimentally validate this claim.
Our next question concerns the expressivity of softmax transformers for capturing counting properties: which class of softmax transformers capture semialgebraic counting properties? To this end, we provide a surprising characterization involving average hard attention (Hao et al., 2022; Pérez et al., 2021), which was devised to “approximate” soft attention by attending to all positions with maximum attention score and forwarding their average. In particular, Average Hard Attention Transformers (AHATs) with only uniform layers (written AHAT[U]) — that is, where maximum attention score is achieved at every position — immediately form a subclass of SoftMax Attention Transformers (SMAT). In the sequel, we write (resp. ) to mean AHAT (resp. AHAT[U]) that do not use Positional Encodings (PEs) (also no positional masking).
Theorem 1.2.
and capture precisely semialgebraic counting properties. In particular, as far as expressing counting properties, is a subset of .
This is surprising, since it is still a major open problem whether AHAT are captured by SMAT (Yang and Chiang, 2024; Hahn, 2020; Yang et al., 2024b) for general (not necessarily counting) properties.
A corollary of Theorem 1.1, combined with Matiyasevich’s celebrated solution to the notorious Hilbert’s 10th Problem (Matiyasevich, 1993), is a kind of universality (i.e. Turing-completeness) of transformers. More precisely, any recursively enumerable counting property can be represented in terms of a program that, given an input string , feeds each string (where , for some ) into a transformer and accepts if accepts some . In this case, we say that is a projection of the language accepted by . In fact, we show that transformers with only two attention layers are sufficient and necessary to achieve this result:
Theorem 1.3.
Every recursively enumerable counting property is a projection of a language recognized by a , and thus by an . Here, two attention layers in and are sufficient.
Similarly, our results yield an undecidability result for analyzing an extremely simple transformer model—surprisingly with neither positional encodings nor masking:
Theorem 1.4.
Given a or (with just two attention layers), it is undecidable whether its language is empty.
Recent results (cf. (Sälzer et al., 2025)) require a substantially more complex architecture to achieve such an undecidability result, i.e., with powerful positional encoding and average hard attention.
Finally, how do general transformers compare with other machine learning models as far as capturing counting properties? To this end, let us discuss two models. First is the class of polynomial separators that can be generated by mapping to a higher dimension and look for a linear separator in this higher dimension. This is a standard technique in classical machine learning literature, where one can apply techniques like Support Vector Machines (SVM) (e.g. using polynomial kernel) in the Vector Space Model (VSM) (Salton et al. (1975); Wong et al. (1985); also see Chapter 10 of Shawe-Taylor and Cristianini (2004)). Our result shows that transformers generalize such counting properties: not only polynomial counting properties can be captured, but also boolean combinations thereof. Second is the model called C-RASP (Huang et al., 2025), which is a simple declarative language that formalizes the so-called RASP-L conjecture (Zhou et al., 2024) capturing “efficiently learnable” properties on transformers. In particular, C-RASP allows only linear counting terms. We prove that C-RASP can capture only linear counting properties. Since our experiments supporting Theorem 1.1 reveals that counting properties like are also efficiently learnable for , it follows that C-RASP is only a partial characterization of efficiently learnable properties.
Organization.
We recall transformer models and define our framework for studying counting properties in Section˜2. We then show how to capture semialgebraic counting properties using transformers in Section˜3. In Section˜4, we provide a natural subclass of softmax transformers that completely characterizes semialgebraic counting properties. In Section˜5, we show applications of our semialgebraic results for a better understanding of expressiveness of transformers, e.g., universality/undecidability and comparison to work on C-RASP transformers. We report our experimental results in Section˜6 and conclude in Section˜7. Some details have been relegated into the Appendix.
2 Framework: Transformers and Counting Properties
Formal language theory primer
We assume some basic understanding of formal language theory (at the level of a standard undergraduate textbook by Sipser (2013)) and will only fix some notation.
For an alphabet . A language is a set of strings over . We write (resp. ) to mean the set of all strings (resp. all nonempty strings) over . We write to denote the length of . For each , we write to mean the number of occurrences of in . A language is a projection of a language if there is a subalphabet such that is obtained from by deleting all occurrences of letters in from words in . For a class of languages, by , we denote the class of projections of languages in .
We will touch upon regular languages and recursively enumerable languages (see Sipser (2013) for details). In summary, regular languages are languages that can be described by regular expressions. Recursively enumerable languages are those that are recognized by (possibly nonterminating) Turing machines. The class of such languages is denoted . In particular, a machine model is said to be Turing-complete if it can capture all recursively enumerable languages.
For an alphabet , we define the Parikh image (a.k.a. Parikh map) as the function , where is the number of ’s in . Intuitively, Parikh image of a word provides the letter counts in , e.g., over , we have . The Parikh map can also be extended to a language ; that is, . For example, if is a language over , we have .
2.1 Transformers
We now recall the formal definition of transformers. Loosely speaking, a transformer is a composition of finitely many attention layers, each converting a sequence of -vectors into another sequence of -vectors, for some and . To turn a transformer into a language recognizer, we have to embed any letter in the finite alphabet as a -vector, where is smaller than the dimension of the first attention layer. For example, , and the one-hot embeddings of , , are (respectively) , , and . Finally, to determine acceptance, we simply run on the embeddings of the input string into a sequence of vectors (possibly expanded with positional information) and check if the last vector satisfies that the dot product is greater than (for some pre-defined vector of weights). In particular, is accepted by iff .
Example.
Suppose we are given the input string . Additionally, suppose we use the positional embedding . Then, checking whether accepts amounts to running on the sequence :
After running on , the resulting sequence is of the form . Determining whether accepts amounts to checking whether . For example, could be:
which will be accepted, whenever .
Next we formalize the definition of transformers by defining how each attention layer functions.
ReLU networks.
We first define ReLU networks, which are used inside an attention layer. A ReLU node is a function , where is referred to as the input dimension, and is defined as , where are the weights, and is the bias. [In practice, GeLU and SwiGLU are also used instead of ReLU, which we do not consider in this paper.] A ReLU layer is a tuple of ReLU nodes , all having the same input dimensionality, computing a function , where is referred to as the output dimension. Finally, a ReLU network is a tuple of ReLU layers , such that the input dimension of is equal to the output dimension of . It computes a function , given by .
Attention layers
Each attention layer involves a weight normalizer , which turns any -sequence of weights into another such -sequence. Two widely used weight normalizers are:
-
1.
The softmax normalizer . That is, given a sequence , define , where .
-
2.
The averaging hard attention normalizer . We define , where
where consists of positions in such that is maximum in . That is, behaves like but maps all non-maximum weights to 0, and all maximum weights to .
One can also allow a temperature scaling to , i.e., and set . This is not so relevant in our paper since our proof works for any .
An attention layer is a function , given by affine maps , (query, key, and value matrices) and a ReLU neural net . Given an input sequence , the output sequence is computed as follows. First, one computes the sequences of key, query, and value vectors: , for each , then we define , with , where .
We say that is a softmax (resp. aha) layer if (resp. ). We say that it is a uniform- layer if it is an layer such that for all , i.e., for all and . Note that a uniform- is both an layer and a layer since noting that
whenever , which can be guaranteed for uniform layers. This holds for all .
Defining transformers.
To define a transformer and its language, we first extend the finite alphabet with an end marker . That is, . A transformer with layers over a finite alphabet is then a function , given by: (i) the “input embedding” function , (ii) the positional encoding , and (iii) a sequence of layers . Given an input word , the output is computed as follows. First, we set . Then we compute , and we set if and only if , and otherwise. The language accepted by is defined as . We say that has no positional encoding (NoPE) if the positional encoding is a constant function.
Remark.
Several studies (e.g., Merrill and Sabharwal (2023b); Sälzer et al. (2025); Li and Cotterell (2025)) consider the capabilities of transformers in the context of restricted precision, such as assuming computations are carried out under the assumption of finite representation sizes. We do not focus on these aspects, but note that it is easy to see that our key results, such as Proposition˜3.1, also apply under so-called log-precision assumptions (cf. Merrill and Sabharwal (2023b); also see Merrill and Sabharwal (2023a)) for rational numbers. This means that the binary representation size of a number grows logarithmically with the length of the input.
A Softmax Attention Transformer is a transformer using only layers whereas an AHA Transformer is a transformer using only layers. By we denote the class of all languages accepted by softmax attention transformers and by we denote the class of all languages accepted by AHA transformers. To all classes we of transformer languages we append “” to denote languages of transformers with only uniform layers, e.g. . We prepend “” to denote only languages of transformers with no positional encoding, e.g. . Note that all transformer models we are considering in this paper have only one attention head.
2.2 Counting Properties
We now define a framework for studying the counting ability of transformers. Intuitively, our framework focuses on “counting properties”. As we shall see below, we can build many interesting formal languages with the help of purely counting properties.
Given a permutation and a string of length , the string is obtained by permuting the letters in according to .
Definition 2.1.
A counting property over the alphabet is a permutation-closed language , i.e., for each , it is the case that iff for each permutation over .
Examples of counting properties are and (see (1), (2)). We often identify a counting property with its set of letter counts (i.e. Parikh image). By , we denote the class of counting properties over . Counting properties are also called permutation-invariant or “proportion-invariant” languages, e.g., see Pérez et al. (2021); Barceló et al. (2024).
Why counting properties?
Certainly, many languages of interests have both a “counting component” and an “order component”. Take, for example, the language . Our framework focuses on purely counting properties for two reasons. Firstly, it abstracts away non-counting components that cannot be captured by the model. Secondly, many formal languages of interests can be constructed by taking intersection of a counting property and an order (and counting-insensitive) language . For example, above can be written as , where and . Finally, multiple key languages in the literature on the expressivity of transformers are in fact counting properties (e.g. and ).
3 Capturing Semialgebraic Counting Properties
A subset is semi-algebraic if it is a Boolean combination of sets of the form for some polynomial . A language is semi-algebraic if there is a semi-algebraic set and such that . Let denote the class of semi-algebraic languages. An example is
| (3) |
since if and only if . Likewise, extending the coefficients of our polynomials to rational numbers does not increase the expressiveness of semialgebraic sets, e.g., can be rewritten as . Note that for every , the set is semi-algebraic, because if and only if . Thus, every solution set to polynomial equations is also semi-algebraic.
We show Theorem 1.1. Since , it sufices to construct a . We will even construct a . The key ingredient is:
Proposition 3.1.
For every polynomial , the language belongs to . Thus, is in SMAT.
Let us see why Proposition˜3.1 implies . First, the complement of each language can be obtained, because is violated if and only if . Moreover, is closed under union and intersection (we prove a stronger fact in Section˜A.2). We can thus accept all Boolean combinations of languages of the form , and hence .
To show Proposition˜3.1, we will use polynomials that are homogeneous, meaning all monomials have the same degree. Note that given an arbitrary polynomial of degree , we can consider the polynomial with , which is homogeneous. It has the property that if and only if . Therefore, from now on, we assume that we have a homogeneous polynomial and want to construct an AHAT[U] for the language .
To simplify notation, we denote the end marker by . Thus, the input will be a string that contains exactly once, at the end. Since is satisfied automatically, our AHAT[U] only has to check that , where . The input encoding is the map with , where is the -th unit vector.
Overall idea
Roughly speaking, we implement multiplication via averaging as follows. For each letter , we have a gadget that can multiply an existing entry (in each vector) by (recall that is the overall word length). This is done by first multiplying the existing entries either (i) by if the current letter is or (ii) by if the current letter is not . This is achieved using a ReLU layer, by observing that for and , we have . After this, we average over the entire input in this component. Since we make sure that all the entries we multiplied with or had the same value , taking the average will result in the value . Repeating this for a monomial , we arrive at the value . Since our homogenization step ensured that all our monomials have the same degree , adding up the entries corresponding to the monomials will yield . Finally, the latter quantity is positive if and only if .
Step I: Compute frequencies
Our AHAT[U] first uses an attention layer to compute new components, where -th component holds , where is the length of the input (including the end marker). This is easily done by attending to all positions and computing the averages of the first components. To simplify notation, we will index vectors starting with index .
Step II: Multiplication gadgets
Second, we have a sequence of gadgets (each consisting of one ReLU layer and one attention layer) that perform the multiplication. Each gadget introduces a new component, and does not change the existing components. Between gadget executions, the following additional invariants are upheld: (i) Overall, a gadget does not change existing components: it introduces one new component. (ii) The components are called the initial components. (iii) All other components are uniform, i.e. they are the same across all positions. (iv) The uniform components carry values in . Thus, we will call components the initial components; and we call components the uniform components.
Our gadgets do the following. Suppose we have already produced additional components. For each initial component and uniform component , gadget , which introduces a new component, will carry the value where is the value in component of all vectors. Recall that we use to denote the number of occurrences in the input for .
We implement the gadget using some ReLU layers and an attention layer. Suppose that before, we have the vector in position . First, using ReLU layers, we introduce a new component that in position has the value . This can be achieved since is in and : Notice that . Indeed, if , then this evaluates to ; if , then we get . We then use uniform attention to compute the average of this new -component across all vectors. Since there are vectors, exactly of them have , and also , we get the desired .
Step III: Computing the polynomial
We now use our gadgets to compute the value of the polynomial. For each monomial of , say , we use gadgets to compute : The frequency computation in the beginning yields , and then we use gadgets to compute , , etc. until . Finally, we use a ReLU layer to multiply each monomial with a rational coefficient, and compute the sum of all the monomials. Thus, we have computed . We accept if and only if . Note that this is the case if and only if .
This completes Proposition˜3.1 and thus . We remark that the embedding dimension and the number of layers of our transformer in Proposition 3.1 depends on the degree and the number of monomials in . We require at most layers, each layer increasing the degree of the computed monomials by one. In the appendix, we detailed that polynomials of degree are accepted by using at most attention layers (see Proposition˜A.1). The embedding dimension is because we store the value of each monomial in a separate dimension.
4 Characterizing semi-algebraic counting properties
We have shown that can capture semi-algebraic counting properties. We now prove that the subclass precisely characterizes .
Proposition 4.1.
.
Proof.
Suppose that is our alphabet, the end marker, and the number of occurrences of in the input. We say that a position is an -position if the input holds at position . Notice that an AHAT without positional encoding cannot distinguish vectors that come from the same input letter. This means, in any layer, any two -positions will hold the same vector. Thus, the vector sequence on layer is described by rational vectors , where is the vector at all the -positions on layer . Moreover, for each , the set of positions maximizing an attention score also either contains all -positions, or none of them. Therefore, if the AHAT has attention layers, there are at most possible ways to choose the positions of maximal score: On each attention layer, and for each , we select a subset of the letters. For each ReLU node and each , there are two ways its expression can be evaluated: as or as . Thus, if there are ReLU nodes, then there are ways to evaluate all those nodes.
For each of these choices, we construct a conjunction of polynomial inequalities that verify that (i) this choice actually maximized scores, (ii) the resulting vector at the right-most position in the last layer satisfies the accepting condition. This is easy to do by building, for each layer and each , expressions in for the vectors , assuming our choice above. These expressions have the form (averaging can introduce denominators). Here, once we have expressions for , we can use them to build expressions for by following the definition of AHAT. Checking (i) and (ii) is then also easy, because inequalities involving quotients can be turned into polynomial inequalities by multiplying with common denominators. Finally, we take a disjunction over all conjunctions. ∎
Inexpressibility of .
Our characterization of (i.e. Proposition˜4.1) implies an interesting inexpressibility result regarding (see (2):
Corollary 4.2.
does not belong to .
is known to be accepted by AHAT (Barceló et al., 2024) and by SMAT (Chiang and Cholak, 2022) (with PE). Inexpressibility of in a length-generalizable subclass of and (with struct future masking and positional encodings) is known (Huang et al., 2025). Similarly, is not expressible by with strict future masking (Hahn, 2020). Corollary˜4.2 complements these results and is an easy corollary of Proposition˜4.1 (see Section˜A.3).
5 Applications
5.1 Universality and undecidability of transformers
Let us discuss why universality/undecidability (i.e. Theorems˜1.3 and 1.4) follow from Theorem˜1.2. First, by the well-known theorem “MRDP” theorem (Matiyasevich, 1993) due to Matiyasevich, Robinson, Davis, and Putnam, every language in is a projection of a language of the form , where is a polynomial. Since belongs to , we thus obtain Theorem˜1.3. Furthermore, since our translation from polynomials to (and thus ) is effective, this also implies Theorem˜1.4: By the MRDP theorem (which is also effective), it is undecidable whether a given polynomial has a solution. Using our translations, we can turn such a into a (or ) that is non-empty if and only if has a solution.
Using only two layers
In fact, in Theorems˜1.3 and 1.4, we even claim that two layers suffice for universality and undecidability. Let us sketch this here. First, our construction above yields a of at most layers, provided that the polynomials in the semialgebraic set all have degree (see Appendix˜A). In particular, we show that for each , is closed under union and intersection (see Section˜A.2). Furthermore, we rely on the well-known fact that the set of solutions of a polynomial equation can always be written as the projection of the set of solutions of a system of quadratic equations. Since by our stronger version of Theorem˜1.2, intersections of solution sets of quadratic equations only require a with layers, this yields the stronger versions of Theorems˜1.3 and 1.4. See Appendix˜B for details (where we also show that with just one layer, Theorems˜1.3 and 1.4 do not hold).
5.2 Comparison with C-RASP and LTL with Counting
C-RASP (Huang et al., 2025; Yang and Chiang, 2024) is a simple programming language that can be converted into softmax transformers. In particular, it is a subset of the so-called LTL with Counting (Yang and Chiang, 2024; Barceló et al., 2024). For example, can be written as the following formula in LTL with Counting: . In particular, only linear expressions can be constructed in such formulas. We show in the appendix that LTL with Counting (and therefore C-RASP) only capture (semi)linear counting properties, i.e., boolean combinations of linear inequalities (and modulo arithmetics), so not languages like .
Proposition 5.1.
LTL with Counting can define only (semi)linear counting properties.
6 Experiments
In this section, we experimentally complement our main result (cf. Theorem˜1.1) that transformers can capture solutions of polynomial equations of higher degree. In particular, our results suggest that softmax transformers should be able to learn languages encoding solutions of polynomial equations.
We test our hypothesis on extensions of with polynomial inequalities. That is, we define the language is defined by , representing the set of solutions for the simple equation .
Do softmax transformer classifiers perform well on language ? Additionally, can we observe tendencies of length-generalization?
In other words, the task of the transformer is a binary classification such that accepts if and it does not if .
We train softmax encoders without positional encoding and otherwise in line with the vanilla model, introduced by Vaswani et al. (2017), as binary classifiers using components offered by Pytorch’s nn.Module based on a balanced dataset of data points sampled from for of words up to length 500 In all experiments, we conduct a single epoch and choosed the best model conducting early stopping based on the binary-cross entropy loss combined with softmax, the typical metric for models outputting a probability for binary classification, offered in a numerical stable version by Pytorch’s nn.Module in form of BCEWithLogitsLoss , on a validation dataset sampled from the same distribution and of the same size as the training dataset. To partially explore the hyperparameter space, we conduct a grid search over number of layers 1 to 5, number of heads per layer 1, 2 or 4. In all experiments, we fixed the input features to 32, the feedforward dimension to 64, the dropout rate to 0.3, and optimized using the AdamW optimizer with a learning rate of and weight decay of 0.01 as, again, offered by Pytorch’s optim package.
| Val. Perf. | Test Perf. | Gen. Perf. | |
|---|---|---|---|
| 1 | 0.015 | 0.016/0.99 | 0.301/0.95 |
| 2 | 0.024 | 0.033/0.99 | 0.324/0.94 |
| 3 | 0.023 | 0.021/0.99 | 0.299/0.96 |
| 4 | 0.019 | 0.020/0.99 | 0.099/0.97 |
| 5 | 0.020 | 0.024/0.99 | 0.107/0.96 |
Figure 2 presents the outcome of our experiments. The table on the left-hand side demonstrates the best observed performance on the validation dataset (first column), a balanced test dataset derived from the same distribution as the training and validation data (second column). This specifically implies that this dataset also only includes words of length up to 500. The final column represents another balanced test dataset encompassing words from length 501 to 1000, used to potentially unveil some length generalization performance. The plot on the right visualizes the same results.
Generally, we observe very high performance with an accuracy of on the in-distribution test dataset. Additionally, while the performance on the test dataset with longer words decreases, it remains relatively high, with an accuracy of in all instances. Especially, it is to be assumed that with a more extensive experimental setup, this gap in performance will decrease. Therefore, we infer that our trained encoders perform well and that length generalization is supported, indicating that the model can capture the semantics of . In Appendix D we report additional results, showing strong performance, with a decrease in performance on longer inputs.
7 Concluding Remarks
Related Work.
Lots of work have been done in recent years on the expressiveness of transformers for general (not necessarily counting) properties (cf. see (Strobl et al., 2024)). Counting properties — e.g., the languages and — have frequently featured in transformers expressivity research, which highlight their importance. Various theoretical transformer models have been used in the literature employing different assumptions on the attention mechanisms (hardmax attention vs. softmax attention), positional encodings, etc. For example, a large proportion of results use hardmax attention, which is not used by practical transformers (which instead use softmax attention). In addition, some works (e.g. Pérez et al. (2021); Barceló et al. (2024)) employ extremely complex positional encodings with no restrictions. That said, several recent works have adopted more practical models. In particular, the works of Yang and Chiang (2024); Huang et al. (2025); Yang et al. (2024b; 2025) employ softmax attention transformers and simple classes of positional encodings (causal masking, local, etc.). Our results also employ a similar model (AHAT[U] and SMAT); in fact, we proved that semialgebraic counting properties can be captured by transformers without any positional encodings. Yang et al. (2025) gave a restriction of softmax attention transformers with bounded finite precision outside the attention computation, which characterizes C-RASP. Our experimental results seem to suggest this transformer model only lower-bounds the expressivity of real-world transformers, which can capture counting properties beyond C-RASP.
Concerning verification of transformers, we mention the works by Yang et al. (2024a) and Bergsträßer et al. (2026), showing that reasoning about Unique-Hard Attention Transformers (UHAT) are decidable with complexity EXPSPACE-complete. UHAT is known to overapproximate what can be captured by softmax transformers with bounded finite precision (Li and Cotterell, 2025). We also mention the recent work (Yang et al., 2026), showing that verifying C-RASP is undecidable.
Potential Applications in NLP.
By Weierstrass theorem, polynomials can approximate any continuous function of the number of occurrences of tokens. This suggests that transformers can solve practical NLP tasks that require computation of nonlinear statistics in the word frequencies.
Counting properties are tightly connected to Vector Space Model (VSM) (Salton et al., 1975; Wong et al., 1985; Shahmirzadi et al., 2019) that has applications in text classification and similarity analysis, where the standard method has been to employ Support Vector Machines (SVM), together with kernel analysis (e.g. using polynomial kernels). Our results imply that transformers are expressive enough to perform such tasks. In VSM, a document is a vector indexed by “terms” that may occur in . That is, is a count on the number of occurrences of in . To compare similarity between two documents , we may consider the Euclidean distance between and , which requires a polynomial. Also, there are often challenges including "related terms" (e.g. husband, wife, and spouse), which are missed when we only use the aforementioned metric. Thus, a similarity measure is often learned (see Section 10.2.2 in (Shawe-Taylor and Cristianini, 2004), where VSM is used in combination with polynomial kernels). Our results show that transformers can solve such a task. A related task is the problem of determining proximity to a human written text, as dictated by Zipf (1935) stating that the frequency of the -th most frequent word is proportional to in a natural language. As above, we may compare using Euclidean distance a document with a predetermined Zipf-vector. This results in a polynomial, and our results show this can be captured by transformers.
Future Work.
We mention several open problems. Firstly, can softmax attention transformers with causal masking capture counting properties beyond semialgebraic sets? Secondly, our work has identified a gap in the formalization of the RASP-L conjecture by Huang et al. (2025). That is, transformers can capture and efficiently learn semialgebraic counting properties, which are beyond the language C-RASP. It is open whether the extension of C-RASP with inequalities over nonlinear polynomials can still be captured by softmax transformers.
Acknowledgments
We thank David Chiang, Michael Hahn, Andy Yang, and anonymous reviews for their feedback.
Marco Sälzer, Chris Köcher, Georg Zetzsche, and Anthony Lin are
funded by the European Union (ERC, LASD, 101089343 and FINABIS, 101077902). Views and opinions expressed are however those of the authors only and do not necessarily reflect those of the European Union
or the European Research Council Executive Agency.
Neither the European Union nor the granting authority can be held responsible for them.
Alexander Kozachinskiy is funded by the National Center for Artificial Intelligence CENIA (FB210017, Basal ANID, and ANID Fondecyt Iniciación grant 11250060).
References
- Exploring length generalization in large language models. In Advances in Neural Information Processing Systems 35: Annual Conference on Neural Information Processing Systems 2022, NeurIPS 2022, New Orleans, LA, USA, November 28 - December 9, 2022, S. Koyejo, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh (Eds.), External Links: Link Cited by: §1.
- Logical languages accepted by transformer encoders with hard attention. In ICLR, Cited by: §1, §2.2, §4, §5.2, §7.
- Transformers are inherently succinct. In The Fourteenth International Conference on Learning Representations, External Links: Link Cited by: §7.
- On the ability and limitations of transformers to recognize formal languages. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing, EMNLP 2020, Online, November 16-20, 2020, B. Webber, T. Cohn, Y. He, and Y. Liu (Eds.), pp. 7096–7116. External Links: Link, Document Cited by: §1.
- Overcoming a theoretical limitation of self-attention. In Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), ACL 2022, Dublin, Ireland, May 22-27, 2022, S. Muresan, P. Nakov, and A. Villavicencio (Eds.), pp. 7654–7664. External Links: Link, Document Cited by: §1, §4.
- An introduction to the theory of linear integer arithmetic (invited paper). In 44th IARCS Annual Conference on Foundations of Software Technology and Theoretical Computer Science, FSTTCS 2024, December 16-18, 2024, Gandhinagar, Gujarat, India, S. Barman and S. Lasota (Eds.), LIPIcs, Vol. 323, pp. 1:1–1:36. External Links: Document Cited by: Appendix B, §C.1.
- Neural networks and the chomsky hierarchy. In The Eleventh International Conference on Learning Representations, ICLR 2023, Kigali, Rwanda, May 1-5, 2023, External Links: Link Cited by: §1.
- A survival guide to presburger arithmetic. ACM SIGLOG News 5 (3), pp. 67–82. External Links: Document Cited by: Appendix B, §C.1.
- Why are sensitive functions hard for transformers?. In Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), ACL 2024, Bangkok, Thailand, August 11-16, 2024, L. Ku, A. Martins, and V. Srikumar (Eds.), pp. 14973–15008. External Links: Link, Document Cited by: §1.
- Theoretical limitations of self-attention in neural sequence models. Trans. Assoc. Comput. Linguistics 8, pp. 156–171. External Links: Link, Document Cited by: §1, §1, §1, §4.
- Formal language recognition by hard attention transformers: perspectives from circuit complexity. Trans. Assoc. Comput. Linguistics 10, pp. 800–810. External Links: Link, Document Cited by: §1, §1, §1.
- Distributional structure. Word 10 (2-3), pp. 146–162. External Links: Document, Link Cited by: §1.
- A formal framework for understanding length generalization in transformers. In The Thirteenth International Conference on Learning Representations, ICLR 2025, Singapore, April 24-28, 2025, External Links: Link Cited by: Appendix D, §1, §1, §1, §4, §5.2, §7, §7, Remark.
- Characterizing the expressivity of fixed-precision transformer language models. In The Thirty-ninth Annual Conference on Neural Information Processing Systems, External Links: Link Cited by: §7, Remark.
- Hilbert’s tenth problem. MIT Press, Cambridge, Massachusetts. Cited by: Appendix B, §1, §5.1.
- A logic for expressing log-precision transformers. In Advances in Neural Information Processing Systems 36: Annual Conference on Neural Information Processing Systems 2023, NeurIPS 2023, New Orleans, LA, USA, December 10 - 16, 2023, A. Oh, T. Naumann, A. Globerson, K. Saenko, M. Hardt, and S. Levine (Eds.), External Links: Link Cited by: Remark.
- The parallelism tradeoff: limitations of log-precision transformers. Trans. Assoc. Comput. Linguistics 11, pp. 531–545. External Links: Link, Document Cited by: Remark.
- Attention is turing-complete. J. Mach. Learn. Res. 22, pp. 75:1–75:35. External Links: Link Cited by: §1, §1, §2.2, §7.
- A vector space model for automatic indexing. Commun. ACM 18 (11), pp. 613–620. External Links: Link, Document Cited by: §1, §1, §7.
- Transformer encoder satisfiability: complexity and impact on formal reasoning. In The Thirteenth International Conference on Learning Representations, ICLR 2025, Singapore, April 24-28, 2025, External Links: Link Cited by: §1, Remark.
- Text similarity in vector space models: A comparative study. In 18th IEEE International Conference On Machine Learning And Applications, ICMLA 2019, Boca Raton, FL, USA, December 16-19, 2019, M. A. Wani, T. M. Khoshgoftaar, D. Wang, H. Wang, and N. Seliya (Eds.), pp. 659–666. External Links: Link, Document Cited by: §1, §7.
- Kernel methods for pattern analysis. illustrated edition edition, Cambridge University Press. External Links: ISBN 0521813972, Link Cited by: §1, §1, §1, §7.
- Introduction to the theory of computation. Third edition, Course Technology, Boston, MA. External Links: ISBN 113318779X Cited by: §2, §2.
- What formal languages can transformers express? A survey. Trans. Assoc. Comput. Linguistics 12, pp. 543–561. External Links: Link, Document Cited by: §1, §7.
- Attention is all you need. In Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, December 4-9, 2017, Long Beach, CA, USA, I. Guyon, U. von Luxburg, S. Bengio, H. M. Wallach, R. Fergus, S. V. N. Vishwanathan, and R. Garnett (Eds.), pp. 5998–6008. External Links: Link Cited by: §1, §6.
- Generalized vector space model in information retrieval. In Proceedings of the 8th annual international ACM SIGIR conference on Research and development in information retrieval, Montréal, Québec, Canada, June 5-7, 1985, J. Tague (Ed.), pp. 18–25. External Links: Link, Document Cited by: §1, §1, §7.
- Length generalization bounds for transformers. Note: Under submission (preprint: https://zenodo.org/records/18800700) External Links: Document Cited by: §7.
- Knee-deep in c-RASP: a transformer depth hierarchy. In The Thirty-ninth Annual Conference on Neural Information Processing Systems, External Links: Link Cited by: §7.
- Masked hard-attention transformers recognize exactly the star-free languages. In Advances in Neural Information Processing Systems, A. Globerson, L. Mackey, D. Belgrave, A. Fan, U. Paquet, J. Tomczak, and C. Zhang (Eds.), Vol. 37, pp. 10202–10235. External Links: Link Cited by: §7, Remark.
- Counting like transformers: compiling temporal counting logic into softmax transformers. CoRR abs/2404.04393. Cited by: §1, §1, §5.2, §7, Remark.
- Simulating hard attention using soft attention. CoRR abs/2412.09925. External Links: Link, Document, 2412.09925 Cited by: §1, §7.
- What algorithms can transformers learn? A study in length generalization. In The Twelfth International Conference on Learning Representations, ICLR 2024, Vienna, Austria, May 7-11, 2024, External Links: Link Cited by: §1.
- The psychobiology of language: an introduction to dynamic philology. Houghton Mifflin, Boston, MA. Cited by: §7.
Appendix A Translating semialgebraic sets to
A.1 Fine-grained analysis of polynomial degree vs. depth
In this subsection, we show the inclusion . In fact, we show a stronger statement (Proposition˜A.1), which requires some notation. By we denote the restriction of the class to the semi-algebraic languages such that the underlying semi-algebraic set is a Boolean combination of sets where are polynomials of degree . In particular, we have . Our construction for actually shows the following:
Proposition A.1.
For each we have .
For showing Proposition˜A.1, we need some more technical definitions. Let be an AHAT with input embedding and layers . We define the function as follows: for a word , if , then . In other words, we have iff .
Proposition A.2.
For every polynomial of degree , the language belongs to .
To show Proposition˜3.1, we will use polynomials that are homogeneous, meaning all monomials have the same degree. Note that given an arbitrary polynomial of degree , we can consider the polynomial with , which is homogeneous. It has the property that if and only if . Therefore, from now on, we assume that we have a homogeneous polynomial and want to construct an AHAT for the language .
To simplify notation, we denote the end marker by . Thus, the input will be a string that contains exactly once, at the end. Since is satisfied automatically, our AHAT only has to check that , where . The input encoding is the map with , where is the -th unit vector.
In a first lemma we show that each monomial of can be computed by a NoPE-AHAT with uniform attention layers.
Lemma A.3.
For every monomial of degree , there is a NoPE-AHAT with uniform attention layers such that
for each word . In particular, we have if and only if .
Proof.
We use the word embedding with for each .
Step I: Compute frequencies
Our AHAT first uses an attention layer to compute new components, where -th component holds , where is the length of the input (including the end marker). This is easily done by attending to all positions and computing the averages of the first components. To simplify notation, we will index vectors starting with index .
Step II: Multiplication gadgets
Second, we have a sequence of gadgets (each consisting of one uniform attention layer and one ReLU layer). Each gadget introduces a new component, and does not change the existing components. Between gadget executions, the following additional invariants are upheld: (i) Overall, a gadget does not change existing components: it introduces one new component. (ii) The components are called the initial components. (iii) All other components are uniform, i.e. they are the same across all positions. (iv) The uniform components carry values in . Thus, we will call components the initial components; and we call components the uniform components.
Our gadgets do the following. Suppose we have already produced additional components. For each initial component and uniform component , gadget , which introduces a new component, will carry the value where is the value in component of all vectors. Recall that we use to denote the number of occurrences in the input for .
We implement the gadget using some ReLU layers and an attention layer. Suppose that before, we have the vector in position . First, using ReLU layers, we introduce a new component that in position has the value . This can be achieved since is in and : Notice that . Indeed, if , then this evaluates to ; if , then we get . We then use uniform attention to compute the average of this new -component across all vectors. Since there are vectors, exactly of them have , and also , we get the desired .
Step III: Computing the monomial
We now use our gadgets to compute the value of the monomial. Let . We use gadgets to compute : The frequency computation in the beginning yields , and then we use gadgets to compute , , etc. until . Finally, we use a ReLU layer to multiply with . Thus, we have computed . ∎
A.2 Combining without additional layers
The following lemma states that two NoPE-AHAT with only uniform attention layers can be parallelized resulting in a NoPE-AHAT with the same number of uniform layers. Their outputs can also be combined via a ReLU neural network. In particular, is closed under union and intersection.
Lemma A.4.
Let be two NoPE-AHAT with uniform attention layers and let be a ReLU neural network computing a function . Then there is a NoPE-AHAT with uniform attention layers computing .
Proof.
The idea of is, that it concatenates the components from with those of and keeps the sets of components always disjoint. By uniformity we are able to apply the attention layers of and in parallel. In the last attention layer we can simply apply to the first components of and .
By we denote the word embedding of . From this we construct a new word embedding with for each .
Now, let be the th layer of for . By , and we denote the parameters of . Since is uniform, the key and query maps and are constantly mapping to zero. We now construct a uniform layer composed of and : the key and query maps and still map to zero. If then we define the new value map by
By this definition we obtain that the attention vectors j in are the concatenation of the attention vectors j,1 and j,2 in resp. . Similarly, we build the composition of and resulting in an FFN computing .
Finally, in the last layer, we add the FFN that takes the first components of the output of and simulates on these two numbers. ∎
Recall that from a polynomial we constructed a homogeneous polynomial such that if and only if holds for all vectors . Let be the monomials in . Since is homogeneous, all monomials have the same degree . Lemma˜A.3 yields NoPE-AHATs that are computing the monomials . Each of these AHATs has exactly uniform attention layers. Finally, we can apply Lemma˜A.4 to construct a NoPE-AHAT with uniform layers computing (since addition is an affine map). Then accepts iff iff iff . In other words, accepts the language .
A.3 Inexpressibility of
Proof of Corollary˜4.2.
By Theorem˜1.2, it suffices to show that is not semi-algebraic. Suppose it is. Then there is a disjunction of conjunctions of polynomial inequalities that characterizes . The polynomials are over , where is the variable for ’s and is the variable for ’s. By plugging in , we conclude that the set of even numbers is semi-algebraic. Hence, there is a disjunction of conjunctions that is satisfied exactly for the even numbers. This implies that for some , there are infinitely many even numbers such that . Therefore, for every , the leading coefficient of must be positive. But then, must hold for all sufficiently large , not just the even ones, a contradiction. ∎
Appendix B Parametric analysis
In this section, we study how the expressive power of NoPE-AHAT[U] and SMAT depends on the number of attention layers. In particular, we show that Theorems˜1.3 and 1.4 hold already in the case of two layers. The main insight of this proof is that the number of layers needed to express a semialgebraic set depends on the degrees of the involved polynomials (see Proposition˜A.1): Note that our sketch of an for in Section˜3 directly yields a with layers, where is the degree of . For Proposition˜A.1, one then has to show that Boolean combinations of such sets can be expressed without growing the number of attention layers. See Appendix˜A for details.
Capturing with two layers
From Proposition˜A.1, we can now deduce the two-attention-layer version of Theorems˜1.3 and 1.4. The first ingredient is the following version of the MRDP theorem on Diophantine sets (Matiyasevich, 1993):
Theorem B.1.
Let . A language belongs to if and only if there is a and a polynomial such that , where
In other words, every language in is a projection of a language of the form , where is a polynomial. Thus, it suffices to place in . First observe that in Theorem˜1.2, we use one attention layer for each multiplication, so this avenue is closed if we want to stay within two attention layers. Instead, we use that for every polynomial , there are quadratic (i.e. degree ) polynomials for some such that for , we have if and only if there is some with : Just introduce a fresh variable for each multiplication in and use the to assign these fresh variables. Since the language belongs to (since the have degree ) and is a projection of , this means belongs to . By Proposition˜A.1, .
NoPE AHAT with a single layer
The fact that two layers suffice for universality among counting properties raises the question of whether this is even possible with a single attention layer. We show here that this is not the case:
Theorem B.2.
.
This means, with a single attention layer, NoPE-AHAT can recognize precisely those counting properties expressible using quantifier-free Presburger formulas. Since satisfiability of Presburger arithmetic is well-known to be decidable (Haase, 2018; Chistikov, 2024), this implies that universality and undecidability of (as we have shown for two attention layers), do not hold with just one attention layer. However, we leave open whether with one attention layer have a decidable emptiness problem.
Before going into details, let us sketch the proof of Theorem˜B.2. For the inclusion , we proceed similarly to Proposition˜4.1, while observing that the inequalities we have to verify are all linear inequalities: This is because a single attention layer averages only once. Conversely, for the inclusion follows easily from Proposition˜A.1.
Proof of Theorem˜B.2.
We begin by proving that . Let be an AHAT with input embedding , a single AHA layer utilising affine maps , , given as matrices, and the ReLU network . Our goal is to construct a quantifier-free PA formula with variables for such that . In the following, we assume and denote by .
First, we observe that for all words , the output of given is computed by
where is exactly the subset of symbols occurring in that maximise . We construct such that it mirrors exactly this computational structure. We have , where ranges over those subsets where is maximal for precisely the . The subformula is defined as follows. For now, we assume that and introduce some auxiliary formulas. Throughout the following construction steps, we assume that atomic formulas are normalised to the form .
Given the ReLU network , it is straightforward to construct a quantifier-free PA formula such that exactly includes those satisfying , where denotes the first output dimension of . The key idea here is that the computation of a single ReLU node , with weights and bias of , is described by the quantifier-free PA formula: . Then, by nesting this construction iteratively from the last layer to the first layer of , and finally replacing with in the atomic formulas related to the first output dimension of , we achieve the construction of . This nesting and replacement also ensures that includes only the variables .
Let such that . Consider the ReLU network , the value matrix , and the embedding . We construct a quantifier-free PA formula such that exactly includes those satisfying . To do so, we adjust the formula as described in the following. To account for the fixed input , we replace each occurrence of to in by the respective entry of . Furthermore, to handle the specific form of the input , we first replace each occurrence of with in the already modified by:
where are the respective entries of . Lastly, we replace each atomic constraint in the adjusted formula with to adjust for the factor present in the input.
Now, we define as . If , we adjust slightly. Assuming , we replace the variable with the constant in . Given this construction, it is clear that , as mimics the computation of for all possible attention situations .
For the inclusion , we observe that , and thus the inclusion follows from Proposition˜A.1. ∎
Appendix C Counting properties expressible by other models
C.1 Semilinear counting properties
A counting property is said to be semilinear if can be defined as a boolean combination of inequalities over linear arithmetic expressions (over variables and integer constants) and modulo arithmetic expressions of the form , where are fixed constants. In particular, semilinear counting properties cannot define semialgebraic counting properties involving polynomials of degrees 2 or above.
It is also convenient to use quantifiers when defining semilinear sets. In particular, they do not increase the expressive power since they can be eliminated. This results in the logic called Presburger arithmetic (PA), which refers to the first-order theory of the structure ; see Haase (2018); Chistikov (2024).
C.2 Permutation-invariant languages of LTL with counting
has the following syntax:
where and . Next we define the semantics of . For any word with , for each , and each formula we write if the formula is satisfied in at position . Formally, this relation is defined inductively as follows:
-
•
(for ) iff ,
-
•
iff ,
-
•
iff or ,
-
•
iff and ,
-
•
iff there is with and for all we have ,
-
•
iff where the semantics of a term is defined as follows: , , , and .
Our main result on is the following:
Theorem C.1.
Every permutation-invariant language definable in has a semilinear Parikh image.
Before we can prove Theorem˜C.1, we need a few more definitions. For an alphabet write for the set . A (-dimensional) Parikh automaton is a tuple where is a finite set of states, is the input alphabet, is an initial state, is a finite transition relation, and are semilinear target sets. A word is accepted by if there are , states , and vectors such that (i) and , (ii) for each there is a transition with , and (iii) . The accepted language of is the set of all words accepted by . It is a well-known fact that for each Parikh automaton the accepted language has a semilinear Parikh image. Observe that -dimensional Parikh automata are essentially NFA and, hence, accept exactly the regular languages.
A Parikh transducer is a Parikh automaton with input alphabet where and are two alphabets. The accepted language of a Parikh transducer can also be seen as a map: if then we can see as the input and as the output of the transducer. Formally, for an input language a Parikh transducer computes the output . If is accepted by a Parikh automaton then is also accepted by a Parikh automaton. To see this, we can take the synchronized product of the Parikh automaton accepting and (i.e., reads the same letter from the input as in its first component). Accordingly, cascading of Parikh transducers is also possible, i.e., if and are Parikh transducers over and , we can also construct a Parikh transducer over computing .
With the definition of Parikh automata and Parikh transducers we are now able to prove Theorem˜C.1.
Proof.
Let be a formula such that the described language is permutation-invariant. We will prove by induction on the structure of that the Parikh image of (or actually a bounded subset of ) is semilinear. Here, a language is bounded if there are letters with . So, let be distinct letters with . Then is clearly bounded and has the same Parikh image as .
For each subformula of we construct a Parikh transducer that labels each position satisfying . In the base case, we decorate each letter by where iff . Note that this transducer handles all atomic formulas at once. For we add the decoration to each letter where iff one of the decorations corresponding to and is . There are similar transducers (which do not introduce counters) for the cases , , and . Note that applying these transducers to a bounded language always yields another bounded language.
Now, consider a counting subformula, i.e. . Observe that the set of positions satisfying is convex in the set of positions satisfying any . This is true since we consider only a bounded input language. Hence, we can split the input word into three (possibly empty) intervals: (i) the positions at the beginning of the input that do not satisfy , (ii) the positions where all positions satisfying a also satisfy , and (iii) the positions at the end of the input that do not satisfy . We describe in the following a Parikh transducer with many counters - one for each of these three intervals and each formula . The transducer guesses the three intervals (note that this is non-deterministic), counts positions satisfying a accordingly, decorates only the positions in the second interval labeled with a with (and everything else with a ), and validates in the end our choice of the intervals (via appropriate semilinear target sets ensuring that the equation in is not satisfied in the first and third interval and is satisfied in the second interval). Clearly, this all can be done in one (non-deterministic) Parikh transducer.
Finally, we have a cascade of (Parikh) transducers decorating each position in a bounded input word with a Boolean value indicating whether holds in that position. If we use as input language for our transducers (note that this language is regular) and intersect the output with all words decorated with a in the first position, we obtain a Parikh automaton accepting exactly the language . Since Parikh automata accept only languages with semilinear Parikh image, we infer that and, hence, have a semilinear Parikh image. ∎
Appendix D Further experimental validation
| Val. Perf. | Test Perf. | Gen. Perf. | |
|---|---|---|---|
| 1,3 | 0.016 | 0.02/0.99 | 0.03/0.99 |
| 3,2 | 0.002 | 0.003/0.99 | 0.60/0.93 |
| 3,3 | 0.001 | 0.002/0.99 | 2.26/0.85 |
| 4,2 | 0.001 | 0.001/0.99 | 0.26/0.96 |
| 5,1 | 0.004 | 0.004/0.99 | 0.03/0.99 |
In this section, we report additional experiments addressing a similar research question as posed in Section 6, namely, do softmax transformers perform well on formal languages with inherent non-linear counting properties? Therefore, we consider the language
for selected values of and . Clearly, recognising this language requires non-linear counting capabilities. Moreover, in contrast to (see Section 6), this language poses a greater challenge in learning tasks due to its structure (all ’s follow all ’s followed by all ’s) and larger alphabet size.
The experimental setup is identical to that presented in Section 6. The results are presented in Figure 4 for five distinct combinations of and . Similar to our previous experiments, the table on the left shows the highest observed performance on the validation dataset (first column) and the best performance on a balanced test dataset derived from the same distribution as the training and validation data (second column). This indicates that this dataset also contains only words of length up to 500. The final column represents another balanced test dataset of words from length 501 to 1000, utilised to potentially reveal length generalisation performance. The plot on the right visualises the results reported in the table.
We again observe very high performance of our trained softmax transformers on the in-distribution test dataset (second column), which shares the same distribution as our training dataset. The performance generally remains high on the generalisation test set (third column) as well. We witnessed a slight decrease compared to the results on the in-distribution test in the case of (accuracy of 0.85). A general decrease in performance on longer inputs is expected and also witnessed in other studies (cf. Huang et al. (2025)), but it also indicates that focused studies are essential to reveal rigorous insights into the relationship between the expressibility of polynomial counting properties we established and their practical learnability.