Module contents
Stage 3 of 8Research 110 min

Grokking and the Fourier algorithm

Reproduce grokking in modular addition with a one-layer transformer and weight decay, then reverse engineer the learned algorithm in full, including sparse embeddings in the Fourier basis, trigonometric products in the MLP and constructive-interference readout. Mechanism-derived progress measures reveal continuous learning beneath an apparently abrupt transition.

After this lesson you can

  • Reproduce the grokking curve with the appropriate data fraction and weight decay.
  • Identify key frequencies with Fourier transforms of embeddings and activations.
  • Verify the algorithm causally with ablations in the Fourier basis.
  • Calculate restricted and excluded loss over training.

Before you start

A jump can conceal progress

Train a model to predict (a+b) mod 113(a+b)\bmod 113 from a subset of the pairs. It may get every seen example right and fail almost all unseen examples. If test accuracy rises later while training accuracy has already saturated, you observe grokking: generalization delayed relative to fitting. Perfect accuracy does not mean zero cross-entropy: increasing margins continues to reduce loss and produce gradients.

The split must be over pairs, not positions in the same sequence. There are 1132=12769113^2=12769 pairs and 30 %, rounded down, gives 3830 for training and 8939 for test. The study by Nanda and colleagues uses one layer, four heads, 30 % of the data, AdamW with learning rate 0.001 and weight decay 1 for 40000 full-batch epochs. This is an experimental configuration, not a universal law: the phenomenon depends on sample size, initialization, optimizer and regularization. Power and colleagues describe delayed generalization on several algorithmic tasks.

The label is a congruence class: 112 + 1 gives 0 modulo 113. The gap between training and test loss connects to implicit regularization, but here the conclusions are supported by an intervention and an observed trajectory. The phase change summarizes the curves; on its own it does not prove the internal mechanism.

InteractiveSpectrum and generalization during training
  • Training
  • Test

One seed. Frequencies 30, 9, 35, 53, 23 were selected using the final neuron-logit map, not this spectrum; they are used in the ablation.

0
Step0
Training0.6 %
Test1.0 %
Explore checkpoints from this run. The curve joins samples every 1000 steps; the spectrum is the norm of the embeddings' DFT. What changes before test accuracy rises?

In the run behind the figure, training accuracy reaches 100 % at step 400. Test accuracy is 2.71 % at step 15000, 18.82 % at 18000 and 99.89 % at 40000. This is one seed’s trajectory, not a guarantee for every run. Losses oscillate; the argument does not depend on pretending that progress is monotonic.

The strength of regularization is an experimental intervention. AdamW separates the adaptive update from shrinkage: with learning rate η\eta and decay λ\lambda, the decay term multiplies the previous weight by 1−ηλ1-\eta\lambda before adding the adaptive update. In general this is not equivalent to adding an L2 penalty to the gradient before Adam’s adaptation, as seen when comparing weight decay and L2. Even when accuracy is already one, cross-entropy retains a gradient while correct probabilities are below one; training can change the solution during the plateau.

Comparison with a run without decay requires fixing architecture, data, initialization and budget, and repeating seeds. In its configuration, the paper observes that decay encourages circuit formation and cleanup, and also studies other regularizers; this does not prove that all grokking problems follow the same dynamics. The 40000-step limit is part of a negative result: “it did not appear before that step” does not mean “it will never appear”.

A change of basis reveals a hypothesis

For k=0,…,112k=0,\dots,112, the waves exp⁡(2πika/113)\exp(2\pi i k a/113) form the discrete Fourier transform basis. If EE contains one embedding per row, transforming its token axis and taking the norm over columns measures how much of each frequency is in the table. In real data, conjugates kk and 113−k113-k appear: they are not two independent discoveries. This measure depends on the chosen normalization and does not show that a frequency is necessary for the output.

This lesson uses the torch.fft convention: the forward transform does not divide by pp, and the inverse divides by pp per axis. The norm shown therefore cannot be directly compared to an orthonormal DFT without converting the scale. For E∈Rp×dE\in\R^{p\times d}, each frequency coefficient is a complex vector of dimension dd; the norm sums its squared magnitudes over those dd coordinates. rfft keeps only nonnegative frequencies up to 56, taking advantage of conjugate symmetry for real input. The special token = is excluded from that DFT because it does not represent a residue class modulo 113.

Fourier circuit reverse engineering proposes a stronger explanation. A sine and cosine pair represents an angle; the identity

cos⁡(ω(a+b))=cos⁡(ωa)cos⁡(ωb)−sin⁡(ωa)sin⁡(ωb)\cos(\omega(a+b))=\cos(\omega a)\cos(\omega b)-\sin(\omega a)\sin(\omega b)

turns addition into a rotation. Another identity combines this representation with waves for candidate class cc and produces cos⁡(ω(a+b−c))\cos(\omega(a+b-c)). The MLP can approximate products through its nonlinearity; the readout combines multiple frequencies. Finding periodicity in embeddings is not enough: examine activations, the readout and the consequences of removing components.

In this architecture, attention carries information from both operands to the separator position. Its weights are input-dependent, so a periodic attention map can contribute to products rather than merely copying a wave. The MLP then introduces nonlinearity and the readout adds evidence for each candidate. This decomposition is a hypothesis about specific components: correlation between a neuron and a sine wave does not by itself identify the path that carries the result to the logit.

Proof

Each summand is at most 1, so S(c)≤∣K∣S(c)\le |K|. At c≡a+bc\equiv a+b all equal 1. If another cc tied, each term would have to equal 1, requiring p∣k(a+b−c)p\mid k(a+b-c) for every k∈Kk\in K. Since pp is prime and kk is not a multiple of pp, this implies p∣(a+b−c)p\mid(a+b-c). Without that assumption there are counterexamples: for composite modulus a frequency can have multiple maxima. With few frequencies the maximum is unique, but secondary peaks can be close; adding frequencies can widen the margin.

∎

In the paper’s main model, the identified frequencies are 14, 35, 41, 42 and 52. These are results from that published run, not values to impose on another model. The ablation acts on logits computed for all pairs: a two-dimensional DFT over a,ba,b allows frequency components to be kept or removed. An intervention on logits demonstrates the importance of those output components; it does not by itself silence a neuron or show that every head uses that frequency.

Progress measures distinguish restricted loss, calculated by retaining selected components, from excluded loss, calculated after removing them. Frequencies are fixed from the final model and the same mask is applied to every checkpoint. Excluded loss can rise while ordinary loss remains low, because a contribution that has become important is removed. Retrospective selection helps interpret the trajectory but is not an independent prospective prediction.

There is a difference between embedding frequencies and logit frequencies. Logits across the full domain form a p×p×pp\times p\times p tensor: the first two axes are aa and bb, and the third is candidate class cc. The DFT is applied only to the two input axes; each frequency pair still has a vector of pp logits. For a real frequency kk, sine and cosine combinations occupy the four positions (±k,±k)(\pm k,\pm k) in that complex basis. Keeping those positions and reconstructing with the inverse is an intervention on the output tensor; it does not change the weights or the network’s internal computation.

Removing components is not retraining without them. It asks a specific counterfactual: what prediction results after modifying the output of this trained model? Removed components can also interact with others in the argmax, so the accuracy difference does not distribute additively across frequencies. Excluded loss is calculated on training data to follow the disappearance of the memorization solution; final-table accuracy is calculated on test data. The sets remain separate.

Lab: reproduce it yourself

The code builds a one-layer transformer and calculates only the last position’s query. In one causal layer, the separator output depends on keys and values from all three positions, so intermediate outputs for the first two are unnecessary. The architecture and initialization are our own and do not reproduce the paper’s weights exactly. You need PyTorch and CUDA to run it; it saves states and metrics in p11_grok_run for the next cell. A run takes time and disk space; if you change the budget, identify it as a short test.

[ ]Train modular addition in a full batchLocal GPU
import json, random, time
from pathlib import Path
import torch
from torch import nn
import torch.nn.functional as F

P, D, H = 113, 128, 4
torch.manual_seed(0)
torch.set_num_threads(1)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
out = Path('p11_grok_run'); out.mkdir(parents=True, exist_ok=True)

class AdditionTransformer(nn.Module):
    def __init__(self):
        super().__init__()
        self.token = nn.Embedding(P+1, D)
        self.position = nn.Embedding(3, D)
        self.q = nn.Linear(D,D,bias=False)
        self.k = nn.Linear(D,D,bias=False)
        self.v = nn.Linear(D,D,bias=False)
        self.o = nn.Linear(D,D,bias=False)
        self.fc = nn.Linear(D,4*D)
        self.proj = nn.Linear(4*D,D)
        self.unembed = nn.Linear(D,P,bias=False)
    def forward(self, x):
        r = self.token(x) + self.position(torch.arange(3,device=x.device))
        q = self.q(r[:,2:3]).reshape(-1,1,H,D//H).transpose(1,2)
        k = self.k(r).reshape(-1,3,H,D//H).transpose(1,2)
        v = self.v(r).reshape(-1,3,H,D//H).transpose(1,2)
        z = F.scaled_dot_product_attention(q,k,v).transpose(1,2).reshape(-1,D)
        r = r[:,2] + self.o(z)
        r = r + self.proj(F.relu(self.fc(r)))
        return self.unembed(r)

pairs = [(a,b) for a in range(P) for b in range(P)]
random.Random(0).shuffle(pairs)
split = int(.3*len(pairs))
data = torch.tensor([(a,b,P) for a,b in pairs],device=device)
labels = (data[:,0]+data[:,1])%P
model = AdditionTransformer().to(device)
optim = torch.optim.AdamW(model.parameters(),lr=.001,betas=(.9,.98),weight_decay=1.)
steps = 40000
with (out/'metrics.jsonl').open('w',encoding='utf-8') as log:
    for step in range(steps+1):
        if step%200 == 0 or step==steps:
            model.eval()
            with torch.no_grad():
                z=torch.cat([model(chunk) for chunk in data.split(1024)])
                row={'step':step,'train_loss':float(F.cross_entropy(z[:split],labels[:split])),
                     'test_loss':float(F.cross_entropy(z[split:],labels[split:])),
                     'train_accuracy':float((z[:split].argmax(1)==labels[:split]).float().mean()),
                     'test_accuracy':float((z[split:].argmax(1)==labels[split:]).float().mean())}
            if step%5000==0 or step in (400,23000):print(row,flush=True)
            log.write(json.dumps(row)+'\n'); log.flush()
            torch.save({'step':step,'model':model.state_dict(),'train_pairs':pairs[:split]},out/f'model-{step:05d}.pt')
        if step==steps: break
        model.train(); optim.zero_grad(set_to_none=True)
        loss=F.cross_entropy(model(data[:split]),labels[:split]); loss.backward()
        for group in optim.param_groups: group['lr']=.001*min((step+1)/10,1)
        optim.step()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Ablation and progress measures

At the end of that run, the product of the MLP output projection and unembedding has five frequencies with the largest norms: 30, 9, 35, 53 and 23. We select them once, at the final checkpoint, and for each retain the four sign pairs in the two-dimensional DFT of the logits, plus the constant term. Removing the five leaves the constant and everything else. The comparison evaluates all 8939 test pairs and calculates both losses on the 3830 training pairs.

At step 40000, full test accuracy is 99.89 %; retaining only those components gives 99.09 %, and removing them gives 0.82 %, close to 1/113≈0.8851/113\approx0.885 % uniform chance. The restricted ablation does not preserve the answer exactly and should not be described as perfect. At step 1000 excluded training loss is 0.000137; at 15000 it is 2.604 while full test accuracy is still 2.71 %. That increase precedes delayed generalization, but the trajectory is not monotonic. The five frequencies were selected retrospectively by norm, so the figure is not a blind prediction.

The next cell reproduces the selection and interventions. A logit DFT is an ablation of the output representation: to study the internal mechanism we also intervene later on the MLP activation and compare an alternative direction.

[ ]Select frequencies and ablate logitsLocal GPU
final = torch.load(out/'model-40000.pt',map_location=device,weights_only=True)
model.load_state_dict(final['model']); model.eval()
with torch.no_grad():
    [email protected]
    norm=torch.fft.rfft(wl,dim=0).abs().square().sum(1).sqrt()
    keys=(torch.topk(norm[1:],5).indices+1).cpu().tolist()
print('Frecuencias finales:',keys)
allpairs=[(a,b) for a in range(P) for b in range(P)]
x=torch.tensor([(a,b,P) for a,b in allpairs],device=device)
y=(x[:,0]+x[:,1])%P
trainset=set(map(tuple,final['train_pairs']))
train=torch.tensor([pair in trainset for pair in allpairs],device=device)
keymask=torch.zeros((P,P),device=device,dtype=torch.bool)
for k in keys:
    for a in (k,P-k):
        for b in (k,P-k):keymask[a,b]=True
restricted_mask=keymask.clone();restricted_mask[0,0]=True
for step in range(0,40001,1000):
    checkpoint=torch.load(out/f'model-{step:05d}.pt',map_location=device,weights_only=True)
    model.load_state_dict(checkpoint['model'])
    with torch.no_grad():
        logits=torch.cat([model(part) for part in x.split(1024)]).reshape(P,P,P)
        coeff=torch.fft.fft2(logits,dim=(0,1))
        restricted=torch.fft.ifft2(coeff*restricted_mask[:,:,None],dim=(0,1)).real.reshape(-1,P)
        excluded=torch.fft.ifft2(coeff*(~keymask)[:,:,None],dim=(0,1)).real.reshape(-1,P)
        flat=logits.reshape(-1,P)
        acc=lambda z:float((z[~train].argmax(1)==y[~train]).float().mean())
        if step in (0,1000,10000,15000,18000,20000,23000,40000):
            print(step, 'test completo/restringido/excluido',acc(flat),acc(restricted),acc(excluded),
                  'pérdida train restringida/excluida',float(F.cross_entropy(restricted[train],y[train])),
                  float(F.cross_entropy(excluded[train],y[train])))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Now check whether the MLP activations contain the trigonometric products. For each frequency, project the 512 post-ReLU values onto the directions used by the neuron-logit matrix to read class cosines and sines. Fit each projection to a constant and the four sine and cosine products of aa and bb, and measure fraction of variance explained (FVE) over all pairs. This is descriptive analysis on the same full domain, not out-of-sample evaluation.

The hook copies the activation it observes and is removed when finished, following the activation caching contract. In this cell it does not modify the network; the previous logit ablation does change the output to measure its consequence.

In the recorded run, the two FVE values for frequencies 30, 9 and 35 are respectively 0.991/0.989, 0.843/0.875 and 0.968/0.969. For 53 and 23 both are below 0.017. Selecting the five largest readout norms therefore does not mean all five have a clean trigonometric explanation: evidence is especially strong for three, while two additional components are not explained by this regression model. That difference is information, not a reason to adjust the plot until it matches the paper.

[ ]Trigonometric products in the MLPLocal GPU
import numpy as np
activation=[]
handle=model.fc.register_forward_hook(lambda module,args,output: activation.append(F.relu(output).detach()))
try:
    with torch.no_grad():
        for part in x.split(1024): model(part)
finally:
    handle.remove()
activation=torch.cat(activation).cpu().numpy()
wl=([email protected]).detach().cpu().numpy()
z=np.arange(P);a=x[:,0].cpu().numpy();b=x[:,1].cpu().numpy()
for k in keys:
    omega=2*np.pi*k/P
    u=np.cos(omega*z)@wl;v=np.sin(omega*z)@wl
    ca,sa=np.cos(omega*a),np.sin(omega*a)
    cb,sb=np.cos(omega*b),np.sin(omega*b)
    design=np.column_stack((np.ones(len(a)),ca*cb,sa*sb,ca*sb,sa*cb))
    observed=np.column_stack((activation@u,activation@v))
    [email protected](design,observed,rcond=None)[0]
    fve=1-((observed-fitted)**2).sum(0)/((observed-observed.mean(0))**2).sum(0)
    print(k,'FVE coseno/seno',fve)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Intervene inside the MLP

The readout above indicates a candidate path, but correlation does not imply the network needs it. Let WL=WUWprojW_L=W_UW_{\mathrm{proj}}, of dimensions 113×512113\times512. For each selected frequency take the real and imaginary parts of the DFT of its rows: these are ten directions in the space of the 512 post-ReLU activations. A QR factorization yields an orthonormal basis QQ. For each example replace the activation hh by QQ⊤hQQ^\top h or (I−QQ⊤)h(I-QQ^\top)h before projection; then let the model compute its logits. Attention and the preceding residual remain active in both cases.

This intervention differs from filtering logits: it changes an internal state and reruns the readout. It does not establish that each of the ten directions is necessary or cleanly separate all frequencies, because readout directions can overlap. The basis was also selected at the final checkpoint and the random control uses one seed. To compare magnitudes, the second control scales the random projection until its removed norm matches that of the candidate intervention for every example; it is no longer a pure orthogonal projection, but avoids interpreting size differences as specificity.

In our checkpoint, evaluating all test pairs on CPU gives 99.89 % without intervention, 99.89 % when retaining only this MLP subspace, and 4.99 % when removing it. Removing a random projection of equal dimension gives 99.89 %; when perturbation norm is matched, the control obtains 74.31 %. The comparison supports a causal contribution from the selected path in this run, subject to the controls and limitations described; it does not individually identify heads or prove that the circuit is universal.

[ ]Internal ablation and MLP controlsLocal GPU
# Se reutiliza el checkpoint, sin volver a entrenar. Los resultados de referencia son CPU.
model=model.cpu().eval(); model.load_state_dict(final['model'])
x=x.cpu(); y=y.cpu(); train=train.cpu()
with torch.no_grad():
    [email protected]
    freq=torch.fft.rfft(wl,dim=0)[keys]
    Q=torch.linalg.qr(torch.cat([freq.real,freq.imag],dim=0).T,mode='reduced').Q
    generator=torch.Generator().manual_seed(37)
    randomQ=torch.linalg.qr(torch.randn(512,10,generator=generator),mode='reduced').Q
    assert torch.allclose(Q.T@Q,torch.eye(10),atol=1e-5)

def evaluate(mode):
    def intervene(module,args):
        h=args[0]
        basis=randomQ if mode in ('random','random_matched') else Q
        part=(h@basis)@basis.T
        if mode=='random_matched':
            size=((h@Q)@Q.T).norm(dim=-1,keepdim=True)
            part=part*size/part.norm(dim=-1,keepdim=True).clamp_min(1e-12)
        return (part if mode=='keep' else h-part,)
    handle=None if mode=='full' else model.proj.register_forward_pre_hook(intervene)
    try:
        with torch.no_grad(): logits=torch.cat([model(part) for part in x.split(512)])
    finally:
        if handle is not None: handle.remove()
    return float((logits[~train].argmax(1)==y[~train]).float().mean())

for mode in ('full','keep','remove','random','random_matched'):
    print(mode, evaluate(mode))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
How many pairs are in the training sample if you take floor(0.30 × 113²)?
Quiz
Which conclusion is compatible with the weight-decay experiments?
Code
Implement fourier_basis(p) for odd p: return a real orthonormal matrix of shape (p,p), with a constant column and, for each k=1,...,(p-1)//2, normalized cosine and sine columns. Implement spectrum(E) returning the norm per transformed column of E, a (p,d) matrix.
import numpy as np
def fourier_basis(p):
  pass
def spectrum(E):
  pass
Shift+Enter to run
Proof
Prove: For prime p and a frequency k nonzero modulo p, cos(2πk(a+b-c)/p) has a unique maximum at the class c = a+b modulo p.
0
Cosine is at most 1.

Step 1 of 2. When is 1 attained?

Key idea
An accuracy curve can hide gradual changes. A circuit hypothesis needs an appropriate basis, an explicit intervention and controls, as well as a distinction between published results and those from your own run.