Simple Algorithm
Deep Learning · Emergence · 28 min

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 c≡a+b(modP)c\equiv a+b\pmod P.
  • 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 a∘b=ca\circ b=c, in which every element is an abstract token with no internal structure: addition, subtraction, division and several polynomials modulo the prime p=97p=97, and composition of permutations in the group S5S_5. 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 4×1054\times10^5 non-embedding parameters, trained with AdamW at learning rate 10−310^{-3} and weight decay 1.

On division modulo 97 with half the equations for training, training accuracy was near perfect within 10310^3 steps. Validation accuracy showed little sign of rising until about 10510^5 steps and reached near-perfect levels only close to 10610^6. Generalization began about a thousand times later than memorization: this is grokking.

Predict before you look

The division table uses x∘y=x/y mod 97x\circ y=x/y\bmod97 for 0≤x<970\le x<97 and 0<y<970<y<97. With 50% of the equations in the training set, how many training equations are there?

Show the answer

4656

There are 97×96=9,31297\times96=9{,}312 equations, since division by 0 is excluded, so half is 4,656. Addition has all 972=9,40997^2=9{,}409 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 S5S_5, 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 10310^3 and 10410^4 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.

Check your understanding

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?

  1. It fell, because smaller training sets are fitted faster
  2. It stayed about the same, like the time to fit the training set
  3. It grew rapidly (by 40–50% per percentage point of data removed near 25–30% on S5S_5), while the time to fit the training set did not grow
  4. 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 S5S_5), while the time to fit the training set did not grow

Fitting the training set took 10310^3 to 10410^4 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 "aa bb ==" as one-hot tokens and predicts c=a+b mod Pc=a+b\bmod P with P=113P=113. 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 1132=12,769113^2=12{,}769 pairs with full-batch AdamW, learning rate 10−310^{-3} and weight decay λ=1\lambda=1, 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 ωk=2πk/P\omega_k=2\pi k/P.

DerivationModular addition as composition of rotations
  1. a ↦ (cos⁡ωka, sin⁡ωka),ωk=2πkPa\ \mapsto\ \big(\cos\omega_ka,\ \sin\omega_ka\big),\qquad\omega_k=\frac{2\pi k}{P}

    Embed. For a few key frequencies kk, the embedding sends the token aa to a point on a circle, rotated by aa steps of angle ωk\omega_k:

  2. cos⁡ωk(a+b)=cos⁡ωkacos⁡ωkb−sin⁡ωkasin⁡ωkb,sin⁡ωk(a+b)=sin⁡ωkacos⁡ωkb+cos⁡ωkasin⁡ωkb\cos\omega_k(a+b)=\cos\omega_ka\cos\omega_kb-\sin\omega_ka\sin\omega_kb,\qquad\sin\omega_k(a+b)=\sin\omega_ka\cos\omega_kb+\cos\omega_ka\sin\omega_kb

    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 a+ba+b:

  3. cos⁡ωk(a+b−c)=cos⁡ωk(a+b)cos⁡ωkc+sin⁡ωk(a+b)sin⁡ωkc\cos\omega_k(a+b-c)=\cos\omega_k(a+b)\cos\omega_kc+\sin\omega_k(a+b)\sin\omega_kc

    Read off. The unembedding gives each candidate answer cc a logit that is linear in these values, a rotation back by cc:

  4. logit⁡(c)≈∑k∈Kαkcos⁡ωk(a+b−c)\operatorname{logit}(c)\approx\sum_{k\in\mathcal K}\alpha_k\cos\omega_k(a+b-c)

    Sum over frequencies. The logits are approximately a weighted sum over the key frequencies K\mathcal K. For the main model K={14,35,41,42,52}\mathcal K=\{14,35,41,42,52\}, and a least-squares fit of the weights αk\alpha_k explains 95% of the variance of the actual logits:

Check your understanding

A single key frequency kk already gives a logit cos⁡ωk(a+b−c)\cos\omega_k(a+b-c) that is largest at the right answer. Why is one frequency not enough?

  1. One frequency cannot represent addition modulo a prime
  2. Each frequency handles a different range of inputs
  3. Some wrong answer always gets almost the same logit: kk is invertible modulo PP, so some m≠0m\ne0 has km≡±1km\equiv\pm1, where the cosine is cos⁡(2π/P)≈0.998\cos(2\pi/P)\approx0.998 for P=113P=113
  4. 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: kk is invertible modulo PP, so some m≠0m\ne0 has km≡±1km\equiv\pm1, where the cosine is cos⁡(2π/P)≈0.998\cos(2\pi/P)\approx0.998 for P=113P=113

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 showInterpretation
Memorization (0 to 1.4k)Training loss and excluded loss fall; test loss and restricted loss stay highA 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 flatOn 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 basisWeight decay removes the memorizing components, and the circuit that already exists takes over the predictions
From Nanda et al. (2023), main model. The jump in test accuracy comes during cleanup, after the generalizing circuit has formed: an abrupt change in behavior hides continuous progress inside the network.

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.

DerivationHow long the decay takes
  1. wt≈(1−ηλ)t w0≈e−ηλt w0⟹tgrok≈ln⁡(w0/wc)ηλw_t\approx(1-\eta\lambda)^t\,w_0\approx e^{-\eta\lambda t}\,w_0\qquad\Longrightarrow\qquad t_{\text{grok}}\approx\frac{\ln(w_0/w_c)}{\eta\lambda}

    Once the training loss is nearly zero its gradient is tiny, and decoupled decay multiplies the weights by 1−ηλ1-\eta\lambda per step (Weight Decay, Dropout & Early Stopping). If the network starts at norm w0w_0 but generalizes only near a smaller norm wcw_c,

  2. This is the heuristic behind Omnigrok (Liu, Michaud & Tegmark, 2023): the delay grows like 1/(ηλ)1/(\eta\lambda), 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 α\alpha and small weight decay λ\lambda: in the limit of large α\alpha, the network stays near a kernel predictor until time about (1−c)ln⁡α/λ(1-c)\ln\alpha/\lambda and reaches a KKT point of the min-norm or max-margin problem by about (1+c)ln⁡α/λ(1+c)\ln\alpha/\lambda, for any constant c>0c>0 (with c<1c<1 for the first).

Predict before you look

With decoupled weight decay at η=10−3\eta=10^{-3} and λ=1\lambda=1, as in the modular-addition runs, about how many steps does decay alone need to shrink the weights tenfold?

Show the answer

2300

(1−10−3)t=0.1(1-10^{-3})^t=0.1 gives t=ln⁡10/(−ln⁡0.999)≈2,301t=\ln10/(-\ln0.999)\approx2{,}301 steps, close to ln⁡10/(ηλ)≈2,303\ln10/(\eta\lambda)\approx2{,}303. Halving λ\lambda 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?

AccountClaimEvidence
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 confusionAn 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 shrinksLarge 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 decayConfirmed 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 laterGrokking 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 oneTheorems for homogeneous networks, with examples where the kernel predictor fails and the max-margin predictor generalizes
Optimizer and numericsWithout explicit regularization, the late dynamics of the optimizer decide when, or whether, the network generalizesGrokking 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 10310^3 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 a+b mod 113a+b\bmod113 embeds inputs as rotations at five key frequencies, composes them with angle-addition identities and reads off logits ∑kαkcos⁡ωk(a+b−c)\sum_k\alpha_k\cos\omega_k(a+b-c) 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 ln⁡(w0/wc)/(ηλ)\ln(w_0/w_c)/(\eta\lambda)), 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.

Question 1

In Nanda et al.'s modular-addition transformer, when does the generalizing circuit form, relative to the jump in test accuracy?

  1. Only at the moment test accuracy jumps
  2. Before it, during circuit formation; the jump comes in the cleanup phase, as weight decay removes the memorizing components
  3. After it, once the network has seen the test pairs
  4. 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.

Question 2

In the large-initialization picture of grokking, decay must shrink the weight norm from w0w_0 to wcw_c after the training set has been fitted. What does halving the weight decay λ\lambda do?

  1. Halves the delay
  2. Leaves the delay unchanged, since it depends only on the data
  3. Prevents grokking entirely
  4. Roughly doubles the delay, which scales like ln⁡(w0/wc)/(ηλ)\ln(w_0/w_c)/(\eta\lambda)
Show the answer

D. Roughly doubles the delay, which scales like ln⁡(w0/wc)/(ηλ)\ln(w_0/w_c)/(\eta\lambda)

Decay multiplies the weights by 1−ηλ1-\eta\lambda per step, so shrinking them by a fixed factor takes about ln⁡(w0/wc)/(ηλ)\ln(w_0/w_c)/(\eta\lambda) 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.

Question 3

What is "ungrokking" (Varma et al., 2023)?

  1. 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
  2. Test accuracy rising before training accuracy
  3. Forgetting the training set after grokking
  4. 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.

Question 4

Why do logits of the form ∑k∈Kcos⁡ωk(a+b−c)\sum_{k\in\mathcal K}\cos\omega_k(a+b-c), with ωk=2πk/P\omega_k=2\pi k/P and PP prime, single out c≡a+bc\equiv a+b?

  1. Each cosine is positive only at the correct answer
  2. Every term equals 1 at c≡a+bc\equiv a+b, while for each frequency the values at the other P−1P-1 answers sum to −1-1, so they partly cancel
  3. The unembedding stores the answer for every pair
  4. Cosines of different frequencies are orthogonal, so only one term is nonzero
Show the answer

B. Every term equals 1 at c≡a+bc\equiv a+b, while for each frequency the values at the other P−1P-1 answers sum to −1-1, so they partly cancel

At m=a+b−c≡0m=a+b-c\equiv0 every cosine is 1, so the logit is ∣K∣\abs{\mathcal K}. For each frequency the PP values sum to zero, so the wrong answers share a total of −1-1 per frequency. With the five key frequencies the correct logit is 5, the wrong ones average −5/112-5/112, 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).