Reverse-Engineering Grokking: How a Laptop-Trained Transformer Solved Modular Math
A PyTorch experiment reveals how a single-layer transformer memorized addition before quietly building a trigonometric circuit to achieve 100% generalization.

When machine learning models encounter algorithmic problems, their learning trajectories often present puzzling behavior. A model can rapidly master its training set through brute memorization while remaining unable to solve unseen examples, only to suddenly achieve flawless generalization thousands of optimization steps later. In a project examining this delayed generalization—a phenomenon termed "grokking" by Power et al. in 2022—independent researcher Abdul M. reproduced the mechanistic findings of Nanda et al. (2023) using a compact, 500-line PyTorch script executed entirely on a standard consumer laptop.
The experiment tracked the internal mechanics of a minimal one-layer transformer tasked with computing (a + b) mod 113. By avoiding LayerNorm and parameter sharing, the architecture permitted direct inspection of its 226,688 parameters, demonstrating how high weight decay pushes neural networks to abandon memorized lookup tables in favor of structured mathematical algorithms.
Inside the trigonometric circuit
The model was evaluated on 12,769 total combinations of input pairs, training exclusively on a random 30 percent slice (3,830 examples) while being evaluated on the remaining 8,939 pairs. Training ran for 12,000 steps using full-batch AdamW, a learning rate of 1e-3, and a heavy weight decay of 1.0 on an Intel i7-1265U processor, completing in 1,021 seconds.
While training accuracy climbed past 99 percent in just 150 steps, test accuracy lingered near pure chance (2.3 percent at step 1,000, against an 0.9 percent random baseline) for thousands of steps. Outside observers might see the subsequent jump to 50 percent accuracy at step 4,600 and 100 percent by step 6,000 as an abrupt shift. However, parameter analysis showed an internal algorithm developing continuously over time.
Rather than storing a discrete lookup table, the transformer formed a circular arithmetic mechanism resembling a clock face with 113 positions. By projecting the input embeddings into a Fourier basis, the author observed that 93 percent of the squared norm concentrated into three distinct frequencies: $k = 1$, $k = 8$, and $k = 21$.
Similarly, 391 of the model's 512 MLP neurons had at least 85 percent of their activation variance driven by one of these three frequencies (137 neurons for $k=1$, 147 for $k=8$, and 107 for $k=21$). Attention heads divided the work as well: heads 0 and 1 operated at frequency 21, while heads 2 and 3 operated at frequency 1. Using trigonometric angle-sum identities, the network mapped inputs into rotating sine and cosine components and evaluated their products. Causal ablation confirmed this structure: restricting logits to only these three frequencies maintained 100 percent test accuracy, whereas isolating and removing them caused the model's training accuracy to collapse to 2.6 percent.
Tracking the three phases of training
By measuring the model's weights and losses at 49 checkpoints across training, the study identified three distinct operational phases:
- Memorisation (Steps 0–1,000): The training loss plummeted to 4e-6, driven by an ungeneralized memorized solution that pushed the sum of squared weights up to a peak of 3,492.
- Circuit Formation (Steps 1,000–4,500): Although test accuracy climbed slowly to just 21 percent, the underlying general circuit quietly took shape. The restricted loss fell from 3.38 to 0.093, showing that the general circuit was already capable of solving the task, even though noise from lingering memorization prevented test scores from reflecting it.
- Cleanup (Steps 4,500–7,000): High weight decay steadily pruned the inefficient memorization component, dropping the sum of squared weights from 2,310 at step 4,000 down to 878 at step 12,000. As the memorized noise disappeared, test accuracy surged to 100 percent.
The project also noted a hardware-level hurdle: training slowed fivefold as gradients fell into subnormal float32 ranges on the CPU. Setting torch.set_flush_denormal(True) resolved the performance degradation by rounding tiny numbers directly to zero.
What it means for developers
This experiment offers several clear insights for engineers building and analyzing machine learning systems:
- Metrics do not tell the whole story: Flat validation accuracy during training does not necessarily mean a model is stagnant. In overparameterized regimes with strong regularization, generalizable representations may form underneath memorized representations long before validation loss visibly drops.
- Weight decay acts as an architectural filter: In algorithmic settings, weight decay actively disfavors high-norm memorization strategies in favor of compact, parameter-efficient circuits like Fourier representations.
- Mechanistic interpretability is accessible: Researchers do not always require massive GPU clusters to study internal neural mechanisms. Small models trained on CPUs can cleanly exhibit core properties of representation learning.
- Precision issues impact optimizer dynamics: As losses reach near-zero thresholds, running in standard float32 can cause CPU slowdowns or optimizer instability (slingshots), requiring measures like denormal flushing or double-precision calculations.
For developers deploying modern systems in production, understanding how models transition from memorization to structured reasoning remains critical. Those evaluating and experimenting with production-ready systems can try top AI models cheaply through one API at https://apixoai.online, which provides a unified endpoint for leading architectures.
Source: My Transformer Memorised the Answers, Then Taught Itself Trigonometry — Towards AI. Written by the Apixo team from that report.
One key for Claude, GPT, GLM, DeepSeek and more. Pay per token with crypto.
Get your API key

