Grokking
Generalization long after memorization, and the circuits that make it happen.
Train a small transformer on half of the division table modulo 97. Within a thousand steps it reproduces every training equation; for about a hundred thousand steps it shows little sign of getting the unseen equations right; then, by about a million steps, it gets nearly all of them right. This delayed generalization, called grokking, has become a laboratory for how networks move from memorizing to computing: in one case the learned algorithm has been read off the weights, phase by phase.
What you’ll learn
- Describe the grokking experiments of Power et al. (2022) and how the delay depends on the training fraction and on weight decay.
- Derive the Fourier-multiplication algorithm a one-layer transformer learns for modular addition, and prove that its logits interfere constructively only at .
- Explain the three training phases found by Nanda et al. (2023) and the progress measures that reveal them before test accuracy moves.
- Compare the main explanations (circuit efficiency, weight-norm dynamics, the lazy-to-rich transition, early versus late implicit biases, optimizer effects) by the evidence for each.
Generalization long after memorization
Power, Burda, Edwards, Babuschkin and Misra (2022) trained networks on tables of binary operations , in which every element is an abstract token with no internal structure: addition, subtraction, division and several polynomials modulo the prime , and composition of permutations in the group . A random fraction of all equations formed the training set and the rest the validation set, so learning means filling in the blanks of a table. The model was a decoder-only transformer with 2 layers, width 128 and 4 heads, about non-embedding parameters, trained with AdamW at learning rate and weight decay 1.
On division modulo 97 with half the equations for training, training accuracy was near perfect within steps. Validation accuracy showed little sign of rising until about steps and reached near-perfect levels only close to . Generalization began about a thousand times later than memorization: this is grokking.
The division table uses for and . With 50% of the equations in the training set, how many training equations are there?
Show the answer
4656
There are equations, since division by 0 is excluded, so half is 4,656. Addition has all pairs. These tables are tiny by deep-learning standards, which is what makes it feasible to train for a million steps and to look inside the network.
Two regularities held across the operations. Less data, much longer waits. For permutation composition in , near 25–30% of the table, removing 1% of the training data raised the median number of steps to reach 99% validation accuracy by 40–50%, while the time to fit the training set stayed between and steps; with too little data, nothing generalized within the budget. Weight decay matters most. Among the interventions compared, including dropout, noise added to the updates and full-batch training, weight decay improved data efficiency the most, more than halving the number of training examples needed relative to most others; decay toward the initialization also worked, though less well.
Grokking is not the whole story of these tasks. Some generalization happened even with full-batch optimizers and no noise when the training fraction was large, and the wait shrank quickly as the fraction grew; with enough data there is no delay at all, as training and test loss fall together (Nanda et al., 2023). The delay is a phenomenon of the regime near the smallest dataset that generalizes.
In Power et al.'s experiments, how did the number of steps needed to reach 99% validation accuracy change as the training fraction was reduced?
- It fell, because smaller training sets are fitted faster
- It stayed about the same, like the time to fit the training set
- It grew rapidly (by 40–50% per percentage point of data removed near 25–30% on ), while the time to fit the training set did not grow
- It grew in proportion to the number of training examples
Show the answer
C. It grew rapidly (by 40–50% per percentage point of data removed near 25–30% on ), while the time to fit the training set did not grow
Fitting the training set took to steps at every fraction, while the time to generalize grew roughly exponentially as data were removed. The gap between the two is the grokking delay, and it widens fast as the dataset approaches the smallest size that generalizes at all.
The algorithm inside: Fourier multiplication
Nanda, Chan, Lieberum, Smith and Steinhardt (2023) reverse-engineered a network that groks. Their one-layer transformer reads " " as one-hot tokens and predicts with . It has width 128, 4 attention heads of size 32, a ReLU MLP of 512 units and no layer normalization, and it trained on 30% of the pairs with full-batch AdamW, learning rate and weight decay , for 40,000 epochs. Training accuracy reached 100% quickly; test accuracy rose to near 100% after about 10,000 epochs. Inside, the network computes with rotations. Write .
Embed. For a few key frequencies , the embedding sends the token to a point on a circle, rotated by steps of angle :
Compose. Attention and the MLP form products of these features (most neurons are well approximated by degree-2 polynomials in the sine and cosine of a single frequency), and the angle-addition identities turn the products into the rotation by :
Read off. The unembedding gives each candidate answer a logit that is linear in these values, a rotation back by :
Sum over frequencies. The logits are approximately a weighted sum over the key frequencies . For the main model , and a least-squares fit of the weights explains 95% of the variance of the actual logits:
A single key frequency already gives a logit that is largest at the right answer. Why is one frequency not enough?
- One frequency cannot represent addition modulo a prime
- Each frequency handles a different range of inputs
- Some wrong answer always gets almost the same logit: is invertible modulo , so some has , where the cosine is for
- Several frequencies are needed to fit the training set, but not the test set
Show the answer
C. Some wrong answer always gets almost the same logit: is invertible modulo , so some has , where the cosine is for
With one frequency the margin between the right answer (1) and the best wrong one (about 0.998) is tiny, so the logits would have to be enormous to make the prediction confident. With the five key frequencies and equal weights, the correct answer gets 5 and the best wrong answer about 2.59, a margin that a moderate logit scale turns into a confident prediction.
Four lines of evidence support this reading. The weights and activations are periodic in the inputs. The embedding is sparse in the Fourier basis, with significant weight at only 6 frequencies, 5 of which the rest of the network uses. 433 of the 512 neurons have over 85% of their variance explained by a single frequency. And ablations behave as predicted: removing the key frequencies drops performance to chance, while removing the other 95% of the Fourier components slightly improves it.
The circuit is not the only possible one. Zhong, Liu, Tegmark and Andreas (2023) found that small changes of hyperparameters or initialization lead networks trained on modular addition to this "clock" algorithm, to a different "pizza" algorithm, or to several running in parallel. Gromov (2023) showed that two-layer MLPs trained by plain gradient descent on the squared loss, with no regularization at all, also grok modular arithmetic, and wrote down analytic weights, built from Fourier features, that solve it.
Three phases and their progress measures
If the generalizing circuit exists before test accuracy jumps, it should be measurable. Nanda et al. built two progress measures from the algorithm. The restricted loss keeps only the key-frequency components of the logits, so it measures how well the Fourier algorithm alone would do. The excluded loss removes exactly those components and is measured on the training data, so it shows how much of the training performance still comes from memorization. Together with the sum of squared weights and the sparsity of the weights in the Fourier basis, they split training into three phases.
| Phase (epochs) | What the measures show | Interpretation |
|---|---|---|
| Memorization (0 to 1.4k) | Training loss and excluded loss fall; test loss and restricted loss stay high | A lookup table of the training pairs; the key frequencies are not yet in use |
| Circuit formation (1.4k to 9.4k) | Excluded loss rises, restricted loss starts to fall and the sum of squared weights falls, while training and test loss stay flat | On the training set the network shifts from memorizing to the Fourier algorithm, apparently driven by weight decay |
| Cleanup (9.4k to 14k) | Test loss drops suddenly, restricted loss keeps falling, the weight norm drops sharply and the weights become sparse in the Fourier basis | Weight decay removes the memorizing components, and the circuit that already exists takes over the predictions |
Weight decay is essential here. In Nanda et al.'s experiments, less decay made the network take much longer to grok, and without weight decay or another regularizer it did not grok at all; with enough data there was no gap between training and test loss. Varma, Shah, Kenton, Kramár and Kumar (2023) proposed why decay should matter, through the efficiency of a circuit: how large a logit it produces per unit of parameter norm.
Once the training loss is nearly zero its gradient is tiny, and decoupled decay multiplies the weights by per step (Weight Decay, Dropout & Early Stopping). If the network starts at norm but generalizes only near a smaller norm ,
This is the heuristic behind Omnigrok (Liu, Michaud & Tegmark, 2023): the delay grows like , so a small decay produces a long delay and no decay may mean no generalization at all, while a larger initialization lengthens it only logarithmically. Lyu, Jin, Li, Du, Lee and Hu (2024) proved a sharp version for homogeneous networks trained by gradient flow with initialization scale and small weight decay : in the limit of large , the network stays near a kernel predictor until time about and reaches a KKT point of the min-norm or max-margin problem by about , for any constant (with for the first).
With decoupled weight decay at and , as in the modular-addition runs, about how many steps does decay alone need to shrink the weights tenfold?
Show the answer
2300
gives steps, close to . Halving doubles it. In real runs the loss gradients also act on the norm, so this is a timescale, not a prediction of the moment of grokking: Nanda et al.'s cleanup came between about 9,400 and 14,000 full-batch steps.
What explains grokking?
| Account | Claim | Evidence |
|---|---|---|
| Representation learning (Liu, Kitouni, Nolte, Michaud, Tegmark & Williams, 2022) | Generalization comes from structured representations of the inputs; phase diagrams over hyperparameters show four regimes: comprehension, grokking, memorization and confusion | An effective theory predicts the dynamics in a toy setting; for transformers the grokking region lies close to the memorization region, hence the delay |
| Weight norm: the LU mechanism (Liu, Michaud & Tegmark, 2023) | Training loss against weight norm is L-shaped and test loss U-shaped, so a network started at too large a norm fits quickly and generalizes only after its norm shrinks | Large initializations induced grokking on MNIST, IMDb reviews and QM9 molecules; constraining the weight norm nearly eliminated grokking on algorithmic data |
| Circuit efficiency (Varma et al., 2023) | A slow but efficient generalizing circuit overtakes a fast memorizing one under weight decay | Confirmed predictions: a critical dataset size, ungrokking and semi-grokking |
| Lazy to rich (Kumar, Bordelon, Gershman & Pehlevan, 2024) | The network first fits with its initial features, like kernel regression, and learns better features only later | Grokking without any regularization for a two-layer network trained on polynomial regression by plain gradient descent, controlled by the scale of the output and by how well the initial NTK aligns with the target |
| Early and late implicit biases (Lyu et al., 2024) | With large initialization and small decay, training sits at a kernel predictor and then switches sharply to a min-norm or max-margin one | Theorems for homogeneous networks, with examples where the kernel predictor fails and the max-margin predictor generalizes |
| Optimizer and numerics | Without explicit regularization, the late dynamics of the optimizer decide when, or whether, the network generalizes | Grokking at the onset of cyclic "slingshot" instabilities of adaptive optimizers (Thilak et al., 2022); floating-point "softmax collapse" that halts learning, and a fix that allows grokking without regularization (Prieto, Barsbey, Mediano & Birdal, 2025) |
These accounts overlap more than they compete. Most describe two solutions, one reached quickly and one that generalizes, and a slow force that carries training from the first to the second: weight decay shrinking the norm, feature learning escaping the initial kernel, or an instability of the optimizer. They differ on what the slow force is in a given setting, and grokking without explicit regularization shows that decay is not the only candidate.
Special, or slow feature learning? On one view grokking is ordinary feature learning, slow because the network starts lazy or at a large norm, plus a force that eventually favors the simpler solution, made dramatic by tasks with a sharp divide between memorizing and computing. It appears on MNIST once the initialization is large, and it disappears when there is enough data. On the other view the algorithmic tasks reveal something general: networks can make continuous internal progress while external metrics stay flat. That links grokking to the debate about emergent abilities in large models (Neural Scaling Laws) and to the hidden progress of SGD on sparse parities (How SGD Learns Features).
Key takeaways
- Grokking: on small algorithmic tables, training accuracy saturates within about steps while test accuracy rises 100 to 1,000 times later; the delay grows steeply as the training fraction shrinks, and of the interventions tried, weight decay improves data efficiency the most (Power et al., 2022).
- A one-layer transformer trained on embeds inputs as rotations at five key frequencies, composes them with angle-addition identities and reads off logits that interfere constructively only at the answer (Nanda et al., 2023).
- Progress measures reveal three phases (memorization, circuit formation, cleanup); the jump in test accuracy comes during cleanup, after the generalizing circuit has formed, as weight decay removes the memorizing components.
- The explanations share a pattern: a fast solution, a better one and a slow force between them, whether weight decay acting on efficiency or norm (a delay of about ), a lazy-to-rich transition or optimizer dynamics. Which force dominates where, and whether grokking matters at scale, are open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In Nanda et al.'s modular-addition transformer, when does the generalizing circuit form, relative to the jump in test accuracy?
- Only at the moment test accuracy jumps
- Before it, during circuit formation; the jump comes in the cleanup phase, as weight decay removes the memorizing components
- After it, once the network has seen the test pairs
- It never forms; the network keeps memorizing and interpolates between training pairs
Show the answer
B. Before it, during circuit formation; the jump comes in the cleanup phase, as weight decay removes the memorizing components
The restricted loss starts falling and the excluded loss rises during circuit formation (epochs 1.4k to 9.4k), while test loss is flat. Test loss drops only in cleanup (9.4k to 14k), as the weight norm falls sharply and the memorizing components are removed.
In the large-initialization picture of grokking, decay must shrink the weight norm from to after the training set has been fitted. What does halving the weight decay do?
- Halves the delay
- Leaves the delay unchanged, since it depends only on the data
- Prevents grokking entirely
- Roughly doubles the delay, which scales like
Show the answer
D. Roughly doubles the delay, which scales like
Decay multiplies the weights by per step, so shrinking them by a fixed factor takes about steps: half the decay, twice the wait. With no decay and no other force toward smaller norms, the wait can be endless, which is why some runs never grok.
What is "ungrokking" (Varma et al., 2023)?
- A network that has grokked, trained further on a much smaller training set, falls back to poor test accuracy, because memorizing has become the more efficient solution
- Test accuracy rising before training accuracy
- Forgetting the training set after grokking
- A network that never generalizes, however long it is trained
Show the answer
A. A network that has grokked, trained further on a much smaller training set, falls back to poor test accuracy, because memorizing has become the more efficient solution
Below the critical dataset size, the memorizing circuit is more efficient than the generalizing one, so cross-entropy plus weight decay favors it. A grokked network retrained on such a small dataset therefore loses its generalizing solution, as the efficiency account predicted.
Why do logits of the form , with and prime, single out ?
- Each cosine is positive only at the correct answer
- Every term equals 1 at , while for each frequency the values at the other answers sum to , so they partly cancel
- The unembedding stores the answer for every pair
- Cosines of different frequencies are orthogonal, so only one term is nonzero
Show the answer
B. Every term equals 1 at , while for each frequency the values at the other answers sum to , so they partly cancel
At every cosine is 1, so the logit is . For each frequency the values sum to zero, so the wrong answers share a total of per frequency. With the five key frequencies the correct logit is 5, the wrong ones average , and the largest wrong one is about 2.59.
Further reading
- A. Power, Y. Burda, H. Edwards, I. Babuschkin & V. Misra, "Grokking: generalization beyond overfitting on small algorithmic datasets," arXiv:2201.02177 (2022).
- N. Nanda, L. Chan, T. Lieberum, J. Smith & J. Steinhardt, "Progress measures for grokking via mechanistic interpretability," ICLR (2023).
- V. Varma, R. Shah, Z. Kenton, J. Kramár & R. Kumar, "Explaining grokking through circuit efficiency," arXiv:2309.02390 (2023).
- Z. Liu, E. J. Michaud & M. Tegmark, "Omnigrok: grokking beyond algorithmic data," ICLR (2023).
- T. Kumar, B. Bordelon, S. J. Gershman & C. Pehlevan, "Grokking as the transition from lazy to rich training dynamics," ICLR (2024).
- K. Lyu, J. Jin, Z. Li, S. S. Du, J. D. Lee & W. Hu, "Dichotomy of early and late phase implicit biases can provably induce grokking," ICLR (2024).