C-RASP

C-RASP interactive editor

C-RASP programs combine Boolean predicates and prefix counts to compute a value at every input position. Write a program, try different input strings, and expand the execution trace to see how its decision is computed.

Background

Explore the ideas behind the editor: the C-RASP language, its connection to transformers, and the assumptions behind length generalization guarantees. Choose a chapter to read its explanation and worked examples.

Chapter overview

Why length generalization?

Why should a rule learned on short sequences keep working on longer ones? Distinguish representability, learning, and generalization.

We want models to apply what they learn to problems larger than those encountered during training. A model trained on short sequences might later need to copy a longer passage, count events across a longer record, or check the structure of a larger program. When the underlying task stays the same, can the model carry out the same computation on inputs longer than the training examples? This is the problem of length generalization.

One motivation is to make better use of training data and computation. Long examples can be costly to collect, annotate, and process, and training cannot cover every input length a model may encounter. If shorter examples are sufficient to learn a reusable rule, we may reduce the need for long training examples while still handling longer inputs at test time. This does not necessarily mean that fewer training examples are needed overall: generalizing across lengths and learning from fewer samples are distinct goals.

Length generalization also asks whether the learned computation continues to work as the task grows. Counting, copying, and checking nested structure provide simple settings in which the same rule applies across lengths. A larger context window allows a model to receive longer inputs, but does not ensure that it processes them correctly. Throughout this tutorial, we therefore distinguish the lengths seen during training from the maximum length the model can process.

To understand what a transformer can learn from shorter inputs, we separate three questions:

  1. Representability: Does there exist a transformer that computes the desired function across input lengths?
  2. Learnability: Can a training procedure find a model that computes the function on the training distribution?
  3. Length-generalizable learnability: Does training on bounded lengths yield a model that also computes the function on longer inputs?

A positive answer to one question does not settle the next. Constructing suitable weights establishes that a computation is possible, but does not show that training will find them. Likewise, perfect accuracy on shorter inputs does not establish length generalization. For example, a rule that checks whether parentheses are correctly nested only up to the maximum training length can agree with the desired recognizer on every training input and fail on every longer valid string. The observations alone do not distinguish that rule from a recognizer that works at all lengths. We therefore need to understand which computations the architecture can represent and which solutions the learning procedure favors.

Our main tool is C-RASP, a small programming language for computations over sequences. Its programs combine predicates on positions with counts over prefixes. A fixed program describes the same computation at every input length, making it possible to state an algorithm without choosing a maximum sequence length. C-RASP also connects these algorithms to transformers: prefix counts can be represented using attention, while feedforward layers implement comparisons and Boolean operations. This connection gives constructive expressivity results; it does not by itself establish a learning guarantee.

We first develop C-RASP through a worked parentheses recognizer and examples of what the language can and cannot express. We then explain its compilation into transformers and the role of positional information. This leads to the length-generalization framework of Huang et al. (2025), which connects suitable representations to eventual generalization under an idealized inference procedure. We keep this guarantee separate from ordinary gradient-based training and discuss what it does, and does not, tell us about the training lengths required. The final sections outline how additional computation through chain of thought changes the question and which limitations remain open.

Foundations

The complexity classes, sequence tasks, and causal transformer model used throughout the tutorial.

Computational complexity

Complexity classes describe which problems can be solved with specified computational resources. For transformers, circuit complexity is useful because it separates the amount of computation performed in parallel from the number of sequential stages.

A Boolean circuit is a directed acyclic graph whose gates compute Boolean operations. Its size is the number of gates; its depth is the longest path from an input to the output. Gates at the same depth can be evaluated in parallel. To recognize inputs of arbitrary length, we use a family of circuits (𝐢𝑛)𝑛β‰₯1, with one circuit for each input length 𝑛. Polynomial size means at most 𝑛{𝑂(1)} gates, while constant depth means a bound independent of 𝑛. We use logspace-uniform families: one algorithm constructs 𝐢𝑛 from 𝑛 using 𝑂(log𝑛) working space, rather than choosing unrelated circuits separately at every length (Immerman, 1999, Chapter 5).

Three circuit classes. The following classes all require polynomial size but differ in their gates and depth:

  • 𝖠𝖒0: Constant-depth circuits with AND, OR, and NOT gates. AND and OR have unbounded fan-in: a single gate may combine arbitrarily many inputs. For example, testing whether a string contains an π‘Ž needs only an OR over the input indicators. Parity cannot be computed in this class.
  • 𝖳𝖒0: Constant-depth circuits that additionally allow unbounded-fan-in majority gates. A majority gate tests whether more than half its inputs are true; this gives the same class as allowing unweighted threshold gates. This class contains both majority and parity.
  • 𝖭𝖒1: Circuits of depth 𝑂(log𝑛) with AND and OR gates of fan-in at most two, and NOT gates. The additional depth allows information to be combined through a tree. For example, a balanced tree of constant-size XOR circuits computes parity in logarithmic depth.

The classes satisfy

𝖠𝖒0βŠ‚π–³π–’0βŠ†π–­π–’1.

The first inclusion is strict; whether the second is strict remains open. Thus, constant depth alone does not determine expressive power: the permitted gates matter as well (Viola, 2023, Chapter 10).

Turing-computable functions. A total function is Turing-computable if a single Turing machine halts and returns its value on every finite input. Unlike the circuit classes above, this imposes no polynomial time or small-depth bound. For a language, the corresponding notion is decidability: the machine must halt with the correct acceptance decision on every input. Computability asks whether an algorithm exists; complexity asks which resources it needs.

Why these classes matter for transformers. A fixed number of transformer layers suggests a bounded number of parallel stages, but a circuit simulation must also account for arithmetic precision and the operations within each layer. With 𝑂(log𝑛)-bit arithmetic and feedforward maps computable in space linear in their input representation, a fixed transformer forward pass can be simulated in 𝖳𝖒0 (Merrill and Sabharwal, 2023). Claims of Turing completeness concern a different resource regime and must specify how computation can grow, for example through additional generated tokens or iterations. Neither a circuit upper bound nor Turing completeness establishes that training will learn a solution that generalizes to longer inputs.

Formal languages and sequence tasks

We use a small set of tasks to study which computations transformers can represent and learn across input lengths. Their rules are easy to state, but involve different operations: counting, tracking order, checking nested structure, and reproducing a sequence. They will serve as running examples throughout the tutorial.

Language recognition. A formal language is a set of finite strings over an alphabet Ξ£. A recognizer decides whether an input string belongs to that set. We consider:

  • Parity: Accept a string over {π‘Ž,𝑏} exactly when it contains an even number of π‘Ž symbols. Encoding π‘Ž as 1 and 𝑏 as 0 gives the usual bit-parity problem. For example, aba is accepted and abb is rejected.
  • Dyck-1: Accept correctly nested parentheses of a single type. Every prefix must have at least as many opening as closing parentheses, and the final counts must agree. For example, ()(()) is accepted, while ())( is rejected despite having equal final counts.
  • Dyck with multiple bracket types: Require both correct nesting and matching bracket types. For example, ([]) is accepted, while ([)] is rejected. Unlike Dyck-1, counting opening and closing brackets alone cannot check that their types match.
  • Flip-flop: For a string over {π‘Ž,𝑏,𝑒}, accept exactly when the last non-𝑒 symbol is 𝑏. The symbol 𝑒 is neutral: appending it leaves the decision unchanged. For example, abee is accepted and baee is rejected. Strings with no π‘Ž or 𝑏, including the empty string, are rejected.

Sequence generation. Copying asks the model to produce an output sequence rather than an acceptance decision. After reading an input and a separator, it must reproduce the input in the same order. Following Huang et al. (2025, Appendix E.2.1), an example is SOS b a b SEP b a b EOS. The paper distinguishes Copy (repeat), with inputs over a binary alphabet that may contain repeated symbols, from Copy (unique), in which all input tokens are distinct. Training loss is applied to the copied sequence and the final EOS token.

Transformer models

We follow the causal transformer model of Huang et al. (2025, Section 2). Its main design choices are:

ChoiceSetting
PositionsNoPE or learned APE.
AttentionCausal softmax, with logits scaled by logπ‘š.
BlocksResidual attention and feedforward layers; fixed depth, width, and head count.
ActivationsReLU or Heaviside.
NormalizationLayerNorm omitted from the formal model.
PrecisionRounded attention logits and exponentials; other activations may have unbounded precision.
ReadoutFinal-position logits for recognition.

Here π‘š includes the beginning-of-sequence token. The details below specify the computation and distinguish the formal model from the experiments.

Transformer equations and numerical assumptions

Inputs and positions. Let 𝑀=𝑀1…𝑀𝑛 be a word over a finite alphabet Ξ£. We prepend a special beginning-of-sequence token, 𝑀0=BOS, and write π‘š=𝑛+1 for the total sequence length. At each position 𝑖, the model maintains a vector β„Žπ‘–β„“βˆˆβ„π‘‘ after layer β„“. The initial vector is

β„Žπ‘–0=𝑒(𝑀𝑖)+𝑝𝑖,0≀𝑖≀𝑛,

where 𝑒 maps token identities to learned vectors. The optional vector 𝑝𝑖 supplies explicit positional information:

  • With no positional encodings (NoPE), 𝑝𝑖=0 at every position. Positions can nevertheless have different representations because causal attention gives them access to different prefixes.
  • With absolute positional encodings (APE), each supported position has a learned vector 𝑝𝑖. The positional table is finite, so a fixed model supports only a finite context window. We discuss how offsets and increasing context lengths enter the generalization framework below.

Causal attention. A model has 𝐿 layers and 𝐻 attention heads per layer. Within layer β„“, head β„Ž applies learned linear maps to the previous layer’s vectors:

π‘žπ‘–=𝑄ℓ,β„Žβ„Žπ‘–β„“βˆ’1,π‘˜π‘—=𝐾ℓ,β„Žβ„Žπ‘—β„“βˆ’1,𝑣𝑗=𝑉ℓ,β„Žβ„Žπ‘—β„“βˆ’1.

The query π‘žπ‘– describes what position 𝑖 uses to score other positions; the key π‘˜π‘— supplies the features against which it is scored. The value 𝑣𝑗 is the information that the head aggregates. Suppressing the layer and head indices, the computation is

π‘Žπ‘–,𝑗=π‘žπ‘–β‹…π‘˜π‘—,
𝛼𝑖,𝑗=exp(π‘ π‘šπ‘Žπ‘–,𝑗)βˆ‘π‘‘=0𝑖exp(π‘ π‘šπ‘Žπ‘–,𝑑),𝑗≀𝑖,
𝑧𝑖=βˆ‘π‘—=0𝑖𝛼𝑖,𝑗𝑣𝑗.

The causal mask excludes positions 𝑗>𝑖: a position can attend to BOS, itself, and earlier tokens, but not to future tokens. All queries, keys, and values in a layer come from the previous layer; the prefix restriction does not turn a layer into a left-to-right recurrent computation. The weights are nonnegative and sum to 1 over the visible prefix, so a head returns a weighted average of its values.

Logit scaling and uniform attention. Ordinary softmax attention uses π‘ π‘š=1. Huang et al. instead use π‘ π‘š=logπ‘š, making the scale depend explicitly on sequence length. For positive π‘ π‘š, the ratio between two attention weights is

𝛼𝑖,𝑗𝛼𝑖,𝑑=exp(π‘ π‘š(π‘Žπ‘–,π‘—βˆ’π‘Žπ‘–,𝑑)).

Thus scaling changes how strongly the head distinguishes unequal scores. If all visible scores are equal, however, every visible position receives weight 1𝑖+1. This is the uniform attention used later to represent prefix counts. The usual fixed factor 1π‘‘π‘˜, where π‘‘π‘˜ is the query/key dimension, can be absorbed into the learned query or key matrices. These equations display the algebraic operations; the rounding convention is stated below.

Residual and feedforward updates. Each head contributes a vector in the model’s width-𝑑 space; its value map incorporates the required output projection. The head outputs are summed and added to the current representation:

𝑒𝑖ℓ=β„Žπ‘–β„“βˆ’1+βˆ‘β„Ž=1𝐻𝑧𝑖ℓ,β„Ž.

The feedforward update is

β„Žπ‘–β„“=𝑒𝑖ℓ+π΅β„“πœ“β„“(𝐴ℓ𝑒𝑖ℓ+𝑏ℓ).

Here 𝐴ℓ maps into the feedforward hidden space, 𝑏ℓ is a bias vector, and 𝐡ℓ maps back to width 𝑑. The activation πœ“β„“ acts coordinatewise. Each coordinate may use ReLU,

ReLU(π‘₯)=max(0,π‘₯),

or Heaviside,

H(π‘₯)={1ifπ‘₯β‰₯00ifπ‘₯<0.

The feedforward map uses the same parameters at every position within a layer. It does not itself combine different positions; that communication occurs through attention. The residual additions retain the preceding representation while adding the attention and feedforward contributions.

LayerNorm. The equations above omit normalization, as does Huang et al.β€˜s main formal model. Their experiments include LayerNorm. Appendix D.3 sketches how to incorporate normalization into the limit-transformer simulation by retaining additional information from which activation norms can be recovered. We therefore distinguish the stated formal model from its proposed extension with normalization. Yang and Chiang’s original C-RASP compilation uses LayerNorm explicitly; we return to its role alongside that construction.

Numerical precision. Huang et al. round attention logits and the outputs of the exponential function to a fixed number 𝑝 of fractional bits before further processing. Rounding to 𝑝 fractional bits restricts these quantities to multiples of 2βˆ’π‘; it does not impose a fixed total bit budget on every number in the computation. Other activations may retain unbounded precision. In particular, this model differs from one that rounds every stored activation and arithmetic result to a fixed number of bits. The circuit upper bound discussed next has its own precision assumptions and should not be transferred to this model without checking them.

Output and computation budget. After 𝐿 layers, a learned linear map produces the output logits

π‘œπ‘–=π‘ˆβ„Žπ‘–πΏ.

For recognition, the output at the final input position 𝑖=𝑛 determines acceptance; for example, a binary readout can compare acceptance and rejection logits. A single forward pass applies the 𝐿 layers once. For a fixed transformer, its parameters, depth, width, and head count do not grow when the input gets longer. Autoregressive generation instead uses the output to append a token and runs another forward pass, introducing additional computation that we consider separately in the chain-of-thought section.

Forward-pass Expressivity

We first ask which languages a fixed transformer can recognize in a single forward pass. Its depth 𝐿, width 𝑑, and number of heads 𝐻 are independent of the input length. Increasing the input length adds positions to the computation, while the number of layers remains fixed.

The circuit classes introduced in the complexity background make this parallel structure precise. Merrill and Sabharwal (2023) show that transformers using 𝑂(log𝑛) bits of arithmetic precision, with feedforward maps computable in space linear in their input representation, can be simulated by logspace-uniform 𝖳𝖒0 circuits. This is an upper bound on their forward-pass expressivity, not a claim that every such circuit can be represented by a transformer.

The precision assumption matters: Huang et al.β€˜s model permits unbounded-precision activations, so this circuit bound does not apply to it directly. Nor does the bound characterize C-RASP: for example, 𝖳𝖒0 contains parity, whereas C-RASP does not. We consider autoregressive generation, which runs further forward passes to generate additional tokens, in the chain-of-thought section.

Programming in C-RASP

Define token predicates and prefix counts, then study a parentheses recognizer and other language examples.

Motivation

  • Why introduce C-RASP?
  • What does it abstract away / capture?

Definition

A C-RASP program is a fixed finite sequence of assignments defining vectors indexed by input positions. Boolean-valued vectors represent predicates on positions; count-valued vectors assign an integer to each position. Assignments are evaluated in sequence, each defining a whole vector from the input and previously defined vectors. Both the number of assignments and the permitted operations are independent of the input length.

Our running example is Dyck-1, the language of correctly nested parentheses over the alphabet Ξ£={(,)}. We will trace the program on the input ()(()).

Input representation. We assume that inputs are words over a finite alphabet Ξ£, corresponding to tokens in a transformer. For each character π‘ŽβˆˆΞ£, we create an initial Boolean vector π‘„π‘Žβˆˆ{0,1}𝑛, where 𝑛 is the input length. Its entry π‘„π‘Ž(𝑖) is 1 if the input character at position 𝑖 is π‘Ž, and 0 otherwise. In other words, each π‘„π‘Ž marks all the positions containing the character π‘Ž.

The two input-marker vectors for our example are:

𝑄(=[1,0,1,1,0,0],
𝑄)=[0,1,0,0,1,1].

Both kinds of vectors have one entry per input position, but their entries mean different things. A Boolean-valued vector answers a yes-or-no question at each position: for example, 𝑄((𝑖) says whether position 𝑖 contains an opening parenthesis. A count-valued vector instead stores a number at each position: 𝐢((𝑖) tells us how many opening parentheses have appeared from the start through position 𝑖. Thus, 𝑄( marks individual tokens, while 𝐢( summarizes prefixes. Prefix counting turns a Boolean predicate into counts; comparing counts, as in 𝑉(𝑖) below, produces a Boolean predicate again.

We now combine these markers into a recognizer.

Prefix counts. First, count how many opening and closing parentheses have appeared up to each position. The notation #[𝑗≀𝑖]𝑃(𝑗) counts the positions 𝑗 up to 𝑖 where the predicate 𝑃 is true:

𝐢((𝑖)≔#[𝑗≀𝑖]𝑄((𝑗)
𝐢)(𝑖)≔#[𝑗≀𝑖]𝑄)(𝑗)

For ()(()), these vectors are 𝐢(=[1,1,2,3,3,3] and 𝐢)=[0,1,1,1,2,3]. Each entry records the count at the corresponding prefix.

Prefix violations. A valid string must never close more parentheses than it has opened. Mark each position where this condition fails:

𝑉(𝑖)≔𝐢((𝑖)<𝐢)(𝑖)

For ()(()), no prefix has more closing than opening parentheses, so 𝑉=[0,0,0,0,0,0].

Then count the positions marked as violations and check whether that count is zero:

𝐢𝑉(𝑖)≔#[𝑗≀𝑖]𝑉(𝑗)
𝑀(𝑖)≔𝐢𝑉(𝑖)=0

For this input, 𝐢𝑉=[0,0,0,0,0,0] and 𝑀=[1,1,1,1,1,1]. In general, 𝑀(𝑖) is true exactly when no prefix ending at or before 𝑖 has violated the nesting condition.

Balanced prefixes. The final condition is that the prefix has equally many opening and closing parentheses:

𝐡(𝑖)≔𝐢((𝑖)=𝐢)(𝑖)
𝐷(𝑖)≔𝑀(𝑖)∧𝐡(𝑖)

For this input, 𝐡=[0,1,0,0,0,1] and 𝐷=[0,1,0,0,0,1]. The prefix () is balanced at position 2, and the entire string is balanced at position 6. Following Yang and Chiang (2024, Definition 3.1), a recognition program must end with a Boolean-valued operation 𝐷 and accepts a word 𝑀 exactly when 𝐷(|𝑀|) is true. Here, 𝐷 is the output vector, and 𝐷(6)=1, so ()(()) is in Dyck-1.

The two conditions are both necessary. The string ())( has equal total numbers of opening and closing parentheses, but it has already closed one too many at position 3. It therefore fails the prefix condition and is rejected.

Reference: all allowed C-RASP operations

The full set of allowed operations is:

Boolean-valued vectors

Input marker𝑃(𝑖)β‰”π‘„π‘Ž(𝑖) for π‘ŽβˆˆΞ£
Negation𝑃(𝑖)≔¬𝑃1(𝑖)
Conjunction𝑃(𝑖)≔𝑃1(𝑖)βˆ§π‘ƒ2(𝑖)
Count comparison𝑃(𝑖)≔𝐢1(𝑖)≀𝐢2(𝑖)
Constant𝑃(𝑖)≔1

Count-valued vectors

Prefix count𝐢(𝑖)≔#[𝑗≀𝑖]𝑃(𝑗)
Conditional𝐢(𝑖)≔𝑃(𝑖)?𝐢1(𝑖):𝐢2(𝑖)
Addition𝐢(𝑖)≔𝐢1(𝑖)+𝐢2(𝑖)
Subtraction𝐢(𝑖)≔𝐢1(𝑖)βˆ’πΆ2(𝑖)
Minimum𝐢(𝑖)≔min(𝐢1(𝑖),𝐢2(𝑖))
Maximum𝐢(𝑖)≔max(𝐢1(𝑖),𝐢2(𝑖))
Constant𝐢(𝑖)≔1

Examples

Below we provide some more examples of C-RASP programms for some formal languages. In contrast we also discuss languages that are not expressible by C-RASP and hence are not expected to length-generalize.

Expressible in C-RASP

π‘Žβˆ—π‘βˆ—

The goal is to accept strings in which every π‘Ž precedes every 𝑏. Thse key idea is to mark an π‘Ž as a violation once a 𝑏 has appeared, then check that there are no violation.

C-RASP Program for π‘Žβˆ—π‘βˆ—
𝐢𝑏(𝑖)≔#[𝑗≀𝑖]𝑄𝑏(𝑗)
𝑆𝑏(𝑖)≔¬(𝐢𝑏(𝑖)≀0)
𝑉(𝑖)β‰”π‘„π‘Ž(𝑖)βˆ§π‘†π‘(𝑖)
𝐢𝑉(𝑖)≔#[𝑗≀𝑖]𝑉(𝑗)
𝑀(𝑖)≔𝐢𝑉(𝑖)=0

Reading the program. 𝑆𝑏 records whether a 𝑏 has appeared; 𝑉 marks an π‘Ž after a 𝑏; and 𝑀 checks that no such position exists.

Check. aaabbb and bbb are accepted; ba is rejected. The empty word also belongs to π‘Žβˆ—π‘βˆ—.

Add equal counts: π‘Žπ‘›π‘π‘›

Now require equally many π‘Ž and 𝑏 symbols, with at least one of each. The following program over {π‘Ž,𝑏} checks block order, equal counts, and nonzero counts:

C-RASP Program for π‘Žπ‘›π‘π‘›
πΆπ‘Ž(𝑖)≔#[𝑗≀𝑖]π‘„π‘Ž(𝑗)
𝐢𝑏(𝑖)≔#[𝑗≀𝑖]𝑄𝑏(𝑗)
𝑆𝑏(𝑖)≔¬(𝐢𝑏(𝑖)≀0)
𝑉(𝑖)β‰”π‘„π‘Ž(𝑖)βˆ§π‘†π‘(𝑖)
𝐢𝑉(𝑖)≔#[𝑗≀𝑖]𝑉(𝑗)
𝑀(𝑖)≔𝐢𝑉(𝑖)=0
𝐸(𝑖)β‰”πΆπ‘Ž(𝑖)=𝐢𝑏(𝑖)
𝑁(𝑖)≔¬(πΆπ‘Ž(𝑖)≀0)
𝐷(𝑖)≔𝑀(𝑖)∧𝐸(𝑖)βˆ§π‘(𝑖)

Reading the program. 𝑆𝑏 records whether a 𝑏 has appeared, and 𝑉 marks any π‘Ž that appears after a 𝑏. The condition 𝑀 requires that there are no such violations, 𝐸 requires equal counts, and 𝑁 requires at least one π‘Ž. The final output 𝐷 combines these three checks. Together they recognize π‘Žπ‘›π‘π‘› for 𝑛β‰₯1; the empty word is excluded.

Check. aabb is accepted. aab fails the count check, while abab has equal counts but fails the order check.

TODO: other programms

Not expressible in C-RASP

Parity. Strings over {π‘Ž,𝑏} containing an even number of π‘Ž symbols. Parity is theoretically expressible by transformers, but both theoreticaly and experimentally it is not learnable. C-RASP can count π‘Ž symbols, but expressing modula properties is not possible. TODO be more precise why Parity not in Crasp

Flip-flop. The language Ξ£βˆ—π‘π‘’βˆ— over Ξ£={π‘Ž,𝑏,𝑒}. Membership depends on the last non-𝑒 symbol being 𝑏. TODO C-RASP can not recover the last occurence of the non-e symbols.

Exercise: three equal blocks

Write a recognizer for strings of the form π‘Žπ‘›π‘π‘›π‘π‘› over {π‘Ž,𝑏,𝑐}, with 𝑛β‰₯1. Extend the two-block construction in three steps:

  1. Compute the three symbol counts.
  2. Mark and count positions that violate the block order.
  3. Combine the order check with equal, nonzero counts in the final Boolean output.

You can use the drag-and-drop C-RASP editor (source and launch instructions) to check your solution on concrete inputs and inspect the intermediate vectors. Test your solution on abc and aabbcc (accept), and on aabcc, acb, and abccba (reject). The last input has equal counts but the wrong order. These tests help catch mistakes; justify separately why your program works for every input length. Use the hint before consulting the solution.

Hint

Start by computing prefix counts for each symbol. Use them to mark positions where the order is broken: an π‘Ž after any 𝑏 or 𝑐, or a 𝑏 after any 𝑐. Count these violations, then combine the no-violation check with a final comparison of the three counts and a check that they are nonzero.

Solution

Use 𝑆bc(𝑖) to mark positions at or after the first 𝑏 or 𝑐, and 𝑆𝑐(𝑖) to mark positions at or after the first 𝑐. The disjunction below is shorthand for negation and conjunction: π‘ƒβˆ¨π‘„β‰”Β¬(Β¬π‘ƒβˆ§Β¬π‘„).

πΆπ‘Ž(𝑖)≔#[𝑗≀𝑖]π‘„π‘Ž(𝑗)
𝐢𝑏(𝑖)≔#[𝑗≀𝑖]𝑄𝑏(𝑗)
𝐢𝑐(𝑖)≔#[𝑗≀𝑖]𝑄𝑐(𝑗)
𝑆bc(𝑖)≔¬((𝐢𝑏(𝑖)≀0)∧(𝐢𝑐(𝑖)≀0))
𝑆𝑐(𝑖)≔¬(𝐢𝑐(𝑖)≀0)
π‘‰π‘Ž(𝑖)β‰”π‘„π‘Ž(𝑖)βˆ§π‘†bc(𝑖)
𝑉𝑏(𝑖)≔𝑄𝑏(𝑖)βˆ§π‘†π‘(𝑖)
𝑉(𝑖)β‰”π‘‰π‘Ž(𝑖)βˆ¨π‘‰π‘(𝑖)
𝐢𝑉(𝑖)≔#[𝑗≀𝑖]𝑉(𝑗)
𝑀(𝑖)≔𝐢𝑉(𝑖)=0
𝐸(𝑖)≔(πΆπ‘Ž(𝑖)=𝐢𝑏(𝑖))∧(𝐢𝑏(𝑖)=𝐢𝑐(𝑖))
𝐾(𝑖)≔¬(πΆπ‘Ž(𝑖)≀0)∧¬(𝐢𝑏(𝑖)≀0)∧¬(𝐢𝑐(𝑖)≀0)
𝐷(𝑖)≔𝑀(𝑖)∧𝐸(𝑖)∧𝐾(𝑖)

π‘‰π‘Ž flags an π‘Ž after a 𝑏 or 𝑐, while 𝑉𝑏 flags a 𝑏 after a 𝑐. Thus 𝑀(|𝑀|) enforces the block order. The conditions 𝐸(|𝑀|) and 𝐾(|𝑀|) require equal, nonzero counts, so the program accepts exactly π‘Žπ‘›π‘π‘›π‘π‘› for 𝑛β‰₯1.

From programs to transformers

How attention and feedforward computations implement C-RASP operations, including the numerical assumptions used by the construction.

C-RASP provides a constructive lower bound on transformer expressivity: any C-RASP program can be simulated by a suitable transformer. Boolean operations are encoded by the transformer’s feedforward layers, while prefix counting is implemented through attention.

The central idea is that uniform causal attention averages a predicate over the visible prefix. The resulting normalized counts share a positive denominator at each position, so comparing them gives the same answer as comparing the integer counts.

Derivation: prefix counting with uniform attention

For an input over a finite alphabet Ξ£, represent the token at position 𝑖 by a one-hot vector π‘₯π‘–βˆˆ{0,1}{|Ξ£|}, where π‘₯𝑖[π‘Ž]=1 exactly when the token is π‘Ž. These coordinates are precisely the C-RASP indicators π‘„π‘Ž(𝑖). A standard transformer’s token-embedding matrix maps this one-hot representation (or its equivalent token ID) to a learned vector.

Counting with attention. Following Counting Like Transformers (Yang and Chiang, 2024), the key idea is that attention can aggregate a predicate over a prefix. At position 𝑖, a causally masked attention head assigns position 𝑗 the weight

𝛼𝑖,𝑗=exp(π‘žπ‘–β‹…π‘˜π‘—π‘‘π‘˜)βˆ‘π‘‘β‰€π‘–exp(π‘žπ‘–β‹…π‘˜π‘‘π‘‘π‘˜),𝑗≀𝑖.

Set π‘žπ‘–β‹…π‘˜π‘—=0 for every visible position 𝑗 (for example, set all keys to zero). Each softmax score is then exp(0)=1, so its normalized weight is 𝛼𝑖,𝑗=1𝑖. With values encoding 𝑃(𝑗), attention returns

Att(π‘₯)𝑖=βˆ‘π‘—β‰€π‘–π›Όπ‘–,𝑗𝑃(𝑗)=1π‘–βˆ‘π‘—β‰€π‘–π‘ƒ(𝑗)=#[𝑗≀𝑖]𝑃(𝑗)𝑖.

Thus attention can encode the C-RASP prefix count 𝐢(𝑖)≔#[𝑗≀𝑖]𝑃(𝑗) as the normalized count

𝐢̃(𝑖)≔𝐢(𝑖)𝑖.

At each position 𝑖, count values share the positive normalization factor 1𝑖, so comparisons between them are unchanged. Counts can also be combined using arithmetic and conditional selection, as described below. Constants must use the same encoding: the integer constant 1 is represented by 1𝑖, and more generally a constant 𝑐 by 𝑐𝑖.

For Dyck-1, for example, 𝐢( becomes 𝐢(Μƒ=[1,1/2,2/3,3/4,3/5,1/2]. Both opening- and closing-counts share divisor 𝑖, so their comparisons-and hence the prefix-balance testβ€”are unchanged.

Arithmetic and numerical precision

Sums, differences, minima, maxima, and conditional selection also preserve this shared divisor, allowing normalized counts to flow through the program. Distinguishing adjacent normalized counts requires resolution on the order of 1𝑖, so a fixed number of fractional bits cannot suffice at arbitrary lengths. This motivates allowing logarithmic precision for these attention results: for inputs of length at most 𝑛, log2(𝑛)+𝑂(1) fractional bits give resolution finer than the smallest adjacent-count gap 1𝑛. This observation concerns the resolution of the normalized counts, rather than a guarantee that rounding every intermediate computation to this precision preserves the full simulation.

Constants and the BOS token

The simplified calculation above omits the beginning-of-sequence (BOS) token used in the full construction. With BOS preceding the 𝑖 ordinary input tokens, uniform attention averages over 𝑖+1 positions. Assigning value 1 at BOS and 0 elsewhere therefore yields 1𝑖+1, the normalized encoding of the integer constant 1. Ordinary predicates are false at BOS, so their counts are encoded as 𝐢(𝑖)𝑖+1. Counts and constants thus share the same denominator (Yang and Chiang, 2024, Appendix B.2).

How LayerNorm is handled

For clarity, this explanation omits LayerNorm, but it can be accounted for in the compilation. Yang and Chiang (2024, Section 5.2 and Appendix B.3) use paired coordinates with opposite signs, ensuring zero mean so that LayerNorm applies a shared scaling factor at each position. Their construction handles this scaling when implementing Boolean values and count comparisons.

Putting these constructions together, any fixed C-RASP program can be compiled into a transformer whose depth and width are independent of the input length.

This compilation establishes representability, but does not imply that training will find the constructed solution. Empirical studies nevertheless find that C-RASP expressibility predicts length generalization on a range of algorithmic and formal-language tasks (Huang et al., 2025).

Positional information

How positions enter the model, from finite positional tables to limit transformers and positional predicates.

So far, we have not used explicit positional embeddings. Positions are distinguished only by their tokens and the information available from their prefixes through causal attention. Positional embeddings provide an additional, explicit representation of where each token occurs. Here we consider absolute positional embeddings: each position 𝑖 has its own learned vector 𝑝𝑖, which is added to the token embedding 𝑒(π‘₯𝑖):

β„Žπ‘–=𝑒(π‘₯𝑖)+𝑝𝑖.

Finite positional tables and offsets

The position vectors are stored in a finite table, so the model is defined only up to its maximum context length 𝐿. To train the embeddings across this table using shorter examples, the offset trick assigns an example of length π‘˜ the positional vectors π‘π‘œ+1,…,π‘π‘œ+π‘˜ for a valid offset π‘œ. Varying the offset allows training examples to occur throughout the context window, but does not guarantee that every position is observed in a finite training run or teach the model to generalize to longer examples. Since the table is still finite, the C-RASP simulation cannot be realized by one such fixed transformer for inputs of arbitrary length. Instead, consider a sequence of transformers with increasing context lengths and corresponding positional tables. To describe the underlying computations across these context lengths, the framework introduces a mathematical object called a limit transformer.

Limit transformers

A limit transformer is an idealized model that captures the positional information provided by positional embeddings while remaining defined on inputs of arbitrary length. It has fixed width and finite-precision parameters. Besides positional vectors 𝑝𝑖, it can use an additional positional function in each attention head. Writing 𝑖 for the query position and 𝑗 for the key position, the attention logit has the form

π‘Žπ‘–,𝑗𝑙,β„Ž=π‘žπ‘–π‘™,β„Žβ‹…π‘˜π‘—π‘™,β„Ž+π‘Ÿπ‘™,β„Ž(𝑖,𝑗).

The term π‘Ÿπ‘™,β„Ž(𝑖,𝑗) directly expresses a relation between positions, such as whether 𝑗 immediately precedes 𝑖. This allows the model to describe positional interactions at every input length without storing a separate learned vector for every position in a growing table.

For the length-generalization result, the positional vectors must be periodic, and the additional positional functions must be translation-invariant and local. Below, π‘Ÿ denotes the positional function of one attention head, with query position 𝑖 and key position 𝑗≀𝑖.

Periodicity. The positional vectors repeat with a fixed positive integer period Ξ”:

𝑝𝑖+Ξ”=𝑝𝑖for every𝑖β‰₯1.

For example, period 2 allows alternating vectors (𝑒,𝑣,𝑒,𝑣,…) for odd and even positions. The sequence is infinite, but only Ξ” vectors need to be specified, independently of the input length.

Translation invariance. Shifting both positions equally leaves the interaction unchanged:

π‘Ÿ(𝑖+𝑠,𝑗+𝑠)=π‘Ÿ(𝑖,𝑗)for every integer𝑠β‰₯0.

For example, assigning score 1 to the preceding position and 0 elsewhere treats (2,1) and (8,7) identically. Singling out absolute position 𝑗=1 would violate translation invariance.

Locality. The additional positional interaction vanishes beyond a fixed nonnegative integer distance 𝜏:

π‘Ÿ(𝑖,𝑗)=0wheneverπ‘–βˆ’π‘—>𝜏.

The preceding-position example is local with 𝜏=1. Assigning score 1 at every even distance is translation-invariant but not local. This restriction applies only to π‘Ÿ; content-based attention can still aggregate over the entire prefix.

Positional information in C-RASP

We can express the same kinds of information at the program level by extending C-RASP to C-RASP[Ξ¦,Ξ¨]. Here, Ξ¦ is a collection of Boolean predicates on individual positions, and Ξ¨ is a collection of Boolean relations between pairs of positions. We add positional predicates

𝑃(𝑖)β‰”πœ‘(𝑖),πœ‘βˆˆΞ¦,

and allow counting to be restricted by a positional relation:

𝐢(𝑖)≔#[𝑗≀𝑖,πœ“(𝑖,𝑗)]𝑃(𝑗),πœ“βˆˆΞ¨βˆͺ{⊀}.

This counts positions 𝑗 for which both 𝑃(𝑗) and πœ“(𝑖,𝑗) hold. Ordinary prefix counting remains a separate allowed primitive, represented here by the always-true relation ⊀. The locality restriction applies to relations in Ξ¨, not to this unrestricted prefix-counting operation.

For example, a unary predicate πœ‘(𝑖) can mark the even positions. A binary relation πœ“(𝑖,𝑗) can hold exactly when 𝑗=π‘–βˆ’1. Counting with this relation gives 1 if the preceding position satisfies 𝑃, and 0 otherwise, including when no preceding position exists. Comparing this count with 0 therefore lets a program test the preceding token.

When the predicates in Ξ¦ are periodic and the relations in Ξ¨ are translation-invariant and local, we obtain the variant we denote by C-RASP[Pos] throughout this tutorial. This abbreviates the notation C-RASP[periodic,local] used by Huang et al. (2025). The position-free language introduced earlier is the special case with no added positional predicates or relations.

Length generalization guarantees

What the idealized learning framework guarantees, and what it leaves unresolved about practical training and required input lengths.

A C-RASP program specifies one computation that works at every input length. Compiling it into a transformer establishes that the computation is representable. Length generalization asks a further question: can a learner identify such a computation from its behavior on shorter inputs?

Training length and context length

To formalize this question, we must separate the lengths seen during training from the lengths the model can process. A model with context length 𝑛 can be tested on longer examples than it has seen, but only up to length 𝑛. Success within one fixed window therefore cannot establish generalization to arbitrarily long inputs. Huang et al. (2025) address this by considering a sequence of transformers 𝑇𝑛 with increasing context length 𝑛. For each 𝑛, an idealized learner observes the target function 𝑓 on all inputs of length at most 𝑛2 and selects 𝑇𝑛. We ask whether, for every sufficiently large 𝑛, this model also computes 𝑓 correctly on all unseen lengths between 𝑛2 and 𝑛.

This definition captures the idea that, once the learner has seen sufficiently long examples, its solution continues to work at greater lengths. Increasing the context window prevents the model’s finite positional table from setting an arbitrary ceiling on the analysis, while leaving the longer inputs unseen makes extrapolation necessary. The factor of two is a convenient choice, rather than an essential assumption of the framework. Observing all inputs through the training length also isolates generalization across lengths from the separate problem of learning from a finite sample. The resulting guarantee concerns this idealized inference procedure; it does not say that one trained finite-context model can process inputs of every length.

The idealized learner

The learner must fit every input through the training length and approximately minimize a complexity regularizer. Its positional contributions must also satisfy an offset-independence restriction. This is an idealized inference procedure; ordinary gradient-based training need not satisfy these assumptions.

Formal selection rule and positional restrictions

The selection rule requires 𝑇𝑛 to match 𝑓 exactly on all inputs through the training length and to approximately minimize a particular complexity regularizer among the models that do so. This regularizer controls quantities such as depth, precision, parameter norms, and positional interactions. The width 𝑑 is not explicitly bounded by the hypothesis class. More precisely, let π‘ˆπ‘› be the set of admissible models that match 𝑓 on all inputs of length at most 𝑛2, at every valid offset. The procedure selects π‘‡π‘›βˆˆπ‘ˆπ‘› satisfying

β„›οΈ€(𝑇𝑛)≀infπ‘‡βˆˆπ‘ˆπ‘›β„›οΈ€(𝑇)+1𝑛.

Why approximate minimization? An exact minimizer need not exist: the infimum may not be attained by any model in π‘ˆπ‘›. The allowance 1𝑛 makes approximate minimization sufficient, with an error that vanishes as 𝑛 grows (Huang et al., 2025, Definition 6).

A separate restriction concerns how the model uses positional information. Although the embeddings 𝑝𝑖 may vary across positions, the parameter products through which they contribute to the computation must be unchanged when all positions are shifted equally. This is stronger than requiring the same final prediction at every offset: the underlying computation must use positional information in the same way. For example, an interaction based on the distance between two positions survives such a shift, whereas one tied to a particular absolute position generally does not.

The main equivalence

Under the framework’s assumptions, Huang et al. (2025, Theorem 7) establish that the following statements are equivalent:

  1. Representation: The target function 𝑓 is representable by a limit transformer with periodic positional vectors and translation-invariant, local additional positional interactions.
  2. Identification with bounded complexity: Any sequence 𝑇𝑛 selected by the idealized inference procedure has uniformly bounded regularizer values and eventually generalizes. That is, there are constants 𝐢 and 𝑁0 such that β„›οΈ€(𝑇𝑛)≀𝐢 for every 𝑛, and for every 𝑛>𝑁0, 𝑇𝑛 matches 𝑓 on all inputs of length at most 𝑛, despite having fitted it only through length 𝑛2.

The forward direction shows that such a representation guarantees eventual generalization with bounded complexity under the inference procedure. The reverse direction shows that a sequence selected by this procedure with both properties implies the existence of such a representation. Bounded regularization is part of this equivalence: eventual generalization alone is not the condition being characterized.

The procedure itself requires approximate minimization of the regularizer, rather than a prescribed uniform bound 𝐢. When the representation in the first statement exists, the theorem guarantees that the selected sequence remains uniformly bounded.

Intuition: eliminating incorrect candidate algorithms

Why is this possible? Under the theorem’s assumptions, bounded complexity leaves only finitely many candidate underlying algorithms. Any incorrect candidate disagrees with 𝑓 on some finite input. As the training length increases, that input eventually becomes visible and rules out the candidate. Once every incorrect candidate has been eliminated, the remaining algorithms agree with 𝑓 at every length. This is a statement about the computations identified by the learner; it does not require the parameter vectors to converge to a unique set of weights.

What follows for C-RASP?

The compilation introduced above connects C-RASP[Pos] directly to the main equivalence: every such program supplies a limit-transformer representation satisfying the theorem’s restrictions. Expressing a target function in C-RASP[Pos] therefore guarantees eventual generalization with bounded regularization under the idealized inference procedure. This is a sufficient condition; the converse claim that every such limit transformer has an equivalent C-RASP[Pos] program is not established.

How much training length is enough?

Eventual identification does not provide a practical stopping rule. Yang et al. (2026), in Length Generalization Bounds for Transformers, show that no computable bound in terms of program description size exists for general C-RASP, even at counting depth two, with a corresponding result for the transformer model considered there. This concerns the maximum input length needed to distinguish candidate programs, rather than simply the number of training examples. The same work also identifies a restricted positive fragment, C-RASP+, for which a computable bound does exist: the required training length is exponential in program description size, and this bound is optimal in the worst case. This fragment restricts count comparisons to nonnegative linear combinations of counts against constants. It is expressively equivalent to the paper’s fully fixed-precision transformer model, for which the authors also obtain exponential bounds.

Limitations and open questions

Directions for further exploration, including chain of thought, richer formalisms, and limitations of the transformer model.

Chain of thought

  • Can CoT increase expressivity? (and how to fix this)
  • C-RASP CoT

Further directions

  • Open C-RASP conjecture
  • Incomputable bound
  • Extensions of C-RASP
  • how the model differs from real transformers (e.g., precision, attention, etc.)
  • Other formalisms of length generalization (RASP-L etc.)

References

The papers and other sources cited throughout the tutorial.

Neil Immerman. 1999. Descriptive Complexity. Springer. Chapter 5: Parallelism.
Emanuele Viola. 2023. Mathematics of the Impossible, Chapter 10: Constant-depth circuits. Author’s chapter.
William Merrill and Ashish Sabharwal. 2023. The Parallelism Tradeoff: Limitations of Log-Precision Transformers. Transactions of the Association for Computational Linguistics, 11:531–545. ACL Anthology.
Andy Yang and David Chiang. 2024. Counting Like Transformers: Compiling Temporal Counting Logic Into Softmax Transformers. COLM. arXiv:2404.04393.
Xinting Huang, Andy Yang, Satwik Bhattamishra, Yash Sarrof, Andreas Krebs, Hattie Zhou, Preetum Nakkiran, and Michael Hahn. 2025. A Formal Framework for Understanding Length Generalization in Transformers. ICLR. arXiv:2410.02140.
Andy Yang, Pascal BergstrÀßer, Georg Zetzsche, David Chiang, and Anthony W. Lin. 2026. Length Generalization Bounds for Transformers. arXiv:2603.02238.