What a transformer can compute
Examine transformer expressivity, resource bounds and in-context learning through theory and experiments.
After this lesson you can
- Write RASP programs for histograms, sorting, reversal and Dyck-1 recognition and relate them to attention and MLP layers.
- State universal approximation results and limits for constant-depth transformers with logarithmic precision.
- Explain why generated intermediate steps expand the class of solvable problems.
- Construct a linear attention layer implementing a gradient descent step for linear regression in context.
- Compare a theoretical construction with what a model learns on a synthetic task.
Before you start
Capacity, learning and resources
If a model does not solve a task, are there no weights capable of solving it, or did training fail to find them? The first question concerns expressivity under explicit assumptions; the second also depends on data, objective, optimizer and test distribution. A hand-built construction can show that something is representable without showing that it is easy to learn. Failed training is not proof of impossibility either.
Programming with select and aggregate
RASP describes operations on sequences. select(keys, queries, predicate) creates a Boolean matrix: row indicates which keys satisfy the predicate for query . aggregate averages the selected values in each row, and elementwise operations transform sequences. The matrix resembles attention: queries and keys decide who reads, and values carry information. This similarity does not mean every RASP operation is literally a softmax head without auxiliary resources. Weiss et al. use the program to reason about bounds on layers and heads.
For a per-position histogram select keys equal to the query and count those selected. To reverse a sequence of length , query selects key . To sort stably, give each element a rank equal to the number of smaller elements plus the number of equal elements before it; select by rank. For Dyck-1, convert ( to and ) to : accept if every prefix has a nonnegative sum and the final sum is zero. Operations that obtain lengths or counts require suitable representation and construction; a normalized average alone does not reveal how many equal elements were averaged.
For example, in input [2, 1, 2, 3], queries with value 2 select columns zero and two. Their counts are 2, while the other two queries select a single key and produce 1: the per-position histogram is [2, 1, 2, 1]. For stable sorting, the ranks are [1, 0, 2, 3]; the two copies of 2 retain their original order. In ())( the prefix sums are [1, 0, -1, 0]: a final sum of zero is not enough, because the third prefix has already closed more parentheses than it opened.
In the lab’s reverse compilation, the logit for query and key is . It can be factored into a product of query and key features of dimension three. Softmax with finite assigns nonzero mass to incorrect positions: it is not exact Boolean selection. With the domain and margin fixed in the experiment, argmax over one-hot values does recover the reversed symbol exactly. The guarantee is for that domain and construction, not for infinite precision or arbitrary lengths.
We also compile the histogram with one head and a ReLU MLP for a known fixed length . Add a sentinel token and use logit for keys equal to the query and zero for the others, including the sentinel. If there are matches, attention to the sentinel is . The possible values are distinct: a piecewise linear MLP can interpolate the pairs exactly at those points. The code explicitly constructs the projection matrices and MLP weights; it verifies the counts with numerical tolerance. This is a minimal layer without normalization or residual connections; its weights depend on and do not prove a uniform compiler for every length.
What the theorems say and do not say
The universal approximation of Yun et al. concerns continuous functions on compact fixed-length domains. Without positions, the family considered approximates permutation-equivariant functions; positional encoding removes that restriction. Approximation does not imply solving a language exactly for any length, or finding weights efficiently. Constructions may require considerable resources as precision and length increase.
Under another family of assumptions, Hahn proves limitations of fixed-depth, fixed-head-count self-attention on formal languages; in hard attention, parity is an example of difficulty under that model. Do not extrapolate the conclusion to every variant with different precision and masks. Circuit complexity offers another perspective: Merrill and Sabharwal place logarithmic-precision transformers, under specific layer assumptions, within uniform constant-depth threshold circuits. Parity belongs to TC⁰, so this inclusion alone does not exclude it. Composing permutations of is a representative NC¹ problem; claiming that TC⁰ cannot solve it would require an unproven class separation. The limitation is conditional, not an already established unconditional impossibility.
A circuit family includes one circuit for each input length; uniformity requires that the family can be described efficiently, to avoid hiding arbitrary answers in its construction. Constant depth allows many operations in parallel, but limits sequential rounds of dependency. A threshold gate, unlike an elementary bounded-input Boolean gate, can respond to a weighted sum of many inputs. Consequently, classes obtained by changing the gate type, precision or position-generation rule are not interchangeable. The theorem restricts a formal family; it does not directly measure how many examples a particular model needs.
The fixed depth of one pass is not the only resource: generating intermediate tokens adds sequential steps. In the framework of Merrill and Sabharwal, the number of steps and normalization details change the class of expressible problems. Intermediate steps can serve as external working memory, but a long chain does not guarantee that the model learned the algorithm or that its explanation faithfully describes its computation.
For parity, an intermediate state can be the accumulated bit after reading each symbol; for permutation composition, it can encode the composition accumulated up to that point. In both cases the next output depends on an already generated state, so computation is distributed across steps. That dependency also has costs: more tokens, more latency, the possibility of propagating an erroneous state and a different distribution between training with correct states and generation with the model’s own states. A fair comparison makes the training budget and final success criterion explicit.
Even when a construction is available, the optimizer can learn a shortcut that works on the short training distribution without implementing the desired recurrent transition. Liu et al. study this contrast in automata and length generalization. To investigate it, compare not only final accuracy but intermediate states, seed, length, noise and out-of-distribution examples; identifying a shortcut requires a specific test and does not follow solely from a drop in accuracy.
We trained 32 small transformers: depths 1 to 8, two tasks and two output formats, with one seed and 300 steps per model. They train on sequences of length 2 to 12 and are evaluated on 128 new examples per point. In this recipe, generating intermediate states did not reliably solve the tasks: parity accuracy stayed near 0.5 and complete permutation composition near 1/120, including within the training range. The theoretical construction shows a possibility with appropriate assumptions and weights; these particular training runs did not find it. The figure demonstrates neither a universal wall nor an improvement that was not observed.
A layer that implements one descent step
Consider regression through the origin, . From , an update with rate is , and the prediction for query is . A linear attention head without softmax with , and produces exactly . The factor must be available: it is not a magic constant for variable lengths. The network weights do not change when processing the context; the computation appears in its activations. This construction illustrates in-context learning as descent; von Oswald et al. study constructions and models trained on regression, and do not prove that every LLM literally executes that algorithm.
The same equality works with : and . The query-key product is now scalar; the value remains scalar. With softmax, regularization or a different initialization, this particular identity no longer follows without modifying the construction.
The constructed step and least squares coincide only in special cases. The former applies the same rate to every direction and uses the correlation between input and output; least squares also corrects for the scale and correlation of inputs when the corresponding matrix is invertible. Thus varying can move the prediction closer to or further from the optimal solution. With noisy or higher-dimensional data, regularization and the number of examples change which comparison is appropriate.
Lab: interpret and compile
The cell uses NumPy, categorical values 0 to 3 and lengths up to 8. The compiler implements reversal and histogram with explicit weights, softmax and a ReLU MLP constructed for the fixed length. It checks both results on 800 inputs.
import numpy as np
def select(keys, queries, predicate):
return np.array([[predicate(k, q) for k in keys] for q in queries], dtype=bool).reshape(len(queries),len(keys))
def aggregate(selection, values, default=0.):
values=np.asarray(values, dtype=float)
count=selection.sum(axis=1)
return np.divide(selection @ values, count, out=np.full(len(count),default), where=count>0)
def histogram(xs):
s=select(xs,xs,lambda k,q:k==q)
return s.sum(1)
def reverse(xs):
i=np.arange(len(xs)); s=select(i,i,lambda k,q:k==len(xs)-1-q)
return aggregate(s,xs)
def sort_program(xs):
# Stable rank is unique even when values repeat.
i=np.arange(len(xs)); ranks=np.array([sum((xs[k]<xs[q]) or (xs[k]==xs[q] and k<q) for k in i) for q in i])
return aggregate(select(ranks,i,lambda k,q:k==q),xs)
def dyck_one(xs):
values=np.array([1 if x=='(' else -1 if x==')' else 0 for x in xs]); n=len(xs)
if any(x not in '()' for x in xs): raise ValueError('solo paréntesis')
i=np.arange(n); s=select(i,i,lambda k,q:k<=q)
prefix=aggregate(s,values)*s.sum(1)
return bool(n==0 or (prefix.min()>=0 and prefix[-1]==0))
def compiled_reverse(xs, alphabet=4, strength=12):
# logits(i,j)=-strength*(i+j-(n-1))², factored as Q @ K.T.
n=len(xs); i=np.arange(n,dtype=float); j=i.copy(); m=n-1
q=np.stack((np.ones(n),i,i*i),axis=1)
k=np.stack((-strength*(j-m)**2,-2*strength*(j-m),-strength*np.ones(n)),axis=1)
logits=q@k.T; p=np.exp(logits-logits.max(1,keepdims=True));p/=p.sum(1,keepdims=True)
value=np.eye(alphabet)[xs]; probabilities=p@value
return probabilities.argmax(-1),p
def compiled_histogram(xs, alphabet=4, strength=3.):
# Un sentinel permite recuperar el número de coincidencias desde su masa.
# La longitud n es fija y conocida al construir los pesos de la MLP.
n=len(xs);d=alphabet
tokens=np.vstack((np.eye(alphabet+1)[xs],np.eye(alphabet+1)[alphabet]))
wq=np.zeros((alphabet+1,d));wk=np.zeros_like(wq);wv=np.zeros((alphabet+1,1))
wq[:alphabet,:]=np.eye(d)*strength*np.sqrt(d);wk[:alphabet,:]=np.eye(d);wv[-1,0]=1
logits=(tokens@wq)@(tokens@wk).T/np.sqrt(d)
attention=np.exp(logits-logits.max(1,keepdims=True));attention/=attention.sum(1,keepdims=True)
sentinel=(attention@(tokens@wv))[:n,0]
# Interpolación lineal por tramos: MLP ReLU exacta en los n+1 valores posibles.
counts=np.arange(n,-1,-1,dtype=float)
knots=1/(n+1+counts*(np.exp(strength)-1))
slopes=np.diff(counts)/np.diff(knots)
first_weights=np.ones((n,1));first_bias=np.concatenate(([0.],-knots[1:-1]))
last_weights=np.concatenate(([slopes[0]],np.diff(slopes)))
last_bias=counts[0]-slopes[0]*knots[0]
hidden=np.maximum(0,sentinel[:,None]@first_weights.T+first_bias)
result=hidden@last_weights+last_bias
return result,attention
rng=np.random.default_rng(41)for n in range(1,3):
for _ in range(100):
x=rng.integers(0,4,n).tolist()
assert np.array_equal(reverse(x),x[::-1])
assert np.array_equal(sort_program(x),sorted(x))
assert np.array_equal(histogram(x),[x.count(v) for v in x])
y,p=compiled_reverse(x);assert np.array_equal(y,x[::-1])
compiled,_=compiled_histogram(x);assert np.allclose(compiled,histogram(x),atol=1e-9)
print('200 casos correctos en longitudes 1 a 2')for n in range(3,5):
for _ in range(100):
x=rng.integers(0,4,n).tolist()
assert np.array_equal(reverse(x),x[::-1])
assert np.array_equal(sort_program(x),sorted(x))
assert np.array_equal(histogram(x),[x.count(v) for v in x])
y,p=compiled_reverse(x);assert np.array_equal(y,x[::-1])
compiled,_=compiled_histogram(x);assert np.allclose(compiled,histogram(x),atol=1e-9)
print('200 casos correctos en longitudes 3 a 4')for n in range(5,7):
for _ in range(100):
x=rng.integers(0,4,n).tolist()
assert np.array_equal(reverse(x),x[::-1])
assert np.array_equal(sort_program(x),sorted(x))
assert np.array_equal(histogram(x),[x.count(v) for v in x])
y,p=compiled_reverse(x);assert np.array_equal(y,x[::-1])
compiled,_=compiled_histogram(x);assert np.allclose(compiled,histogram(x),atol=1e-9)
print('200 casos correctos en longitudes 5 a 6')for n in range(7,9):
for _ in range(100):
x=rng.integers(0,4,n).tolist()
assert np.array_equal(reverse(x),x[::-1])
assert np.array_equal(sort_program(x),sorted(x))
assert np.array_equal(histogram(x),[x.count(v) for v in x])
y,p=compiled_reverse(x);assert np.array_equal(y,x[::-1])
compiled,_=compiled_histogram(x);assert np.allclose(compiled,histogram(x),atol=1e-9)
print('200 casos correctos en longitudes 7 a 8')for x,expected in [('()',True),('(())()',True),(')(',False),('(()',False),('',True)]:
assert dyck_one(x)==expected
print('cinco secuencias Dyck correctas')
print('selección de inversión:',select(range(4),range(4),lambda k,q:k==3-q).astype(int))
print('atención compilada:',compiled_reverse([0,1,2,3])[1].round(6))
print('histograma compilado:',compiled_histogram([2,1,2,3])[0].round(9))Local lab: depth and intermediate steps
To reproduce the sweep, 32 models are trained: two tasks, direct answers or intermediate states, and depth from 1 to 8. Each model uses 300 steps with sequences of 2 to 12 symbols and 128 evaluation examples per length. Evaluation generates its own states, although training uses correct states. The recorded run uses ORYON_DEPTH_DEVICE=cpu and ORYON_DEPTH_THREADS=1.
import itertools, json, math, os, random
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
P=list(itertools.permutations(range(5)));lookup={p:i for i,p in enumerate(P)}
IDENTITY=lookup[tuple(range(5))];SEP=240;VOCAB=241;DEVICE=os.environ.get('ORYON_DEPTH_DEVICE','cuda' if torch.cuda.is_available() else 'cpu')
if DEVICE=='cpu' and 'ORYON_DEPTH_THREADS' in os.environ:torch.set_num_threads(int(os.environ['ORYON_DEPTH_THREADS']))
def compose(a,b):return tuple(a[b[i]] for i in range(5))
COMPOSE=torch.tensor([[lookup[compose(a,b)] for b in P] for a in P],dtype=torch.long)
def data(task,n,b,generator):
high=2 if task=='parity' else 120
inputs=torch.randint(high,(b,n),generator=generator)
current=torch.zeros(b,dtype=torch.long) if task=='parity' else torch.full((b,),IDENTITY,dtype=torch.long)
states=[]
for t in range(n):
current=(current ^ inputs[:,t]) if task=='parity' else COMPOSE[current,inputs[:,t]]
states.append(current+120)
return inputs.to(DEVICE),torch.stack(states,1).to(DEVICE)
class Network(nn.Module):
def __init__(self,depth):
super().__init__();d=32
self.embedding=nn.Embedding(VOCAB,d);self.position=nn.Embedding(130,d)
self.blocks=nn.ModuleList([nn.TransformerEncoderLayer(d,4,64,batch_first=True,dropout=0.,activation='gelu',norm_first=True) for _ in range(depth)])
self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,VOCAB)
def forward(self,x):
n=x.shape[1];h=self.embedding(x)+self.position(torch.arange(n,device=x.device))[None,:,:]
mask=torch.triu(torch.ones(n,n,dtype=torch.bool,device=x.device),1)
for block in self.blocks:h=block(h,src_mask=mask)
return self.head(self.norm(h))
def train_one(task,mode,depth,steps=300):
torch.manual_seed(51);rng=random.Random(51);g=torch.Generator().manual_seed(51)
net=Network(depth).to(DEVICE);opt=torch.optim.AdamW(net.parameters(),lr=.001)
for step in range(steps):
n=rng.randint(2,12);inputs,states=data(task,n,32,g)
target=states if mode=='scratch' else states[:,-1:]
x=torch.cat((inputs,torch.full((32,1),SEP,device=DEVICE,dtype=torch.long),target[:,:-1]),1)
logits=net(x)[:,n:,:];loss=F.cross_entropy(logits.reshape(-1,VOCAB),target.reshape(-1))
opt.zero_grad(set_to_none=True);loss.backward();nn.utils.clip_grad_norm_(net.parameters(),1.);opt.step()
if (step+1)%100==0:print(task,mode,depth,'paso',step+1,'pérdida',float(loss.detach()))
gen=torch.Generator().manual_seed(999);rows=[];net.eval()
with torch.no_grad():
for n in (8,12,16,24,32):
source,states=data(task,n,128,gen)
x=torch.cat((source,torch.full((128,1),SEP,device=DEVICE,dtype=torch.long)),1)
count=n if mode=='scratch' else 1
for _ in range(count):x=torch.cat((x,net(x)[:,-1].argmax(-1,keepdim=True)),1)
rows.append({'length':n,'accuracy':float((x[:,-1]==states[:,-1]).float().mean()),'n':128})
return {'task':task,'mode':mode,'depth':depth,'steps':steps,'device':DEVICE,
'threads':torch.get_num_threads() if DEVICE=='cpu' else None,'rows':rows}
results=[]
for task in ('parity','permutation'):
for mode in ('direct','scratch'):
for depth in range(1,9):
result=train_one(task,mode,depth);results.append(result);print(result)
Path('depth-results.json').write_text(json.dumps(results,indent=2),encoding='utf8')
npm run lab and open the connection link.Local lab: what a network learns
Each task chooses a normally distributed slope and normal examples, with noiseless . The network receives pairs and a query; it trains with 1 to 16 examples and is evaluated on 2048 new regressions per length, including 32. Its multi-head attention, residuals and FFN are implemented explicitly with tensor operations; PyTorch provides autograd and the optimizer. Least squares through the origin is nearly exact in this noiseless task. We compare MSE with one to 16 descent steps and a fixed rate; the steps can behave poorly on extreme samples. PyTorch and a GPU are needed to reproduce training in reasonable time; the code supports CPU.
import json, random, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
torch.manual_seed(2026); np.random.seed(2026); random.seed(2026)
device='cuda' if torch.cuda.is_available() else 'cpu'
class Block(nn.Module):
def __init__(self,d=64,heads=4):
super().__init__();self.heads=heads
self.n1=nn.LayerNorm(d);self.n2=nn.LayerNorm(d)
self.q=nn.Linear(d,d);self.k=nn.Linear(d,d);self.v=nn.Linear(d,d);self.o=nn.Linear(d,d)
self.up=nn.Linear(d,2*d);self.down=nn.Linear(2*d,d)
def forward(self,x):
b,t,d=x.shape;z=self.n1(x)
def split(layer):return layer(z).reshape(b,t,self.heads,d//self.heads).transpose(1,2)
q,k,v=split(self.q),split(self.k),split(self.v)
weights=(q@k.transpose(-2,-1)/(d//self.heads)**.5).softmax(-1)
attended=(weights@v).transpose(1,2).contiguous().reshape(b,t,d)
x=x+self.o(attended);return x+self.down(F.gelu(self.up(self.n2(x))))
class RegressionTransformer(nn.Module):
def __init__(self):
super().__init__()
self.input=nn.Linear(3,64)
self.blocks=nn.ModuleList([Block(),Block()])
self.out=nn.Linear(64,1)
def forward(self,x,y,q):
context=torch.stack((x,y,torch.zeros_like(x)),dim=-1)
query=torch.stack((q,torch.zeros_like(q),torch.ones_like(q)),dim=-1)[:,None,:]
h=self.input(torch.cat((context,query),1))
for block in self.blocks:h=block(h)
return self.out(h[:,-1]).squeeze(-1)
def batch(n,b,gen):
w=torch.randn(b,1,generator=gen,device=device); x=torch.randn(b,n,generator=gen,device=device)
q=torch.randn(b,generator=gen,device=device); return x,w*x,q,w[:,0]*q
def baseline(x,y,q,steps,eta=.2):
w=torch.zeros(len(x),device=x.device)
for _ in range(steps): w=w-eta*(x*(w[:,None]*x-y)).mean(1)
return w*q
def fit(steps=2500):
net=RegressionTransformer().to(device)
opt=torch.optim.AdamW(net.parameters(),lr=.0005)
gen=torch.Generator(device=device).manual_seed(11)
for step in range(steps):
n=random.randint(1,16);x,y,q,target=batch(n,64,gen)
loss=(net(x,y,q)-target).square().mean()
opt.zero_grad(set_to_none=True);loss.backward();opt.step()
if (step+1)%250==0:print('paso',step+1,'MSE',float(loss.detach()))
gen=torch.Generator(device=device).manual_seed(991);net.eval()
with torch.no_grad():
for n in (1,2,4,8,16,32):
x,y,q,target=batch(n,2048,gen)
ols=((x*y).sum(1)/(x*x).sum(1).clamp_min(1e-12))*q
predictions={'transformer':torch.cat([net(x[i:i+128],y[i:i+128],q[i:i+128]) for i in range(0,len(q),128)]),'ols':ols}
for k in (1,2,4,8,16):predictions[f'gd{k}']=baseline(x,y,q,k)
print(n,{name:round(float((p-target).square().mean()),6) for name,p in predictions.items()})
return net
model=fit()
npm run lab and open the connection link.On the RTX 3060, with PyTorch 2.11 and 2500 steps, evaluation produced the following mean squared errors over 2048 new tasks per column. Least squares through the origin gave MSE below in all cases, as expected for noiseless data. At one sample, sixteen descent steps were unstable on some extreme tasks and MSE was 16.3729; more steps at a fixed rate are not always better.
| Context examples | 1 | 2 | 4 | 8 | 16 | 32 |
|---|---|---|---|---|---|---|
| Transformer | 0.0896 | 0.0482 | 0.0100 | 0.0050 | 0.0037 | 0.0082 |
| Descent, 1 step | 0.6877 | 0.6747 | 0.6456 | 0.6935 | 0.5682 | 0.6961 |
| Descent, 16 steps | 16.3729 | 0.1328 | 0.0449 | 0.0243 | 0.0063 | 0.0038 |
The network achieved lower error than one descent step on these samples, but that does not identify its internal mechanism. At 32 examples it is outside the training range and its error rises relative to 16. Training used one seed and a noiseless scalar distribution; it does not support conclusions about which algorithm a general language model uses.
Exercises
import numpy as np
def reverse_rasp(xs):
passStep 1 of 3. What is the gradient at w=0?