# My Transformer Memorised the Answers, Then Taught Itself Trigonometry

> Source: <https://pub.towardsai.net/my-transformer-memorised-the-answers-then-taught-itself-trigonometry-0fd2453c5c21?source=rss----98111c9905da---4>
> Published: 2026-11-27 19:01:01+00:00

**Key takeaway:** In a 226,688-parameter one-layer transformer trained on 30% of (a + b) mod 113 pairs, 93% of embedding squared norm landed in frequencies k = 1, 8 and 21 and 391 of 512 MLP neurons were at least 85% single-frequency, so test accuracy only reached 100% at step 6,000 despite 99% train accuracy by step

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](https://github.com/abdulm-ai/grokking-circuits).

The 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.

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.

Before 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:

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.

**The 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.

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.

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.

**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:

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.

This 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.

```
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:

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.

One 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.

```
pip install -r requirements.txtpython train.py                              # about 17 minutes on a laptop CPUpython analyze.py --run runs/p113 --figures figures
```

python 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](https://github.com/abdulm-ai/grokking-circuits).

[My Transformer Memorised the Answers, Then Taught Itself Trigonometry](https://pub.towardsai.net/my-transformer-memorised-the-answers-then-taught-itself-trigonometry-0fd2453c5c21) was originally published in [Towards AI](https://pub.towardsai.net) on Medium, where people are continuing the conversation by highlighting and responding to this story.
