Grokking › Grokking Phase Transitions

Michael BrenndoerferNovember 11, 202515 min read
Language AI HandbookAll chapters
Part 30 of 67Emergent Capabilities
Chapter 219Grokking › Grokking Phase Transitions
Reading section 6 of 13 · Grokking Phase Transitions · 15 minSection 6 of 13 · 15 min

Book contents

Section 6 of 13 · 15 min read

Grokking › Grokking Phase TransitionsOne section · Sections in this chapter6 / 13 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Grokking exhibits sharp phase-transition behavior characteristic of many complex systems in physics and mathematics. Generalization can appear over a relatively small number of training steps compared with the total training time. This distinguishes grokking from standard learning curves, where test accuracy typically improves smoothly alongside training accuracy.

The suddenness of the transition is itself informative. It suggests that grokking is a qualitative change in the network's internal organization rather than a simple quantitative accumulation of knowledge. Something structural changes when grokking occurs, beyond a small improvement in a few parameters. The network reorganizes from one kind of solution to another, and that reorganization, when it happens, happens fast. This is a key distinguishing feature: if grokking were merely a very slow version of ordinary learning, we would expect test accuracy to improve slowly and continuously. The fact that it jumps suddenly implies a threshold effect, where the algorithmic solution must cross some minimum quality threshold before it can dominate the memorization solution's contributions to the output.

Think of this like a phase transition in physics. When water cools toward 0 degrees Celsius, most properties change gradually with temperature. But at exactly 0 degrees, a sharp transition occurs: liquid water becomes solid ice. The system's structure reorganizes fundamentally. Grokking is analogous: during the plateau phase, internal reorganization is happening gradually, but the observable behavior (test accuracy) only changes when the reorganization crosses a threshold, at which point the transition appears sudden from outside. Statistical physics has developed advanced tools for characterizing and predicting such phase transitions, and some researchers have begun applying these tools to grokking, searching for mathematical signatures of the transition that can be computed from the model's state before the transition occurs.

Critical Points and Thresholds

Several factors influence when grokking occurs, and understanding these factors helps predict and control the transition.

Weight decay strength is the primary control knob. Too little weight decay means the model memorizes without sufficient pressure to reorganize toward generalization. Too much weight decay interferes with learning entirely, preventing the model from finding any low-loss solution. A necessary range exists where weight decay is strong enough to favor the algorithmic solution but not so strong that learning becomes impossible. Within this range, grokking occurs reliably, and increasing weight decay within this range generally accelerates grokking by increasing the pressure on the memorization circuit.

Training data fraction affects the memorization-generalization tradeoff in a more subtle way. More training data means more examples for the network to memorize, which increases the cost of the memorization solution while keeping the cost of the algorithmic solution roughly constant. More data therefore accelerates grokking by widening the gap between memorization cost and algorithm cost. Less training data makes memorization cheaper relative to the algorithm, delaying or preventing grokking. This is a somewhat counterintuitive result: in standard machine learning, we expect more data to always help, and it does here too, but through a specific mechanism related to the cost differential between the two solutions rather than through improved signal quality.

Model capacity plays a complex, non-monotonic role. Very small models may lack the capacity to stand for either memorization or the algorithm. Very large models memorize so easily that regularization cannot effectively distinguish between the two solutions. An intermediate model capacity is optimal: it must work to memorize, allowing regularization to favor the algorithm. The sweet spot for grokking exists when the model is large enough to stand for both solutions but not so large that memorization becomes trivially cheap.

In[13]:
Code
# Compare grokking at different weight decay values
def compare_weight_decay(weight_decays, n_epochs=150):
    """Train with different weight decay values to show its effect on grokking."""
    results = {}

    for wd in weight_decays:
        torch.manual_seed(42)
        model = GrokkingTransformer(
            vocab_size=p_demo,
            d_model=64,
            nhead=4,
            num_layers=1,
            dim_feedforward=128,
        )

        history = train_with_logging(
            model,
            train_loader,
            test_loader,
            n_epochs=n_epochs,
            lr=1e-3,
            weight_decay=wd,
            device=device,
        )
        results[wd] = history

    return results


# Test several weight decay values
weight_decays = [0.01, 0.1, 1.0, 2.0]
wd_comparison = compare_weight_decay(weight_decays, n_epochs=20)
In[14]:
Code
use_book_style()
Out[15]:
Console
Weight Decay Comparison Results:
  WD=0.01: Train Acc=0.131, Test Acc=0.002
  WD=0.1: Train Acc=0.129, Test Acc=0.002
  WD=1.0: Train Acc=0.125, Test Acc=0.002
  WD=2.0: Train Acc=0.119, Test Acc=0.002

The experiments train four separate lightweight models with weight decay values ranging from 0.01 to 2.0. This comparison reveals how regularization strength affects the timing and occurrence of the grokking transition. The final accuracy values show how different regularization strengths lead to varying degrees of generalization, with intermediate values typically achieving the best balance between memorization and generalization.

Out[16]:
Visualization
Four curves showing test accuracy at different weight decay values
**Weight decay effect on test accuracy**: Test accuracy curves for weight decay values 0.01, 0.1, 1.0, and 2.0 show that regularization strength controls early grokking dynamics. Insufficient decay can leave the model close to memorization. Intermediate values can improve generalization pressure. Excessive regularization can inhibit learning. A narrow optimal range balances memorization and generalization.

The relationship between weight decay and grokking speed illustrates the phase transition nature of the phenomenon. At low weight decay, the model memorizes and stays memorized. As weight decay increases past a necessary threshold, grokking appears and happens progressively faster. Beyond some optimal range, strong regularization can interfere with learning entirely, preventing even memorization. The necessary range where grokking occurs reliably is task-specific and model-specific, which is why careful hyperparameter selection matters. You cannot simply apply any positive weight decay and expect grokking; the weight decay must be strong enough to matter but not so strong that it overwhelms the task signal.

The Role of Optimization

The optimizer choice influences grokking dynamics in ways that go beyond simple learning rate effects. AdamW, which uses decoupled weight decay, tends to produce more reliable grokking behavior than standard Adam with L2 regularization implemented as a loss term. This distinction matters: in standard Adam, weight decay is effectively scaled by the adaptive learning rates, which means parameters with high gradient variance receive weaker regularization. In AdamW, weight decay acts uniformly on all parameters. This gives cleaner pressure toward compactness.

The decoupling in AdamW is mathematically straightforward but practically important. Standard Adam with L2 regularization computes the gradient as gt=∇L+λθtg_t = \nabla \mathcal{L} + \lambda \theta_t, then applies adaptive scaling to the entire gradient including the regularization term. This means the regularization effect is weaker for parameters with high gradient variance (those with large second moment estimates). AdamW instead applies weight decay directly to the parameters after the adaptive update step: θt+1=θt−αm^t/v^t−αλθt\theta_{t+1} = \theta_t - \alpha \hat{m}_t / \sqrt{\hat{v}_t} - \alpha \lambda \theta_t. The weight decay term is not scaled by the adaptive learning rate, so it applies uniformly. For studying grokking, this uniformity ensures that the regularization pressure on the memorization circuit is predictable and controllable.

Learning rate also matters. Higher learning rates can accelerate the phase transition once it begins, letting the network to rapidly reorganize from memorization to algorithmic solution. However, too-high learning rates cause instability that can prevent grokking entirely by disrupting the delicate process of representation reorganization. Lower learning rates lead to slower but more stable grokking. There is evidence that learning rate schedules, particularly warmup followed by cosine decay, can improve grokking reliability by letting stable memorization early in training followed by gradual pressure toward generalization.

The interaction between learning rate and weight decay is particularly important. Both affect the effective scale of parameters, and their ratio determines how aggressively the optimizer pushes toward compact solutions. Scanning both hyperparameters together, rather than independently, produces more systematic understanding of grokking behavior. Practitioners working with tasks where grokking dynamics may be needed should treat both learning rate and weight decay as primary hyperparameters to tune jointly rather than sequentially.

Measuring the Phase Transition

We can quantify the sharpness of the grokking transition by examining the rate of change of test accuracy over training. Rather than looking at raw accuracy values, which tell us where the model is, examining the derivative reveals how quickly the model is improving at each point in training. This derivative perspective helps distinguish between gradual improvement, where accuracy increases smoothly over time, and the sudden transitions characteristic of grokking, where almost all improvement is concentrated in a narrow window.

The derivative of test accuracy with respect to training step is:

d(accuracy)d(step)\frac{d(\text{accuracy})}{d(\text{step})}

where:

  • accuracy\text{accuracy}: the test accuracy at a given point in training, a value between 0 and 1
  • step\text{step}: the training step number, counting gradient updates or epochs
  • d(accuracy)d(step)\frac{d(\text{accuracy})}{d(\text{step})}: the derivative showing how quickly accuracy changes per training step, representing the instantaneous rate of improvement measured in accuracy units per step

This derivative measures the instantaneous rate at which test accuracy improves during training. A large positive value indicates rapid improvement: the model is quickly getting better at the task. Values near zero indicate periods of stagnation where accuracy remains roughly constant despite continued training. During grokking, the derivative shows a distinctive pattern: it stays near zero during the plateau phase, spikes sharply during the transition, then returns to near zero after full generalization is achieved.

These peaks in the derivative characterize the transition from memorization to generalization. The sharper the spike, the more abrupt the transition from one regime to the other. This concentration of improvement within a narrow window of training steps is what makes grokking visually striking on learning curves. The mathematical signature of grokking is high eventual accuracy paired with this distinctive pattern of delayed-then-rapid improvement.

Out[17]:
Visualization
S-shaped sigmoid line chart of test accuracy over training steps showing flat memorization phase then sharp rise to near perfect accuracy
**Test accuracy trajectory**: Shows the characteristic S-shaped sigmoid curve of grokking. The curve remains flat during memorization (epochs 0-50), rises sharply during the transition phase (epochs 50-150), then saturates near perfect accuracy. This pattern of delayed-then-rapid improvement distinguishes grokking from gradual learning.
Line chart of rate of change of test accuracy over training steps with a sharp spike marking the grokking transition point
**Derivative of test accuracy** (scaled by 1000): The mathematical signature of grokking appears as a sharp peak marking the transition phase. During this peak, improvement accelerates sharply before returning to near-zero. This concentrated burst of improvement in a narrow training window distinguishes grokking from the gradual improvements seen in standard learning curves.

The derivative plot gives a quantitative view of the learning dynamics. Peaks in the rate of change show when the model's test accuracy is improving most rapidly. The location and magnitude of these peaks help characterize the transition from memorization to generalization. The sharp spike in d(accuracy)d(step)\frac{d(\text{accuracy})}{d(\text{step})} during the transition indicates that grokking involves rapid improvement concentrated within a small window of training steps. This contrasts with gradual steady progress, where improvement would be distributed more evenly across training. The mathematical signature of grokking is high eventual accuracy paired with this distinctive pattern of delayed-then-rapid improvement. We can quantify this transition by computing key metrics: memorization step (when training accuracy exceeds 99%), grokking step (when test accuracy exceeds 90%), and maximum acceleration (the sharpest improvement point). This numeric characterization lets comparison across different hyperparameter settings.

In[18]:
Code
import numpy as np


def compute_grokking_metrics(history):
    """Compute metrics characterizing the grokking transition."""

    test_acc = np.array(history["test_acc"])
    steps = np.array(history["step"])

    # Find when training accuracy first exceeds 99%
    train_acc = np.array(history["train_acc"])
    memorization_idx = (
        np.argmax(train_acc > 0.99)
        if np.any(train_acc > 0.99)
        else len(train_acc)
    )

    # Find when test accuracy first exceeds 90%
    grokking_idx = np.argmax(test_acc > 0.90) if np.any(test_acc > 0.90) else -1

    # Compute acceleration (second derivative) of test accuracy
    if len(test_acc) > 2:
        acc_diff = np.diff(test_acc)
        acc_diff2 = np.diff(acc_diff)
        max_acceleration_idx = np.argmax(acc_diff2) if len(acc_diff2) > 0 else 0
    else:
        max_acceleration_idx = 0

    return {
        "memorization_step": steps[memorization_idx]
        if memorization_idx < len(steps)
        else None,
        "grokking_step": steps[grokking_idx] if grokking_idx >= 0 else None,
        "max_acceleration_step": steps[max_acceleration_idx + 2]
        if max_acceleration_idx + 2 < len(steps)
        else None,
        "final_test_acc": test_acc[-1],
    }
Out[19]:
Console
Grokking Transition Metrics:
Memorization achieved at step: None
Grokking achieved at step: None
Final test accuracy: 0.4%

Note: The delay between memorization and grokking is the plateau phase
where the model appears to have overfit but is actually developing the generalizing solution.

These metrics quantify the grokking transition in concrete numerical terms. The delay between memorization (when training accuracy exceeds 99%) and grokking (when test accuracy exceeds 90%) reveals how long the model remains in the plateau phase before generalization emerges. This delay, often spanning thousands or millions of steps, is the defining characteristic of grokking and what distinguishes it from standard learning curves where generalization tracks training performance closely.

The delay between memorization and grokking can be substantial. In our demonstration, grokking occurs relatively quickly due to the small scale and aggressive weight decay. In larger experiments from the original paper, this delay could span orders of magnitude in training time: a model might memorize in 1,000 steps but not grok until step 500,000 or beyond. This range means that standard training budgets may fall orders of magnitude short of the training needed for generalization on tasks with grokking dynamics.

Out[20]:
Visualization
Area plot showing gap between train and test accuracy
Generalization gap (shaded red region) displays three stages between training and test accuracy. The gap widens during memorization as training accuracy approaches 100% while test accuracy remains low, persists during the plateau phase, then shrinks sharply during grokking as test accuracy surges. Vertical dashed lines mark memorization completion and generalization onset.

This visualization shows the generalization gap, the difference between training and test accuracy, throughout the full training run. The shaded region is how much better the model performs on training data than test data. During memorization, this gap grows rapidly as the model reaches high training accuracy while test accuracy remains low. The gap then persists, sometimes for thousands of additional steps, during the plateau phase. Finally, during grokking, the gap shrinks sharply as test accuracy catches up to training accuracy, closing in a fraction of the time it took to open. The annotated vertical lines mark the key transition points, which makes it easy to identify the three phases visually and measure the delay between them quantitatively.