Learning Theory2022intermediate12 min read
Grokking: Generalization Beyond Overfitting on Small Algorithmic Datasets
الاستيعاب المتأخّر: تعميم يتجاوز فرط التخصيص في مجموعات بيانات خوارزمية صغيرة
Power, A. · Burda, Y. · Edwards, H. · Babuschkin, I. · Misra, V. — ICLR Workshop
The problem
Deep neural networks are known to memorize data when they have far more parameters than examples. Conventional wisdom says that once a model overfits, more training only makes things worse. But is that always true? When we train overparameterized models on small, algorithmically generated datasets, does the story end at — or can something surprising happen if we keep training?
The contribution
The discovery of "": a phenomenon where neural networks first memorize training data completely (reaching perfect training accuracy while validation stays at chance), then — after orders of magnitude more training steps — suddenly transition to perfect . The paper systematically studies this on binary operations in and permutation groups, showing that dataset size, , and optimization noise are critical factors. Smaller datasets require disproportionately more training to generalize, revealing a sharp from memorization to true understanding.
The impact
Grokking challenged the assumption that is a dead end and revealed that generalization can emerge as a phase transition. It inspired a wave of mechanistic interpretability research (Nanda et al., 2023), connections to (Davies et al., 2023), and new theories linking representation learning, weight decay, and implicit . The phenomenon reshaped how researchers think about the relationship between optimization time, model capacity, and generalization — and suggested that some forms of "understanding" require patience far beyond what standard training schedules allow.
Imagine a student preparing for a math exam. They memorize every problem and answer from the textbook — all 500 of them. On a practice test with those same problems, they score 100%. On a new exam with different numbers? They fail.
Most teachers would say: "This student has memorized, not understood. More practice won't help." But something extraordinary happens. The student keeps reviewing those 500 problems — day after day, week after week, long after they've memorized them perfectly. And then one morning, it clicks. They suddenly see the underlying rules, the patterns beneath the numbers. Now they can solve any problem, not just the ones they memorized.
This paper discovered that neural networks do exactly this. They call it grokking — and it challenges everything we thought about when to stop training.
The playground: binary operations on small groups
To study generalization in a clean, controlled setting, the authors chose algorithmically generated datasets. These are not natural images or text — they are arithmetic problems with a known, exact answer. The core task: given two numbers and , predict the result of a binary operation like , where is a prime number.
Why modular arithmetic? Because the complete dataset is finite and small. For a prime , there are possible input pairs. The is a random fraction of this table — say 50%. The test set is the rest. There is no ambiguity: every answer is deterministic.
The paper tested a variety of operations, including addition, subtraction, division, polynomial combinations like , and even composition in the symmetric group (permutations of 5 elements). This diversity lets the authors check whether grokking is specific to one operation or a general phenomenon.
The model is a small : 2 layers, 128-dimensional embeddings, 4 heads, and approximately 290,000 parameters. The input tokens represent the two operands and , and the network predicts the result from 97 possible output classes.
This model is massively overparameterized for the task — 290K parameters to learn a function with fewer than 10K examples. In classical machine learning, this should guarantee overfitting and poor generalization. And indeed it does — at first. What happens next is the surprise.
The discovery: memorization first, understanding later
Here is what the authors observed. When training on division modulo 97 with 50% of the data, the training accuracy reaches 100% within a few hundred epochs. At this point, the validation accuracy is barely above random chance — the network has simply memorized the training examples without learning any generalizable pattern.
If training stopped here, the conclusion would be textbook: the model overfit. But the authors kept training — for thousands, then tens of thousands of additional epochs. And then, something remarkable happened. After roughly to epochs of stagnation, the validation accuracy suddenly shoots up from near-chance to near-perfect. The network transitions from rote memorization to genuine generalization — and it does so abruptly, like a phase transition in physics.
The authors named this phenomenon grokking, after Robert Heinlein's term for deep, intuitive understanding. The network doesn't just learn the training examples; it groks the underlying mathematical structure.
The three phases of grokking
Grokking training can be divided into three distinct phases, each with a different relationship between training and validation performance:
Phase 1 — Memorization. The network rapidly fits the training data. Training loss drops to near zero, training accuracy reaches 100%. But validation accuracy remains at chance level. The network has stored individual input-output mappings without discovering any underlying rule. Think of it as a lookup table — fast, perfect on known inputs, useless on anything new.
Phase 2 — Plateau. Training metrics stay perfect while validation shows no improvement. This phase can last for orders of magnitude more epochs than Phase 1. It appears that nothing is happening, but the internal representations are slowly reorganizing. Weight decay is gradually simplifying the network's parameters, pushing the weights toward solutions that encode patterns rather than individual examples.
Phase 3 — Generalization. Validation accuracy suddenly rises — often from near-chance to near-perfect in a relatively short window of epochs. The network has discovered the algebraic structure of the operation. For modular addition, follow-up research by Nanda et al. (2023) showed the network learns discrete Fourier components — a genuinely mathematical representation.
Dataset size: the more data, the faster the click
One of the paper's key findings is how dataset size affects the time to generalization. The relationship is far from linear: as the training fraction decreases, the number of epochs required to reach 99% validation accuracy increases dramatically — often by orders of magnitude.
At 70–90% of the data, training and validation curves track each other closely and generalization happens quickly. At 50%, there is a clear gap, and grokking takes thousands of extra epochs. Below about 30%, generalization may not happen at all within the optimization budget.
This suggests the existence of a critical dataset size — a threshold below which the network cannot discover the underlying pattern, no matter how long you train. Above this threshold, the network will eventually generalize, but the time required grows sharply as you approach it from above.
Weight decay: the pressure toward simplicity
The paper found that weight decay is crucial for grokking. Without it, the network memorizes and stays stuck. With it, grokking happens reliably. But why?
Weight decay adds a penalty proportional to the squared magnitude of the weights. At each training step, the weights are pulled slightly toward zero. During the memorization phase, this has little visible effect — the network compensates by adjusting other parameters. But over thousands of epochs, this constant pressure gradually erodes the large, specialized weights that store individual examples and favors smaller, more structured weights that encode general patterns.
Think of it as a sculptor working on a block of marble. In the beginning, the raw shape (memorization) emerges quickly. But the sculptor keeps refining, chipping away excess stone (large weights) until the smooth, essential form (generalization) is revealed. Weight decay is the chisel.
Which operations grok?
Not all operations grok equally. The paper tested 12 binary operations and found that simpler, more symmetric operations grok more reliably:
Operations that grok consistently include , , (mod ), (mod ), and group composition in .
Some polynomial operations like (mod ) and (mod ) did not grok within the training budget. These operations have more complex algebraic structure that may require either more training time, more data, or different model configurations.
A key insight: operations with more inherent symmetry tend to generalize faster. Modular addition is fully commutative and associative — properties that create redundancy in the training data, effectively increasing the information per example. The symmetric group operations, while non-commutative, have rich structural regularity that the network can exploit.
The bigger picture: connections to double descent and emergence
Grokking sits at the intersection of several deep puzzles in .
Double descent. Classical bias-variance theory predicts that test error should rise with model complexity once you pass the . But modern deep learning shows a second descent: very overparameterized models generalize better. Davies et al. (2023) showed that grokking can be viewed as -wise double descent — the same phenomenon playing out over training time rather than model size. The model first reaches an interpolation peak (memorization), then descends again to low test error (grokking).
. Large language models sometimes exhibit sudden capability jumps at certain scales — tasks that go from random-chance to high accuracy over a narrow range of model sizes. Grokking suggests that similar phase transitions can happen along the time axis rather than the scale axis. Both phenomena share the pattern: prolonged apparent failure, then sudden success.
Mechanistic interpretability. Nanda et al. (2023) used grokking as a case study for mechanistic interpretability. They showed that a grokked network performing modular addition learns to embed inputs as points on a circle and computes addition via rotation — a discrete Fourier transform implemented in the network's weights. This was one of the first demonstrations that neural networks can learn interpretable algorithms, not just statistical patterns.
Reproducing grokking: the modular addition experiment
Grokking is surprisingly easy to reproduce. Below is the essential setup: generate a modular addition dataset, split it, train a small Transformer with weight decay, and wait. The key ingredients are the small dataset, the overparameterized model, and sufficient weight decay.
Simplified to show the idea — not the real implementation.
import torch
import torch.nn as nn
# Generate all (a + b) mod p examples
p = 97
pairs = [(a, b, (a + b) % p) for a in range(p) for b in range(p)]
# Random 50/50 split
perm = torch.randperm(len(pairs))
split = len(pairs) // 2
train_data = [pairs[i] for i in perm[:split]]
val_data = [pairs[i] for i in perm[split:]]
# Optimizer: AdamW with weight decay = 1.0
optimizer = torch.optim.AdamW(
model.parameters(), lr=1e-3, weight_decay=1.0
)
# Training loop — train for 100K+ epochs
for epoch in range(100_000):
train_loss, train_acc = train_step(model, train_data)
val_loss, val_acc = eval_step(model, val_data)
# Phase 1: train_acc -> 100%, val_acc ~ 1/97
# Phase 2: both losses plateau
# Phase 3: val_acc suddenly jumps to ~100%Legacy: from curiosity to research program
2022
This paper (Power et al.)
Discovered and named the grokking phenomenon. Showed that neural networks can generalize long after overfitting on small algorithmic datasets, and that weight decay and dataset size are critical factors.
2022
Omnigrok (Liu et al.)
Extended grokking beyond algorithmic data to other domains, showing it can occur in standard classification tasks under the right conditions.
2022
Towards Understanding Grokking (Liu et al.)
Proposed that grokking results from the difficulty of learning good representations. Introduced an effective theory connecting representation quality to the delayed generalization transition.
2023
Mechanistic interpretability of grokking (Nanda et al.)
Showed that grokked networks learn discrete Fourier representations for modular addition — the first mechanistic explanation of what the network actually learns during the phase transition.
2023
Unifying grokking and double descent (Davies et al.)
Demonstrated that grokking and double descent are manifestations of the same underlying phenomenon — effective model complexity changing over time under the influence of regularization.
2023
Circuit efficiency explanation (Varma et al.)
Explained grokking through competition between sparse generalizing circuits and dense memorizing circuits. Weight decay gradually favors the more parameter-efficient generalizing solution.
Four years after its discovery, grokking has become a touchstone in deep learning theory. It demonstrates that neural networks are capable of far more nuanced learning dynamics than the simple "fit and overfit" narrative suggests. The phenomenon sits at a crossroads of generalization theory, mechanistic interpretability, and optimization dynamics — and continues to yield insights about the nature of learning itself.
CitationPower, Burda, Edwards, Babuschkin, Misra. Grokking: Generalization Beyond Overfitting on Small Algorithmic Datasets. ICLR Workshop (arXiv:2201.02177), 2022.
Terms in this paper
- Grokkingالاستيعاب المتأخّر
- Generalizationالتعميم
- Overfittingفرط التخصيص
- Memorizationالحفظ
- Weight Decayاضمحلال الأوزان
- Regularizationالضبط الهيكلي
- Modular Arithmeticالحساب المعياري
- Phase Transitionالتحوّل الطوري
- Validation Setمجموعة بيانات التحقق
- Epochالدورة التدريبية الشاملة
- Loss Landscapeسطح الخسارة
- Double Descentالهبوط المزدوج
- Emergent Abilitiesالقدرات المعرفية الناشئة فجأة
- Optimizerالـمُحسِّن
- Overparameterizationفرط المعاملات