My Transformer Memorised the Answers, Then Taught Itself Trigonometry
From the publisher’s feed, collected in the ZeroLabs newsroom.
A one-layer transformer on my laptop got every training example right in 150 steps and stayed near chance on new ones for 4,000 more. Its weights show it was building a cosine circuit the whole time.Train a small transformer on a simple maths task with only part of the data, and something odd happens. It gets the training set right almost at once, which looks like memorisation, and test accuracy stays near zero. Keep training long after the training loss has stopped going down, and at some point test accuracy climbs to 100%. Power et al. (2022) called this grokking.Nanda et al. (2023) then took one of these networks apart and found the algorithm it learned for modular addition. It’s not a lookup table. It’s trigonometry. I wanted to see this for myself, on my own laptop, without an interpretability library. So I wrote the model, the training loop and the analysis from scratch in PyTorch, about 500 lines in total, and tried to read the algorithm straight out of the weights.It worked better than I expected. The code, the figures and every number below are in grokking-circuits.The setupThe task is (a + b) mod 113. The input is three tokens, a, b and =, and the model predicts the answer at the = position. There are 113 × 113 = 12,769 possible pairs. The model trains on a random 30% of them (3,830) and is tested on the other 8,939.The model is as small as a transformer gets: one layer, four attention heads of 32 dimensions, a 512-neuron ReLU MLP, a 128-dimensional residual stream, no LayerNorm and no tied weights. 226,688 parameters. Leaving out LayerNorm matters here, because it means every weight matrix can be read directly.Training follows the paper: full-batch AdamW, learning rate 1e-3, weight decay 1.0 (very high, on purpose), 12,000 steps. On an Intel i7–1265U that took 1,021 seconds, about 17 minutes.The curveTrain and test loss and accuracy. Train accuracy passes 99% at step 150. Test accuracy passes 50% at step 4,600 and 99% at step 5,450.Train accuracy passes 99% at step 150. At step 1,000 the train loss is 4e-6 and test accuracy is 2.3%, which is about what you’d get by guessing (1 in 113 is 0.9%). The test loss is 25.8, far worse than guessing, because the model is confidently wrong.Then nothing visible happens for a long time. Test accuracy is 21% at step 4,000. It passes 50% at step 4,600 and 99% at step 5,450. By step 6,000 it’s 100%.From the outside, that looks like a sudden jump. The question is what the network was doing for those 4,000 steps.How you’d add numbers on a clockBefore reading the weights, it helps to know what to look for. Nanda et al. found the algorithm, and it’s easiest to picture as a clock.Put the numbers 0 to 112 around a circle. Adding mod 113 is then adding angles: a is a rotation by w·a, b is a rotation by w·b, and doing one after the other is a rotation by w(a + b). Going all the way round is the "mod". Here w = 2πk/113 for some whole number k, the frequency.In numbers, the network does this:Embed each input as cos(w·a) and sin(w·a) for a few frequencies.Combine them into cos(w(a + b)) and sin(w(a + b)). That's the angle-sum identity, cos(x + y) = cos x cos y − sin x sin y. It needs products of the two inputs, which attention plus a ReLU MLP can approximate.Read out a score for every possible answer c. The unembedding is linear, so it can compute cos(w(a + b))·cos(w·c) + sin(w(a + b))·sin(w·c), which is cos(w(a + b − c)). That's 1 exactly when c = (a + b) mod 113 and smaller everywhere else.One frequency isn’t enough on its own. At k = 1, the neighbouring answers score cos(2π/113) ≈ 0.998, almost a tie. A high frequency separates neighbours well but nearly ties with some distant answers. Add a few frequencies together and they only all peak at the same place: the right answer.That gives four things to check: the embedding should use only a few frequencies, the MLP neurons should each be tuned to one of them, the logits should be a sum of cos(w(a + b − c)) terms, and removing those terms should break the model.Reading it out of the weightsThe embedding. Project the 113 input embeddings onto a Fourier basis (a constant, then a cos and a sin for each frequency from 1 to 56) and measure how much norm each frequency has. At initialisation it’s spread evenly. After training, 93% of the squared norm sits in three frequencies: k = 1, 8 and 21.The embedding in the Fourier basis at step 0 and step 12,000. The three key frequencies are in orange.I didn’t pick those three by looking at this plot. They come from the neurons.The neurons. Each of the 512 MLP neurons has an activation for every (a, b) pair, a 113 × 113 image. Move that image into the 2D Fourier basis and ask how much of its variance one frequency explains. 391 of the 512 neurons get at least 85% of their variance from a single frequency, and they fall into three groups: 137 neurons on k = 1, 147 on k = 8 and 107 on k = 21. No neuron reaches 85% on any other frequency.Left, the number of neurons with at least 85% of their variance explained by each frequency. Right, the activation over every (a, b) of the best neuron in each group.You can see it in the activation images. A k = 1 neuron has one smooth bump in each direction. A k = 21 neuron is a fine grid of 21 bumps.The attention. How much the = token attends to a instead of b is also a periodic function of the inputs. Measured the same way, heads 0 and 1 run at k = 21 (95% and 86% of their variance), and heads 2 and 3 at k = 1 (96% and 91%). No head runs at k = 8, so that frequency must reach the MLP through the embedding and the residual stream alone. I didn't expect that, and I haven't looked into it further.Attention from “=” to a, for every (a, b), per head.The logits. Fit the logits, over all 11³³ combinations of a, b and c, to Σ α_k cos(w_k(a + b − c)) with just the three frequencies. That's three coefficients for 1.4 million numbers. The fit explains 98.8% of the variance (R² = 0.988).The ablations. The last check is causal, and it’s the one I trust most. Nanda et al. define two versions of the logits:Restricted: keep only the part of each logit that moves with cos(w_k(a + b)) and sin(w_k(a + b)) for the three key frequencies, plus its average. Throw everything else away.Excluded: remove exactly that part, and keep everything else.The restricted logits still get 100% of the test set right, with a loss of 5.5e-8. The excluded logits get a training loss of 7.8, worse than uniform guessing (ln 113 ≈ 4.7), and only 2.6% of the training set right. So the three frequencies are enough on their own, and without them the model can’t even fit the data it trained on.The circuit was there before the test score movedThis is the part I find most interesting. The final model is a clean trig machine, but the test accuracy jumped late. If you run the same measurements on every checkpoint (one every 250 steps, 49 in all, all scored with the final model’s three frequencies), the jump turns out not to be sudden at all.Left, train, test, excluded and restricted loss over training. Right, the sum of squared weights and the share of the embedding’s norm in the three key frequencies.step train test excluded restricted Σ w² key share 0 4.75 4.74 4.75 4.74 1,398 6%1,000 4e-6 25.8 1.0e-3 3.38 3,492 13%2,000 3e-7 24.3 0.035 1.95 2,872 17%3,000 3e-7 18.2 1.35 0.86 2,582 22%4,000 3e-7 10.3 6.87 0.093 2,310 29%5,000 2e-7 0.62 17.8 5e-6 1,823 44%6,000 1e-7 6e-5 13.9 6e-8 1,228 65%8,000 1e-7 2e-7 7.93 6e-8 914 89%12,000 9e-8 2e-7 7.80 5e-8 878 93%Read down the columns:Up to about step 1,000, memorisation. The train loss collapses. The excluded loss is just as low (1e-3), which means the model fits the training set without the three frequencies. The weights grow to their largest size.From about 1,000 to 4,500, the circuit forms. Training accuracy is already 100% and test accuracy creeps from 2% at step 1,000 to 21% at step 4,000. Underneath, the excluded loss climbs from 1e-3 past 6, so the model now relies on the cosine circuit to fit its own training data. At the same time the restricted loss falls from 3.4 to 0.09: the circuit on its own already generalises. The full model’s test loss stays high because the memorised part is still in there, adding noise on top.From about 4,500 to 7,000, cleanup. Weight decay strips the memorised part out. This is where the weight norm falls fastest, and the test loss drops from 4.6 at step 4,500 to 3e-7 at step 7,000.These three phases match what Nanda et al. report, though my step numbers are different. The frequencies are different too: their model used a different set, which as far as I understand depends on the random seed.My reading of the middle phase is the paper’s: the model builds the general solution slowly, and the test score only moves once the memorised solution is gone. I think that’s right, but these measurements show the two losses moving together, not that one causes the other. A cleaner test would be to remove the memorised component on purpose partway through and see if the test accuracy jumps earlier. I haven’t done that.Why would weight decay prefer the cosine circuit at all? The usual explanation is that it fits the same training data with smaller weights than a lookup table, so weight decay keeps pushing towards it. The weight norm here falls from 3,492 to 878 while the training loss stays near zero, which fits that story. I didn’t test it directly.A detour: the CPU got 5x slowerOne practical thing that cost me a run. My first training run started at 0.055 seconds per step and slowed to 0.284 seconds per step by step 6,000, with nothing else using the CPU.The cause was denormal (subnormal) floats. Once the training loss is around 1e-7, the gradients and Adam’s running averages of squared gradients get tiny enough to fall below float32’s normal range. x86 CPUs handle those numbers through a slow path. One line fixes it:torch.set_flush_denormal(True)That rounds those values to zero. In the rerun, the step time stayed at about 0.085 seconds from start to finish. That’s slower than the first run’s opening steps, which I can’t fully explain, but it didn’t creep up. Flushing changes the numbers slightly, so every result above comes from the rerun. I think anyone reproducing grokking on a CPU will run into this, because grokking means training for a long time after the loss is already tiny.What I’m not sure aboutOne seed, one modulus, one train fraction. I don’t know how much the grokking step moves between seeds.The progress measures use the final model’s frequencies. If the model used some other frequency for a while and then dropped it, these measurements wouldn’t show it.k = 16. The embedding has a smaller peak at k = 16 (norm 2.8, against about 6 to 7 for the three key frequencies). No neuron is tuned to it. It’s 2 × 8, so it might be a harmonic that helps k = 8, but that’s a guess.Float precision. The loss is computed in float64, because late in training float32 runs out of precision and can cause loss spikes (Thilak et al., 2022, call it the slingshot). Everything else is float32 on a CPU, so a GPU run with the same seed won’t match step for step.Run itpip install -r requirements.txtpython train.py # about 17 minutes on a laptop CPUpython analyze.py --run runs/p113 --figures figurespython train.py --steps 7000 takes about 10 minutes and still groks, with less cleanup. analyze.py works on any run train.py writes, for any odd modulus.The repo: github.com/abdulm-ai/grokking-circuits.ReferencesPower, Burda, Edwards, Babuschkin and Misra (2022). Grokking: Generalization Beyond Overfitting on Small Algorithmic Datasets. arXiv:2201.02177.Nanda, Chan, Lieberum, Smith and Steinhardt (2023). Progress measures for grokking via mechanistic interpretability. ICLR 2023. arXiv:2301.05217.Thilak, Littwin, Zhai, Saremi, Paiss and Susskind (2022). The Slingshot Mechanism: An Empirical Study of Adaptive Optimizers and the Grokking Phenomenon. arXiv:2206.04817.My Transformer Memorised the Answers, Then Taught Itself Trigonometry was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.