Search the guide

Start with a guide

Build

Compile an Exact Sequence Operation

Turn a RASP token-counting program into transformer weights with Tracr and compare the two computations.

Count every occurrence of the token a in a sequence and return that count at each position. Write the rule in RASP, compile it with Tracr, and execute the resulting transformer. Download the complete Python example.

Start with a checkable operation#

The input is a nonempty sequence drawn from a, b, and c, with at most eight tokens. At each position, the program returns the total number of a tokens in the entire sequence. Every position therefore receives the same number.

InputExpected outputWhy
a b a c2, 2, 2, 2Two occurrences of a across four positions.
b b b0, 0, 0No occurrences of a.
a1One occurrence at the single position.
c a a a b3, 3, 3, 3, 3Three occurrences across five positions.

The Python expression [tokens.count("a")] * len(tokens) is a reference implementation. The experiment asks whether the RASP program and the compiled transformer compute that same function.

Write the program in RASP#

RASP expresses sequence computations using sequence-valued operations and selectors. A selector relates each query position to key positions. Here, every query selects the keys whose token is a. SelectorWidth counts how many keys each query selected.

python
from tracr.rasp import rasp

count_a = rasp.SelectorWidth(
    rasp.Select(rasp.tokens, rasp.tokens, lambda key, query: key == "a")
).named("count_a")

print(count_a(["a", "b", "a", "c"]))

The predicate uses the key token and ignores the query token. That is why every position selects the same set of a positions. For a b a c, each query selects positions zero and two, giving width two. For b b b, every selected set is empty, giving zero.

A computation you can inspect

Match each token, then add the matches. Change the sequence or target to see every intermediate value.

a1
b0
a1
c0
Count = 2

This interactive view shows the exact counting computation. The Tracr example below compiles a sequence program into transformer weights.

Install Tracr in a separate environment#

The example uses the official Tracr implementation. The command pins the source revision used by this example. Its dependencies include JAX and Haiku; the small counting program runs on a CPU.

bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install "git+https://github.com/google-deepmind/tracr.git@9ce2b8c82b6ba10e62e86cf6f390e7536d4fd2cd"

Construct the transformer weights#

Tracr compiles the source computation for a declared vocabulary and maximum sequence length. Its compiler constructs the attention and MLP parameters that implement the RASP operations. This example has no gradient-training loop, task dataset, teacher model, or pretrained language model.

python
from tracr.compiler import compiling

model = compiling.compile_rasp_to_model(
    count_a,
    vocab={"a", "b", "c"},
    max_seq_len=8,
    compiler_bos="BOS",
)

for module, arrays in model.params.items():
    for name, value in arrays.items():
        print(module, name, value.shape)

The returned model contains the constructed parameters, input encoder, output decoder, and transformer configuration. Printing model.params shows the numerical arrays that implement the program. Reuse this compiled model for successive sequences within the declared input domain.

The vocabulary and sequence bound are compiler inputs. Changing the counted token edits the source predicate; changing the supported input domain edits the compiler configuration. Recompile after either change.

Execute and compare#

Tracr requires its beginning-of-sequence token on input. Add BOS before the sequence and discard the corresponding first decoded position when comparing the result with the source program.

python
tokens = ["a", "b", "a", "c"]
expected = [tokens.count("a")] * len(tokens)
rasp_output = list(count_a(tokens))
transformer_output = [
    float(value) for value in model.apply(["BOS", *tokens]).decoded[1:]
]

print({
    "input": tokens,
    "expected": expected,
    "rasp_output": rasp_output,
    "transformer_output": transformer_output,
})
assert rasp_output == expected
assert len(transformer_output) == len(expected)
assert all(abs(actual - target) < 1e-5
           for actual, target in zip(transformer_output, expected))

The source operation returns integers. The transformer computes with numerical arrays, so the check compares its decoded values with a small numerical tolerance. Both the source result and the transformer result are printed.

The complete script compiles once and checks several sequences against that same model. Include a sequence with no a tokens: it exercises the empty-selector case.

bash
python tracr_count.py
python tracr_count.py --sequence abac --sequence bbb --sequence aaaaaaaa
python tracr_count.py --all-up-to 4

The last command checks every nonempty sequence of lengths one through four over the three-token vocabulary, plus the default examples. Each JSON line includes the actual RASP output, actual transformer output, and a match flag. A mismatch makes the script exit with a failure status.

What this example establishes#

The computation is explicit before the network is built. RASP supplies the source semantics; Tracr supplies a constructive translation into weights. Reading the source identifies the intended operation, and running both forms exposes disagreements.

This gives interpretability experiments a model with a known program behind its weights. A researcher can compare an analysis of its attention and MLP computations with the computation used to construct them. The Tracr paper develops that use of compiled models.

The PAW urgency example starts from a natural-language policy. Its trained compiler generates a program for a shared interpreter, and test emails check whether that program follows the policy. Both examples retain a neural program for new inputs. They differ in the source language, the compiler construction, the interpreter, and how correctness is established.

For a third construction route, read the Sparks experiment analysis: a general-purpose LLM reasons about numerical weights and edits them. The method comparison puts these routes beside task-specific optimization and learned weight generators.

Sources and resources

Read next