Reverse-engineering an algorithm: grokking and modular arithmetic
Investigate a one-layer transformer trained on addition modulo p, its delayed generalization, Fourier-based circuits, frequency ablations, progress measures, and the question of universality.
After this lesson you can
- Reproduce grokking on modular addition and study dependence on weight decay and data fraction.
- Identify key embedding and neuron frequencies with the discrete Fourier transform.
- Explain how attention and MLP implement cos(w(a+b−c)) using trigonometric identities.
- Calculate restricted and excluded losses and distinguish memorization, circuit formation, and cleanup.
- Discuss universality in light of clock and pizza algorithms.
Before you start
Learning after memorization
In addition modulo , each input is a pair and the answer is . A split separates ordered training pairs from test pairs: both contain operands from the same set but not the same pairs. Commutativity means may appear in training even when is in test; the split evaluates held-out pairs, not a distribution unrelated to the operation. Grokking describes generalization improving long after training error is already low. Power and colleagues observed this delay in small algorithmic tasks. It is not guaranteed for every seed, architecture, or training budget.
To study the phenomenon, record training and test loss and accuracy against steps, along with optimizer, fraction of pairs, seed, and regularization. Accuracy can change abruptly at a threshold even as logit differences evolve gradually. This alone does not establish that all internal mechanisms evolve smoothly: they must be measured.
Our four runs use the same initialization and a shared pair permutation, with nested fractions 0.3 and 0.5 and weight decay 0 or 1. With decay 1, the first checkpoint reaching 99% training accuracy appears at step 500 for fraction 0.3 and 750 for fraction 0.5. The first test checkpoints exceeding that threshold are 15500 and 4000 respectively. The time separation is visible at 250-step resolution, but one seed and one split do not quantify between-run variability.
At step 20000 all four runs retain training accuracy 1.0. On test, fractions 0.3 and 0.5 with decay 1 reach 1.0; without decay they end at 0.281 and 0.445 respectively. The comparison shows what happened for this architecture, initialization, and split, not a guarantee decay always yields grokking. Restricted and excluded curves signal the proposed spectral hypothesis; choosing frequencies at the end prevents treating them as prospective predictions.
Addition as rotation
In the Fourier circuit, the angle of at frequency is . Adding operands adds angles. The following idealized scorer assigns each candidate :
If is prime and contains at least one nonzero frequency modulo , the correct candidate reaches and every other scores lower. For a composite modulus this requires that the frequencies share no divisor with allowing an invisible shift. The figure uses and consecutive frequencies starting at 1; it is a mathematical construction, not a trained model.
Identities and show how to combine sinusoidal input representations with output directions. In the model studied by Nanda and colleagues, analysis of weights and activations together with Fourier ablations supported an explanation in this family. An algebraic identity shows an algorithm is possible; it does not prove a particular network learned it.
One implementation uses attention to bring sinusoidal coordinates of both operands to the output position. The MLP combines them through nonlinear functions: for example, turns forming products into approximating squares. The output readout mixes products with and to contribute to . Approximation, frequencies, and division between attention and MLP must be verified per network; they do not follow solely from a correct answer.
Measuring hidden progress
Progress measures are defined after proposing a mechanism. Restricted loss projects logits onto identified frequencies and evaluates prediction from that part; excluded loss removes those frequencies and evaluates the remainder. The published analysis transforms the logit matrix along both input axes a and b; the later exercise uses a simplified class-axis projection and does not reproduce that measure. A precise definition must state transformed axes, retained frequencies, treatment of the constant term, and cross-entropy calculation. The studied case distinguishes memorization, circuit formation, and cleanup; these phases are an interpretation supported by measurements and ablations, not labels to impose on every curve.
In the main model of Nanda and colleagues the five reported key frequencies are 14, 35, 41, 42, and 52 modulo 113. The authors place memorization approximately through epoch 1400, formation through 9400, and cleanup through 14000. Those boundaries describe that run, not universal thresholds. During formation, restricted loss begins falling while ordinary losses remain almost flat; later cleanup removes components associated with memorization and improves test performance. The scale and optimizer of your experiment may produce different curves.
The DFT changes basis: spectral concentration of embeddings suggests periodic structure but does not establish that output causally depends on it. Project or remove frequencies and compare loss change against controls; then test the idealized mechanism and held-out examples. Frequencies chosen in one seed need not recur in another.
At that run’s final checkpoint, the five most energetic embedding frequencies are 33, 8, 12, 6, and 9. Original test loss is approximately with accuracy 1.0. Retaining only those embedding frequencies raises loss to 0.000577 while accuracy remains 1.0; removing them raises loss to 20.53 and reduces accuracy to 0.0117. The test uses the same split to evaluate each intervention and changes every number embedding; it neither isolates a neuron nor proves only one algorithm is possible. The idealized clock scorer, scaled using training logits, gives accuracy 1.0 and test loss : an output comparison rather than an internal network replacement.
Transforming all MLP neuron preactivations over both operands yields aggregate peaks including and , a conjugate pair because . Aggregate attention peaks include and . These summarize this network’s energy; they do not assign a causal role to each neuron or head.
Clocks, pizzas, and universality
The universality hypothesis asks how often internal algorithms recur across models solving a task. Zhong and colleagues describe clock and pizza solutions, including combinations, as training conditions vary. Chughtai and colleagues find mixed evidence when studying group operations. A well-validated toy circuit teaches a research method, but does not justify attributing the same mechanism to a large language model without interventions of its own.
In the pizza algorithm, embeddings of and lie on a circle and are averaged. For a fixed sum, those averages lie on a line through the origin; classifying the pair of sectors of that line recovers sum information. The average magnitude depends on operand separation, making nearly opposite pairs noise-sensitive. The authors use several circles and study, among other diagnostics, how the correct logit changes with separation. Solving the task and having circular embeddings is insufficient to conclude a network uses the clock.
Lab: the clock by hand
The code checks all pairs modulo 17 and calculates the minimum margin between correct and competing answers for several frequency sets. The construction includes ; a positive margin is not a training measurement and does not demonstrate grokking.
import numpy as np
p = 17
for n in (1, 2, 3, 4):
margins = []
for a in range(p):
for b in range(p):
c = np.arange(p)
logits = sum(np.cos(2*np.pi*k*(a+b-c)/p) for k in range(1,n+1))
target = (a+b) % p
margins.append(logits[target] - np.max(np.delete(logits, target)))
assert int(np.argmax(logits)) == target
print('frecuencias', n, 'parejas', p*p, 'margen mínimo', round(min(margins), 6))The next column contains one real embedding coordinate from our checkpoint at fraction 0.5 and decay 1, step 20000, rounded to ten decimals. The DFT runs in the browser; this coordinate’s five dominant frequencies need not exactly match those of the full matrix.
import numpy as np
columna = np.array([0.17599006,-0.0816745386,-0.1600349247,-0.1156858057,-0.1999360323,-0.2847805619,0.1180965453,0.3095875978,0.1479087919,0.1018499807,0.1848227233,0.0159973018,-0.2132001519,-0.1562101394,-0.1548909843,-0.1728748083,0.1689092368,0.3026849329,0.1250732392,-0.0135220382,0.1183219776,-0.0542618558,-0.2893919647,-0.2677018046,-0.129627347,-0.0232822839,0.1580265313,0.2804724872,0.1952113211,-0.007383002,0.1271390915,0.0700069368,-0.2161750346,-0.2258767635,0.0990929827,0.1748611629,0.0288619399,0.0892239213,0.0148698073,-0.2061095685,-0.15019162,-0.0921057686,-0.2585301101,-0.1622988433,0.3108139038,0.3228197396,0.1812863797,0.1936351806,0.165928632,-0.1385157257,-0.2674457431,-0.1915869713,-0.2590950131,-0.1823559105,0.2364914864,0.2894490659,0.0886203051,0.0823974609,0.1743870527,-0.10691984,-0.2772381008,-0.1691689044,-0.062401589,-0.0371458977,0.1398915499,0.2096469253,-0.0296435021,-0.07491,0.1235230714,-0.0102931019,-0.2712165415,-0.0826065838,0.2514065206,0.1848863363,0.1112084389,0.164838016,-0.0555315427,-0.2797668576,-0.1982923001,-0.2039924115,-0.3168082833,-0.0653826594,0.3358412385,0.2787487805,0.1671388,0.2201360017,0.1961665452,-0.1558391899,-0.2053626031,-0.1553666592,-0.2464628816,-0.0579494722,0.263266921,0.1813365072,-0.0925527588,0.0612534955,0.1049624532,-0.2076718062,-0.2617545128,-0.1232469305,0.0322568268,0.1065720767,0.2650197744,0.2387923896,-0.0858655199,-0.0142258108,0.0532135963,-0.1798363477,-0.2840484381,0.0103512919,0.2331011295,0.1123746559,0.139907375])
energia = np.abs(np.fft.rfft(columna))**2
energia[0] = 0
orden = np.argsort(energia)[-5:][::-1]
print('Frecuencias principales de esta coordenada:', orden.tolist())
print('Fracción de energía en ellas:', float(energia[orden].sum()/energia.sum()))Local lab: train and audit
The one-layer model learns over pairs split deterministically. The sequence is , with causal attention and a ReLU MLP. AdamW uses rate 0.001 and its PyTorch defaults; ORYON_GROK_FRACTION and ORYON_GROK_DECAY set the split and decay. A shared permutation permits comparison of nested fractions, and every update uses all training pairs. Every 250 steps a checkpoint saves optimizer and random state; ORYON_GROK_RESUME resumes a compatible configuration. Choose the directory with ORYON_GROK_DIR. Run each configuration in a different directory. Mode ORYON_QUICK=1 retains but limits execution to four steps to check the flow; it does not reproduce full training.
import json, os, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(1)
torch.manual_seed(190)
p=113; d=128; heads=4; hidden=512
device='cuda' if torch.cuda.is_available() else 'cpu'
steps=4 if os.environ.get('ORYON_QUICK')=='1' else int(os.environ.get('ORYON_GROK_STEPS','20000'))
fraction=float(os.environ.get('ORYON_GROK_FRACTION','.3'))
decay=float(os.environ.get('ORYON_GROK_DECAY','1.0'))
out=Path(os.environ.get('ORYON_GROK_DIR','oryon-grokking'))
out.mkdir(parents=True,exist_ok=True)
class Model(nn.Module):
def __init__(self):
super().__init__();self.embed=nn.Embedding(p+1,d);self.pos=nn.Parameter(torch.randn(3,d)*.02)
self.qkv=nn.Linear(d,3*d,bias=False);self.proj=nn.Linear(d,d,bias=False)
self.mlp=nn.Sequential(nn.Linear(d,hidden),nn.ReLU(),nn.Linear(hidden,d));self.out=nn.Linear(d,p,bias=False)
def forward(self,x):
b,t=x.shape;r=self.embed(x)+self.pos[:t];q,k,v=self.qkv(r).chunk(3,-1)
q,k,v=[z.view(b,t,heads,d//heads).transpose(1,2) for z in (q,k,v)]
[email protected](-1,-2)/(d//heads)**.5
mask=torch.ones(t,t,device=x.device,dtype=torch.bool).tril()
att=score.masked_fill(~mask,-torch.inf).softmax(-1)
r=r+self.proj((att@v).transpose(1,2).reshape(b,t,d));last=r[:,-1]
return self.out(last+self.mlp(last))
a=torch.arange(p).repeat_interleave(p);b=torch.arange(p).repeat(p)
x=torch.stack([a,b,torch.full_like(a,p)],1).to(device);y=((a+b)%p).to(device)
perm=torch.randperm(p*p,generator=torch.Generator().manual_seed(191));n=int(len(perm)*fraction)
train=perm[:n].to(device);test=perm[n:].to(device)
model=Model().to(device);opt=torch.optim.AdamW(model.parameters(),lr=.001,weight_decay=decay)
records=[];started=time.time();start=0
resume=os.environ.get('ORYON_GROK_RESUME')
if resume:
state=torch.load(resume,map_location=device,weights_only=True)
if state['fraction']!=fraction or state['decay']!=decay:raise ValueError('Configuración incompatible')
model.load_state_dict(state['state_dict']);opt.load_state_dict(state['optimizer'])
torch.set_rng_state(state['rng'].cpu());start=state['step']
records=json.loads((out/'metrics.json').read_text(encoding='utf-8'))
records=[r for r in records if r['step']<start or (r['step']==start and start%250!=0 and start!=steps)]
for step in range(start,steps+1):
if step%250==0 or step==steps:
with torch.no_grad():
z=model(x);ce=F.cross_entropy(z,y,reduction='none');pred=z.argmax(-1)
emb=model.embed.weight[:p].detach().cpu().numpy();power_by_coordinate=np.abs(np.fft.rfft(emb,axis=0))**2
power=power_by_coordinate.sum(axis=1);power[0]=0
top=np.argsort(power)[-5:][::-1].copy();grid=z.reshape(p,p,p).detach().cpu().numpy().astype(np.float64)
ft=np.fft.fft2(grid,axes=(0,1));mask=np.zeros((p,p,1),dtype=bool)
for k in top:
for sign_a in (-1,1):
for sign_b in (-1,1):mask[(sign_a*k)%p,(sign_b*k)%p]=True
retain=mask.copy();retain[0,0]=True
restricted=np.fft.ifft2(ft*retain,axes=(0,1)).real;excluded=np.fft.ifft2(ft*(~mask),axes=(0,1)).real
def cross(z,indices):
ix=indices.cpu().numpy();z=z.reshape(-1,p)[ix];target=y[indices].cpu().numpy();m=z.max(axis=1);return float(np.mean(m+np.log(np.exp(z-m[:,None]).sum(1))-z[np.arange(len(z)),target]))
row={'step':step,'train_loss':float(ce[train].mean()),'test_loss':float(ce[test].mean()),'train_acc':float((pred[train]==y[train]).float().mean()),'test_acc':float((pred[test]==y[test]).float().mean()),'restricted':cross(restricted,test),'excluded':cross(excluded,train),'weight_norm':sum(float((q*q).sum()) for q in model.parameters())**.5,'spectrum':power.tolist(),'top':top.tolist()}
if step%2000==0 or step==steps:
heat=power_by_coordinate.reshape(57,16,8).sum(axis=2);heat[0]=0
heat=heat/max(float(heat.max()),1e-30)
row['energy_map']=[[round(float(v),4) for v in line] for line in heat]
records.append(row);print(json.dumps({k:v for k,v in row.items() if k not in ('spectrum','energy_map')},ensure_ascii=False),flush=True)
torch.save({'state_dict':model.state_dict(),'optimizer':opt.state_dict(),'rng':torch.get_rng_state(),'step':step,'seed':190,'fraction':fraction,'decay':decay},out/f'ckpt-{step}.pt')
(out/'metrics.json').write_text(json.dumps(records),encoding='utf-8')
if step==steps:break
model.train();z=model(x[train]);loss=F.cross_entropy(z,y[train])
if not torch.isfinite(loss):raise FloatingPointError(f'pérdida no finita en paso {step}')
opt.zero_grad(set_to_none=True);loss.backward();opt.step()
print('seconds',time.time()-started,flush=True)npm run lab and open the connection link.The first pass selects the five most energetic embedding frequencies at each checkpoint. The next cell instead fixes the five chosen at the end and reevaluates every checkpoint: in the two-dimensional logit DFT it retains the constant term and four sign combinations of each frequency for restricted loss, or removes those combinations for excluded loss. The former is evaluated on test and the latter on training. Projection and loss computation use float64 from float32 logits to reduce cancellation. This embedding selection is an exploratory variant of the method by Nanda and colleagues, who select frequencies from the neuron-logit map; choosing them after seeing the end introduces retrospective selection.
records=json.loads((out/'metrics.json').read_text(encoding='utf-8'))
final_top=records[-1]['top'];mask=np.zeros((p,p,1),dtype=bool)
for k in final_top:
for sa in (-1,1):
for sb in (-1,1):mask[(sa*k)%p,(sb*k)%p]=True
retain=mask.copy();retain[0,0]=True
a=torch.arange(p).repeat_interleave(p);b=torch.arange(p).repeat(p)
x=torch.stack([a,b,torch.full_like(a,p)],1).to(device);y=((a+b)%p).numpy()
perm=torch.randperm(p*p,generator=torch.Generator().manual_seed(191)).numpy()
n=int(len(perm)*fraction);train=perm[:n];test=perm[n:]
model=Model().to(device);model.eval()
def cross(z,ix):
z=z.reshape(-1,p)[ix];target=y[ix];m=z.max(axis=1)
return float(np.mean(m+np.log(np.exp(z-m[:,None]).sum(1))-z[np.arange(len(z)),target]))
for r in records:
ck=torch.load(out/f'ckpt-{r["step"]}.pt',map_location=device,weights_only=True);model.load_state_dict(ck['state_dict'])
with torch.no_grad():grid=model(x).reshape(p,p,p).cpu().numpy().astype(np.float64)
ft=np.fft.fft2(grid,axes=(0,1));restricted=np.fft.ifft2(ft*retain,axes=(0,1)).real;excluded=np.fft.ifft2(ft*(~mask),axes=(0,1)).real
r['restricted']=cross(restricted,test);r['excluded']=cross(excluded,train)
print('frecuencias finales fijadas',final_top,'checkpoints',len(records),flush=True)
(out/'metrics-fixed.json').write_text(json.dumps(records,ensure_ascii=False,separators=(',',':')),encoding='utf-8')npm run lab and open the connection link.Finally calculate spectra of embeddings, neuron preactivations, and attention patterns. Then intervene in embedding rows: retain only the five frequencies or remove them, leaving the token and positions intact. The idealized replacement is a trigonometric scorer fitted by least squares to training logits, not an internal intervention equivalent to the network mechanism.
ck=torch.load(out/f'ckpt-{steps}.pt',map_location=device,weights_only=True)
model=Model().to(device);model.load_state_dict(ck['state_dict']);model.eval()
a=torch.arange(p).repeat_interleave(p);b=torch.arange(p).repeat(p)
x=torch.stack([a,b,torch.full_like(a,p)],1).to(device);y=((a+b)%p).to(device)
perm=torch.randperm(p*p,generator=torch.Generator().manual_seed(191));n=int(len(perm)*fraction);test=perm[n:].to(device)
saved=[]
hook=model.mlp[0].register_forward_hook(lambda m,args,out:saved.append(out.detach().cpu().numpy()))
with torch.no_grad():z=model(x)
hook.remove();neuron=saved[0].reshape(p,p,hidden)
emb=model.embed.weight[:p].detach().cpu().numpy();spec=np.fft.rfft(emb,axis=0);energy=(abs(spec)**2).sum(1);energy[0]=0
top=np.argsort(energy)[-5:][::-1].copy()
def evaluate(logits):
logits=logits[test];target=y[test]
return {'loss':float(F.cross_entropy(logits,target)),'accuracy':float((logits.argmax(-1)==target).float().mean())}
original=evaluate(z)
old=model.embed.weight.detach().clone()
def filtered(keep):
filtered_spec=spec.copy()
for k in range(1,len(filtered_spec)):
if (k in top)!=keep:filtered_spec[k]=0
replacement=np.fft.irfft(filtered_spec,n=p,axis=0).real
with torch.no_grad():
model.embed.weight[:p].copy_(torch.tensor(replacement,device=device,dtype=old.dtype))
result=evaluate(model(x));model.embed.weight.copy_(old)
return result
restricted,excluded=filtered(True),filtered(False)
nf=np.fft.fft2(neuron,axes=(0,1));neuron_energy=(abs(nf)**2).sum(2)
with torch.no_grad():
r=model.embed(x)+model.pos[:3];q,k,v=model.qkv(r).chunk(3,-1)
q,k=[u.view(p*p,3,heads,d//heads).transpose(1,2) for u in (q,k)]
attention=(q[:,:,-1:]@k.transpose(-1,-2)/(d//heads)**.5).softmax(-1).cpu().numpy().reshape(p,p,heads,3)
attention_energy=(abs(np.fft.fft2(attention,axes=(0,1)))**2).sum((2,3))
c=np.arange(p);aa=np.arange(p)[:,None,None];bb=np.arange(p)[None,:,None]
ideal=sum(np.cos(2*np.pi*freq*(aa+bb-c)/p) for freq in top).reshape(-1,p)
# Ajustar escala por mínimos cuadrados sobre las parejas de entrenamiento.
train=perm[:n].numpy();raw=z.detach().cpu().numpy();alpha=float((ideal[train]*raw[train]).sum()/(ideal[train]**2).sum())
ideal_z=torch.tensor(alpha*ideal,device=device,dtype=z.dtype)
def peaks(power):
power=power.copy();power[0,0]=0
return [list(map(int,np.unravel_index(i,power.shape))) for i in np.argsort(power.ravel())[-5:][::-1]]
result={'step':steps,'fraction':fraction,'decay':decay,'top':top.tolist(),'spectrum':energy.tolist(),'original':original,'only_top_embeddings':restricted,'without_top_embeddings':excluded,'ideal_scale':alpha,'ideal_test':evaluate(ideal_z),'neuron_peaks':peaks(neuron_energy),'attention_peaks':peaks(attention_energy)}
(out/'analysis.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(result,ensure_ascii=False),flush=True)npm run lab and open the connection link.Exercises
Step 1 of 2. What value does the correct candidate obtain?
def restricted_loss(logits, labels, key_freqs):
pass