Universal length generalization with Turing Programs

## Abstract

Abstract Length generalization refers to the ability to extrapolate from short training sequences to long test sequences and is a challenge for current large language models. While prior work has proposed some architecture or data format changes to achieve length generalization, these proposals typically apply to a limited set of tasks. Building on prior scratchpad and Chain-of-Thought (CoT) techniques, we propose Turing Programs , a novel CoT strategy that decomposes an algorithmic task into steps mimicking the computation of a Turing Machine. This framework is both universal, as it can accommodate any algorithmic task, and simple, requiring only copying text from the context with small modifications. We show that by using Turing Programs, we obtain robust length generalization on a range of algorithmic tasks: addition, multiplication and in-context SGD. We then demonstrate that transformers achieve length generalization on random Turing Programs, suggesting that length generalization is possible for any algorithmic task.
Finally, we theoretically prove that transformers can implement Turing Programs, constructing a simple RASP (Weiss et al. [ 53 ] ) program that simulates an arbitrary Turing machine.

## 1 Introduction

Figure: Figure 1: Turing Program example for simulating a Turing Machine with scratchpad.
Refer to caption: x1.png

Transformer-based language models have shown impressive abilities in natural language generation,
reading comprehension, code-synthesis, instruction-following, commonsense reasoning, and
many other tasks [, , , , , ]. Despite these impressive abilities, transformers struggle with *length generalization*, which refers to the ability to generalize to longer sequences than seen during training [, , , ]. This limitation raises a central question about transformers: are they capable of actually learning an algorithm or do they solve algorithmic tasks by resorting to
memorization or shortcuts []?

Recently, several works have reported poor length generalization of transformers on a wide range of algorithmic tasks [, , , ]. In parallel, a myriad of papers [, , , , ] have optimized the data formats choice (see Section 3 for details) to improve the length generalization of transformers when trained to perform multi-digit addition of two numbers. While the recent progress is impressive—Zhou et al. [] achieve almost perfect accuracy on addition with 100-digit operands while trained on 40-digit, all these “tricks” are specific to the case of addition and may not generalize to other tasks. In contrast, our goal is to develop a technique that is *general* enough to enable length generalization on *any* algorithmic task.

**Table 1: Length generalization results on various problems with Turing Programs. We use $x\to y$ to denote training on $n=x$ and generalizing to $n=y$.**
| Problem | Generalization | Accuracy |  |
| --- | --- | --- | --- |
| Addition ($n+n$) | $50\rightarrow 100$ ($\bm{2\times}$) | $98\%$ |  |
| Multiplication ($n\times 1$) | $50\rightarrow 100$ ($\bm{2\times}$) | $97\%$ |  |
| Multiplication ($n\times 3$) | $50\rightarrow 100$ ($\bm{2\times}$) | $97\%$ |  |
| SGD ($n$ examples) | $50\rightarrow 80$ ($\bm{1.6\times}$) | $95\%$ |  |

To achieve this, we introduce *Turing Programs*, a novel scratchpad technique that may be applied to general algorithmic tasks. This technique is motivated by the operations of a Turing Machine, a mathematical model of computation that is capable of implementing any computable algorithm. A Turing machine consists of a “tape” with symbols and a “head” that, at each step, moves left or right on the tape, and can read and write symbols in a single tape cell. Therefore, when a Turing Machine processes an input, the tape at each step is a copy of the previous one up to a few changes.
Our Turing Programs follow this philosophy by decomposing an algorithmic task into a series of steps.
At each step we update a “tape” by copying the previous tape with a few elementary changes.
We refer the reader to Figure 1 for the correspondence between Turing Machines and Turing Programs and to Figures 2 and 4, for examples of Turing Programs.

Using the Turing Programs technique, we show that transformers enhanced with the Hard-ALiBi positional encoding []—a recent encoding that achieves state-of-the-art length generalization on copying—are capable of length generalization on a wide range of algorithmic tasks. Our method achieves non-trivial length generalization on addition, multiplication and simulation of SGD steps (see Table 1).
Additionally, we show that transformers can be trained to execute random Turing machines, extrapolating from 50 to over 100 input tokens, suggesting that our method can work for general algorithmic tasks. To our knowledge, these are the first results showing non-trivial length generalization on multiplication, and the first attempt to study length generalization on complex algorithms like SGD. We hope that this recipe will be further used to unlock novel length generalization on other algorithmic tasks.

Our key contributions are summarized as follows:

- –
In Section 3, we present length generalization results on multi-digit addition using a Turing Program and Hard-ALiBi positional encoding.
- –
In Section 4, we present the Turing Program framework in full generality and its connections to Turing machines. Additionally, we theoretically prove that transformers can implement Turing Programs, constructing a RASP program [] simulating Turing machines.
- –
In Section 5, we demonstrate that Turing Programs are general and lead to novel length generalization results in unexplored algorithmic tasks: multiplication by 1 or 3-digit operand, SGD for linear regression and Turing Machine simulation.

## Related work

Length generalization remains an important challenge for large language models as underlined in several works [, , , , ]. Despite their advanced reasoning capabilities,
Transformer-based large language models
struggle to process longer sequences than they were trained on []. The main approaches for improving length generalization focus on changing the positional encoding and optimizing the data format.

##### Positional encodings for length generalization.

Shaw et al. [] were early to notice that the weak length generalization of Transformers was due to the choice of absolute positional encoding. Following this, many alternatives were proposed to replace the absolute positional encoding: relative positional encodings, which focus on
the relative distances between tokens []; and weighted attention mechanisms in place of position
embeddings [, , , , ]. These alternatives showed substantial improvements in length generalization on natural language processing tasks. On the other hand, Kazemnejad et al. [] found that a causal language model with no positional encoding can length generalize better than some of these specialized positional encodings on algorithmic tasks. In this work, we apply the Hard-ALiBi positional encoding [], that achieved state-of-the-art length generalization on the specific task of copying, to more general algorithmic tasks.

##### Data formatting for length generalization.

A wide range of data formatting methods have been introduced to achieve length extrapolation in algorithmic tasks. Scratchpad and Chain-of-Thought formats were proposed to learn arithmetic either through finetuning or in-context learning [, ]. When training from scratch, some other proposed techniques to improve length generalization on addition include: reversed formatting and random space augmentation [], adding padding to the sequence [], and setting index hints in front of each digit []. Closer to our work, several works [, , , , ] report that training or finetuning a model on scratchpad data does not yield any significant length generalization improvement. In our work, we demonstrate that length generalization is possible using a combination of a particular scratchpad variant and a favorable positional encoding. Additionally, we develop Turing Programs, a novel scratchpad strategy that is general and may be applied to achieve length generalization on any algorithmic task.

##### Neural networks and Turing Machines.

Many prior works designed architectures inspired by Turing Machines [, , ]. From a theoretical perspective, some works proved the Turing completeness of RNNs [, ], transformers [, , , , ] and even linear next-token predictors [] under a wide range of assumptions. Lastly, another line of work characterizes the computational model that Transformers express: Weiss et al. [] introduce RASP, a human-readable programming language that can be implemented by transformers, Lindner et al. [] show how human-readable programs are compiled into transformer models and other works [, ] study how transformers can emulate computer programs. Closer to our work, Zhou et al. [] hypothesize that Transformers can length generalization on any algorithmic task that may written as a “simple” RASP program. In this work, we construct a simple RASP program that generates Turing Programs to simulate arbitrary Turing machines.

## 2 Setting

In this section, we present the length generalization problem and some instances where it appears. Then, we discuss scratchpad prompting [], a technique that lets the model generate solution steps before producing the final answer. Finally, we introduce various positional encoding methods and discuss their implications on length generalization.

### 2.1 Length generalization

Many sequence modeling tasks have problem instances of different lengths. Shorter instances are often easier to state, process and handle, and require less compute to find the answer. By contrast, longer instances are more challenging to parse and require more compute to solve. Reasoning tasks such as multi-hop reasoning, program execution, deductive reasoning, and theorem proving fit in this category.

Algorithmic reasoning tasks consist of inputs that are sequences of tokens describing the task (e.g. addition, multiplication) and outputs that are the corresponding solutions. We assume that the language model is allowed to generate (many) intermediate tokens before outputting the answer. Then formally, the *length generalization* problem consists of training a language model on inputs of length $\leq L$ and solving problems of length $>L$ at test time.

### 2.2 Scratchpad

It has been shown in prior work that the performance of LLMs on algorithmic tasks can be greatly improved by generating step-by-step solutions instead of immediately outputting the final answer []. Among the multiple methods described in the literature, we focus on the scratchpad method [].
Given an algorithmic task, this method encodes the intermediate steps of the algorithm as text and trains the model to emit them to a buffer that is referred to as the “scratchpad”.

Nye et al. [] showed that scratchpad finetuning can be used to achieve strong in-distribution performance on execution based tasks such as code
execution and computing polynomials. They also report modest length generalization results
on integer arithmetic. The limitation of scratchpad training for length generalization is further highlighted in [, , , , ].

In this paper, we revisit the use of scratchpad training to achieve length generalization on algorithmic tasks. We begin with the observation that the scratchpad technique can be realized as an iterative sequence of copying operations, where at each iteration the input is slightly modified. Building on previous works showing that with the right positional encoding, transformers can achieve length generalization on the copying operation [], we hypothesize that combining the scratchpad technique with a favorable positional encoding can unlock length generalization capabilities. We verify this hypothesis in Section 3 and Section 5, but first we review various choices of positional encoding.

### 2.3 Positional encodings

The inability of transformers to extrapolate to longer sequences has been primarily attributed to the positional encoding [, ]. In this section, we review the different positional encoding schemes and in Section 3, we report their length generalization performance. We review here specific choices for positional encodings that are known to perform well for length generalization, and discuss additional encoding schemes (such as absolute and relative positional encodings) in Appendix A.

##### No Positional Encoding (NoPE).

Decoder-only models with causal attention, as shown by Haviv et al. [], acquire positional understanding, without explicit positional encoding. Kazemnejad et al. [] shows that a model without positional encoding extrapolate better than those with specialized positional encodings on some algorithmic tasks.

##### ALiBi.

Press et al. [] introduces this additive positional encoding where the bias function follows $b(i,j)=-r|i-j|$, where $r>0$ is some hyperparameter. This scheme has led to state-of-the-art length generalization on natural language tasks. However, Jelassi et al. [] notices that it struggles at length generalization on the copy task and hypothesize that it is due to the slow decay of $r$.

##### Hard-ALiBi.

Jelassi et al. [] introduce Hard-ALiBi, an additive positional encoding where the bias satisfies $b(i,j)=-\infty$ for $j\leq i-m$ and $b(i,j)=0$ for $j>i-m$, for some hyperparameter $m>0$. Intuitively, with this hard thresholding, tokens can only attend to the $m$ closest tokens. Different heads may have different values of $m$ and some heads use $m=\infty$ which corresponds to softmax attention with no positional embedding at all (allowing for propagation of global information). The authors demonstrate empirically that models equipped with the Hard-ALiBi positional encoding achieve remarkable length generalization on the copy task. In this work, we use the Hard-ALiBi position encoding to enable length generalization on algorithmic tasks as we show below.

## 3 Length generalization on addition

Figure: Figure 2: Turing Program for addition, text in comments is not part of the input.
Refer to caption: x2.png

In this section, we address the length generalization problem for addition. We first review prior results on this problem and describe the techniques used in these works. We then demonstrate that Transformers trained with Turing Program scratchpads and Hard-ALiBi positional encoding achieve good length generalization performance, extrapolating from length-50 to length-100 addition. This is a remarkable improvement over previous length generalization results using the “vanilla” scratchpad technique (e.g. []), which showed weak length generalization performance. As mentioned, there is a long list of works that focus on length generalization on addition (see Appendix B for a complete review). Notably, Zhou et al. [] report somewhat better length generalization results compared to our results. However, we note that these results rely on particular choices for the formatting of the input and the output, which are “tailored” for the task of multi-digit addition.

### 3.1 Length generalization on addition with Turing Programs and Hard-ALiBi

In this section, we present our Turing Program scratchpad strategy for addition and report length generalization results.

#### 3.1.1 Experimental setup

##### Data.

We adopt the scratchpad format and write all the steps into one sequence, where steps are separated by a separator token. Figure 2 shows our scratchpad strategy for getting length generalization on addition(^1^11In the experiments, we use a slightly more compact version of the scratchpad, where each examples is represented as $4324+139|432e+13j(1,3)|43c+1d(0,63)|4d+b(0,463)|e+${\text{}}^{\wedge}$(0,4463)|4463.).
If not specified otherwise, our token space is of size 24 and made of $\mathcal{V}=\{0,\dots,9,+,a,\dots,j,\texttt{${\text{}}^{\wedge}$},\texttt{<|
BOS|>},\texttt{
},\texttt{
}\}$. All the digits are sampled uniformly as follows: we first sample the length of each operand (between $2$ and $L=50$) and then independently sample each digit. Finally, we “pack the context” with i.i.d. sequences during training, i.e. we fill the context with multiple independent samples of the task (similarly to []). We set the training context length to 500. At test time, we evaluate our models using a sliding window: we generate tokens until the training context length ($500$) is filled, and then each additional token is generated by feeding the context of the most recent $500$ tokens, effectively dropping all past tokens(^2^22For efficiency reasons, once we reach the context length we advance the “window” by $20$ tokens.). This way, we are able to generate very long sequences of tokens without training or evaluating on long context windows. To evaluate the accuracy at a given length, we test the model’s output on $288$ examples. We report the accuracy of exactly matching the desired output.

##### Model and Training.

Our base model is a 150M parameter Transformer with $L=12$ layers, a $D=1024$ hidden size, feedforward layer with a hidden dimension of 4096 and $H=16$ attention heads. The backbone of our model is based on the GPT-NeoX architecture []. We pick a context length of 500 tokens. We use the AdamW optimizer [] to train the model with a weight decay value of $0.1$ and no dropout, for 200,000 steps. The learning rate schedule incorporates
an initial 100-step linear warm-up, followed by a linear decay, starting at 7e-5.

##### Hard-ALiBi positional encoding.

Similarly to [], we use $M$ masked heads and $(H-M)$ NoPE heads. In the masked heads, we respectively set the hyperparameter $m$ to $1$, $2$,$\dots$ and $M$. We swept over $\{3,4,5,6,7,8\}$ and found that $M=6$ is the best choice.

Figure: (a)
Refer to caption: x3.png

#### 3.1.2 Results

In Figure 3(a) we show the length generalization performance of transformers trained to perform multi-digit addition
using the scratchpad described above. We compare the performance of different choices of positional encodings, as well as comparing to the performance on addition without scratchpad (directly outputting the answer).
We observe that by using Hard-ALiBi together with scratchpad, transformers are able to generalize well beyond the length of the training examples. In particular, the Hard-ALiBi model achieves a $98\%$ accuracy at length $100$.
As shown by Figure 8 in the appendix, the model also length generalizes well when the operands are of different lengths.
Finally, in Figure 3(b) we analyze the robustness of length generalization performance to different choices of initialization seed. We observe that, while there is significant variance in performance when testing on longer sequences, our method is more robust compared to prior results (as reported in []).

## 4 Turing Programs

In Section 3, we showed that Transformers with Hard-ALiBi trained on a specific choice of scratchpad format can length generalize to sequences that are $2\times$ longer. On closer inspection, each line in the scratchpad in Figure 2 is a slightly modified copy of the previous one where a few elementary changes are applied, e.g. removing one digit for each operand and updating the intermediate result/carry. Since Hard-ALiBi yields robust length generalization on copying, this may explain why we achieve better extrapolation than previous works that trained their models with scratchpad.

In this section, we generalize this approach and claim that every algorithmic task can be written as a sequence of modified copy operations: i.e. copy operations with small and localized modifications. Such decomposition follows immediately from the standard construction of a Turing Machine, a universal model of computation. We therefore refer to this scratchpad strategy as a Turing Program. We start this section introducing the standard definition of a Turing Machine, and then present Turing Programs, our scratchpad strategy for achieving length generalization on any algorithmic task. Lastly, we present our main theoretical result: Transformers can implement Turing Programs over long sequences of inputs.

### 4.1 Background: Turing Machines

A Turing Machine [] is a computational model that consists of an infinite tape(^3^33We assume that the tape is unbounded from the right side, but bounded from the left. Namely, there are infinitely many cells to the right of the input, but no empty cells to the left. This is computationally equivalent to a tape that is infinite from both sides.) with *cells*, a head that can read from a cell, write to a cell and move left or right over the tape, and a set of rules which direct the head based on the symbol it reads and the current state of the machine. More formally, a Turing Machine is defined as follows.

###### Definition 4.1

A Turing Machine is specified as a quadruple $T=(Q,\Sigma,s,\delta)$ where: 1) $Q$ is a finite set of states, 2) $\Sigma$ is a finite set of symbols, 3) $s\in Q$ is the initial state and $f\in Q$ is the final state, 4) $\delta$ is a transition function determining the next move: $\delta\colon(Q\times\Sigma)\rightarrow(\Sigma\times\{L,R\}\times Q)$.

At the first iteration, the machine is set to state $s\in Q$, the head is on the first (leftmost) cell of the tape, and the input is written on the tape from left to right. At each iteration, the head is on the $i$-th cell in the tape, is in state $q\in Q$ and reads the $i$-th symbol on the tape $\alpha$. Then, if $\delta(q,\alpha)=(\alpha^{\prime},D,q^{\prime})$, the head writes the symbol $\alpha^{\prime}$, moves in the direction $D\in\{L,R\}$, and the machine changes its state to $q^{\prime}$. If the machine reaches the state $f$, it stops, and its “output” is written on the tape.

Turing Machines are a powerful model for solving algorithmic tasks since (a) the framework is *universal* i.e. it is possible to write any algorithmic task in the Turing Machine formalism, (b) Turing Machines can solve a wide range of algorithmic problems—ranging from simple arithmetic to determining whether a number is a prime []—in a polynomial number of steps. In the next section, we show how to use the Turing Machine formalism to obtain a novel scratchpad strategy that unlocks length generalization on any algorithmic task.

###### Definition 4.1

### 4.2 Turing Programs: a universal scratchpad strategy for length generalization

The left panel of Figure 1 represents the simulation of a Turing Machine and shows how the state, the head and the tape evolves with time. Note that at each time step, the state of the tape is a copy of the previous tape with a few elementary changes such as a move of the head, an edit of a single symbol and a change of state.

The steps in a Turing Machine simulation are similar to a scratchpad strategy where each string is a copy of the previous one with a few modifications. Therefore, we claim that for any algorithmic task that can be solved by a Turing-computable algorithm, there is a corresponding scratchpad strategy for solving this problem (as demonstrated in the right panel of Figure 1). We refer to this novel scratchpad strategy as *Turing Programs*.

Turing Programs decompose an algorithmic task into a series of intermediate reasoning steps. Each step is a “tape” that maintains the state of the machine, and the next step is a copy of the previous tape with a few elementary changes, such as trimming of digits and update of carry/intermediate result as in the case of addition and multiplication (see Figures 2 and 4) or update of the parameters in the case of SGD on linear regression (see Subsection 5.2). In Section 5, we show how to use Turing Programs to unlock novel length generalization results on challenging algorithmic tasks.

### 4.3 Theory: Turing Programs in RASP

To further motivate the use of Turing Programs to achieve length generalization on arbitrary algorithms, we prove that transformers can implement Turing Programs over long sequences of inputs. In particular, we show that Turing Programs can be implemented in RASP [], a programming language that was suggested as an abstract description of the operations of a transformer. Following Zhou et al. [], we use a restricted version of RASP that does not allow direct index operations, as Zhou et al. [] hypothesized that RASP programs with index arithmetics may not length generalize(^4^44Our RASP program does not follow all the restrictions of the RASP-L language suggested in [], as we do not restrict the tokens to have $\mathtt{int8}$ values.). Therefore, our result should be viewed as a length-generalization-friendly construction of a transformer that can execute (most) Turing Programs (and hence, can simulate most Turing machines).

Figure: Figure 4: Turing Program for 3-digit multiplication. At each step, we update three information: the head position, the result of the “local” multiplication, the carry and the intermediate result of the “global” multiplication.
Refer to caption: x5.png

To avoid index operations, we leverage the $n$-gram hashing mechanism suggested by Jelassi et al. [] as a basis for the copying ability of transformers. In their construction, copying a string from the input was achieved by storing a sequence of $n$ preceding tokens ($n$-gram) at each position, and iteratively retrieving the next token after the uniquely matched $n$-gram. Our Turing Program construction is very similar, except that instead of copying a string from the input, we copy the next state of the Turing machine as computed from the previous string. As in the construction of Jelassi et al. [], our RASP program is limited to operating on inputs that have no repeated $n$-grams (i.e., no sequence of $n$ tokens appears twice in the input), which can be guaranteed with high probability for uniformly random sequences of tokens of length $\leq\exp(n)$. Additionally, we require that the Turing machine does not generate repeated $n$-grams when processing the input, and that all the operations of the Turing machine are applied in-memory(^5^55Namely, we assume that the head of the Turing machine does not go beyond the input sequence. We believe that this restriction may be removed at the cost of constructing a more complex RASP program. While this may seem like a limiting restriction, we note that this limitation can be easily mitigated by padding the input with random tokens.). Under these assumptions, we get the following result:

###### Theorem 4.1

Let $T$ be a Turing Machine s.t. 1) $T$ does not generate repeated $n$-grams and 2) $T$ operates in-memory. Then, there exists a RASP program $P$ of size (number of lines) $O(n)$ s.t. for every input $x$ without repeated $n$-grams, $P$ correctly simulates $T$ for $\exp(n)$ steps.

We give the full code for the construction of such RASP programs in Appendix D.

###### Theorem 4.1

## 5 Length generalization on other algorithmic tasks

Building upon the encouraging length generalization results on addition from Section 3 and the Turing Programs framework from Section 4, we show that Transformers enhanced with Hard-ALiBi may achieve robust length generalization on complex algorithmic tasks. We show that our framework achieves length generalization on multiplication by $1$-digit and $3$-digit operands, on SGD applied to linear regression, and finally, on next-state prediction of a random Turing Machine.

### 5.1 Multiplication by a fixed-length operand

##### Prior work.

Multiplication is known to be a challenging task for length generalization and very few works report positive length generalization results on this task. On pretrained models, Zhou et al. [] shows that elaborate prompting techniques slightly improve the length generalization of Codex on $(n\leq 3)$-multiplication. Dziri et al. [] show that even fine-tuned
GPT-3 struggles with performing 3-digit multiplication. On randomly intialized networks, Lee et al. [] show that models can learn in-distribution the 2-digit multiplication in a sample efficient way using scratchpad. Shen et al. [] shows that with padding and reversed products it is possible to perfectly learn in-distribution 12-digit multiplication. Jelassi et al. [] focuses on 3-digit multiplication and shows that when training on ($5\times 3$)-digit-multiplication and adding a few examples of ($35\times 3$)-digit-multiplication, the model length generalizes to ($35\times 3$)-digit-multiplication. In summary, prior work mainly focused on in-distribution learning of multiplication and did not manage to obtain length generalization results.

Figure: Figure 5: Length generalization on multiplication by 1 and 3 digit numbers.
Refer to caption: x6.png

##### Data setup.

Our experimental setup is similar to the one in Section 3. We focus on multiplication by a fixed-length operand, i.e. $(n\times k)$-digit-multiplication where the first operand has variable length $n$ and the second operand always has a fixed length $k\in\{1,3\}$ across all examples. We adopt the scratchpad format and write all the steps into one sequence, where steps are separated by a separator token. The Turing Program for multiplication is described in Figure 4.(^6^66In the experiments, we use a slightly more compact version of the scratchpad, where each examples is represented as $4324*135|432e*135(0540$\sim$054,0)|43c*135(0270$\sim$032,40)|4d*135(0405$\sim$043,740)| e*135(0540$\sim$058,3740)|${\text{}}^{\wedge}$*135(0000$\sim$005,83740)|${\text{}}^{\wedge}$*135(0000$\sim$000,583740)|583740.)
Our token space is similar to the token space used in Section 3, using a $*$ symbol instead of $+$ and using an additional separator token $\sim$. All the digits are sampled uniformly as follows: we first sample the length of the first operand (between $2$ and $50$) and then independently sample each digit. The remaining details of the training/test protocols are similar to those in Section 3.

##### Results.

Figure 5 reports our length generalization results on $(n\times 1)$ and $(n\times 3)$ multiplications respectively. We obtain robust length generalization by a factor $\bm{\times 2}$ (from 50 to 100-digit numbers) on $(n\times 1)$ and $(n\times 3)$ multiplication. We note that, up to length 100, $(n\times 1)$ and $(n\times 3)$ multiplication perform roughly the same ($(n\times 1)$ has accuracy $97.1\%$ and $(n\times 3)$ has accuracy $96.8\%$), which demonstrates the generality of our Turing Programs framework.
Both results are achieved with $M=7$ masked heads and peak learning rate $0.0003$.
The head numbers were again chosen by sweeping over candidate numbers as before while the learning rates were chosen from the candidate set $\{\texttt{7e-5},\texttt{e-4},\texttt{3e-4}\}$.

### 5.2 SGD on Linear Regression

Figure: Figure 6: Length generalization on running the SGD algorithm, varying the number of examples.
Refer to caption: x7.png

In this section, we train a model to perform SGD and demonstrate its ability to length generalize. While in previous examples we varied the number of digits in the operands, here we instead vary the number of examples.

##### Problem Description.

Let $D=\{(\vec{x}_{i},y_{i})\}_{i=0,...,n-1}$ with $\vec{x}_{i}\in\mathbb{R}^{2}$ and $y_{i}\in\mathbb{R}$ be a dataset of size $n$.
Given initial weights $\vec{w}_{0}\in\mathbb{R}^{n}$, we can obtain the final weight $\vec{w}_{n-1}$ by performing gradient descent:
$\vec{w}_{i+1}=\vec{w}_{i}-\lambda\nabla_{w_{i}}(y_{i}-\vec{w}_{i}\cdot\vec{x}_
{i})^{2}$,
where $\lambda$ is the learning rate.
For our experiment, we pick $\lambda=0.5$ and $\vec{w}_{0}=0$.

##### Tokenization and Data.

We divide the interval $[-1,1]$ into 200 discrete tokens $\{\bm{a}_{0},\bm{a}_{1},...,\bm{a}_{199}\}$.
As an input, the model receives a sequence of $n$ examples, each encoded as two input coordinate and one output (label) value. The model then needs to compute the iterates of the SGD algorithm when processing the data examples, starting from the last data point, and output the resulting weight vector $\vec{w}_{n-1}$. A detailed description of the Turing Program for solving SGD is detailed in Appendix E.

##### Results.

Unlike previous experiments, where we report accuracy w.r.t. exact string matching, here we allow the network to err by two quantization unit, counting any output that is within $2/100$ from the ground-truth output (in $\ell_{\infty}$ norm) as correct. In other words, we disregard errors that may occur to differences in quantization of the real-valued iterates of SGD. As shown by the blue curve in Figure 6, training the transformer to perform SGD on dataset of sizes $n\leq 50$ generalizes with accuracy $>95\%$ to datasets of size $n=80$.
Our Hard-ALiBi model has $M=7$ masked heads, a context length of $600$, and was trained with peak learning rate 7e-5 for $400,000$ steps with a batchsize of $16$.
For comparison, we also trained a model to directly compute the final answer as shown by the red curve in Figure 6. We observe that training the model to immediately output the answer significantly degrades its performance.

### 5.3 Turing simulations

Figure: Figure 7: Length generalization performance on 10 different randomly generated Turing machines.
Refer to caption: x8.png

In this section, we test the length generalization of transformers trained to predict the next state of an arbitrary, randomly generated, Turing machine.
Our experimental setup is similar to the one in Section 3 except for the data as detailed below.

##### Data setup.

We first sample a random Turing Machine $T$ with $5$ states, $15$ input symbols and a random transition function (i.e., for every pair of state and symbol we randomly draw a triplet of state, symbol and move-direction). During training, each input example is generated as follows: we randomly choose an input sequence length $L$ between $2$ and $50$, then randomly choose $L$ tokens, a random position for the head and a random state for the machine. At each step of training, we generate in an online manner a batch of size 16 of Turing simulations from $T$ and focus on learning 1-step prediction: given the input tape, the model has to generate the output of the transition function followed by the next state of the tape. At test time, we evaluate the model on tapes of length $L\geq 50$. Further details are in Appendix F.

##### Results.

Figure 7 shows that transformers enhanced with Hard-ALiBi predict almost perfectly the 1-step Turing Machine transition of tapes that are $\bm{2\times}$ to $\bm{3\times}$ longer than those seen during training. Trained with a peak learning rate of 7e-5, the models have $M=8$ masked heads and a context length of 450. This experiment suggests that transformers may length generalize on *arbitrary*
Turing Programs(^7^77We note that, formally, the experiment demonstrates the ability of transformers to learn in the “average case”, but does not rule out the possibility that some “worst case” Turing Programs have much more restricted length generlization.). However, this admittedly does not imply that transformers can successfully execute Turing Programs for multiple steps, as accumulating errors might cause the programs to fail. That said, we note that in many cases we get length generalization with virtually zero error, suggesting that multiple steps of the machine can be execute while still maintaining accurate performance.

## 6 Discussion and Limitations

Studying and improving the length generalization abilities of transformers on algorithmic tasks has been the focus of various recent works. In parallel, it has been established experimentally that the ability of language models to solve algorithmic tasks is greatly enhanced when allowing them to use scratchpad/CoT data. Additionally, recent theoretical works demonstrate that transformers can use CoT to simulate arbitrary algorithms [], establishing that they are computationally “universal”. These results motivate us to study whether transformers are universal *learners*, able to learn from examples to execute arbitrary algorithms. Since algorithms are typically defined over arbitrary sequence lengths, we use length generalization as a measure of whether the model has learned the *true* algorithm. To establish this, we use the key observation that transformers can length generalize on the copying operation. Since executing an algorithm can be implemented as a sequence of “smart” copy operations, the copying ability of transformers can be leveraged to achieve non-trivial length generalization performance on a wide range of algorithmic tasks.

That said, we acknowledge that our work still falls short of demonstrating that transformers can robustly length generalize on *any* algorithmic task. In some of our results, the extrapolation to longer sequence length is not robust, and degradation in performance may appear shortly after moving out-of-distribution. Additionally, our results rely on potentially very long and cumbersome CoT data, in a way that is not necessarily useful for real-world applications of language models. Thus, we view our results as theoretical evidence that length generalization is possible, and leave the development of more practical and robust methods for real-world length generalization to future work.

## Acknowledgments

This work has been made possible in part by a gift from the Chan Zuckerberg Initiative Foundation to establish the Kempner Institute for the Study of Natural and Artificial Intelligence. SJ acknowledges funding supported by the Center of Mathematical Sciences and Applications.
SK acknowledges support from the Office of Naval Research under award N00014-22-1-2377 and the National Science Foundation Grant under award #IIS 2229881.

## Appendix A Additional Positional Encodings Review

##### Absolute Positional Encoding (APE).

APE consists in maintaining a positional vector $\bm{p}_{i}$ for each position $i$. This vector is either predefined via a sinusoidal function [] or learned []. Then, $\bm{p}_{i}$ is added to the token embedding $\bm{e}_{i}$ before being processed by the Transformer. Prior work observed that this positional encoding does not generalize well to longer sequences in both natural language [] and algorithmic tasks [, ].

##### Additive Relative Positional Encoding (RPE).

Shaw et al. [] were the first to integrate positional encodings at the level of each attention layer (instead of doing it at the input level). Raffel et al. [] built upon this approach and added scalar biases to pre-softmax logits as follows:

$$ $\bm{A}=\bm{X}\bm{W}_{Q}(\bm{X}\bm{W}_{K})^{\top}+\bm{B},$ (1) $$

where $\bm{X}$, $\bm{W}_{Q}$, $\bm{W}_{K}$ are the input and query and key weight matrices. The bias matrix $\bm{B}\in\mathbb{R}^{n\times n}$ is induced by some positional encoding function $b\colon{\mathbb{N}^{*}}^{2}\rightarrow\mathbb{R}$. For instance, the T5 relative positional encoding [] set $b(i,j)=f(i-j)$, where $f$ is some function. Most of the subsequent positional encodings such as ALiBi [], Kerple [], Randomized Positional Encoding [] and Fire [] rely on changing the pre-softmax logits and differ in their definition of $b$.

##### Rotary Positional Encoding (RoPE).

RoPE [] encodes position information in
attention logits by applying a rotation transformation to the query and key vectors based on their relative positions.
Despite being widely used, RoPE exhibits limited length generalization [, ].

## Appendix B Prior results on multi-digit addition

In this section, we summarize the methods proposed by prior work to get length generalization on addition along with their corresponding performance. In what follows, we indicate in red the positional encoding and in green the data format used in these works. We also take as a running example the addition 576+361=937.

– Lee et al. [] from 7 to 7-digit ($\bm{1.0\times}$). APE + Reversed format. They train their models by reversing each operand as 675+163=739. Therefore, the causal model that processes information from left to right can start with the least significant digit and proceed to the most significant digit, which corresponds to the algorithm for addition. They do not achieve any length generalization.

– Kazemnejad et al. [] from 8 to 9-digit ($\bm{1.125\times}$): NoPE + Reversed format. They show that a model without positional encoding trained on reversed additions like 675+163=739 outperforms those with specialized positional encodings like T5’s relative positional [] or RoPE [].

– Shen et al. [] from 10 to 11-digit ($\bm{1.1\times}$): NoPE + Reversed format + random space augmentation. They introduced random spacing between digits, aiming to alleviate the model’s reliance on absolute positional information. Combining this with the reversed format, the running example becomes 6 75+16 3=739. They show that NoPE Transformers length generalize from 10 to 11 digit-addition.

– Zhou et al. [] from 30 to 45 digits ($\bm{1.5\times}$): NoPE + Index Hints. They define "index hints", a formatting that consists in adding a letter in front of each digit in the addition to indicate their position. For instance, the running example becomes a5b7c6+a3b6c1=a9b3c7. This change is applied during training and inference and enables transformers to execute indexing via induction heads [].

– Zhou et al. [] from 40 to 100 digits ($\bm{2.5\times}$): Fire [] + Randomized positional encoding [] + Reversed format + Index Hints . They use a combination of two positional encodings: Fire [], a additive relative positional encoding that has obtained strong length generalization on natural language benchmarks and Randomized positional encoding []: a technique that samples encodings from a range exceeding test-time lengths. The goal is to ensure that Transformers can adapt to larger positional encodings during training and not encounter any OOD encoding at test-time. With reversed format and index hints, the data format looks like a6b7c5+a1b6c3=a7b3c9. By using all these modifications, they reach state-of-the-art performance on length generalization for addition. However, these choices seem to be specific to the addition case and hard to transfer to other algorithmic tasks.

## Appendix C Additional experimental results

To the best of our knowledge, [] achieved length generalization mainly for addition when the two summands had the same length.
Our method generalizes even when the two summands have different lengths.
For $L_{1},L_{2}\in\{17,32,47,62,77,92\}$, we sampled $96$ addition examples where the first summand has length $L_{1}$ and the second summand has length 2.
The accuracy for each combination is shown in Figure 8.
We see that it generalizes well beyond the trained distribution ($L_{1},L_{2}\leq 50$).

Figure: Figure 8: Grid displaying the accuracy of our model on addition when changing the length of each operand. We observe that our model is able to generalize on operands with different lengths.
Refer to caption: x9.png

## Appendix D RASP Turing Programs

### D.1 RASP Python Definitions (from [ 55 ] )

### D.2 Additional Functions (from [ 55 ] )

### D.3 Utility Functions

### D.4 Turing Machine Transition Function

### D.5 Computation of Next Tape State

### D.6 Hashing Functions

### D.7 Next-Token Prediction for Turing Programs

## Appendix E SGD Turing Program Description

We briefly describe here the Turing Program we used in Subsection 5.2.
Beyond the numerical tokens “a0, a1, a2,… a199", we include tokens “$, d, yp, g , cur , |" to aid the calculation.
A typical CoT for a gradient descent then looks like the following:

$$ $ d a179 a166 , a76 d a80 a145 , a102 d a77 a139 , a103 | d a179 a166 , a76 d a80 a145 , a102 d a77 a139 , a103 yp a100 g a101 a99 cur a99 a101 | d a179 a166 , a76 d a80 a145 , a102 yp a101 g a100 a99 cur a99 a102 | d a179 a166 , a76 yp a100 g a120 a117 cur a79 a85 | $$

In the above example, the first line provides a dataset of size three where “d a179 a166 , a76" denotes the first example (“a179"and “a166" are the coordinates of $\vec{x}$, “a76" is the value of $y$, and “d" is a token that denotes the start of an example).
From the second line onward, we perform gradient descent starting from the last data point, working backward:
On the second line, the original dataset is copied, while the “a100" following “yp" is the predicted value of $y$ given the initial weight and the last feature vector “a77 a139", the “g a101 a99" says that $\lambda\nabla_{w_{i}}||y_{i}-\vec{w}_{i}\cdot\vec{x}_{i}||$ has value “a101 a99", and “cur a99 a101" means that the current weight after update is “a99 a101".
After a example’s gradient is calculated, we delete that example.

## Appendix F Turing Programs for Simulating Turing Machines

We use the tokens space $\bm{a_{1}},\bm{a_{2}},\dots,\bm{b_{1}},\bm{b_{2}},\dots,\bm{s_{1}},\bm{s_{2}},
L,R|,(,),\sim,\texttt{
},\texttt{
},\texttt{
}\}$, where the $\bm{a}_{j}$’s are input symbols, the $\bm{b}_{j}$’s are symbols substituting the $\bm{a}_{j}$’s when the head is pointing to them and $(,),|,\sim,L,R$ are symbols used to encode the transitions. For instance, the transition $(\bm{s_{1}},\bm{a_{6}},L)$ means that the Turing machines moves to state $\bm{s_{1}}$, edits the tape by writing $\bm{a}_{6}$ and moves the head to the left.

## Peer Reviews

confidence: 4
contribution: 2
initial_rating: 5
presentation: 2
questions: Q1. Did authors think about other algorithm classes which can be learnt with a copying based CoT? 

Q2. Is there any limitation of this idea for longer sequence, i.e. going with a 3x generalization multiplier? Did authors collected some results there?

Q3. Are there additional tasks the authors think of to show the full potential of this idea? Maybe some graph related tasks?
soundness: 3
strengths: S1. It seems this is the first work which achieves a non-trivial length generalization on arithmetic problems without using data curation or representation tricks and customized positional embeddings to solve arithmetic task. 

S2. Result from Section 5.3 is pretty interesting because of the generalization capability it may bring.

S3. Empirical results on non-trivial tasks shows the effectiveness of their method.
summary: Authors showed that a (very long) CoT which slightly change an input $x_i$ into $x_{i+1}$ up to a point where it solves a problem completely can achieve state-of-the-art results on arithmetic tasks. Authors showed that a bunch of problems can be solved with this approach. Finally authors showed that transformer can indeed implement Turing programs.
weaknesses: W1. The strongest weakness is Theorem 4.1. The code is shown in Appendix D, but the construction proof is not justified at all. 

W2. Authors didn't spend any time on explaining why HAlibi embedding is strongly needed and what practitioners can do to solve similar math problems without using this embedding. In particular it's not obvious how to escape from embedding choice and rely only on the multiple CoT idea. 

W3. In general, ideas and theorems are not well motivated and explained. For example, only Figure 2 explains how to create a synthetic dataset for addition or Figure 4 for multiplication. 

W4. It's not obvious how to extend this idea to fairly similar arithmetic tasks, for example 20-multiplication. 

W5. (minor nit) some citations are reported twice, firstly in black and right after then in blue.

---

confidence: 2
contribution: 2
initial_rating: 6
presentation: 4
questions: None.
soundness: 4
strengths: 1. Good writing, can be followed with relative ease.
2. Meticulous contextualization with respect to the previous work.
summary: A well-presented work on what is in its present state a toy deep learning problem.
weaknesses: 1. While a considerable part of Sections 1 and 2 has been dedicated to justification of the effort and the setting in the context of previous work, one cannot escape the feeling that the overall contribution and subsequent impact of this work are most likely to be minute. The setting of this effort is one where function-calling models already excel with unprecedented precision and at a considerably lower cost. To have a transformer model carry out arithmetic digit-by-digit, albeit in a learnable fashion, is a waste of computational resources, and hence this is not really a good set of experiments to consider.  While the work in its present state hints at a promise, it falls short of demonstrating any potential utility. A suggestion for the future direction of this effort would therefore be to attempt to address some other still "basic" but nevertheless useful tasks such as regular text manipulation or automated formal reasoning.
2. Minor - presentation focus:  The main text seems to assume familiarity with recent developments on algorithmic length generalization while dedicating an entire half-page to the well-known concept of Turing machines. I would suggest re-balancing.

---

confidence: 3
contribution: 2
initial_rating: 3
presentation: 2
questions: 1. Can you provide more experiments with additional baselines to compare length generalization performance under the same experimental setup, including:
   - Various positional encodings with and without the scratchpad.
   - Other prior approaches (e.g., those listed in Appendix B) for addition tasks.
   - Could the methods in Appendix B be applied to multiplication tasks? Would they exhibit non-trivial length generalization abilities?

2. Is it possible that combining effective positional encoding, the scratchpad technique, and improved data formats could yield even better length generalization for addition or multiplication tasks?

3. In line 250, what are the reasons for retaining only the most recent 500 tokens during testing? Is this crucial for achieving better length generalization results, considering that the training and testing context lengths are identical in this setup? An extensive ablation study appears essential to assess the impact of retaining versus dropping past tokens.
soundness: 2
strengths: This work presents a novel approach for improving length generalization by thoughtfully combining two existing methods. The experimental results on random Turing machines effectively demonstrate the proposed methods' applicability to more general tasks.
summary: This paper proposes a method that combines effective positional encoding (Hard-Alibi) with a scratchpad technique to enhance length generalization in Transformers. The authors identify length generalization capabilities of copying task as a potential underlying factor contributing to this enhancement. Empirically, the paper explores the length generalization properties of the proposed methods through tasks involving addition ($n+n$), multiplication ($n\times 1$, $n\times 3$), $n$-sample SGD, and random Turing machines. Theoretically, it investigates the expressive power of Transformers simulating Turing machines.
weaknesses: 1. Although the paper effectively combines appropriate positional encodings with the scratchpad technique to enhance length generalization, it lacks comparative results against a broader array of positional encoding mechanisms and additional baselines under the same experimental conditions.

2. The theoretical section appears disconnected from the experimental findings. While the experiments concentrate on length generalization, the theoretical analysis solely illustrates the expressive power of Transformers in simulating Turing machines. The assumptions made are somewhat strong, and the result of $\exp(n)$ steps renders the theorem less impactful.

Meta-review: This paper proposes "Turing Programs", a  Chain-of-Thought strategy mimicking Turing Machine computations to improve length generalization in transformers for algorithmic tasks. The authors claim universality, demonstrating generalization on addition, multiplication, and in-context SGD, and providing a theoretical argument via RASP programs. 

Strengths: Novel approach, good presentation, strong background and contextualization, and potential for generality.

Weaknesses and what's missing: Limited practical impact (focused on basic arithmetic), insufficient theoretical justification (especially Theorem 4.1), unclear necessity of HAlibi embeddings, lack of exploration of limitations (e.g., longer sequences, repeating n-grams), insufficient experimental validation (missing more complex tasks and ablation studies), and unclear motivation for some ideas.

Reasons for Rejection: Limited impact and practical relevance, insufficient theoretical justification (especially Theorem 4.1), and lack of thorough experimental validation and analysis on practical reasoning tasks. While the idea is interesting and well-presented, these significant weaknesses outweigh the strengths, making the paper unsuitable for ICLR in its current form.

Decision: Reject