On Limitation of Transformer for Learning HMMs

## Abstract

Abstract Despite the remarkable success of Transformer-based architectures in various sequential modeling tasks, such as natural language processing, computer vision, and robotics, their ability to learn basic sequential models, like Hidden Markov Models (HMMs), is still unclear. This paper investigates the performance of Transformers in learning HMMs and their variants through extensive experimentation and compares them to Recurrent Neural Networks (RNNs). We show that Transformers consistently underperform RNNs in both training speed and testing accuracy across all tested HMM models. There are even challenging HMM instances where Transformers struggle to learn, while RNNs can successfully do so. Our experiments further reveal the relation between the depth of Transformers and the longest sequence length it can effectively learn, based on the types and the complexity of HMMs. To address the limitation of transformers in modeling HMMs, we demonstrate that a variant of the Chain-of-Thought (CoT), called block CoT in the training phase, can help transformers to reduce the evaluation error and to learn longer sequences at a cost of increasing the training time. Finally, we complement our empirical findings by theoretical results proving the expressiveness of transformers in approximating HMMs with logarithmic depth.

## 1 Introduction

Transformer-based architectures (Vaswani et al., ) have demonstrated exceptional capabilities in tackling sequential modeling tasks across diverse domains, including natural language processing (Brown et al., ), computer vision (Dosovitskiy et al., ), robotics (Brohan et al., ), reinforcement learning (Janner et al., ; Lee et al., ), etc. Despite their widespread success, the effectiveness of Transformers in learning basic sequential models, such as the Hidden Markov Model (HMM), remains unclear. Investigating this question is crucial for understanding the strengths and limitations of Transformers, especially considering that HMMs are arguably among the simplest yet fundamental tools for modeling natural language (Merialdo, ; Vogel et al., ; Chiu and Rush, ) and time series from applications ranging from control systems (Franklin et al., ) to robotics (Doucet et al., ).

Furthermore, HMMs bear close relation to the widely adopted Partially Observable Markov Decision Process (POMDP) framework in reinforcement learning (e.g. Hausknecht and Stone, ; Rashid et al., ), as an HMM can be regarded as a simplification of POMDP, which has no action-input control.
To this end, this paper investigates the following fundamental questions through extensive empirical experiments and theoretical analysis:

- 1.
Can Transformer effectively learn HMM models and their variants?
- 2.
How does its performance compare to that of Recurrent Neural Network (RNN) in terms of training speed, hyperparameter tuning difficulty, and final accuracy?
- 3.
Furthermore, when presented with an HMM sequence of a specific length, how many attention layers are required to achieve a desired level of accuracy?

We are particularly interested in the last question due to the pivotal advantage of Transformers over RNNs in long sequence modeling: the depth of the computation graph in Transformers scales linearly with the number of layers and remains (almost) independent of the sequence length, whereas that of RNNs scales linearly with both. It is vital to verify whether such advantage indeed exists in long sequence modeling tasks such as HMMs.

In this paper, we primarily focus on two fundamental tasks associated with HMMs: autoregression and belief inference (Rabiner and Juang, ). Autoregression involves predicting the next observation based on all preceding ones, while belief inference aims to deduce the distribution of the hidden states from previous observations. In our experiments, we evaluate the performance of Transformer and RNN in addressing these tasks across three distinct types of HMMs: discrete HMM with fast mixing speed, discrete HMM with slow mixing speed, and Linear Dynamical System (LDS)—HMM with continuous states and observations. Below, we present an overview of our findings concerning the three aforementioned questions.

- 1.
Transformers effectively learn to perform belief inference across all tested HMMs when the training dataset includes true beliefs at each time step. However, in the task of next-observation prediction, certain challenging HMM instances exist where Transformers struggle to achieve low prediction loss.
- 2.
In comparison, RNNs demonstrate the capability to successfully tackle all tasks across the tested HMMs at a faster training speed, yielding lower testing error. Notably, RNN training exhibits greater robustness compared to Transformers, particularly in the realms of hyperparameter tuning and curriculum scheduling.
- 3.
Our experiments reveal distinct patterns in the relationship between sequence length and the minimal depth required for Transformers to learn effectively. These patterns can be categorized into three groups:
•
Constant depth: For simple sequential models such as random HMM and LDS, a constant depth, independent of sequence length, is sufficient for Transformers to learn accurately.
•
Logarithmic scaling: For more complex sequential models such as structured HMMs, we observe an approximate logarithmic dependency between the minimal depth required and the sequence length. This relationship holds for various structured HMM instances, as corroborated by both theory and experiments.
•
Hard instances: There exists challenging HMM instances where Transformers struggle to learn, even for constant sequence length. These instances require further investigation to identify the underlying reasons for the learning difficulties.

In order to address the limitations of Transformers in learning HMMs, we employ a variant of the CoT prompting in the training phase called block CoT. Block CoT feeds the output of the Transformer back to itself as input every $b$ tokens, which reduces to the standard CoT when $b=1$. The exact value of $b$ can be determined from the scaling between the sequence length and the minimal depth of Transformers required to learn the sequence. This method integrates a recursive inductive bias into the vanilla Transformer architecture. Our findings show that block CoT significantly decreases evaluation error and enhances the sequence length that shallow Transformers can handle. We remark that this approach will nevertheless increase the computational demands, and thereby slows down the training process.

Finally, we also complement our empirical findings by theoretical results, which proves the scaling between the sequence length and minimal depth from the perspective of expressiveness power. Specifically, it is proved that an $L$-layer finite precision Transformer is able to fit any HMMs of at least $2^{L}$ sequence length.

### 1.1 Related work

Our work can be viewed as part of a broader effort to assess the ability of Transformer models on simple, basic and well-defined tasks with synthetic data. Such an approach is advantageous because it allows us to precisely evaluate the Transformer’s capabilities in a particular aspect, as we have access to the ground truth model that generates the training data. Below, we highlight some related works along this direction.

Recently, a line of works (e.g., Garg et al., ; Bai et al., ; Bhattamishra et al., ; Von Oswald et al., ) have studied training Transformer models for in-context learning of regression tasks (e.g., linear regressions) utilizing synthetic datasets. A notable distinction between in-context learning and learning HMMs lies in the data sequence’s nature. In in-context learning, all tokens within a data sequence are independently sampled from the same data distribution. Conversely, in HMMs, tokens are recursively generated, with each token strongly influenced by the preceding ones, establishing a mutual dependency among them.

Previous studies have also explored the capability of Transformer models to learn elementary algorithms, such as formal language transduction (Delétang et al., ), arithmetic calculation (Dziri et al., ), recognizing formal languages (Bhattamishra et al., ), sorting (Zhou et al., ) and learning semi-automata (Liu et al., ). These problems, as noted in (Liu et al., ), can all be considered special cases of learning finite-state deterministic automata, which is in turn special cases of of HMMs as noted in Appendix A.2.
In comparison, our work focuses on training Transformer models to learn stochastic HMMs, which is a special case of more general stochastic POMDP but without input control. By focusing on stochastic HMMs, our work aims to contribute to the understanding of how Transformer models can learn and generalize from sequential data in the presence of intrinsic uncertainty.

## 2 Preliminaries

In this section, we briefly introduce the basics of HMM models and neural network models considered in this paper.

### 2.1 Sequential Models

An HMM can be formulated by a tuple $(\mathcal{S},\mathcal{O},\mathbb{P},\mathbb{O},S_{0})$, where $\mathcal{S}$ is the state space, $\mathcal{O}$ is the observation space, $\mathbb{P}(s^{\prime}\mid s)$ is the transition probability of transitioning to state $s^{\prime}$ from state $s$, $\mathbb{O}(o\mid s)$ is the probability of emitting observation $o$ from state $s$, and $S_{0}$ is the initial state. By interacting with the HMM for $T$ steps, one can obtain a trajectory (i.e., a sequence of states and observations) $(s_{0}=S_{0},o_{0},...,s_{T},o_{T})$, where $o_{t}$ is sampled from distribution $\mathbb{O}(\cdot\mid s_{t})$ and unobserved. $s_{t+1}$ is sampled from $\mathbb{P}(\cdot\mid s_{t})$. We are particularly interested in two basic tasks for learning an HMM in this paper, which are also known as two of the three key problems of HMMs (Rabiner and Juang, ):

- •
*Belief state inference:* Assuming the size of the state space is $n$ (i.e., $|\mathcal{S}|=n$, the states are numbered from 1 to $n$) for a given HMM, belief state inference aims at computing the belief state $b_{t}\in\mathbb{R}^{n}$ at step $t$ given an observation sequence $(o_{1},o_{2},...,o_{t})$. The belief state $b_{t}$ is defined as the posterior probability of the HMM being at each state given the observation sequence $(o_{1},o_{2},...,o_{t})$: $\bm{b}_{t}(s)\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\mathrm{Pr}(s_{t}
=s\mid o_{1},o_{2},...,o_{t}).$
It is easy to derive the following equation using Bayes’ rules
$\displaystyle\bm{b}_{t+1}=\frac{\mathrm{diag}(\mathbb{O}(o_{t+1}\mid\cdot))
\mathbb{P}\bm{b}_{t}}{\left\|\mathrm{diag}(\mathbb{O}(o_{t+1}\mid\cdot))
\mathbb{P}\bm{b}_{t}\right\|_{1}},$
(2.1)
where $\mathbb{O}(o\mid\cdot)=(\mathbb{O}(o\mid 1),...,\mathbb{O}(o\mid n))^{\top}\in
\mathbb{R}^{n}$, $\mathrm{diag}(v)$ is the diagonal matrix generated by vector $v$, and $\mathbb{P}\in\mathbb{R}^{n\times n}$ is the transition matrix with $\mathbb{P}(s^{\prime},s)=\mathbb{P}(s^{\prime}\mid s)$ with a little abuse of notations.
- •
*Next-Observation prediction:*
Another fundamental task is to predict the distributions of the next observation given the history of observations. It is in general simpler than belief state inference in that
$\displaystyle\mathrm{Pr}(o_{t+1}\mid o_{1},...,o_{t})=\mathbb{O}\mathbb{P}\bm{
b}_{t}.$
(2.2)
However, it is more realistic in the sense that the observations are convenient to access for an HMM with unknown transition and emission probability, while the belief states are not.

Throughout the paper, we use $n$ to denote the size of the state space $\mathcal{S}$ if it is finite, or the dimension of $\mathcal{S}$ if it is a Euclidean space. The size of the observation space is always finite, which we denote by $m$.

### 2.2 Neural Network Models

Two fundamental sequence-to-sequence models are considered in this paper: the recurrent neural network (RNN) and Transformer.

#### RNN.

Given a length-$T$ sequence $(x_{1},...,x_{T})$ as input, an RNN with embedding dimension $d$ and initial hidden state $h_{0}\in\mathbb{R}^{d}$ processes the input sequence as follows:

$$ $\displaystyle h_{t}=\mathrm{ReLU}\left(W_{1}x_{t}+W_{2}h_{t-1}+b\right),$ (2.3) $$

where $W_{1},W_{2},b$ are the parameters of the RNN.

The final output sequence is obtained by applying a linear decoder layer on sequence $(h_{1},...,h_{T})$ at each position.

#### Transformer.

The Transformer (Vaswani et al., ) is also a well-known sequence-to-sequence model with significant successes on various prediction tasks. A Transformer with depth $L$ (i.e., $L$ layers) processes the data as follows:

Let $\bm{X}^{(0)}\in\mathbb{R}^{T\times d}$ be the output of a position-wise embedding layer ($d$ is the embedding dimension of the Transformer) given $m_{0}$-dimensional length-$T$ input sequence $(x_{1},x_{2},...,x_{T})^{\top}\in\mathbb{R}^{T\times m_{0}}$, the Transformer apply $L$ attention blocks sequentially on $\bm{X}^{(0)}$. The $l$-th attention block transforms the input by

$$ $\displaystyle\bm{Y}^{(l-1)}=\bm{X}^{(l-1)}+\operatorname{Attn}^{(l)}\left(\bm{ X}^{(l-1)}\right),\bm{X}^{(l)}=\bm{Y}^{(l-1)}+\mathrm{FFN}^{(l)}\left(\bm{Y}^{ (l-1)}\right),\quad l\in[L],$ (2.4) $$

where $\operatorname{Attn}$ is a multi-head self-attention layer and $\operatorname{FFN}$ is a two-layer feed-forward network with $\operatorname{GeLU}$ (Hendrycks and Gimpel, ) as activation functions (defined by Eqn. (A.1) and Eqn. (A.2) in Appendix). The final output is obtained by forwarding $\bm{X}^{(L)}$ to a linear readout layer.

## 3 Model

In this section, we introduce the HMMs and their variant models explored in this paper, broadly classified into two categories: fast-mixing models and slow-mixing structured models. The mixing speed characterizes
the “effective length” of past histories that influence the current belief state. For instance, in a fast-mixing model, the belief state at the current step is essentially influenced only by a few of the most recent observations, making them more amenable to fitting by neural networks. When we mention “HMM” in the rest of the paper, it means standard HMMs and their variants. The motivation for studying these HMMs is discussed in Appendix A.4.

### 3.1 Fast-Mixing HMMs

#### HMM : Random HMM.

The initial set of sequential models under consideration comprises random HMM instances with randomly initialized transition and emission probabilities. Our primary focus is on the belief state inference problem within these random HMMs. This choice is motivated by the observation that, as per (2.2), next-observation prediction is a relatively simpler task compared to belief state inference when dealing with random HMMs.

#### LDS : Linear Dynamical System.

A linear dynamical system is given by the following equation

$$ $\displaystyle x_{t+1}=Ax_{t}+\zeta_{t},y_{t}=Bx_{t}+\xi_{t},$ (3.1) $$

where $x_{t}\in\mathbb{R}^{n}$ is the (hidden) state at step $t$, $y_{t}\in\mathbb{R}^{m}$ is the observation at step $t$, and $\zeta_{t},\xi_{t}$ are independent random noises. It can be regarded as a continuous HMM with linear transition and emission. We choose $A,B$ as random orthogonal matrices with $n=m$ and $\zeta_{t},\xi_{t}$ standard Gaussian noises for simplicity.
It’s worth noting that predicting the belief state and the next observation is equivalent in this context, given that $B$ is orthogonal. Therefore, our focus lies on next-observation prediction, distinguishing it from the HMM model.

### 3.2 Structured HMM Models and Variants

#### MatMul : Matrix Multiplication.

This model is directly motivated from the belief state inference problem, which can be specified by $|\mathcal{O}|$ matrices $A_{1},...,A_{|\mathcal{O}|}$. With a little abuse of notations, given the state $\bm{b}_{t}\in\mathbb{R}^{n}$ at step $t$ and an observation $o_{t+1}$ at next step, the next state is recursively defined as
$\bm{b}_{t+1}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}A_{o_{t+1}}\bm{b}_
{t}.$
Compared to the standard belief state inference equation, the only difference in this model is the absence of the $\ell_{1}$ normalization after the matrix multiplication (c.f. Eqn. (2.1)). In order to stabilize the system (i.e., preventing the $\ell_{2}$ norm of $\bm{b}_{t}$ from exploding exponentially over time), we generate orthonormal matrix $A_{o}$ for all $o\in\mathcal{O}$. For simplicity, the observation $o_{t}$ at each step follows a uniform distribution over the observation space $\mathcal{O}$.

#### CyclicHMM-DET : Deterministic Cyclic HMM.

Figure: Figure 1: An illustration of CyclicHMM-DET model and CyclicHMM-HARD model. Left: A CyclicHMM-DET model with 4 states and 2 actions. The transition graph of each action is a cyclic permutation over the state space. Different actions may induce different cyclic permutation. Right: Given a CyclicHMM-RND or CyclicHMM-DET model, the CyclicHMM-HARD model transforms it into a larger HMM. The transition in CyclicHMM-HARD model always goes from stage 1 to 3 then back to stage 1. The dotted line denotes a stochastic transition from stage 1 to stage 2 with probability $\alpha$, and the solid line denotes deterministic transition. States in stage 2 always emit a signal observation $*$ indicating the entrance of stage 3, and states in stage 3 emit the current state as observation.
Refer to caption: extracted/5648862/PAPER/images/model.png

Consider a deterministic cyclic automaton (Liu et al., ) with $n$ states, $m$ actions, and the state transition function $q:[n]\times[m]\to[n]$. For each action $i\in[m]$, the state transition $q(\cdot,i)$ forms a cyclic permutation (i.e., a single cycle) over the state space (see the left of Figure 1 for an example). Let $A_{i}$ be the permutation matrix of this cycle, $\bm{b}_{t}\in\mathbb{R}^{n}$ be the one-hot encoding of the state $s_{t}$ at step $t$, $a_{t}\in[m]$ be the action at step $t$, then the updating rule is
$\bm{b}_{t+1}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}A_{a_{t}}\bm{b}_{t}$,
where action $a_{t}$ is assumed to be sampled from a uniform distribution over the action space.

Although this can be viewed as a matrix multiplication task with different choices of $A_{a}$ ($a\in[m]$), it is also
equivalent to an HMM with $nm$ states and $m$ observations (c.f. Proposition A.1). Moreover, the mixing speed of this model is zero because current belief state is influenced by the entire observation history.

#### CyclicHMM-RND : Stochastic Cyclic HMM.

Proposition A.1 indeed presents a robust argument, suggesting that any finite automaton augmented with random transitions has an equivalent HMM representation. This insight prompts us to introduce some level of randomness into the cyclic automaton to generate a stochastic cyclic HMM. However, the randomness must be carefully calibrated; otherwise, it may transform into a fast-mixing model, making it easy for neural networks to fit. For any cyclic permutation induced by an action $i\in[m]$, we simply introduce a small probability $\varepsilon$ for state $s$ to transit to its predecessor when taking action $i$. The transition probability to its successor $q(s,i)$ is $1-\varepsilon$.

#### CyclicHMM-HARD : Cyclic HMM with multiple stages.

The task of next-observation prediction is straightforward for the three structured HMMs introduced earlier, as the next observation always follows a uniform distribution. To investigate the difficulty of next-observation prediction in these structured models, we devise a variant of the CyclicHMM-DET model depicted in Figure 1 (right part).
Consider a CyclicHMM-DET model with state space $\mathcal{S}$, observation space $\mathcal{O}$, transition probability $\mathbb{P}(s^{\prime}\mid s)$, and emission probability $\mathbb{O}(o\mid s)$, we construct the CyclicHMM-HARD model as follows, given a prediction rate $0<\alpha<1$.

The CyclicHMM-HARD model comprises three stages from left to right, with each stage having an independent copy of state space $\mathcal{S}$.
The transition and emission probabilities of states in the first stage are almost identical to the CyclicHMM-DET model, except that each state in the first stage has a small probability $\alpha$ of transitioning to the second stage. The states in the second stage always emit a prediction signal $*$ as the observation and transition to the last stage. The final stage, also called the prediction stage, has states that always emit an observation indicating the state itself and then transition back to the first stage.

Our specific interest lies in the next-observation prediction accuracy of states in the third stage, which is equivalent to predicting the state after a random length of transitions. The formal definition is provided as follows:

- •
The state space consists of pairs $(s,i)$ for any $s\in\mathcal{S}$ and $i\in\{0,1,2\}$, the observation space is defined as the union set $\mathcal{S}\cup\mathcal{O}\cup\{*\}$.
- •
For all states $(s,0)$ in the first stage, it transitions to $(s^{\prime},0)$ with probability $(1-\alpha)\mathbb{P}(s^{\prime}\mid s)$, and transitions to $(s,1)$ with probability $\alpha$. It emits $o\in\mathcal{O}$ with probability $\mathbb{O}(o\mid s)$.
- •
For all states $(s,1)$ in the second stage, it transits to $(s,2)$ with probability 1 and emits $*$ with probability 1.
- •
For all states $(s,2)$ in the final stage (i.e., the prediction stage), it transition to $(s,0)$ with probability 1 and emits $s$ with probability 1.

###### Remark 3.1 (Why is CyclicHMM-HARD model hard?) .

It is hard because it not only has long history dependency to infer the current state at the prediction stage, but contains a large portion of uninformative observations in training. The transformers cannot fit the sequence when these two conditions hold simultaneously. Specifically, the target state after obtaining a sequence of observations will be revealed only when the target state is at the prediction stage. This happens rarely since the probability $\alpha$ from the first stage to the second stage is very small, which leads to highly insufficient hidden information and poses a great challenge for the Transformers.

###### Remark 3.1 (Why is CyclicHMM-HARD model hard?) .

## 4 Experiments

We systematically conducted experiments to assess the learnability of RNNs and Transformers across various sequential models introduced in Section 3. The results consistently highlight the superiority of RNNs over Transformers in terms of both convergence speed and evaluation accuracy across all tasks. Additionally, to delve deeper into the efficiency of Transformers with varying depths, we illustrate an approximate scaling relationship between sequence length and required depth in Figure 3.

The HMM models exhibit distinct patterns in terms of scaling. Fast-mixing models demonstrate compatibility with constant-depth Transformers, indicating ease of learnability of these models. The scaling of structured HMMs for the belief state inference task is constrained to at most $\log T$ for a specific sequence length $T$. The most challenging task lies in predicting the next observation in an HMM with a specific structure, where Transformers of different depths consistently struggle to fit a sequence of constant length.

### 4.1 Experimental Design

#### Training and evaluation data.

For a given HMM, we initiate by generating a random instance $\mathcal{M}$. Subsequently, we roll out $N_{\operatorname{train}}=5\times 10^{6}$ trajectories, each of length $T=120$, forming the training dataset. In a trajectory
$(s_{0},o_{1},s_{1},...,o_{T},s_{T},o_{T+1},s_{T+1})$,
the input sequence is consistently $(o_{1},o_{2},...,o_{T})$. The target sequence is defined as $(\bm{b}_{1},\bm{b}_{2},...,\bm{b}_{T})$ for belief state inference (where belief states are computed using (2.1)), or $(o_{2},o_{3},...,o_{T+1})$ for next-observation prediction. All trajectories are trained in a random order within a single epoch. To ensure fair comparison among different neural network models, we keep the instance $\mathcal{M}$ fixed for a particular HMM. For evaluating trained neural networks, we generate fresh data using $\mathcal{M}$, and the reported evaluation loss is the average loss across $E=256$ trajectories.

#### Model Training.

We employ a standard decoder-only Transformer with learnable positional encoding (Radford et al., ) for both belief state inference and next-observation prediction.
The depth $L$ of the Transformer is varied from 1 to 7. The RNN model is always single-layer and takes the raw sequence as input. Both models are trained by AdamW optimizer (Loshchilov and Hutter, ) with the MSE loss (for MatMul and LDS) or cross entropy loss (for others). The total training epochs for both models are 100. Additional details and hyperparameters can be found in Appendix B.

#### Evaluation metric.

At the end of each epoch, we roll out $E$ fresh trajectories from the instance to evaluate the neural network. Suppose the sequence predicted by neural network is $(\hat{x}_{1},\hat{x}_{2},..,\hat{x}_{T})$, which is the predicted belief state or the predicted next observation distribution. Given the groundtruth sequence $(x_{1},x_{2},..,x_{T})$, the evaluation loss at length $t$ is defined as $\operatorname{el}_{t}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\|\hat{x}
_{t}-x_{t}\|_{p}/(3-p)$, where $p=2$ for MatMul and LDS(^1^11The norm of $\|x_{t}\|$ is increasing in LDS model, so we compute the relative loss to be $\|\hat{x}_{t}-x_{t}\|_{2}/\max(1,\|x_{t}\|_{2})$ in this case.), and $p=1$ for others (because $x_{t}$ and $\hat{x}_{t}$ are distributions so it is essentially the total variation distance).

In practice, Transformers tend to learn more slowly than RNNs and are more sensitive to dataset randomness and optimization. Consequently, Transformers may not successfully fit the sequential model at the full length $T$. We consider Transformers to successfully fit the model at length $t$ with an error rate of
$\epsilon$ if $\operatorname{el}_{t}<\epsilon$ for any $t$ starting from some epoch, where $\epsilon$ is chosen as $0.05$ or $0.1$ in the paper. The maximal length at which Transformers successfully fit at an error rate of $\epsilon$ is also referred to as the $\epsilon$-fit length.

### 4.2 Curriculum Training

Given that fitting long sequences of length
$T$ directly from scratch might pose challenges for Transformers, curriculum learning emerges as a widely adopted strategy to expedite and stabilize training (Spitkovsky et al., ; Wang et al., ; Garg et al., ). Curriculum learning involves dividing the training dataset into different subsets (curriculum stages) based on the measure of difficulty, and regularly switching the training data subset from simple ones to challenging ones.

In HMM models, a natural difficulty measure is the length of the training sequences (Spitkovsky et al., ; Garg et al., ). Following this curriculum design, we regularly increase the training sequence length until it reaches $T$. Motivated by the theoretical insight that an $L$-layer Transformer has a fit length of at least $2^{L}$ for HMMs (cf. Section 5.2), we adopt a doubling curriculum schedule. Commencing from length $2^{L}$, this curriculum schedule doubles the length of the training sequence after a fixed number of epochs. The total number of curriculum stages is set to $8-L$. The 7-layer Transformer is supposed to have only one stage at $T=120$, the 6-layer Transformer has two stages at length 64 and 120, etc.

### 4.3 Experimental Results

#### Comparisons between RNNs and Transformers.

The comparison between RNNs and Transformers involves assessing the convergence rate, evaluation accuracy, and fit length, as depicted in Figure 2. We select four HMMs representing different categories and showcase the evaluation loss at specific sequence lengths for different neural networks during training. Across all four tasks, RNN consistently converges faster than all Transformers. The evaluation accuracy of RNN is consistently superior or as small as that of Transformers at all steps during training. Consequently, the fit length of RNN is at least as long as that of Transformers. We do not plot the evaluation loss at the full length
$T$ because most shallow Transformers struggle to fit length $T$, whereas RNN achieves a
0.05-fit length of $T$ across all tasks.

Figure: Figure 2: The evaluation loss at a specific sequence length of neural networks for 4 HMMs. To illustrate the difference between RNNs and Transformers of different depth, we choose the evaluation sequence length as 10, 30, 30, 120 for 4 tasks from left to right respectively. The evaluation loss of CyclicHMM-HARD model only considers the states at prediction stage since the prediction for other stages is simply a constant. The convergence speed and final accuracy of RNN are at least as good as all Transformers, which are strictly better in many cases.
Refer to caption: extracted/5648862/PAPER/images/RNNvsTF.png

#### Scaling between fit length and depth.

Since shallow Transformers cannot fit all the HMMs at full length $T$, we provide an illustration of the scaling between fit length and depth for different Transformers in Figure 3 (reported as the best value of 4 experiments of different seeds and w./w.o. curriculum training). The left two figures show the fit length of error rate 0.05 and 0.1 for all tasks. The scaling curves reveal that tasks can be roughly categorized into three classes based on Transformer performance. Fast-mixing tasks HMM and LDS can be learned by constant-depth Transformers. The most challenging CyclicHMM-HARD task cannot be fitted by an
$L(\leq 7)$-layer Transformer even at constant length, while other tasks exhibit at least an exponential dependency between fit length and depth. The exponential $2^{L}$ scaling, as evident in the figure, aligns with our theoretical constructions discussed in the next section(^2^22The only exception is the result of 7-layer Transformer on MatMul task. The fit length of this task is still below 26 even if we have tries various tricks (e.g., different curriculum schedule, more training epochs, etc.). We conjecture this is because the training of MatMul task converges slower than others (c.f. Appendix B.4).). It is also observed during training that the Transformers suffer from optimization instability occasionally, which results in several decreasing trends on the curve.

Figure: Figure 3: The left and middle figure: The approximate scaling between fit length of error rate 0.05/0.1 and the depth of the Transformer. “State" denotes a belief state inference task, and “observation" denotes a next-observation prediction task. There are roughly 3 different scaling pattern for the tasks, which is affected by the mixing time and hidden information in training data. The closeness between 0.05-fit length and 0.1-fit length reflects a small possibility of optimization caveats in the curves. The right figure: The evaluation loss at length 60 for 8/12 block CoT training for 3-layer Transformer on CyclicHMM-DET task and 4-layer Transformer on MatMul task. None of them has fit length 60 (dashed curves) without block CoT. The evaluation loss reduces dramatically with 8/12 block CoT, where 8/12 is approximately the half of their 0.05-fit length.
Refer to caption: extracted/5648862/PAPER/images/LvL7.png

#### The benefits of curriculum training.

In practice, we observed that the double schedule curriculum training proves beneficial in terms of training time, convergence speed, and fit length. If the number of curriculum stages is denoted as
$C$, the double schedule effectively reduces the training time by a multiplicative factor proportional to $1/C$. This is because the training time scales quadratically with the sequence length. Additionally, it facilitates faster convergence and/or longer fit length for certain Transformers, as demonstrated in Figure 4 in the Appendix.

### 4.4 Block Chain-of-Thought

For those tasks cannot be fitted by constant-depth Transformers, we investigate the possibility of applying Chain-of-Thought (CoT) (Wei et al., ; Feng et al., ) or scratchpad training (Nye et al., ) to reduce the required depth of the Transformers at a cost of extra training time. Intuitively, it works for the tasks that is accessible to sufficient hidden information, such as the hidden belief states or informative observations (i.e., observations helpful to infer the hidden state). For example, the belief state inference tasks MatMul and CyclicHMM-DET , as they have belief states as labels, are likely to benefit from the CoT training. Unfortunately, the CyclicHMM-HARD model does not have access to belief states nor informative observations for states in the first stage during training (since the observations are uniformly generated for states in the first stage), so it does not enjoy the benefits.

CoT training involves using the output of the Transformer at each step as the input to predict the next token autoregressively. However, this approach can be highly inefficient(^3^33While we could use the hidden belief state in training labels as the autoregressive input to avoid computing the output of the Transformer, this becomes challenging when sufficient hidden information is lacking in reality.). Leveraging the scaling law of fit length for layers, we can feed the output back into the Transformer every
$b$ steps, where $b>1$ is a constant whose value can be guided by the fit length of the Transformer. We refer to this as $b$-block CoT training, which reduces the forward passes to $1/b$ of the original CoT training. $b$-block CoT training significantly reduces the evaluation loss of shallow Transformers at long sequence length, as demonstrated in the right side of Figure 3. In this picture, two Transformers of layer 3 and 4 with
0.1-fit length much smaller than 60 can fit a sequence of length 60 after 8-block CoT training. This showcases the effectiveness of $b$-block CoT training on tasks like MatMul and CyclicHMM-DET .

The training time of $b$-block CoT would be $\sum_{i=1}^{\lfloor T/b\rfloor}(ib)^{2}\sim\Theta(T^{3}/b)$. Choosing $b=T$ reduces to the standard training without block CoT, and choosing $b=1$ is equivalent to vanilla CoT. This relationship can be approximately verified from Table 1.

## 5 The Expressiveness Power of RNN and Transformer

In order to understand the experimental results (e.g., the strong inductive bias of RNN, the logarithmic scaling of the fit length of Transformers, the hardness of CyclicHMM-HARD model, etc.), we ask the question whether there exists an RNN or Transformer that can produce (or express) these sequences (e.g., the belief state or observation distributions) in a theoretical perspective. This question has already been answered in general since it is known the RNN and Transformer can approximate a large number of sequence-to-sequence models (Schäfer and Zimmermann, ; Yun et al., )
given sufficient depth or width. In contrast, our interest lies in the *representation efficiency* of the neural networks to approximate the sequential models. This prompts the question of how large the neural networks should be to effectively approximate them.

### 5.1 RNN

First of all, we show that RNNs can approximate HMMs with determinsitic transition conveniently.

###### Theorem 5.1 .

For a deterministic HMM with state space size $n$ and observation space size $m$, there exists a single layer RNN model with embedding dimension $d=O(nm)$ and ReLU activation approximating the belief state sequence of length $T$ with no error. The $\ell_{\infty}$ norm of the parameters of the RNN model is bounded by $O(\|\bm{b}_{0}\|_{2})$.

The proof can be found in Appendix D.1.

###### Theorem 5.1 .

### 5.2 Transformer

To avoid the unrealistic assumption that the neurons in Transformers have infinite precision (Dehghani et al., ; Pérez et al., ), we require the neurons to be floating-point numbers of finite precision in this paper. All the floating-point number computations will be rounded back (e.g. round-up, round-down, round-to-the-nearest) to a floating-point number as in a classical computer. To be specific, if we restrict the floating-point to have $O(\log T)$ bits, it can represent all real numbers of magnitude $O(\operatorname{poly}(T))$ with a $O(\operatorname{poly}(1/T))$ rounding error. Note that the rounding error of shallow neurons may propagate to the deeper layers
and get magnified along the trajectory. After carefully analyzing the error propagation, we come to the following theorem in terms of the expressiveness of the Transformers for HMMs with deterministic transitions:

###### Theorem 5.2 .

For an HMM model with deterministic transition matrix, state space size $n$, and observation space size $m$, there exists a $\log T$-precision Transformer approximating the belief state sequence of length $T$ with $O(\operatorname{poly}(1/T))$ $\ell_{\infty}$ approximation error. The Transformer has depth $L=\lceil\log_{2}T\rceil$, embedding dimension $2n^{2}+6$, MLP width $4n^{3}+2n^{2}$, and $H=2$ attention heads. The magnitude of the parameters in the Transformer is bounded by $O(\mathrm{poly}(T))$.

###### Proof Sketch..

For an HMM with deterministic transition, the belief state $\bm{b}_{t}$ is always a one-hot vector. Thus, we can reduce the HMM to a MatMul model with state dimension $n$ and observation space size $m$ by setting $A_{o}=\mathbb{P}$ for all $o\in\mathcal{O}$. It suffices to consider how to approximate the MatMul model. Let $A_{i:j}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\prod_{k=i}^{j}A_{o_{k}}$, then the output sequence of the Transformer should be $(A_{1:i}\bm{b}_{0})_{i=1}^{T}$. The intuition to produce such sequence with $L$ layers is the divide-and-conquer approach (Liu et al., ) computing the matrix multiplications

$$ $A_{\max(1,j-2^{l}):j}=A_{\max(j-2^{l},1):\max(j-2^{l-1},0)}\times A_{\max(j-2^ {l-1}+1,1):j}$ (5.1) $$

as the output of layer $l$ at position $j$, where $A_{1:0}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\bm{I}$.
The analysis of the error propagation is somehow more complicated here than other divide-and-conquer construction due to the continuous representation of the state. The full proof can be found in Appendix D.2.
∎

Approximating the stochastic HMMs is more challenging since they cannot be reduced to a MatMul model due to the $\ell_{1}$ normalization step (c.f. Eqn. (2.1)). We show that if the Transformers have $T$-precision (i.e., $O(T)$ bits) and an MLP at the end of the last attention block in place of the linear $\mathrm{DECODER}$ layer, then it is possible for them to approximate stochastic HMMs with constant stochastic transition matrix and emission matrix:

###### Theorem 5.3 .

For an HMM model with state space size $n$ and observation space size $m$ whose entries in transition matrix and emission matrix are uniformly lower bounded by $\sqrt{c_{l}}$, there exists a $T$-precision Transformer approximating the belief state sequence of length $T$ followed by an MLP with $O(\log T)$ layers and $O(n)$ width. The $\ell_{\infty}$ approximation error of the neural network is $O(\exp(-T))$. The Transformer has depth $L=\lceil\log_{2}T\rceil$, embedding dimension $2n^{2}+6$, MLP width $4n^{3}+2n^{2}$, and $H=2$ attention heads.

###### Proof Sketch..

Define $A_{o}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\mathrm{diag}(\mathbb{O}(
o\mid\cdot))\mathbb{P}$ according to the belief state updating rule (2.1), then

$$ $\bm{b}_{t+1}=\frac{A_{o_{t+1}}\bm{b}_{t}}{\|A_{o_{t+1}}\bm{b}_{t}\|_{1}}.$ $$

This is equivalent to computing $\tilde{\bm{b}}_{T}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}A_{1:T}\bm{b
}_{0}$ and normalizing the $\ell_{1}$ norm of $\tilde{\bm{b}}_{T}$ to 1, so we still hope to follow the construction in Theorem 5.2 to accomplish the computation. Unfortunately, the entries in $A_{i:j}$ may get exponentially small (i.e., $O(\exp(i-j))$) according to the definition of $A_{o}$, and we cannot simply round these numbers to 0. Therefore, the Transformers need $O(T)$ bits to store the entries of $A_{i:j}$.

After the computation of $\tilde{\bm{b}}_{T}$, it remains to normalize this vector to ensure its $\ell_{1}$ norm exactly equals 1. We prove that this can be done by a $O(\log T)$ layer MLP with $O(n)$ width. The full proof can be found in Appendix D.3.

∎

###### Remark 5.4 .

Since any automaton can be formulated as an HMM (c.f., Appendix A.2), the hardness results in Liu et al. () also apply to our cases. That means there exists no $\log$-precision Transformers with depth independent of $T$ and width polynomial in $T$ that can approximate any HMMs with $O(1/\mathrm{poly}(T))$ error, unless $\mathrm{TC}^{0}=\mathrm{NC}^{1}$ (^4^44Both are circuit complexity classes. Their relationship is widely conjectured to be $\mathrm{TC}^{0}\subset\mathrm{NC}^{1}$.) (Feng et al., ; Liu et al., ).

###### Theorem 5.2 .

###### Proof Sketch..

###### Theorem 5.3 .

###### Proof Sketch..

###### Remark 5.4 .

## 6 Conclusion and Discussion

We study the effectiveness of Transformers in learning HMM models and its variants from both theoretical and empirical perspective, which is one of the most natural and fundamental sequential models. Apart from random HMM models, we construct structured HMM models with slow mixing speed and long history dependency to assess the accuracy of belief state inference or next-observation prediction by Transformers. The extensive experiments conducted reveal several limitations of Transformers in learning these tasks.

One limitation is the consistent underperformance of Transformers compared with RNN in terms of training speed, evaluation accuracy, and optimization stability. Another limitation is the failure of Transformers to learn challenging HMMs. Intuitively speaking, successful learning requires the HMM model to have fast mixing speed (such as random HMMs) or the training data to carry sufficient information about the hidden belief states (such as belief inference in MatMul and CyclicHMM-DET). In other words, Transformers may fail completely for tasks with slow mixing speed and insufficient hidden information provided during training. This raises concerns for the application of Transformer-based RL in RL environments with slow mixing and rather uninformative observations.

In order to overcome this limitation, we integrated the block CoT tricks in the training phase, which greatly accelerates the procedure of learning HMMs for Transformers. At a cost of paying more training time, it enables shallow Transformers to fit longer sequences.

Finally, we observe different patterns in the scaling between fit length and the depth of the Transformer. For certain HMM models, we demonstrate an approximate logarithmic dependency between depth and fit length in both experiments and theory.

## 7 Acknowledgement

Chi Jin gratefully acknowledges the funding support from Google LLC, Princeton Project X innovation fund, and NSF CAREER IIS2239297.

## Appendix A Additional Background and Discussion

### A.1 The Transformer Architecture

Different from the standard encoder-decoder Transformer architecture introduced by Vaswani et al. (), we employ the decoder-only Transformer in this paper to investigate its learnability of the sequential models. The decoder-only Transformers are largely applied on sequential text generations tasks, especially in large language models such as GPT-2 (Radford et al., ), GPT-4, LaMDA (Thoppilan et al., ), LLaMA (Touvron et al., ), etc. Let $\bm{X}_{\operatorname{input}}\in\mathbb{R}^{T\times m}$ be the input sequence to the Transformer, where $T$ is the sequence length and $m$ is the input token dimension. The first block of the Transformer model is a position-wise linear encoder layer $\operatorname{ENCODER}:\mathbb{R}^{m}\to\mathbb{R}^{d}$ mapping each token in $\bm{X}_{\operatorname{input}}$ from $\mathbb{R}^{m}$ to $\mathbb{R}^{d}$, where $d$ is the embedding dimension of the Transformer. Let $\bm{X}^{(0)}\in\mathbb{R}^{T\times d}$ be the output of the linear encoder layer, it is then forwarded into $L$ attention blocks sequentially.

Each attention block consists of a self-attention layer with $H$ attention head and a two-layer MLP GeLU activated MLP. An implicit requirement for $H$ is that $H$ is a divisor of $d$ (Vaswani et al., ). Let the input of the $l$-th attention block be $\bm{X}^{(l-1)}\in\mathbb{R}^{T\times d}$, it propagates through a self attention layer $\operatorname{Attn}^{(l)}$ at first, where

$$ $\displaystyle\operatorname{Attn}^{(l)}(\bm{X})=\operatorname{Concat}\left( \left\{\operatorname{softmax}\left(\bm{X}\bm{W}_{Q}^{(l,h)}\left(\bm{X}\bm{W}_ {K}^{(l,h)}\right)^{\top}+\bm{M}\right)\bm{X}\bm{W}_{V}^{(l,h)}\bm{W}_{O}^{(l, h)}\right\}_{h=1}^{H}\right).$ (A.1) $$

Here $\bm{M}\in\{0,-\infty\}^{T\times T}$ is the causal mask matrix, which is defined as $\bm{M}_{ij}=-\infty$ iff $i<j$. In other words, the output of the self-attention layer is obtained by concatenating the outputs of all the attention heads, where $\bm{W}_{Q}^{(l,h)},\bm{W}_{K}^{(l,h)},\bm{W}_{V}^{(l,h)}\in\mathbb{R}^{d\times
d}$ and $\bm{W}_{O}^{(l,h)}\in\mathbb{R}^{d\times(d/H)}$ are the query, key, value, and output matrix respectively. The output to the self-attention layer is linked with input $\bm{X}^{(l-1)}$ by a residual connection (He et al., ) $\bm{Y}^{(l-1)}=\bm{X}^{(l-1)}+\operatorname{Attn}^{(l)}(\bm{X}^{(l-1)})$. After the self-attention layer, $\bm{Y}^{(l-1)}$ is then forwarded into a 2-layer feedforward network (MLP) with a residual connection as the output of the attention block:

$$ $\displaystyle\operatorname{FFN}^{(l)}\left(\bm{X}\right)=\sigma\left(\bm{X}\bm {W}_{1}^{(l)}\right)\bm{W}_{2}^{(l)},\bm{X}^{(l)}=\bm{Y}^{(l-1)}+\operatorname {FFN}^{(l)}\left(\bm{Y}^{(l-1)}\right).$ (A.2) $$

The final output sequence of the transformer is obtained by feeding $\bm{X}^{(L)}\in\mathbb{R}^{T\times d}$ into a position-wise linear decoder layer $\operatorname{DECODER}$.

We also add two LayerNorm layer right before the multi-head attention and the MLP, and feed the final output to a LayerNorm layer as suggested by a pre-LN architecture (Baevski and Auli, ; Wang et al., ; Xiong et al., ). The positional encoding is a learnable $d$-dim vector of length $256$.

### A.2 The Equivalence Between Automaton and HMM

For an automaton $q:[n]\times[m]\to[n]$ with cyclic transition for each action (c.f. Figure 1), let $A_{i}$ be the permutation matrix of the cyclic permutation induced by action $i$. Recall that the transition matrix $A_{i}$ of action $i\in[m]$ satisfies $A_{i}(s^{\prime},s)=1$ iff $q(s,i)=s^{\prime}$ for any $s,s^{\prime}\in[n]$. We construct the equivalent HMM model as follows:

- •
The state space consists of all pairs $(s,o)\in[n]\times[m]$, while the observation space is the action space $[m]$ of the automaton.
- •
The transition probability is defined as $\mathbb{P}((s^{\prime},o^{\prime})\mid(s,o))\stackrel{{\scriptstyle\textup{
\tiny def}}}{{=}}A_{o}(s^{\prime},s)/m$.
- •
The emission probability is defined as $\mathbb{O}(o^{\prime}\mid(s,o))\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}
}\bm{1}[o^{\prime}=o]$.

The following proposition shows that each Markov decision process (MDP) with $n$ states and $m$ actions uniform action probability is equivalent to some HMM assuming the action $a_{t}$ is uniformly chosen at random for each step $t$ by the following construction:

- •
The state space consists of all pairs $(s,o)\in[n]\times[m]$, while the observation space is the action space $[m]$ of the MDP.
- •
The transition probability is defined as $\mathbb{P}((s^{\prime},o^{\prime})\mid(s,o))\stackrel{{\scriptstyle\textup{
\tiny def}}}{{=}}P_{o}(s^{\prime},s)/m$, where $P_{o}(s^{\prime},s)$ is the probability of transiting to state $s^{\prime}$ from state $s$ given action $o$.
- •
The emission probability is defined as $\mathbb{O}(o^{\prime}\mid(s,o))\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}
}\bm{1}[o^{\prime}=o]$.

###### Proposition A.1 .

Given a For any $t\geq 0$, the sampling probability of any trajectory $(s_{0},o_{1},s_{1},...,o_{t},s_{t})$ is identical for the constructed HMM and the MDP.

###### Proof.

Given any $(s_{0},o_{1},...,o_{t},s_{t})$, the probability that next observation $o_{t+1}$ equals $o$ in the HMM is

$$ $\sum_{s^{\prime}}\frac{P_{o_{t}}(s^{\prime},s_{t})}{m}=\frac{1}{m}.$ $$

Therefore, the next observation distribution is a uniform distribution as in the automaton. On the other hand, the next state $s_{t+1}$ follows the distribution $P_{o_{t}}(\cdot,s_{t})$ according to the construction. Therefore, these two models are equivalent for any $t$ by induction.
∎

Since a deterministic automaton is definitely an HMM, the equivalence between the HMM and automaton is proved throught Proposition A.1.

###### Proposition A.1 .

###### Proof.

### A.3 Comparisons between this work and Liu et al. ( 2022 )

The key difference is the introduction of uncertainty in the HMMs constructed in this paper. The uncertainty is derived from at least two sources: the first one is the uncertainty of hidden states given an observation sequence (e.g., the HMM , LDS and CyclicHMM-RND model) due to stochastic state transition and observation emission, the second one is the uncertainty of the observations in the training data in next-observation prediction task. As a result, the standard HMM CyclicHMM-HARD is very hard to fit for Transformers, but a standard automaton can be fitted by a shortcut Transformer.

### A.4 Motivations for the Constructed HMMs

We also dicuss our motivation for studying the HMMs and why we construct the 6 HMMs in the main text.

#### Why HMM models?

First, the investigation into the learnability of Transformers on various HMMs holds intrinsic value due to the universality of HMM models. This is pointed out in the introduction as the HMMs serve as useful tools for a wide range of practical problems such as part-of-speech (Kupiec, ) and named-entity recognition (Zhou and Su, ) in NLP, time-series forecasting (Zhang et al., ).

Furthermore, many real-world problems in control systems and reinforcement learning can be abstracted into HMMs as their simplest instances. Understanding the capabilities and limitations of Transformers in learning these models provides crucial insights that extend beyond HMMs themselves. For instance, the partially observable Markov decision process (POMDP) model, which extends HMMs by incorporating actions at each step, is a cornerstone in reinforcement learning. By investigating how Transformers perform on HMMs, we pave the way for understanding their efficacy in tackling more complex problems like POMDPs (since the HMMs are special cases of POMDPs). This is an important problem given the abundance of research efforts aimed at devising efficient reinforcement learning algorithms for learning POMDPs and their applications in various domains (see, e..g, Nguyen et al. () for a survey of methods, and Cassandra () for a survey of applications).

#### Why constructing the 6 HMMs?

The six HMMs can be divided into two types: random instances and structured instances. The HMM and LDS are random instances chosen as they represent a natural starting point for exploring Transformers’ learning capabilities on HMMs. Notably, the successful learning of these random instances by constant-layer Transformers suggests that HMMs lacking specific structures are relatively easy for Transformers to learn. This observation inspired us to design more challenging instances to better understand the limitations and capabilities of Transformers. We provide two motivations for studying the remaining 4 structured HMMs.

For one thing, we found that the hard instances require the Transformers to consider all previous tokens to predict the next token, instead of only checking the latest ones as in the random instances (i.e., the hard instances have long credit assignment length). This motivates us to consider the CyclicHMM model (and its variants) which has a long credit assignment length.

For another, there are specific real problems inspiring us to design these strucutred HMMs. The MatMul model is motivated from the belief state inference task, and the only difference is the absence of a normalization step compared with standard belief state inference. The cyclicHMM model is motivated from a specific semiautomaton called modular addition (Nanda et al., ). Given a sequence of numbers, modular addition task requires the model to add these numbers then module a constant. The structured nature of these HMMs may also coincide with real-world problem instances, thereby facilitating a more comprehensive evaluation of Transformers’ efficacy in handling complex sequential data.

## Appendix B Details of Experiments

#### Training.

The training data consists of $N_{\operatorname{train}}=5\times 10^{6}$ trajectories rolled out from the same random instance for each task. We change $N_{\operatorname{train}}$ to $10^{6}$ for the simplest task HMM , LDS , and the block CoT training to save the computation time. The input data is the observation sequence $(o_{0},...,o_{T})$ of length $T+1$ ($o_{0}$ is a placeholder symbol) concatenated by a 3-dim positional encoding $(\sin(\pi t/4T),\cos(\pi t/4T),1)$ at position $t$. The target data is the belief state of length $T+1$ for belief state filtering tasks or next observation sequence of length $T$ for next-observation prediction tasks. In epoch $l$, the training loss is computed as

$$ $\displaystyle\frac{1}{T_{l}}\cdot\sum_{t=0}^{T_{l}}\mathcal{L}\left(\hat{x}_{t },x_{t}\right),$ (B.1) $$

where $\hat{x}_{t}$ is the output of the neural network given $(o_{0},...,o_{t})$, $x_{t}$ is the training label, $\mathcal{L}$ is the loss function, and $T_{l}\leq T$ is the training sequence length at epoch $l$. $\mathcal{L}$ is chosen as the MSE loss for MatMul and LDS , and chosen as the cross entropy loss for other tasks. The training sequence length $T_{l}$ is $T$ if curriculum training is disabled, and set according to the curriculum stage if it is toggled on.

#### Tasks.

Although the combination of belief state filtering problem and observation prediction problem with each HMM is possible, many of them are trivial. For example, predicting the next observation distribution in MatMul , CyclicHMM-DET , and CyclicHMM-RND is trivial since it follows a uniform distribution. Generally speaking, predicting the belief state is harder than predicting the next observation distribution since the latter is a linear mapping of the former. Importantly, we assume the access to belief states (should be hidden) at each step as training labels in the belief state filtering problem, but the next-observation prediction problem does not have access to the hidden belief states. Therefore, the belief state filtering problem in the paper provide much more hidden information during training than observation prediction. For the CyclicHMM-HARD model, we use CyclicHMM-DET to construct the first stage of CyclicHMM-HARD instead of CyclicHMM-RND to reduce the number of states. The instance used for training and evaluation is randomly generated but keep fixed for all the neural networks. The state dimension (or number of states if it is discrete) and observation dimension (or number of observations if it is discrete) are both 5 for CyclicHMM-DET , MatMul , LDS , HMM model, and constructed accordingly for CyclicHMM-RND and CyclicHMM-HARD model. The initial state is the first state for all tasks. We choose the parameter $\alpha=1/T$ for CyclicHMM-HARD and $\varepsilon=0.01$ for CyclicHMM-RND model.

#### Evaluation.

The evaluation stage is at the end of each epoch. $E=256$ trajectories are rolled out freshly, and the neural networks are fed in the sequences to do the prediction. The evaluation loss is at step $t$ is $\|\hat{x}_{t}-x_{t}\|_{p}/(3-p)$ where $p=2$ for MatMul and LDS , and $p=1$ for others (i.e., total variation distance). The reported evaluation loss is the average over $E$ trajectories.

#### Curriculum Training.

We employ a double schedule for curriculum training for Transformers (no curriculum training for RNNs). For an $l$-layer Transformer, we choose $8-l$ curriculum stages and set the length of each stage to be $\lfloor{100/(8-l)}\rfloor$ epochs. The training sequence length of the first stage is $2^{l}$, and doubled immediately after $\lfloor{100/(8-l)}\rfloor$ epochs.

#### Block Chain-of-Thought.

The $b$ block CoT training feeds the output of the Transformer back into it every $b$ steps. For the belief state filtering tasks, the output is the predicted belief state ate current step. Therefore, the necessary computation depth is reduced from $T$ to $b$ if the prediction is approximately correct. For the observation prediction task, the output is the distribution of the next observation conditioned on current observation sequence $\mathbb{E}[o_{t+1}\mid o_{0},...,o_{t}]$. This conditional distribution may be highly correlated with the hidden belief state $\bm{b}_{t}$ (such as the prediction stage of CyclicHMM-HARD ), or be irrelevant with the hidden belief state (such as the CyclicHMM-RND model). A measurement of such “correlation" is called the observability of the HMM (Golowich et al., ). The block CoT also works for observation prediction task with good observability (i.e., the correlation is strong), since the hidden state can be (approximately) inferred from the observation distribution. Since the observability of the first stage of CyclicHMM-HARD model is very bad, the CyclicHMM-HARD model cannot be resolved by block CoT training.

Theoretically speaking, the value of $b$ can be determined by the fit length of the Transformers, if the error rate is ignored. In reality, the prediction error at early steps will accumulate to later steps and so we have to choose a smaller value than $\epsilon$-fit length if we hope to reduce the evalution loss below $\epsilon$. We choose the half of the $\epsilon$-fit length in our experiments.

The averaged training time of different block sizes on MatMul and CyclicHMM-DET are listed in Table 1. The time cost of $b$-block CoT is approximately $1/b$ of that of vanilla CoT.

**Table 1: Training time (in seconds) per epoch of block CoT for different tasks of length 60 on 4 GPUs. We choose the 3-layer Transformer for both tasks.**
|  | block length 1 | block length 8 | block length 12 | no block CoT |
| --- | --- | --- | --- | --- |
| MatMul | 4838 | 608 | 390 | 94 |
| CyclicHMM-DET | 4828 | 620 | 393 | 94 |

### B.1 Hyperparameters and Packages

The RNN models is employed from pytorch directly with embedding dimension 64, and number of layers 1. The Transformer model has embedding dimension 512, number of heads 8, MLP layer 2 with GeLU activation, and drop out rate 0.1. The optimizer is AdamW (Loshchilov and Hutter, ) with default parameters in pytorch. The initial learning rate for both models are 1e-3, and decays by a factor of $0.5$ every 20 epochs. We adopt the learning rate warmup procedure (Xiong et al., ) to warmup the learning rate from 1e-7 to 1e-3 with a linear increasing for 4000 optimization steps. The batch size is chosen from 256, 512, or 1024 depending on the layers of the Transformers, and 256 for RNN.

### B.2 Benefits of Curriculum Training

Besides saving lost of training time, curriculum training also helps warm-up the model, so as to accelerate the training as well as the final performance. Figure 4 shows the convergence speed and final value of fit length would be better with curriculum training.

Figure: Figure 4: The benefits of curriculum training. Left: The $0.1$-fit length of Transformers with different depth, reported as the best of 2 experiments with different seed. The fit length of curriculum training is comparable with vanilla training in CyclicHMM-DET in general, and better than vanilla training in MatMul. Right: The convergence speed for different Transformers on MatMul model. The convergence of $0.1$-fit length for curriculum training is consistently faster than vanilla training.
Refer to caption: extracted/5648862/PAPER/images/DvN.png

### B.3 The Possibility of Overfitting

In order to verify whether the large Transformers overfit the training data, we listed the training loss at the end of the last epoch of Transformers and RNNs in Table 2 (“w. CT" means with curriculum training). From the table, we know the fitting ability of Transformers on the MatMul , CyclicHMM-DET , and CyclicHMM-RND model is much worse than RNNs due to the sequential nature of HMMs. For the fast-mixing models HMM and LDS , the performance of the RNNs and Transformers are comparable since the predicting these models only require a short memory.

**Table 2: The final training loss of different models on different tasks.**
| Task | Model | Final training loss |
| --- | --- | --- |
| MatMul | RNN | $2.3475\times 10^{-6}$ |
|  | TF ($L=5$) | 0.10927 |
|  | TF ($L=5$), w. CT | 0.09885 |
|  | TF ($L=6$) | 0.11073 |
|  | TF ($L=6$), w. CT | 0.10999 |
| CyclicHMM-DET | RNN | $2.2662\times 10^{-7}$ |
|  | TF ($L=5$) | 0.67059 |
|  | TF ($L=5$), w. CT | 0.76278 |
|  | TF ($L=6$) | 0.68182 |
|  | TF ($L=6$), w. CT | 0.77835 |
| CyclicHMM-RND | RNN | $3.7769\times 10^{-6}$ |
|  | TF ($L=5$) | 1.24707 |
|  | TF ($L=6$) | 1.13770 |
| HMM | RNN | 1.40139 |
|  | TF ($L=2$) | 1.40107 |
| LDS | RNN | 2.58242 |
|  | TF ($L=2$) | 2.61545 |

### B.4 The Failure Case of 7-Layer Transformers

We conjecture the failure of a 7-layer Transformer to fit the MatMul task primarily due to some optimization issues, and it requires a longer training process to tackle the issue. It can be observed from the experiments that the training loss converges much slower for MatMul than other tasks from Table 3. We have tried various tricks such as different curriculum scheduling, smaller training dataset, different warmup epochs, different learning rate, but they all fail to address the issue.

**Table 3: The training loss of 3 tasks of 7-layer Transformers. The total epochs for MatMul is increased to 200. The training for CyclicHMM-DET and CyclicHMM-RND have already converged at the end of epoch 100 (note that the loss for CyclicHMM-RND is larger due to the randomness and we implement an augmented HMM constructed in Appendix A.2). The training for MatMul converges much slower than the other two tasks.**
| Epoch | 60 | 70 | 80 | 90 | 100 | 125 | 150 | 175 | 200 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| CyclicHMM-DET | 0.014 | 0.006 | 0.004 | 0.005 | 0.003 | N/A | N/A | N/A | N/A |
| CyclicHMM-RND | 1.506 | 1.503 | 1.503 | 1.502 | 1.503 | N/A | N/A | N/A | N/A |
| MatMul | 0.1069 | 0.0999 | 0.0969 | 0.0934 | 0.0916 | 0.0894 | 0.0885 | 0.0875 | 0.0870 |

### B.5 Implementations and Resources

The RNN and Transformer are implemented with Pytorch from scratch. Each of the experiments are trained on 4 NVIDIA GeForce RTX 4090 GPUs for 2-20 hours, where a single worker runs on each GPU.

## Appendix C Technical Lemmas

### C.1 Useful Lemmas for MLP

First of all, it is ensured that an MLP with GeLU activation can approximate a scalar product.

###### Lemma C.1 (Lemma C.1 of Feng et al. ( 2023 ) ) .

Let $f:\mathbb{R}^{2}\to\mathbb{R}$ be a two-layer MLP with GeLU activation with 4 hidden neurons at the second layer. For any $\epsilon>0$ and $M>0$, there exist a set parameters of $f$ such that $|f(a,b)-ab|\leq\epsilon$ for all $a,b\in[-M,M]$. The $\ell_{\infty}$ norm of the parameters are bounded by $O(\operatorname{poly}(M,1/\epsilon))$.

It is straightforward to show that a two-layer MLP can simulate a matrix multiplication with Lemma C.1.

###### Lemma C.2 .

Given two matrices $A,B\in\mathbb{R}^{n\times n}$, let the vector $\operatorname{vec}(X)\in\mathbb{R}^{n^{2}}$ be the vectorization of matrix $X$. There exists a two-layer MLP $g:\mathbb{R}^{2n^{2}+1}\to\mathbb{R}^{n^{2}}$ with $4n^{3}$ hidden neurons and GeLU activation such that for any input vector $[\operatorname{vec}(A),\operatorname{vec}(B),1]\in\mathbb{R}^{2n^{2}}$ with $\|A\|_{F}\leq M-n,\|B\|_{F}\leq M$, it holds that $\|g([\operatorname{vec}(A),\operatorname{vec}(B)])-\operatorname{vec}((A-\bm{I
})B)\|_{\infty}\leq\epsilon$. The $\ell_{\infty}$ norm of the parameters are bounded by $O(\operatorname{poly}(M,n,1/\epsilon))$.

###### Proof.

According to the matrix multiplication formula, it suffices to compute all the scalar product $(A-\bm{I})_{ik}B_{kj}$ for $1\leq i,j,k,\leq n$ at the hidden layer, the total number of which is $n^{3}$. The output layer can be used to gather these products to the desired output $\operatorname{vec}((A-\bm{I})B)$. For a positive number $\epsilon^{\prime}>0$, the constructed MLP $f$ in Lemma C.1 is

$$ $\displaystyle f(a,b)=\frac{\sqrt{2\pi}\lambda^{2}}{8}\left(\sigma\left(\frac{a +b}{\lambda}\right)+\sigma\left(\frac{-a-b}{\lambda}\right)-\sigma\left(\frac{ a-b}{\lambda}\right)-\sigma\left(\frac{-a+b}{\lambda}\right)\right),$ (C.1) $$

where $0<\lambda\lesssim M^{3}/\epsilon^{\prime}$, and $\sigma$ is the GeLU activation.

Therefore, we can compute and store

$$ $\displaystyle u_{ijk}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\left( \sigma\left(\frac{(A-\bm{I})_{ik}+B_{kj}}{\lambda^{\prime}}\right),\sigma\left (\frac{-(A-\bm{I})_{ik}-B_{kj}}{\lambda^{\prime}}\right),\sigma\left(\frac{(A- \bm{I})_{ik}-B_{kj}}{\lambda^{\prime}}\right),\sigma\left(\frac{-(A-\bm{I})_{ ik}-B_{kj}}{\lambda^{\prime}}\right)\right)\in\mathbb{R}^{4}$ $$

using the $4n^{3}$ hidden neurons of $g$ for all $i,j,k$.

By choosing an appropriate $\lambda^{\prime}=O(\operatorname{poly}(M,1/\epsilon^{\prime}))$, a single neuron at the output layer of $g$ approximate $\sum_{k=1}^{n}(A-\bm{I})_{ik}B_{kj}$ with $\ell_{\infty}$ error $n\epsilon^{\prime}$ by a linear combination of all entries of $\{u_{ijk}\}_{k=1}^{n}$. It implies $\|g([\operatorname{vec}(A),\operatorname{vec}(B)])-\operatorname{vec}((A-\bm{I
})B)\|_{\infty}\leq n\epsilon^{\prime}$. The theorem is proved by choosing $\epsilon^{\prime}=\epsilon/n$.
∎

The next lemma shows that two-layer MLPs with GeLU activation and ReLU activation are equivalent.

###### Lemma C.3 (Lemma C.2 of Feng et al. ( 2023 ) ) .

Given $\epsilon>0$, for any two-layer MLP $f$ with GeLU activation with parameter scale bounded by $M$, there exists a two-layer MLP $g$ with ReLU activation of the same size such that for any $x$ it holds that $\|f(x)-g(x)\|_{\infty}\leq\epsilon$. The parameters of $g$ is bounded by $O(\mathrm{poly}(M,1/\epsilon))$.

###### Lemma C.1 (Lemma C.1 of Feng et al. ( 2023 ) ) .

###### Lemma C.2 .

###### Proof.

###### Lemma C.3 (Lemma C.2 of Feng et al. ( 2023 ) ) .

### C.2 Softmax to Approximate Hard Maximum

The following lemma quantifies the error of using softmax to approximate hard max in an $n$-dimensional vector.

###### Lemma C.4 (Lemma 4 of Liu et al. ( 2022 ) ) .

Suppose $z\in\mathbb{R}^{n}$, the $\operatorname{softmax}:\mathbb{R}^{n}\to\mathbb{R}^{n}$ function transforms $z$ into

$$ $\displaystyle\operatorname{softmax}(z)_{i}=\frac{e^{z_{i}}}{\sum_{j=1}^{n}e^{z _{j}}}.$ (C.2) $$

Let $t^{*}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\operatorname*{arg\,max}_
{t}z_{t}$, and suppose for any $t\neq t^{*}$ it holds that $z_{t}\leq z_{t^{*}}-\gamma$, then

$$ $\displaystyle\left\|\operatorname{softmax}(z)-e_{t^{*}}\right\|_{1}\leq 2ne^{- \gamma}.$ (C.3) $$

###### Lemma C.4 (Lemma 4 of Liu et al. ( 2022 ) ) .

### C.3 Sinusoidal Positional Encoding

###### Lemma C.5 .

For any $0\leq\alpha<\alpha+\pi/4T\leq\beta<\pi/4$, it holds that

$$ $\displaystyle\cos(\alpha)-\cos(\beta)\geq\frac{\pi^{2}}{32T^{2}}.$ (C.4) $$

###### Proof.

Define $f_{\alpha,\beta}(x)\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\cos(x)-
\cos(x+\beta-\alpha)$ for $0\leq x\leq\pi/4$, then $f_{\alpha,\beta}(0)\geq\pi^{2}/32T^{2}$ given that fact that $\cos x\leq 1-x^{2}/2$.

Since $f^{\prime}_{\alpha,\beta}(x)=\sin(x+\beta-\alpha)-\sin(x)\geq 0$, it is proved that

$$ $\displaystyle f_{\alpha,\beta}(\alpha)=\cos(\alpha)-\cos(\beta)\geq f_{\alpha, \beta}(0)\geq\frac{\pi^{2}}{32T^{2}}.$ (C.5) $$

∎

###### Lemma C.5 .

###### Proof.

### C.4 Robust Matrix Multiplication

###### Lemma C.6 .

Given two matrices $A,B\in\mathbb{R}^{n\times n}$ and their approximation $\widehat{A},\widehat{B}\in\mathbb{R}^{n\times n}$ such that

$$ $\displaystyle\|\operatorname{vec}\left(A-\widehat{A}\right)\|_{\infty}\leq \alpha,\|\operatorname{vec}\left(B-\widehat{B}\right)\|_{\infty}\leq\beta.$ (C.6) $$

Then it holds that

$$ $\displaystyle\|\operatorname{vec}\left(AB-\widehat{A}\widehat{B}\right)\|_{ \infty}\leq\alpha\left\|\widehat{B}\right\|_{1}+\beta\left\|A\right\|_{\infty}.$ (C.7) $$

The proof to this lemma is elementary.

###### Lemma C.6 .

## Appendix D Proof of Main Theoretical Results

### D.1 Proof of Theorem 5.1

For any deterministic HMM $(\mathcal{S},\mathcal{O},\mathbb{P},\mathbb{O},S_{0})$, the belief state $\bm{b}_{t}$ at any step $t\geq 0$ is guaranteed to be a one-hot vector. Therefore, it almost reduces to an MatMul model with $A_{o}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\mathbb{P}$ for all $o\in\mathcal{O}$. The only difference is that $A_{o}$ is now a deterministic transition matrix instead of an orthogonal matrix, which is negligible to the approximation of the MatMul model for both RNNs and Transformers (because $A_{o}$ keeps the $\ell_{2}$ norm of an one-hot vector). The state dimension of this MatMul model is $n$, and the observation space size of it is $m$. Now we show how to approximate the output of an MatMul model.

Recall the updating rule of MatMul model (c.f. Section 3.2):

$$ $\displaystyle s_{t+1}=A_{o_{t+1}}s_{t}.$ (D.1) $$

$s_{0}$ is fixed and $A_{o}A_{o}^{\top}=I$ for any $o\in\mathcal{O}$.

The RNN updating rule is

$$ $\displaystyle h_{t}=\mathrm{ReLU}\left(W_{i}x_{t}+b_{i}+W_{h}h_{t-1}+b_{h} \right).$ (D.2) $$

Define the following sequence $\bar{h}_{t}\in\mathbb{R}^{n}$ such that

$$ $\bar{h}_{t+1}=\sum_{o=1}^{m}\operatorname{ReLU}\left(A_{o}\bar{h}_{t}+\alpha \bm{1}\bm{e}_{o}^{\top}\bm{e}_{o_{t+1}}-\frac{\alpha}{2}\bm{1}\right)-\frac{ \alpha}{2}\bm{1},$ (D.3) $$

where $\bar{h}_{0}=s_{0}$ and $\alpha>2\max_{o\in\mathcal{O},1\leq t\leq T}\|A_{o}\bar{h}_{t}\|_{\infty}$. We will prove that $\bar{h}_{t}=s_{t}$ for all $0\leq t\leq T$.

Leveraging a inductive argument, suppose it is known that $s_{t}=\bar{h}_{t}$. It holds that

$$ $\displaystyle\operatorname{ReLU}\left(A_{o}\bar{h}_{t}+\alpha\bm{1}\bm{e}_{o}^ {\top}\bm{e}_{o_{t+1}}-\frac{\alpha}{2}\bm{1}\right)=\begin{cases}A_{o}\bar{h} _{t}+\alpha\bm{1}/2&\quad\text{if }o=o_{t+1}\\ \bm{0}&\quad\text{otherwise.}\\ \end{cases}$ (D.4) $$

Then $\bar{h}_{t+1}=s_{t+1}$ due to $\bar{h}_{t}=s_{t}$.

Next we construct an RNN that implements (D.3) with $d=nm$. Let $h_{t}\in\mathbb{R}^{d}$ be the hidden state at step $t$, we write $h_{t}$ as

$$ $\displaystyle h_{t}=\left[h_{t,1}^{\top},h_{t,2}^{\top},...,h_{t,m}^{\top} \right]^{\top},$ (D.5) $$

where $h_{t,i}\in\mathbb{R}^{n}$ for any $t,i$. Suppose for step $t\geq 1$ we have

$$ $\displaystyle h_{t,i}=\operatorname{ReLU}\left(A_{i}\bar{h}_{t-1}+\alpha\bm{1} \bm{e}_{i}^{\top}\bm{e}_{o_{t}}-\frac{\alpha}{2}\bm{1}\right)$ (D.6) $$

and
as inductive hypothesis. Since $\bar{h}_{t}=\sum_{o=1}^{m}h_{t,o}-\alpha\bm{1}/2$, then it is straightforward to construct weight matrix $W_{h}\in\mathbb{R}^{d\times d}$ and bias $b_{h}\in\mathbb{R}^{d}$ so that

$$ $\displaystyle W_{h}h_{t}+b_{h}=\left[A_{1}\bar{h}_{t},A_{2}\bar{h}_{t},...,A_{ m}\bar{h}_{t}\right].$ (D.7) $$

Moreover, we choose $W_{i}\in\mathbb{R}^{d\times n}$ and $b_{i}\in\mathbb{R}^{d}$ such that

$$ $\displaystyle W_{i}x_{t+1}+b_{i}=\alpha\left[\bm{1}\bm{e}_{1}^{\top}\bm{e}_{o_ {t+1}},\bm{1}\bm{e}_{2}^{\top}\bm{e}_{o_{t+1}}-\frac{\alpha}{2},...,\bm{1}\bm{ e}_{m}^{\top}\bm{e}_{o_{t+1}}\right]-\frac{\alpha}{2}\bm{1}^{d}$ (D.8) $$

since $x_{t+1}=\bm{e}_{o_{t+1}}$.
Therefore, it holds that

$$ $\displaystyle h_{t+1,i}=\operatorname{ReLU}\left(A_{i}\bar{h}_{t}+\alpha\bm{1} \bm{e}_{i}^{\top}\bm{e}_{o_{t+1}}-\frac{\alpha}{2}\bm{1}\right),$ (D.9) $$

which indicates that (D.6) holds for any $t\geq 1$ as long as it holds for $t=1$.

When $t=1$, we shall construct $h_{0}$ so that (D.6) holds for $t=1$ with the constructed parameters by (D.7) and (D.8), which is true as long as $\bar{h}_{0}=\sum_{o=1}^{m}h_{0,o}-\alpha\bm{1}/2$. Therefore, we can simply choose $h_{0}$ as

$$ $\displaystyle h_{0}=\left[s_{0}-\frac{\alpha}{2}\bm{1}^{n},\bm{0}^{n},...,\bm{ 0}^{n}\right].$ (D.10) $$

The only remaining problem now is to determine the value of $\alpha$. Since $\|A_{o}\bar{h}_{t}\|_{\infty}\leq\|A_{o}\bar{h}_{t}\|_{2}=\|A_{o}s_{t}\|_{2}=
\|s_{t}\|_{2}=\|s_{0}\|_{2}$, it suffices to choose $\alpha=4\|s_{0}\|_{2}$.

### D.2 Proof of Theorem 5.2

It suffices to consider an MatMul model with state dimension $n$ and observation space size $m$ according to the first paragraph of D.1.

Denote the constructed $L$-layer (decoder-only) Transformer as $\mathcal{T}$, which has embedding dim $d=2n^{2}+6$, (2-layer) MLP width $4n^{3}+2n^{2}$, and $H=2$ attention heads. Let us recall the forwarding architecture of $\mathcal{T}$. Given the (one-hot) input sequence $(o_{1},o_{2},...,o_{T})^{\top}\in\mathbb{R}^{T\times m}$, we first transforms it into an augmented input sequence $\bm{X}_{\operatorname{input}}\in\mathbb{R}^{(T+1)\times(m+4)}$ before feeding it into $\mathcal{T}$. This is achieved by adding an extra token to the input from the beginning modifying the input sequence to be $(o_{0},o_{1},...,o_{T})^{\top}\in\mathbb{R}^{(T+1)\times(m+1)}$, where $o_{0}=\bm{e}_{m+1}$ is a specially token marking the beginning of the sequence. Motivated by Liu et al. (), we concatenate a 3-dimensional sinusoidal positional encoding at each position to form the $\bm{X}_{\operatorname{input}}$ as

$$ $\displaystyle\bm{X}_{\operatorname{input}}=\begin{bmatrix}o_{0}^{\top},\sin \left(\frac{\pi\cdot 0}{4T}\right),\cos\left(\frac{\pi\cdot 0}{4T}\right),1\\ \vdots\\ o_{i}^{\top},\sin\left(\frac{\pi i}{4T}\right),\cos\left(\frac{\pi i}{4T} \right),1\\ \vdots\\ o_{T}^{\top},\sin\left(\frac{\pi}{4}\right),\cos\left(\frac{\pi}{4}\right),1 \end{bmatrix}.$ (D.11) $$

In the rest of the proof, we will give a brief summary of construction at first, and leave the technical details as the last part of the proof.

#### Brief construction.

Feeding $\bm{X}_{\operatorname{input}}$ into the $\mathcal{T}$, it will be transformed into an embedding sequence $\bm{X}^{(0)}\in\mathbb{R}^{(T+1)\times d}$ by a linear encoding layer, where $d$ is the embedding dimension of $\mathcal{T}$. Choosing $d=2n^{2}+6$, the encoding layer is constructed so that

$$ $\displaystyle\bm{X}^{(0)}=\begin{bmatrix}\vdots\\ \bm{0}^{n^{2}},0,0,0,\operatorname{vec}\left(\Lambda_{i,0}\right),\sin\left( \frac{\pi i}{4T}\right),\cos\left(\frac{\pi i}{4T}\right),1\\ \vdots\\ \end{bmatrix},$ (D.12) $$

where $\Lambda_{i,0}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}A_{o_{i}}$ for $0\leq i\leq T$ and $A_{o_{0}}=\bm{I}_{n}$. Assume all the operations have no approximation error, we show that the output of the $l$-th ($l\geq 1$) attention block of $\mathcal{T}$ is

$$ $\displaystyle\bm{X}^{(l)}=\begin{bmatrix}\vdots\\ \bm{0}^{n^{2}},0,0,0,\operatorname{vec}\left(\Lambda_{i,l}\right),\sin\left( \frac{\pi i}{4T}\right),\cos\left(\frac{\pi i}{4T}\right),1\\ \vdots\\ \end{bmatrix},$ (D.13) $$

where $\Lambda_{i,l}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}A_{\max(i-2^{l}+1
,0):i}$ for $l\geq 0$ and $\Lambda_{i,l}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\bm{I}$ for $l<0$. Recall that $A_{i:j}=\prod_{k=i}^{j}A_{o_{k}}$.

Suppose this is true for $\bm{X}^{(l-1)}$, we now prove this induction for layer $l$ assuming no approximation error. Recall the $l$-th self-attention layer processes as

$$ $\displaystyle\operatorname{Attn}^{(l)}(\bm{X}^{(l-1)})=\operatorname{Concat} \left(\left\{\operatorname{softmax}\left(\bm{X}^{(l-1)}\bm{W}_{Q}^{(l,h)}\left (\bm{X}^{(l-1)}\bm{W}_{K}^{(l,h)}\right)^{\top}+\bm{M}\right)\bm{X}^{(l-1)}\bm {W}_{V}^{(l,h)}\bm{W}_{O}^{(l,h)}\right\}_{h=1}^{H}\right),$ (D.14) $$

where $\bm{W}_{Q}^{(l,h)},\bm{W}_{K}^{(l,h)},\bm{W}_{V}^{(l,h)}\bm{W}_{O}^{(l,h)}$ are query, key, value, output matrices of the $h$-th head.

For the first attention head $h=1$, we construct matrix $\bm{W}_{Q}^{(l,1)}$ so that

$$ $\displaystyle\bm{X}^{(l-1)}\bm{W}_{Q}^{(l,1)}=\gamma\cdot\begin{bmatrix}\vdots \\ \sin\left(\frac{\pi(i-2^{l-1})}{4T}\right),\cos\left(\frac{\pi(i-2^{l-1})}{4T} \right)\\ \vdots\\ \end{bmatrix}\in\mathbb{R}^{(T+1)\times 2}.$ (D.15) $$

The $\bm{W}_{K}^{(l,1)}$ matrix is constructed to form

$$ $\displaystyle\bm{X}^{(l-1)}\bm{W}_{K}^{(l,1)}=\gamma\cdot\begin{bmatrix}\vdots \\ \sin\left(\frac{\pi i}{4T}\right),\cos\left(\frac{\pi i}{4T}\right)\\ \vdots\\ \end{bmatrix}\in\mathbb{R}^{(T+1)\times 2}.$ (D.16) $$

In this way, we can choose an appropriate value of $\gamma$ to ensure the attention mask matrix of the first attention head is approximately

$$ $\displaystyle\operatorname{softmax}\left(\bm{X}^{(l-1)}\bm{W}_{Q}^{(l,1)}\left (\bm{X}^{(l-1)}\bm{W}_{K}^{(l,1)}\right)^{\top}+\bm{M}\right)=\begin{bmatrix} \vdots\\ \lambda_{i,l}^{\top}\\ \vdots\\ \end{bmatrix}\in\mathbb{R}^{(T+1)\times(T+1)},$ (D.17) $$

where $\lambda_{i,l}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\bm{e}_{\max(i-2^
{l-1},0)}\in\mathbb{R}^{(T+1)}$.
The value of $\gamma$ is chosen as

$$ $\displaystyle\gamma=\frac{4\sqrt{2}T\log(2T/\eta)}{\pi},\text{ where }\eta= \frac{1}{(8n)^{L+1}\cdot T}$ (D.18) $$

As a result, the output of the first attention head $\bm{H}^{(l,1)}\in\mathbb{R}^{(T+1)\times(d/2)}$ will be approximately

$$ $\displaystyle\bm{H}^{(l,1)}=\begin{bmatrix}\vdots\\ \operatorname{vec}\left(\Lambda_{\max(i-2^{l-1},0),l-1}\right),0,0,0\\ \vdots\\ \end{bmatrix}$ (D.19) $$

by constructing appropriate value and output matrices.

For the second head $h=2$, we simply produce a all-zero matrix $\bm{H}^{(l,2)}=\bm{0}^{(T+1)\times(d/2)}$. The final output of the attention layer $\bm{Y}^{(l-1)}\in\mathbb{R}^{(T+1)\times d}$ is produced by concatenating the output of two attention heads plus a residual connection:

$$ $\displaystyle\bm{Y}^{(l-1)}$ $\displaystyle=\bm{X}^{(l-1)}+\left[\bm{H}^{(l,1)},\bm{H}^{(l,2)}\right]$ (D.20) $\displaystyle=\begin{bmatrix}\vdots\\ \operatorname{vec}\left(\Lambda_{\max(i-2^{l-1},0),l-1}\right),0,0,0, \operatorname{vec}\left(\Lambda_{i,l-1}\right),\sin\left(\frac{\pi i}{4T} \right),\cos\left(\frac{\pi i}{4T}\right),1\\ \vdots\\ \end{bmatrix}.$ (D.21) $$

The construction of the 2-layer MLP at the end of the $l$-th attention block will be divided into two parts. First of all, we use $4n^{3}$ hidden neurons to compute $(\Lambda_{\max(i-2^{l-1},0),l-1}-\bm{I}_{n})\Lambda_{i,l-1}=\Lambda_{i,l}-
\Lambda_{i,l-1}$ according to Lemma C.2. Then a simple 2-layer ReLU network with $2n^{2}$ hidden neurons can flip the sign of the first $n^{2}$ entries of the input $\bm{Y}^{(l-1)}$, which we can use a GeLU network with the same size to simulate according to Lemma C.3. The output of the MLP is

$$ $\displaystyle\operatorname{FFN}^{(l)}(\bm{Y}^{(l-1)})=\begin{bmatrix}\vdots\\ -\operatorname{vec}\left(\Lambda_{\max(i-2^{l-1},0),l-1}\right),0,0,0, \operatorname{vec}\left(\Lambda_{i,l}-\Lambda_{i,l-1}\right),0,0,0\\ \vdots\\ \end{bmatrix}\in\mathbb{R}^{(T+1)\times d}.$ (D.22) $$

Finally, the output of the $l$-th attention block is

$$ $\displaystyle\bm{Y}^{(l-1)}+\operatorname{FFN}^{(l)}(\bm{Y}^{(l-1)})=\begin{ bmatrix}\vdots\\ \bm{0}^{n^{2}},0,0,0,\operatorname{vec}\left(\Lambda_{i,l}\right),\sin\left( \frac{\pi i}{4T}\right),\cos\left(\frac{\pi i}{4T}\right),1\\ \vdots\\ \end{bmatrix}=\bm{X}^{(l)},$ (D.23) $$

which proves the induction of (D.13).

Without approximation error, the output of the last attention block $\bm{X}^{(L)}$ is

$$ $\displaystyle\bm{X}^{(L)}=\begin{bmatrix}\vdots\\ \bm{0}^{n^{2}},0,0,0,\operatorname{vec}\left(\Lambda_{i,L}\right),\sin\left( \frac{\pi i}{4T}\right),\cos\left(\frac{\pi i}{4T}\right),1\\ \vdots\\ \end{bmatrix},$ (D.24) $$

where $\Lambda_{i,L}=A_{0:i}$ since $L=\lceil{\log_{2}T}\rceil$. A final linear decoder layer transformers $\bm{X}^{(L)}$ to the desired output sequence

$$ $\displaystyle\left(\bm{b}_{1},\bm{b}_{1},...,\bm{b}_{T}\right)=\left(A_{0:1} \bm{b}_{0},A_{0:2}\bm{b}_{0},...,A_{0:T}\bm{b}_{0}\right).$ (D.25) $$

#### The self-attention layer.

We still assume no approximation error in the sequel. According to the expression of $\bm{X}^{(l-1)}\in\mathbb{R}^{(T+1)\times d}$ in (D.13), the query matrix $\bm{W}_{Q}^{(l,1)}\in\mathbb{R}^{d\times 2}$ is constructed as

$$ $\displaystyle\bm{W}_{Q}^{(l,1)}=\gamma\cdot\begin{bmatrix}0&0\\ \vdots&\vdots\\ \cos\left(\frac{\pi 2^{l-1}}{4T}\right)&\sin\left(\frac{\pi 2^{l-1}}{4T}\right )\\ -\sin\left(\frac{\pi 2^{l-1}}{4T}\right)&\cos\left(\frac{\pi 2^{l-1}}{4T} \right)\\ 0&0\\ \end{bmatrix}$ (D.26) $$

according to the sine/cosine difference formula. The construction of $\bm{W}_{K}^{(l,1)}$ is straightforward.

As a result, the attention mask matrix is

$$ $\displaystyle\bm{M}^{(l)}_{ij}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}} \left[\bm{X}^{(l-1)}\bm{W}_{Q}^{(l,1)}\left(\bm{X}^{(l-1)}\bm{W}_{K}^{(l,h)} \right)^{\top}\right]_{ij}=\gamma^{2}\cos\left(\frac{\pi(j-i+2^{l-1})}{4T}\right)$ (D.27) $$

for $j\leq i$. The entry for $j>i$ is obviously $-\infty$ since $\bm{M}$ is the causal mask. The $i$-th row of this matrix is

$$ $\displaystyle\gamma^{2}\left[\cos\left(\frac{\pi(-i+2^{l-1})}{4T}\right),\cos \left(\frac{\pi(1-i+2^{l-1})}{4T}\right),...,\cos\left(\frac{\pi 2^{l-1}}{4T} \right),-\infty,...\right].$ (D.28) $$

Since $0\leq i,2^{l-1}\leq T$, the maximum value is take at position $i-2^{l-1}$ if $i-2^{l-1}\geq 0$, and position 0 otherwise. Choosing

$$ $\displaystyle\gamma=\frac{4\sqrt{2}T\log(2T/\eta)}{\pi},$ (D.29) $$

the softmax of this row would be $\lambda_{i,l}=\bm{e}_{\max(i-2^{l-1},0)}$ with $\ell_{1}$ error $\eta$ according to Lemma C.5 and Lemma C.4.

Finally, it suffices to use matrix $\bm{W}_{V}^{(l,1)}=\bm{I}$ and $\bm{W}_{O}^{(l,1)}\in\mathbb{R}^{d\times(d/2)}$ by

$$ $\displaystyle\bm{X}^{(l-1)}\bm{W}_{V}^{(l,1)}\bm{W}_{Q}^{(l,1)}=\begin{bmatrix }\vdots\\ \operatorname{vec}\left(\Lambda_{i,l-1}\right),0,0,0\\ \vdots\\ \end{bmatrix}$ (D.30) $$

to produce the output $\bm{H}^{(l,1)}$ of the first attention head.

#### The approximation error.

The approximation error of $\mathcal{T}$ needs to be bounded carefully in order to prove the $O(\mathrm{poly}(1/T))$ total $\ell_{\infty}$ error due to the exponential propagation over layers. We assume the number of states $n$ is a constant in the proof.

There are three places in the construction introducing approximation error:

- •
The softmax operation to the attention mask matrix (D.28). Let
$\displaystyle\operatorname{softmax}\left(\widehat{\bm{M}}^{(l)}\right)
\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\begin{bmatrix}\vdots\\
\widehat{\lambda}_{i,l}^{\top}\\
\vdots\\
\end{bmatrix}\in\mathbb{R}^{(T+1)\times(T+1)}$
(D.31)
be the exact output of the softmax attention mask matrix in $\mathcal{T}$, then $\|\widehat{\lambda}_{i,l}-\lambda_{i,l}\|_{1}\leq\eta$ for any $i,l$
according to Lemma C.5, C.4 and the choice of $\gamma$ (c.f. (D.18)).
- •
The matrix multiplication operation performed by the MLP, which is the place error may propagate over layers. Let $\widehat{\bm{X}}^{(l)}$ be the exact output of $\mathcal{T}$ after $l$-th attention block, then
$\displaystyle\widehat{\bm{X}}^{(l)}=\begin{bmatrix}\vdots\\
\hat{\bm{\varepsilon}}_{i,l},0,0,0,\operatorname{vec}\left(\widehat{\Lambda}_{
i,l}\right),\sin\left(\frac{\pi i}{4T}\right),\cos\left(\frac{\pi i}{4T}\right
),1\\
\vdots\\
\end{bmatrix}.$
(D.32)
Here the matrix $\widehat{\Lambda}_{i,l}$ may not equal to $\Lambda_{i,l}$ due to the approximation error of the MLP.
- •
The last occurrence of the approximation error is $\hat{\bm{\varepsilon}}_{i,l}\in\mathbb{R}^{n^{2}}$. This term is supposed to be $\bm{0}$ in our construction, which would be the case if our MLP uses ReLU as activation. According to Lemma C.3, it holds that $\|\hat{\bm{\varepsilon}}_{i,l}\|_{\infty}\leq\eta$ for any $i,l$ as long as we use our GeLU MLP to simulate the ReLU MLP with parameters bounded by $O(\mathrm{poly}(1/\eta))=O(\mathrm{poly}(T))$ according to (D.18).

Now we analyze the error propagation in a single attention block. Suppose at the beginning of the $l$-th attention block we have $\|\operatorname{vec}(\Lambda_{i,l-1}-\widehat{\Lambda}_{i,l-1})\|_{\infty}\leq
\epsilon_{l-1}$ for all $0\leq i\leq T$, so $\epsilon_{0}=0$.

The first place introducing the error is the output of the first attention head $\bm{H}^{(l,1)}$ in (D.19). The exact output $\widehat{\bm{H}}^{(l,1)}$ of the Transformer $\mathcal{T}$ is

$$ $\displaystyle\widehat{\bm{H}}^{(l,1)}=\operatorname{softmax}\left(\widehat{\bm {M}}^{(l)}\right)\widehat{\bm{X}}^{(l-1)}\bm{W}_{V}^{(l,1)}=\begin{bmatrix} \vdots\\ \widehat{\lambda}_{i,l}^{\top}\\ \vdots\\ \end{bmatrix}\cdot\begin{bmatrix}\vdots\\ \operatorname{vec}\left(\widehat{\Lambda}_{i,l-1}\right),0,0,0\\ \vdots\\ \end{bmatrix}.$ (D.33) $$

The approximation can then be decomposed as

$$ $\displaystyle\widehat{\bm{H}}^{(l,1)}-\bm{H}^{(l,1)}$ $\displaystyle=\operatorname{softmax}\left(\widehat{\bm{M}}^{(l)}\right)\left( \widehat{\bm{X}}^{(l-1)}\bm{W}_{V}^{(l,1)}-\bm{X}^{(l-1)}\bm{W}_{V}^{(l,1)}\right)$ (D.34) $\displaystyle\quad+\left(\operatorname{softmax}\left(\widehat{\bm{M}}^{(l)} \right)-\operatorname{softmax}\left(\bm{M}^{(l)}\right)\right)\bm{X}^{(l-1)} \bm{W}_{V}^{(l,1)}.$ (D.35) $$

Elementary inequalities show that

$$ $\displaystyle\left\|\operatorname{vec}\left(\widehat{\bm{H}}^{(l,1)}-\bm{H}^{( l,1)}\right)\right\|_{\infty}$ $\displaystyle\leq\max_{0\leq i\leq T}\left(\left\|\widehat{\lambda}_{i,l} \right\|_{1}\cdot\max_{0\leq j\leq T}\left\|\operatorname{vec}\left(\widehat{ \Lambda}_{j,l-1}-\Lambda_{j,l-1}\right)\right\|_{\infty}\right)$ (D.36) $\displaystyle\quad+\max_{0\leq i\leq T}\left(\left\|\widehat{\lambda}_{i,l}- \lambda_{i,l}\right\|_{1}\cdot\max_{0\leq j\leq T}\left\|\operatorname{vec} \left(\Lambda_{j,l-1}\right)\right\|_{\infty}\right)$ (D.37) $\displaystyle\leq(1+\eta)\epsilon_{l-1}+\eta.$ (D.38) $$

The second inequality follows from the definition of $\epsilon_{l-1}$, $\|\widehat{\lambda}_{i,l}-\lambda_{i,l}\|_{1}\leq\eta$, and the fact that $\Lambda_{j,l-1}$ is an orthogonal matrix.

Write $\widehat{\bm{H}}^{(l,1)}$ as

$$ $\displaystyle\widehat{\bm{H}}^{(l,1)}=\begin{bmatrix}\vdots\\ \widehat{\bm{h}}_{i,l}\in\mathbb{R}^{n^{2}},0,0,0\\ \vdots\\ \end{bmatrix}.$ (D.39) $$

It is shown by (D.38) that $\|\operatorname{vec}(\Lambda_{\max(i-2^{l-1},0),l-1})-\hat{\bm{h}}_{i,l}\|_{
\infty}\leq(1+\eta)\epsilon_{l-1}+\eta$.

The input to the MLP in $\mathcal{T}$ is

$$ $\displaystyle\widehat{\bm{Y}}^{(l-1)}=\widehat{\bm{X}}^{(l-1)}+\left[\widehat{ \bm{H}}^{(l,1)},\bm{H}^{(l,2)}\right]=\begin{bmatrix}\vdots\\ \widehat{\bm{\varepsilon}}_{i,l-1}+\widehat{\bm{h}}_{i,l},0,0,0,\operatorname{ vec}\left(\widehat{\Lambda}_{i,l-1}\right),\sin\left(\frac{\pi i}{4T}\right), \cos\left(\frac{\pi i}{4T}\right),1\\ \vdots\\ \end{bmatrix}.$ (D.40) $$

The MLP at layer $l$ implements an approximate matrix multiplication on the matrix reshaped by $\widehat{\bm{\varepsilon}}_{i,l-1}+\widehat{\bm{h}}_{i,l}-\bm{I}_{n}$ and $\widehat{\Lambda}_{i,l-1}$. Now that

$$ $\displaystyle\left\|\operatorname{vec}\left(\Lambda_{\max(i-2^{l-1},0),l-1} \right)-\hat{\bm{h}}_{i,l}-\widehat{\bm{\varepsilon}}_{i,l-1}\right\|_{\infty} \leq(1+\eta)\epsilon_{l-1}+2\eta,\left\|\operatorname{vec}\left(\Lambda_{i,l-1 }-\widehat{\Lambda}_{i,l-1}\right)\right\|_{\infty}\leq\epsilon_{l-1}$ (D.41) $$

we have

$$ $\displaystyle\left\|\operatorname{vec}\left(\Lambda_{i,l}-\Lambda_{i,l-1} \right)-\operatorname{vec}\left(\hat{\Lambda}_{i,l}-\hat{\Lambda}_{i,l-1} \right)\right\|_{\infty}$ $\displaystyle\leq\left((1+\eta)\epsilon_{l-1}+2\eta\right)\left(n\epsilon_{l-1 }+\sqrt{n}\right)+\sqrt{n}\epsilon_{l-1}$ (D.42) $\displaystyle\leq(1+\eta)n\epsilon_{l-1}^{2}+\left((1+\eta)\sqrt{n}+2\eta n+ \sqrt{n}\right)\epsilon_{l-1}+2\eta\sqrt{n},$ (D.43) $$

which implies

$$ $\displaystyle\left\|\operatorname{vec}\left(\Lambda_{i,l}-\hat{\Lambda}_{i,l} \right)\right\|_{\infty}\leq(1+\eta)n\epsilon_{l-1}^{2}+\left((1+\eta)\sqrt{n} +2\eta n+\sqrt{n}+1\right)\epsilon_{l-1}+2\eta\sqrt{n}.$ (D.44) $$

Define $\epsilon_{l}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}\max_{i}\|
\operatorname{vec}(\Lambda_{i,l}-\hat{\Lambda}_{i,l})\|_{\infty}$, then the sequence $\epsilon_{l}$ satisfies

$$ $\displaystyle\epsilon_{l}\leq(1+\eta)n\epsilon_{l-1}^{2}+\left((1+\eta)\sqrt{n }+2\eta n+\sqrt{n}+1\right)\epsilon_{l-1}+2\eta\sqrt{n}.$ (D.45) $$

Thanks to the construction of $\eta$ in (D.18), we prove by induction that $\epsilon_{l}\leq(8n)^{l-L}\cdot T^{-1}$, which is obvious when $l=0$. Suppose this is true for $l-1$, then

$$ $\displaystyle\epsilon_{l}$ $\displaystyle\leq(1+\eta)n\epsilon_{l-1}^{2}+\left((1+\eta)\sqrt{n}+2\eta n+ \sqrt{n}+1\right)\epsilon_{l-1}+2\eta\sqrt{n}$ (D.46) $\displaystyle\leq(1+\eta)n\epsilon_{l-1}+\left((1+\eta)\sqrt{n}+2\eta n+\sqrt{ n}+1\right)\epsilon_{l-1}+2\eta\sqrt{n}$ $\displaystyle(\text{from }\epsilon_{l-1}<1)$ (D.47) $\displaystyle\leq 4n(1+\eta)\epsilon_{l-1}+2\eta n$ $\displaystyle(\text{from }n\geq 1)$ (D.48) $\displaystyle\leq 6n\epsilon_{l-1}+2\eta n$ (D.49) $\displaystyle\leq\frac{1}{(8n)^{L-l}\cdot T}\left(\frac{3}{4}+2\eta nT\cdot(8n )^{L-l}\right)$ $\displaystyle(\text{from the induction hypothesis})$ (D.50) $\displaystyle\leq\frac{1}{(8n)^{L-l}\cdot T}\left(\frac{3}{4}+\frac{1}{4}\right)$ $\displaystyle(\text{from the definition of }\eta)$ (D.51) $\displaystyle\leq\frac{1}{(8n)^{L-l}\cdot T}.$ (D.52) $$

This inductive argument shows that $\epsilon_{L}=1/T=O(\mathrm{poly}(1/T))$. Moreover, the parameters of $\mathcal{T}$ are all bounded by $O(\mathrm{poly}(T,n))$ from the choice of $\eta$ and $\gamma$.

### D.3 Proof of Theorem 5.3

The Transformers constructed here is slightly different from the ones constructions in Theorem 5.2 in that we choose a different $\eta$ (recall that the Transformers now has $T$-precision):

$$ $\eta=\frac{1}{(8n)^{L+1}\cdot\exp(4T)}.$ $$

Recall that $\tilde{\bm{b}}_{t}=A_{1:t}\bm{b}_{0}$, then from the same analysis as (D.46) to (D.52) we know that the output of the last attention block can be regrouped to vectors $\hat{\bm{b}}_{t}$ such that $\|\hat{\bm{b}}_{t}-\tilde{\bm{b}}_{t}\|_{\infty}=O(\exp(-4T))$. It then remains to normalize the vector $\hat{\bm{b}}_{t}$ to have 1 $\ell_{1}$ norm.

Next we consider how to normalize the vector $\hat{\bm{b}}_{t}$ by a $O(\log T)$-layer MLP with width $O(n)$. The MLP is divided into two parts to achieve the following goals:

- 1.
Find a multiple $c_{0}$ such that $1/2\leq\|c_{0}\hat{\bm{b}}_{t}\|_{1}\leq 1$;
- 2.
Divide the vector $c_{0}\hat{\bm{b}}_{t}$ by its $\ell_{1}$ norm.

#### Finding the multiple c 0 subscript 𝑐 0 c_{0} italic_c start_POSTSUBSCRIPT 0 end_POSTSUBSCRIPT .

Let $C_{l}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}1/c_{l}>1$. On the $n$-dimensional input $\hat{\bm{b}}_{t}$, we calculate $\hat{\bm{b}}_{t,0}=C_{l}^{T}\hat{\bm{b}}_{t},v_{0}\stackrel{{\scriptstyle
\textup{\tiny def}}}{{=}}\|\hat{\bm{b}}_{t,0}\|_{1}$ using the first two layers. It holds that $1-O(\exp(-3T))\leq v_{0}\leq C_{l}^{T}+O(\exp(-3T))$ since $\|\hat{\bm{b}}_{t}-\tilde{\bm{b}}_{t}\|_{\infty}=O(\exp(-4T))$ and $c_{l}^{T}\leq\|\tilde{\bm{b}}_{t}\|_{1}\leq 1$. We use

For the next $4k+1$-st to $4k+4$-th layers ($k=0,1,...,\lceil\log_{2}T\rceil$), we process the vector $\hat{\bm{b}}_{t,k}$ as follows:

- •
Use layer $4k+1$ and $4k+2$ to compute $p(v_{k}-C_{l}^{\lfloor T/2^{k+1}\rfloor})$ where
$p(x)=\mathrm{ReLU}\left(1-\mathrm{ReLU}(-x)\right)=\begin{cases}1&x\geq 1\\
x&0\leq x<1\\
0&0<x\end{cases}$
(D.53)
.
- •
Use layer $4k+3$ and $4k+4$ to approximate
$\displaystyle v_{k+1}$
$\displaystyle\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}p\left(v_{k}-C_{l
}^{\lfloor T/2^{k+1}\rfloor}\right)c_{l}^{\lfloor T/2^{k+1}\rfloor}v_{k}+\left
(1-p(v_{k}-C_{l}^{\lfloor T/2^{k+1}\rfloor})\right)v_{k}$
(D.54)
$\displaystyle\hat{\bm{b}}_{t,k+1}$
$\displaystyle\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}p\left(v_{k}-C_{l
}^{\lfloor T/2^{k+1}\rfloor}\right)c_{l}^{\lfloor T/2^{k+1}\rfloor}\hat{\bm{b}
}_{t,k}+\left(1-p(v_{k}-C_{l}^{\lfloor T/2^{k+1}\rfloor})\right)\hat{\bm{b}}_{
t,k}$
(D.55)
by Lemma C.2 to perform the multiplication, so that $v_{k+1}=\|\hat{\bm{b}}_{t,k+1}\|_{1}$. We choose the parameters of these two layers to guarantee that the approximation error is $O(\exp(-3T))$.
Let the output of layer $4k+4$ for $v_{k}$ be $\hat{v}_{k}$.

Now we prove by induction that $1/2\leq v_{k}\leq C_{l}^{\lfloor T/2^{k}\rfloor}+1$ for all $k$, where the case for $k=0$ is trivial. If $C_{l}^{\lfloor T/2^{k}\rfloor}+2\geq v_{k}\geq C_{l}^{\lfloor T/2^{k+1}\rfloor
}+1$, then $1\leq v_{k+1}=v_{k}c_{l}^{\lfloor T/2^{k+1}\rfloor}\leq C_{l}^{\lfloor T/2^{k+
1}\rfloor}+1$. The case for $v_{k}\leq C_{l}^{\lfloor T/2^{k+1}\rfloor}$ is similar.

If $C_{l}^{\lfloor T/2^{k+1}\rfloor}<v_{k}<C_{l}^{\lfloor T/2^{k+1}\rfloor}+1$, then we can rewrite $v_{k+1}$ using the difference $p_{k}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}p(v_{k}-C_{l}^{\lfloor T/
2^{k+1}\rfloor})=v_{k}-C_{l}^{\lfloor T/2^{k+1}\rfloor}$:

$$ $\displaystyle v_{k+1}=(1-p_{k})C_{l}^{\lfloor T/2^{k+1}\rfloor}+p_{k}^{2}c_{l} ^{\lfloor T/2^{k+1}\rfloor}+p_{k}(2-p_{k}),0<p_{k}<1.$ (D.56) $$

It is nor hard to show that it still holds that $1/2\leq v_{k+1}\leq C_{l}^{\lfloor T/2^{k+1}\rfloor}+1$.

Next we analyze the approximation error of multiplication. For $k=0$ it holds that $|\hat{v}_{k}-v_{k}|=0$. Note that

$$ $\hat{v}_{k+1}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}p(\hat{v}_{k}-C_{ l}^{\lfloor T/2^{k+1}\rfloor})c_{l}^{\lfloor T/2^{k+1}\rfloor}\hat{v}_{k}+(1-p (\hat{v}_{k}-C_{l}^{\lfloor T/2^{k+1}\rfloor}))\hat{v}_{k}.$ $$

Since the function $p$ is 1-Lipschitz and $v_{k}=O(\exp(T/2^{k}))$, it holds that $|\hat{v}_{k+1}-v_{k+1}|\leq O(\exp(T/2^{k}))|\hat{v}_{k}-v_{k}|+O(\exp(-3T))$. The $\ell_{\infty}$ approximation error of $\hat{\bm{b}}_{t,k}$ is the same as that of $v_{k}$.

Let $\bar{\bm{b}}_{t}$ be the output of the $4\lceil\log_{2}T\rceil+4$ layer, then it holds that $\|\bar{\bm{b}}_{t}/\|\bar{\bm{b}}_{t}\|_{1}-\hat{\bm{b}}_{t}/\|\hat{\bm{b}}_{t
}\|_{1}\|_{\infty}\leq O(\exp(-2T))$ and $1/4\leq\|\bar{\bm{b}}_{t}\|_{1}<3/2$.

#### Normalizing the vector 𝒃 ¯ t subscript ¯ 𝒃 𝑡 \bar{\bm{b}}_{t} over¯ start_ARG bold_italic_b end_ARG start_POSTSUBSCRIPT italic_t end_POSTSUBSCRIPT .

The output $\bar{\bm{b}}_{t}$ of the first part of the MLP is then fed into the second part of the MLP. Denote $0\leq c_{1}\stackrel{{\scriptstyle\textup{\tiny def}}}{{=}}1-2\|\bar{\bm{b}}_{
t}\|_{1}/3<5/6$, then the final target is to compute

$$ $\frac{2\bar{\bm{b}}_{t}}{3(1-c_{1})}=\frac{2\bar{\bm{b}}_{t}}{3}\left(1+c_{1}+ c_{1}^{2}+\cdots\right).$ $$

If we use $O(k)$-layers in the second part of the MLP, then we can approximate the sum

$$ $1+c_{1}+c_{1}^{2}+\cdots+c_{1}^{2^{k}-1}$ $$

with error $O(\exp(-T))$ by picking appropriate parameters according to Lemma C.2.

Moreover,

$$ $\displaystyle\left|\frac{1}{1-c_{1}}-1+c_{1}+c_{1}^{2}+\cdots+c_{1}^{2^{k}-1} \right|=\frac{c_{1}^{2^{k}}}{1-c_{1}}\leq 6\left(\frac{5}{6}\right)^{2^{k}}.$ (D.57) $$

Therefore, it suffices to choose $k=O(\log T)$ to approximate $2\bar{\bm{b}}_{t}/3(1-c_{1})$ in $\ell_{\infty}$ error $O(\exp(-T))$. Aggregating the approximation error of both parts of the MLP, the overall approximation error is $O(\exp(-T))$.

## Peer Reviews

confidence: 3
contribution: 2
initial_rating: 5
presentation: 2
questions: I am afraid I had a lot of questions about the details that I think can be clarified, which will help me perform a better evaluation of the paper.  I list them here in no particular order.

1. With your RNN's -- did you end up using ReLU RNN's ? It's surprising they perform so much better than transformers, even though LSTM's were typically the best in class RNNs years past.
2. I'm not entirely sure why you created the exact forms of HMM you did in this paper. The essence of the method seems to be to generate HMMs' that have different Markov-orders and different correlations between belief states and output sequences. Could this have been explored with other alternatives such as the complexity of the Markov Chains of the hidden sequences and the complexity of the emission distributions ? 
3. Can you please provide more information about the experiments ? I am not sure what was the state sizes for different experiments, 
4. With discrete state HMMs, and continuous outputs it would make sense that the output distribution would be a mixture model, rather than a single model. As such using an l2 loss may cause problems.  Did the authors attempt to use mixture density network type approaches for these cases ? 
5. Are the loss functions averaged over batch ? i.e. is loss divided by the batch size and sequence length ? I see only sequence length, in (B.1) and so I want to be sure.
6. B.1 lays you the loss function for training -- L2 for Matmul, RanLDS and cross entropy for other tasks. But evaluation on line 877 seems to suggest that evaluation loss is the l2 loss.. Is this also the case for categorical outputs ? I would think that the right evaluation objective would be the KL from the predictive distribution or the posterior belief state of the HMM itself. What is the case here ? 
7. Do you have a study on the effect of the block size, b, of the block COT on the results ?
8. Epsilon on like 410 is overloaded with epsilon in line 344. 
9. Line 455 - .."we can feed the output back into the transformer every b steps". Is this the actual output from the model ? If so, is gradient back propagated through this, and with what method (straight through, or reinforce, etc) ? If not, isn't it just teacher force model durning training, just like language models, and so training speed should be unaffected ?
10. During curriculum training, as I understand it here, you use increasingly longer sequences. Is batch size kept the same ? Are learning rate and other things adjusted for the changing batch size ? Does the training proceed from the previous point, or is learning rate warmup performed once more ? 
11.  In figure 6, why does the Cyclc-DET w.o. curriculum fall so significantly when going from 5 to 6 layers ?
12. It is really detailed to follow the HMM construction -- will you be releasing the code to create Cyclic-DET and Cyclic-RND ? 
13. Any thoughts on why transformers perform almost a million times worse than a single layer RNN, for Matmult, Cyclic-DET and RND -- are these are with continuous outputs ? These results are quite surprising to me.
soundness: 2
strengths: I thought the idea of using sequences from HMMs to study the learning abilities of transformers quite a good one -- it is possible to control the complexity of the sequences by the Markov-order of the HMMs; it is possible to control the number of states, and output distribution etc. The authors created Cyclic-{DET, RND,HARD} models which have different properties in terms of complexity, mixing length etc. 

The block COT method seems to be good way to propagate more information through the model. During training this makes the model more autoregressive, which making it less computationally demanding than a fully next step autoregressive model based of the state of the model.
summary: The paper applies transformers to learning models for output sequences of several types of  HMMs and Linear Dynamical Systems models.
The authors used two main tasks for evaluation -- next observation prediction and belief state prediction from the observations.

They compared the convergence speed of the transformer models with recurrent models and found, surprisingly (at least to me)
that RNN's converged faster and better than transformer models that they implemented. 

The authors explored two main factors in the learning efficiency. Firstly they explored the effect of longer mixing length 
on the ability of the transformer models to learn good models. Secondly they explored the effect of uncertainty in predicting
the belief state of the model from the observations, on the predictive capacity of the models.  They found that when
the mixing length increased transformer models performed worse. They also found that when belief states were more strongly
correlated with next step predictions, then predicting belief states in the intermediate blocks could result in 
improved performance by a block COT type approach. 

Finally, the authors show some theoretical proofs related to - 
1. The ability of RNNs and transformers to model sequences from HMMs with different levels of predictions based on depth
and length of sequences.
2. Existence of transformer models that can learn to model outputs from HMMs with arbitrary accuracy based on minimum
depth -- they used prior work which showed that transformers can model any arbitrary automata (of which HMM is but a sub-case).
weaknesses: I don't want to be too certain about what the weakness of the paper are, until I read the authors' rebuttals and clarifications, since its possible I may have missed some details and motivations.

My first reaction, is, sadly an instinctive one. In as much as it makes sense to me that deeper models should perform better, and that the more complex the sequence type, the harder it would be for an algorithm to model it. However, I am quite surprised, to see that recurrent models learn so much faster, and I want to be certain that this observation, which is repeated in various forms in the paper, holds.  I have left several questions in the Questions section to help me understand the details. What I would have to say here is that it seems to me that transformers can mimic recurrent models, by learning to put all the attention in the previous step and previous step alone. In doing so, it can cause the models to flow information almost in a recurrent way. So I am puzzled that the recurrent model can outperform it.

Another thing that comes to mind is that I think to some extent the model studies not just the learning properties of transformers, but the combination of the transformers and the loss function. HMM's can often produce complicated, multi-modal output distributions. Modeling these with an L2-loss is likely to lead to over smoothed models. Such problems are well studied in ML, back to early days of using mixture density networks, where the model's output was a mixture model, and not just a single mean value. I suppose this is true also for the Recurrent models, but have the authors explored the impact of this on the learning ? I left some clarification questions below in the questions section to tease this apart a little bit more. 

It is not clear why curriculum is important here. If I understand correctly, the same HMM is used over training a model. In that case, the complexity of each task is really just dependent on the property of the HMM, and the complexity is the same through the sequence. Is it not true that a shorter sequence from the HMM should be no more complex than a longer sequence from the same HMM ? 

Experimental details are somewhat sparse; specifically what were the sizes of state space, n, what were the output dimensions ? Were continuous data normalized before training transformers. For discrete outputs, what were the output space (m) ?

---

confidence: 3
contribution: 3
initial_rating: 6
presentation: 3
questions: About block Chain of Thought: if the reviewer understood correctly, this is rather different from the CoT that is generally used in LLMs where instruction is given to prompt the LLM to think through the question before answering. In this paper, the block CoT refers to ‘block’ autoregressive decoding where the output predictions in the previous steps are fed as input tokens to inform generation at the current step. If that right? It might be worth clarifying, e.g. with a simple sketch diagram, to make it clearer to the reader.

Typo at Line 886: “ate” -> “at”
soundness: 3
strengths: The work is timely given the widespread adaptation of transformer-based models. HMMs are important area to study.

The findings are backed by theoretical analyses.

The paper is well written and easy to follow.
summary: This paper studies the capability of transformers in learning variants of Hidden Markov Models (HMMs), while comparing with RNNs. The authors demonstrated several key findings and support them with theoretical analysis. One such finding implies that transformers can model HMMs and its depth scales logarithmically with the input sequence length. The experiments show that there is a subset of HMMs that are challenging for transformers to learn while RNNs can model. More specifically, HMMs with long mixing time and which have limited supervision signal during training are particularly challenging for transformers but not so for RNNs. The authors show that including the output of the transformer as its input, a method the authors called block Chain of Thought, can mitigate this limitation of transformers.
weaknesses: The experiments were mostly conducted with model HMMs. If experiments with real-world datasets are included, this can show this can translate to practical benefits and implications

---

confidence: 2
contribution: 3
initial_rating: 5
presentation: 2
questions: * How do you embed the continuous inputs and outputs?  Are the inputs/outputs of the transformer the same size as the transformer hidden state?  Similarly for the discrete 
* The step/stage description in Cyclic-HARD (and corresponding Figure) I found unclear.  Could you elaborate (maybe in a short appendix) what it would actually expand into for a small problem?  
  * As an aside, it would help build intuition if you provided some samples from each of the systems in an Appendix, or provided them for download.
* How do you feed the gradient through feeding in the output token in the CoT approach?  Is there a stop-gradient involved?
“network cannot use it as input since the transition is unknown.” isn’t very clear what it is referring to - it could learn the transitions after all?
soundness: 3
strengths: * Understanding our tools is important in ML; different methods have different trade-offs and this is another demonstration of the types of problems that transformers struggle with and other models (or hybrid models) should be applied.  
* Their proof in 5.2 of the number of layers L needed in the transformer to model an HMM of length 2^L is a useful bound that’ll find applications outside of this domain.  Many problems being solved in LLMs are highly sequential, and there can be trade-off between depth and width of each layer, for which this bound could be informative.  
* Their dataset could prove interesting in understanding the behavior of other sequence models, like SSMs, and thus in developing new sequence models.
summary: The authors introduce various Hidden Markov models (HMM) datasets as a tool to study the learning behavior of Transformers and RNNs.  This includes RanHMM, a HMM with randomly sampled transitions and observations.  They claim that belief inference (inferring the hidden state of the HMM) is harder than predicting the emission, so they also introduce define HMMs with more structure, that they derive from Markov Decision Processes (MDPs).  This includes CyclicHMM-DET, a deterministic MDP with random actions that gives an aperiodic HMM, CyclicHMM-RND, a version that can slip backward, and Cyclic-HARD.  The demonstrate that the different model systems have quite different behaviors and mixing times.  In addition they also test two continuous varieties, MatMul and RanLDS, a random linear system.  

Generally they find that RNNs learn HMMs more quickly and robustly than Transformers, and there are certain HMMs that transformers fail to learn at all.  In particular, long mixing times particularly hurt transformers as the recent past is not as predictive of the current state.  

They also introduce what they call block Chain of Thought (CoT) reasoning can help transformers reduce evaluation error and learn longer sequences.  This involves feeding back the output distribution of the transformer as input.  Note that this is not just the output symbol, as they claim that this output distribution is very informative about the hidden state of the HMM.    

Finally, they prove that a transformer with L layers can model a sequence of effective length 2^L, which motivates them to introduce a curriculum training by increasing the doubling the sequence length during training, which also helps.
weaknesses: * HMMs are intrinsically a sequential problem - in a way, it’s unsurprising that the Transformer model would perform worse at them. E.g., expressing the “copy the symbols from N characters ago) task is pretty hard in a HMM or an RNN, but is very natural in a Transformer.  Limiting the scope of problems you look at is fine, but it would be useful to have at least a short discussion of the types of problems that would be well modeled by a HMM or not.  
* The paper would have been stronger if a parallel state space model like MAMBA had been included, as it would be interesting to see parallel trained SSM could learn and represent this inherently sequential computation in a parallel manner.
* Calling their method of feeding output token distributions back in as “Chain of thought” (CoT) is a bit of loose analogy.  In CoT you prompt with other examples and the reasoning happens first, unlike in their system.  Their block CoT does appear to help, so this is more of a comment on the naming.
* Only using a single evaluation per HMM can make the results too noisy to draw reliable conclusions.  
  * E.g., Figure 2, Cyclic-Hard, the fact that L=5 beat L=4 and L=6 could just be noise.  It would be better to rerun at least 3 times and plot error-bars.

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 3
questions: - What are the implications of your findings?
- Why was ReLU chosen over classical activations like tanh or sigmoid? Was this to address the vanishing gradient problem?
- Could you provide an ablation study on the positional encoding dimensionality? Additionally, could you conduct an experiment with RoPE on a task where the Transformer struggles (e.g., Cyclic-HARD)?
- I recommend mentioning in the main text that pre-LN was used, as it helps with convergence speed -- yet RNNs still converge faster than Transformers.
- I suggest adjusting the y-axis limit to (0, 120) in Figure 3.
- Line 68: Consider replacing "training speed" with "convergence speed" for clarity.
- Line 81: Define "LDS".
- Line 111: Replace "sequence's nature" with "sequential nature."
- Appendix A5: The motivation for the choice of tasks is great; I suggest moving (part of) it to the main text.
soundness: 3
strengths: - The choice of synthetic tasks based on random and structured HMMs is well-justified and relevant to a range of practical applications.
- The experimental setup is modern and reasonable.
- The experimental results, while expected, are interesting and theoretically supported.
- The paper is generally clear and well-structured.
summary: The authors empirically and theoretically investigate the ability of Transformers and RNNs to learn six synthetic sequential tasks derived from both random and structured Hidden Markov Models (HMMs). They justify choosing HMMs due to their broad applicability in various tasks like part-of-speech tagging, named-entity recognition, time-series forecasting, control systems, and reinforcement learning. The study introduces three key findings: (1) Transformers can effectively learn many HMMs, provided their depth increases logarithmically with sequence length; (2) RNNs perform better on certain complex HMMs and surpass Transformers in both convergence speed and accuracy; (3) Transformers struggle with long mixing times due to their lack of intermediate latent states. The authors examine the use of chain-of-thought (CoT) prompting to address these Transformer limitations.
weaknesses: - The implications of the empirical and theoretical findings are not discussed. For example, the authors could suggest potential improvements for Transformers in applications with long mixing times or discuss the practical applicability of RNNs, given their superior convergence speed and performance on the synthetic tasks.
- I believe the impact of the work to be limited.
- The choice of the ReLU activation in RNNs is not motivated.
- The choice of a positional encoding with a dimensionality of 3 might not be optimal.

Meta-review: ## Summary
This paper examines the ability of transformers to learn sequences generated by Hidden Markov Models (HMMs). Through a combination of theoretical analysis and experiments, the authors compare transformers and Recurrent Neural Networks (RNNs) in their capacity to learn HMMs.

The experiments reveal three key findings: (1) Transformers can learn many HMMs effectively but require depth that scales logarithmically with sequence length. (2) RNNs outperform transformers in training speed and accuracy across all tested HMMs and are more capable of handling challenging HMMs. (3) Transformers face difficulties when HMMs involve long mixing times or lack access to intermediate latent states, while RNNs are less impacted.

To address these challenges, the authors propose a variant of the Chain-of-Thought (CoT) approach called “block CoT,” which improves transformers’ performance on longer sequences at the cost of increased training time. Theoretical results also demonstrate that transformers with sufficient depth can approximate HMMs accurately, building on prior findings about their expressiveness.

## Decision

Overall, this work is timely and important and the authors support their findings are backed by theoretical analyses. The paper seems to be well-written and easy to follow. However, it seems to be rushed, especially the experiments. The reviewers were not fully convinced by the claims and the experimental results. Thus, they raised several concerns during the rebuttal. However, the authors didn't submit a rebuttal to address these concerns. As a result, in its current state, this paper is not ready for acceptance.

Decision: Reject