A Transformer Without Training: 40 Digits, Exactly

Set every weight by hand in NumPy. A transformer without training adds 40-digit numbers exactly, while a trained model of the same shape fails past 13.

Cover Image for A Transformer Without Training: 40 Digits, Exactly

Suppose you want a model to add two numbers, and you want to inspect every step of the calculation. With a trained transformer, you would first have to work out which operations its weights learned. For a small computation whose steps you already know, you can work in the other direction and write those weights yourself. A transformer without training can then run the calculation on its first forward pass, giving you a model whose intended behaviour you can check from the start.

That makes these models useful for studying how transformers compute. Weiss, Goldberg and Yahav's RASP language (2021) describes programs using attention and elementwise maps, and Lindner and colleagues' Tracr compiler (2023) turns such programs into transformer weights. Interpretability researchers can use the resulting models as ground truth because the circuit was specified in advance. The same idea has also been taken much further, including a 21-billion-parameter transformer assembled to render Doom in 2026. Here, the computations are small enough to follow by hand.

Writing the weights turns the architecture inside out. The residual stream stops being an opaque vector and becomes a set of registers you named. Attention stops being a learned affinity and becomes a lookup you specified. An MLP stops being a black box and becomes a function table you built out of ReLUs.

By the end of this post you will have three working transformers in NumPy, none of them trained: one that reverses a sequence, one that counts, and a nine-dimensional two-layer adder that is exact on 40-digit numbers. Then you will train a transformer of the same shape on the same task and find out where it stops.

Let's Build It

Open this in Colab and run it top to bottom. There is no training, so it finishes instantly.

Open In Colab

Here is a transformer that reverses a sequence. One attention head, no MLP, every number chosen by hand.

import numpy as np

def attention(x, w_q, w_k, w_v, w_o):
    scores = (x @ w_q) @ (x @ w_k).T
    w = np.exp(scores - scores.max(-1, keepdims=True))
    w = w / w.sum(-1, keepdims=True)
    return w @ (x @ w_v) @ w_o, w

def build_reverser(vocab=10, n=8, beta=100.0):
    d = vocab + n + vocab                        # token block, position block, output block
    w_e = np.zeros((vocab, d)); w_e[:, :vocab] = np.eye(vocab)
    w_p = np.zeros((n, d));     w_p[:, vocab:vocab + n] = np.eye(n)

    w_q = np.zeros((d, n))
    for i in range(n):
        w_q[vocab + i, n - 1 - i] = beta         # position i asks for position n-1-i
    w_k = np.zeros((d, n));     w_k[vocab:vocab + n] = np.eye(n)
    w_v = np.zeros((d, vocab)); w_v[:vocab] = np.eye(vocab)
    w_o = np.zeros((vocab, d)); w_o[:, -vocab:] = np.eye(vocab)
    w_u = np.zeros((d, vocab)); w_u[-vocab:] = np.eye(vocab)
    return w_e, w_p, (w_q, w_k, w_v, w_o), w_u

Run it.

w_e, w_p, head, w_u = build_reverser()
seq = [3, 1, 4, 1, 5, 9, 2, 6]

x = w_e[seq] + w_p                               # the residual stream
delta, pattern = attention(x, *head)
print(((x + delta) @ w_u).argmax(-1))
[6 2 9 5 1 4 1 3]

That is the input backwards, and nothing was fitted to produce it. The attention pattern shows why.

Attention pattern of the hand-built reverser, a clean permutation matrix

Every row puts weight 1.00 on exactly one column: row ii picks column n−1−in-1-i, so the weights run from the bottom-left corner to the top-right. A softmax that normally spreads a soft average over the sequence is behaving as a permutation matrix, because that is what the query and key matrices ask it to do.

What Just Happened?

The residual stream as named registers

A transformer's residual stream is a vector per position that every layer reads from and writes to. In a trained model, features are distributed across that vector in whatever superposed arrangement gradient descent found, which is what makes reading circuits out of a trained network hard work.

Setting the weights yourself, you get to allocate the space first. The reverser uses three blocks of dimensions: ten for the token identity, eight for the position, ten for the answer. w_e writes a one-hot token into the first block, w_p writes a one-hot position into the second, and the attention head's output matrix w_o writes into the third. Nothing overlaps, so nothing interferes.

The adder later in this post takes the idea further and gives every dimension a name.

The adder's residual stream: nine named dimensions, coloured by which layer writes each one

Nine dimensions, nine jobs. The embedding fills four of them, the first MLP three more, the attention head one, and the last MLP one. Reading a layer's weights is then a matter of reading which registers it takes as input and which it writes.

Attention as a lookup table

An attention head computes softmax(qi⋅kj)\text{softmax}(q_i \cdot k_j) over positions jj, then averages the values at those positions with those weights. Two matrices decide where it looks.

The reverser's query matrix maps the one-hot for position ii to the one-hot for position n−1−in-1-i. Its key matrix is the identity on the position block, so kjk_j is the one-hot for jj. The dot product is therefore 1 when j=n−1−ij = n-1-i and 0 everywhere else:

qi⋅kj=β 1[ j=n−1−i ]q_i \cdot k_j = \beta \, \mathbb{1}[\, j = n - 1 - i \,]

Read the loop that builds w_q again and it is a lookup table written as a matrix. Row vocab + i, column n - 1 - i. Attention is doing an array index, and the index is one you wrote.

The value and output matrices carry the payload. w_v reads the token block, w_o writes into the output block, and the unembedding reads the output block. The head moves a token from one position to another and leaves everything else alone.

The temperature knob

Softmax is a soft argmax, which is a problem when you want an exact computation. beta is the fix: scaling w_q by β\beta scales every score by β\beta, and softmax over scores β⋅sj\beta \cdot s_j is softmax at temperature 1/β1/\beta. Push β\beta up and the distribution collapses onto the argmax.

How high it has to go depends on what reads the result, and the two constructions in this post disagree by three orders of magnitude.

Two panels: attention mass on the target position against beta for the reverser, and exact-match accuracy against beta for the adder

The reverser is forgiving. Its output is already correct at β=0.75\beta = 0.75, where only a quarter of the attention mass sits on the right position and three quarters is smeared over the others. The unembedding takes an argmax, and a token that wins by a nose wins outright. Attention mass does not reach 1.000 until β≈10\beta \approx 10, long after the answers stopped changing.

The adder has no argmax to hide behind. Its attention output is a carry bit that goes straight into arithmetic, and a carry of 0.7 is a wrong carry. At β=56\beta = 56 it gets 12% of 8-digit sums right, at β=100\beta = 100 it gets 63%, and it reaches 1.000 only at β=562\beta = 562.

Read those two panels together and you have the real rule. A soft attention pattern is harmless when the next thing that happens is a comparison, and fatal when the next thing is a sum. Real transformers divide scores by dhead\sqrt{d_{\text{head}}} to keep them small, because large scores saturate the softmax and kill its gradient. That divisor exists to make training work. With no training to protect, saturation is the goal.

Going Deeper

Counting with a head that averages

Here is the second construction, and the reason transformers struggle with arithmetic. Set the query and key matrices to zero. Every score is then 0, softmax spreads attention evenly, and the head returns the plain mean of its values. Set w_v to fire on one token and the head returns the fraction of positions holding that token.

A fraction is not a count. To recover the count you multiply by the sequence length, which the model does not know unless you tell it.

Counting head: correct at the length its MLP was built for, wrong at every other length

The MLP here was built for n=8n = 8, and at n=8n = 8 it reads out 1, 2 and 3 correctly. Hand it a sequence of 12 and the same head writes 0.1667 for a true count of 2; the MLP multiplies by 8 and reports 1. At n=16n = 16 a count of 3 comes back as 1.

Attention gives you a weighted average and nothing else. Anything that needs a sum has to reconstruct it from a mean and a length, and every length-dependent constant you bake in is a length you will later fail at. Hold onto that, because it comes back at the end of this post.

An MLP as a function table

A transformer MLP is Wout relu(Winx+b)W_{\text{out}} \, \text{relu}(W_{\text{in}} x + b). With one ReLU layer you can build any piecewise-linear function of a scalar register, and on integer inputs that includes indicator functions.

Column addition needs two of them. Let t=a+bt = a + b be the sum of one column's digits, before any carry. Then:

generate=1[t≥10],propagate=1[t=9]\text{generate} = \mathbb{1}[t \geq 10], \qquad \text{propagate} = \mathbb{1}[t = 9]

A column generates a carry when its digits already reach ten, whatever arrives from below. A column propagates when it sums to exactly nine, so it passes on whatever arrives and nothing more. Both are three ReLUs and a subtraction:

generate  = relu(t - 9) - relu(t - 10)
propagate = relu(t - 8) - 2 * relu(t - 9) + relu(t - 10)

Three ReLU ramps on the left, and the step and spike they combine into on the right

The left panel shows the three ramps. The right shows what the output matrix makes of them: a step at 10 and a spike at 9. Neither is exact for real-valued tt, and neither has to be. Digits are integers, so the function is only ever asked at 19 points, and it is exact at all of them.

Carry lookahead in a single attention layer

Now the part that decides the whole post. School addition ripples: you add a column, and if it carries you go up one column and repeat. A ripple of nn steps needs nn sequential operations, and a fixed-depth transformer does not have nn layers.

Carry lookahead solves it in one shot. The carry into column ii is fully determined by the nearest column below ii that does not propagate:

ci=generatej∗,j∗=max⁡{ j<i:propagatej=0 }c_i = \text{generate}_{j^*}, \qquad j^* = \max \{\, j < i : \text{propagate}_j = 0 \,\}

Every column between j∗j^* and ii propagates, so whatever leaves j∗j^* arrives at ii unchanged. Column j∗j^* itself either generates a carry or kills one, and it does so without reference to anything below it. The recursion is gone.

"The nearest earlier column satisfying a predicate" is exactly what an attention head does. Every column asks the same question, so the query is constant. The key ranks columns first by not propagating, then by position:

w_q[reg["one"], :] = beta                # every column asks the same thing
w_k[reg["one"], 0] = 1.0                 # k[0] = 1 - propagate
w_k[reg["prop"], 0] = -1.0
w_k[reg["idx"], 1] = eps                 # k[1] = eps * position, the tie-break
w_v[reg["gen"], 0] = 1.0                 # the value carried back is `generate`

With ε\varepsilon small enough that the position term can never outweigh the propagate term, the argmax is the nearest non-propagating column below ii, and the value it returns is that column's generate bit. One layer, any length of carry.

Two details make it work. The mask is j<ij < i rather than a decoder's usual j≤ij \leq i, because a column's carry comes from columns below it and never from itself. And position 0 holds a sentinel token with both bits zero, so the lookup always has something to land on and a column with no generator below it correctly reads a carry of zero.

Watch it run on 4999 + 1, where a carry born in the lowest column has to travel three columns to reach its destination.

The residual stream of the hand-built adder filling in one register at a time, each labelled with the layer that writes it

from transformer_by_hand_core import build_adder, add_with_transformer

model, reg = build_adder()
print(add_with_transformer(model, 4999, 1, width=5))
5000

The static version of the same trace, stage by stage:

Four heatmaps showing the adder's registers after embedding, after MLP 0, after the carry lookup and after MLP 1

After the embedding, only a, b, idx and the constant are set. MLP 0 fills in sum, generate and propagate: column 1 generates, columns 2 and 3 propagate, column 4 does neither. The attention layer then fills carry, and MLP 1 turns sum + carry into the output digit by subtracting 10 where needed.

The carry row is where the lookahead shows. Columns 2, 3 and 4 each read a carry of 1, and all three read it from the same place: column 1, the only column below them that generates. That is the ripple flattened, three columns asking one question of one source in a single layer rather than passing a value up a chain. Column 5 reads from column 4, the nearest non-propagator below it, and gets a carry of 0.

The whole model in 397 numbers

The adder has nine dimensions in its residual stream, two blocks, and one live attention head. The head in block 0 has its output matrix set to zero, which is how you write "this head does nothing"; trained models turn out to be full of heads doing about as much.

Counting every entry that is not zero gives 397 numbers, and most of them are lookup tables rather than computation: 281 in the token embedding, which is a 101-row table of digit pairs, and 63 in the positional embedding. The two blocks that do the work hold 53 non-zero numbers between them, and all of them are integers or simple fractions.

The payoff for that discipline is that nothing in the computation refers to the length of the input. The positional embedding is filled from a formula, εi\varepsilon i, so its table extends to whatever length you want. The carry lookup is a comparison, not a fixed offset. The model is therefore exact at every length tested:

Digits per operand481216203040
Exact match1.0001.0001.0001.0001.0001.0001.000

That is 400 random pairs at each width, and it holds on adversarial inputs too. Force the carry to travel every column, and the accuracy stays at 1.000.

One caveat, and it is the interesting kind. The tie-break that picks the nearest non-propagating column separates neighbours by βε\beta \varepsilon in the scores, and ε\varepsilon shrinks as you make room for more positions. At the 64 positions used here, that gap is 4000/128≈314000/128 \approx 31, so the loser gets a weight around 10−1410^{-14} and float64 has room to spare. Support ten times as many positions and ε\varepsilon falls tenfold, so β\beta has to rise tenfold to keep the same gap. The construction has no length limit; the number format does. Pérez and colleagues make the same point formally when they assume arbitrary precision, and it is easy to skip over in a proof and hard to skip over in NumPy.

The same architecture, trained

Now the honest closing question, and the one the construction cannot answer on its own. A hand-built circuit proves that the architecture can represent the algorithm. It says nothing about whether gradient descent finds it.

So train one. Same tokens, same task, same two blocks and one head, with the weights initialised randomly and fitted by AdamW on random operands. Nothing in the setup is stacked against it: the trained model gets a residual stream ten dimensions wide against the hand-built nine, or 64 dimensions in the larger run, and an MLP four times wider than anything the construction needs.

It learns the task. At the width it was trained on, the 64-dimensional model reaches exact match on random operands, and it holds on the adversarial inputs too. Random 4-digit operands produce a carry that travels more than one column only 13% of the time, and more than two columns under 1% of the time, so a model that handled the common case and guessed the rest would still score well. Forcing the carry to ripple across all four columns is where that model breaks.

Columns the carry travels1234
Hand-built, 9 dimensions1.0001.0001.0001.000
Trained, 10 dimensions1.0000.9990.9840.953
Trained, 64 dimensions1.0001.0001.0001.000

The wider model does not break. Training finds a working carry mechanism, not a lookup of common cases. The 10-dimensional model, the one closest in size to the hand-built adder, is less sure of itself and slips as the chain lengthens, which is what running out of room looks like.

Its attention says something similar. Here is the trained model's two heads beside the hand-built lookup, on the same 4999 + 1.

The hand-built carry lookup beside the trained model's two attention heads on the same input

The trained model returns 5000, so this is a comparison of two working circuits. Its first head attends one column back, and its second has columns 2, 3 and 4 converging on a single column, the same many-to-one shape as the hand-built lookup, anchored one column later. That reads as a shift head feeding a lookahead: block 0 moves each column's information up by one, and block 1 does the convergent search over the shifted copy. Elhage and colleagues would call it Q-composition, and it is what the hand-built model does too, with the shift absorbed into a tighter mask instead of a head.

Whatever training found here, it is not a different family of algorithm.

The length cliff

Then ask for one more digit than training ever showed it.

Exact-match accuracy against operand length: the hand-built model flat at 1.0, the trained models falling off a cliff at the edge of their training range

The model trained on widths 1 to 12 is exact through 12 and then falls off a cliff. At 13 digits, one more than it ever saw, 0.424 of the sums come back right. At 14 it is 0.237, and by 20 it is at zero. The model trained on width 4 alone is worse still: 0.454 at width 5.

The obvious suspect is the positional embedding. A learned lookup table has nothing in the rows for positions that never appeared, so of course it fails. That explanation is testable, and it accounts for one digit. Swap the learned table for fixed sinusoids, a formula defined at every position, retrain, and 13 digits comes back at 0.958 instead of 0.424. Then it falls off the same cliff, 0.619 at 14, 0.226 at 16, zero at 20.

So the position table was a small part of it and not the cause. The circuit is length-bound somewhere else, and no amount of accuracy inside the training range tells you where. The counting head earlier in this post failed the same way for a reason we could name: its MLP had the sequence length baked in as a constant. The trained adder fails the same way for a reason its attention patterns do not reveal.

That is what a hand-built model is for. Nobody needs a transformer to add, so the construction earns its place as a specimen with a known circuit rather than as an adder. Holding it next to a trained one turns vague questions into sharp ones. Both models compute carries. Both use a convergent lookup. One runs at 40 digits and the other stops at 13, and the difference is not visible in the loss, not visible in the in-distribution accuracy, and not visible in the attention. Representability was the cheap part: nine dimensions and 397 numbers. Finding a representation that holds outside the data you trained on is the part still open.

Where This Comes From

Weiss, Goldberg and Yahav (2021), "Thinking Like Transformers" gave this practice a language. RASP has two primitives that mirror the architecture: select builds a boolean attention matrix from a predicate over pairs of positions, and aggregate averages values under it, with elementwise maps for everything a feedforward layer would do. The paper's discipline is to write a program in those primitives and then argue about how many layers and heads it needs.

We propose a computational model for the transformer-encoder in the form of a programming language, the Restricted Access Sequence Processing Language (RASP). [...] We show how a RASP program can be compiled into a transformer, and how the transformer's attention patterns can be read as the selectors of the program.

The carry lookup in this post is a RASP select with the predicate "the nearest earlier position that does not propagate", and the counting construction is RASP's selector_width idiom, which the paper handles more carefully than the version here does.

Lindner, Kramár, Farquhar, Rahtz, McGrath and Mikulik (2023), "Tracr: Compiled Transformers as a Laboratory for Interpretability" built the compiler. Tracr takes a RASP program and emits real weights for a real model, allocating residual-stream dimensions to variables the way the register table above does, and handling the awkward parts this post handled by hand: numerical encodings for categorical variables, the BOS trick that makes counting length-independent, and layer allocation. Its purpose is interpretability research. If you are testing a method that claims to recover circuits from weights, a compiled model gives you the answer key.

Elhage and colleagues (2021), "A Mathematical Framework for Transformer Circuits" supplies the vocabulary. The residual stream as a communication channel that layers read from and write to, the QK circuit deciding where a head attends and the OV circuit deciding what it moves, heads composing across layers: those are the terms the construction here is built in. The two-layer adder is a Q-composition, since MLP 0 writes the propagate register that block 1's keys read.

Pérez, Marinković and Barceló (2019), "On the Turing Completeness of Modern Neural Network Architectures" marks the outer limit. Transformers with arbitrary precision and unbounded steps are Turing complete, so "can a transformer represent this computation" is almost always yes. The interesting questions are the ones this post ends on: at what width, at what depth, and reachable by gradient descent from a random start, or not.

Interactive Tools

  • Attention Visualizer: Step through query, key, value, scores, masking and softmax on a sentence, the same pipeline the hand-built heads above run.
  • Gradient Descent Visualizer: Watch the ordinary route to a set of weights, the one this post skips entirely.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions