5. Phase Transitions, Order Parameters & Grokking in Deep Learning
Statistical mechanics of phase transitions, Landau theory, mean field theory of transformers, interpolation thresholds, grokking as first-order transitions, and REM collapse modes.
In the study of complex physical systems, macroscopic phenomena—such as the sudden freezing of water into crystalline ice or the spontaneous emergence of bulk magnetization in a cooling iron bar—cannot be understood by examining individual particles in isolation. These phenomena are phase transitions: abrupt, non-analytic transformations in the macroscopic behavior of a system driven by smooth variations in underlying control parameters (such as temperature, pressure, or magnetic field).
Deep learning models operate under a precisely analogous regime. As we scale dataset size , parameter count , sequence length , network depth , or training duration , neural networks do not simply improve smoothly. Instead, they exhibit sharp, qualitative transitions:
- Spontaneous Symmetry Breaking & Specialization: Neurons or attention heads transition from an isotropic, degenerate state into highly specialized functional modes.
- The Interpolation Threshold (): A geometric jamming transition where the training loss landscape reorganizes, accompanied by the double descent of generalization error.
- Grokking (Delayed Generalization): A discontinuous, first-order dynamical phase transition wherein a network abruptly shifts from a high-entropy, memorizing state to a low-complexity, perfectly generalizing state after millions of gradient steps.
- Signal Propagation Collapse: Critical freezing transitions in deep transformers, where representation geometry abruptly collapses into either rank-degenerate subspace alignment or single-token attention freeze-out.
This chapter develops the analytical machinery of statistical mechanics—including Landau's phenomenological theory, the Bogoliubov variational mean-field bound, high-dimensional replica theory, and Derrida's Random Energy Model (REM)—to provide a rigorous, microscopic foundation for these deep learning phenomena.
1. Classical Statistical Mechanics vs. Modern Deep Learning
To build a rigorous bridge between statistical physics and deep learning theory, we establish the direct dictionary mapping thermodynamic variables to machine learning observables:
| Physical Statistical Mechanics | Mathematical Definition | Deep Learning / Optimization Formulation |
|---|---|---|
| Microstate | Network weights or token states | |
| Energy / Hamiltonian | Empirical risk / regularized loss | |
| Temperature | Thermal fluctuation scale | SGD noise covariance / learning rate ratio: |
| Partition Function | ||
| Free Energy Density | Asymptotic generalization log-partition / cumulant generating function | |
| Order Parameter | Magnetization , overlap | Generalization overlap , attention head overlap, rank ratio |
| Control Parameter | Temperature , external field , coupling | Sample ratio , weight decay , depth , context |
| Phase Transition | Non-analyticity in | Sharp transition in generalization error, grokking jump, attention collapse |
2. Theory of Phase Transitions & Landau Theory
2.1 Thermodynamic Limit and the Origin of Non-Analyticity
For any system with a finite number of degrees of freedom , the partition function is a finite sum (or well-behaved finite-dimensional integral) of strictly positive, analytic functions:
Because for all real , the finite- free energy density:
is infinitely differentiable () with respect to and any external field . Consequently, true phase transitions cannot occur in finite systems.
Theorem: Yang-Lee Theorem on Phase Transitions
Let be the partition function extended to the complex fugacity / field plane . For finite , all zeros of (the Yang-Lee zeros) lie strictly off the positive real axis in the complex plane.
A phase transition occurs if and only if, in the thermodynamic limit , the distribution of Yang-Lee zeros pinches the real positive axis at a critical point , rendering the limiting free energy density:
non-analytic at .
In machine learning, the thermodynamic limit corresponds to scaling the input dimension , dataset size , or network width/depth while holding critical ratios (such as the sample complexity or aspect ratio ) constant.
2.2 Ehrenfest Classification of Phase Transitions
Phase transitions are classified according to the lowest-order derivative of the free energy density that exhibits a mathematical discontinuity or divergence:
-
First-Order Phase Transitions: The first derivative of the free energy is discontinuous across the transition boundary:
- Thermodynamic features: Latent heat, coexistence of distinct metastable phases, hysteresis loops, and a non-zero free energy barrier separating competing minima.
- Deep Learning counterpart: Grokking (where the parameter state tunnels across a free energy barrier from a memorization basin to a generalization basin) and Attention Entropy Collapse in deep transformers.
-
Second-Order (Continuous) Phase Transitions: The first derivative of is continuous, but the second derivative exhibits a discontinuity or divergence:
- Thermodynamic features: Divergence of the spatial correlation length , critical slowing down, scale invariance, and universal critical exponents.
- Deep Learning counterpart: Spontaneous symmetry breaking in weight initialization, bifurcation of student-teacher networks, and the jamming transition at the interpolation capacity .
2.3 Order Parameters and Spontaneous Symmetry Breaking
Let a physical or computational system possess a microscopic Hamiltonian invariant under a global symmetry group (e.g., the spin-flip symmetry , or the permutation group of hidden units):
An order parameter is a macroscopic observable defined such that:
- in the symmetric, disordered, high-temperature phase.
- in the broken-symmetry, ordered, low-temperature phase.
When , although the Gibbs measure remains formally symmetric under , the system in the thermodynamic limit spontaneously settles into a single pure thermodynamic state , breaking the symmetry. The free energy barrier between disjoint symmetric ground states scales as:
rendering transitions between pure states impossible on any finite physical timescale (ergodicity breaking).
2.4 Mathematical Formulation of Landau Theory
Landau's phenomenological theory posits that in the vicinity of a critical point , the macroscopic free energy density can be systematically expanded as an analytic power series in the scalar order parameter , constrained strictly by the underlying symmetries of the system.
Assuming an inversion symmetry in the absence of an external conjugate field :
where is the background free energy of the disordered phase. Near the critical temperature , we expand the quadratic coefficient to leading order:
Analytical Derivation: Continuous vs. Discontinuous Landau Minima
The equilibrium value of satisfies the Euler-Lagrange saddle-point condition :
Case 1: Continuous Phase Transition (, , )
For , ; the only real root is , representing a stable disordered minimum with .
For , ; becomes an unstable local maximum. Solving for the non-trivial roots:
This yields the classical mean-field critical exponent:
The magnetic susceptibility diverges upon approaching :
Case 2: First-Order Phase Transition (, , )
When , the quartic term destabilizes the potential, requiring stabilization by the positive sextic term :
Setting , the secondary local minima are located at:
A first-order transition occurs at the coexistence temperature where the free energy of the ordered state precisely equals that of the disordered state (). Solving and simultaneously yields:
Key Physical Takeaway: The Free Energy Barrier
At , the order parameter jumps discontinuously from to . The disordered state at and the ordered states at are separated by an energy barrier of height:
This barrier prevents instantaneous transformation and dictates the activated dynamical timescales in algorithms like stochastic gradient descent.
3. Mean Field Theory & Self-Consistent Effective Fields
Mean Field Theory (MFT) approximates complex, many-body interacting systems by replacing the fluctuating microscopic interactions experienced by each degree of freedom with an average, self-consistent effective field.
3.1 The Variational Principle (Bogoliubov-Feynman Inequality)
Let be the intractable true Hamiltonian of our learning system, with true partition function and true free energy .
Let be a family of tractable reference Hamiltonians parameterized by variational parameters . The trial partition function and trial free energy are and .
Theorem: Bogoliubov-Feynman Free Energy Bound
The true free energy is bounded from above by the variational free energy:
where denotes the expectation taken with respect to the trial Gibbs measure .
Proof:
Using the definition of the true partition function:
Taking the natural logarithm and applying Jensen's inequality ( due to the strict concavity of the logarithm):
Multiplying by reverses the inequality, completing the proof:
In modern machine learning, this is the exact foundation of Variational Autoencoders (VAEs) and Variational Bayesian Inference, where is the negative Evidence Lower Bound ().
3.2 Microscopic Derivation of the Curie-Weiss Mean Field Equation
Consider the fully connected (infinite-range) Ising ferromagnet of binary spins :
where is the empirical magnetization.
Exact Solution via Hubbard-Stratonovich Transformation
The partition function is:
Using the Gaussian Hubbard-Stratonovich identity with and :
Substituting this into allows decoupling the sum over spins:
We define the effective free energy functional per spin :
In the thermodynamic limit , Laplace's method (saddle-point approximation) yields the exact free energy density:
The saddle-point condition produces the Curie-Weiss Self-Consistent Equation:
Systematic Derivation of Landau Coefficients from Microscopic Physics
Expanding in a Taylor series around :
Setting :
Comparing directly with the phenomenological Landau form :
- , where .
- .
This proves that Landau theory is not merely an empirical curve-fit, but the exact leading-order asymptotic expansion of the microscopic partition function near criticality.
4. Statistical Mechanics Theory of Transformers in the Thermodynamic Limit
Modern transformer architectures parameterized by self-attention mechanisms exhibit sharp, non-trivial representational phase transitions as context length , embedding dimension , and dataset size scale to infinity (Tiberi et al., NeurIPS 2024).
4.1 The Scaled High-Dimensional Transformer Setup
Consider a transformer layer receiving a sequence of tokens . The single-head scaled dot-product attention mapping is:
We define the thermodynamic scaling limit:
Let the combined query-key interaction matrix be . In a teacher-student synthetic task, the teacher produces target labels using ground-truth weight matrix , while the student optimizes weights over training sequences .
4.2 Replica Free Energy Formulation
Using the replica trick , the replicated partition function over identical replicas of student weights is:
To compute the quenched average over the random token inputs , we introduce the microscopic overlap order parameters:
- Teacher-Student Overlap (): Measures how well the student has aligned its attention heads with the true underlying semantic task:
- Student-Student (Edwards-Anderson) Overlap (): Measures the mutual alignment / glassiness between distinct training runs:
- Empirical Attention Kernel Overlap (): Measures inter-token attention concentration:
Enforcing these definitions via Dirac delta constraints integrated over conjugate Lagrange multipliers , the Replica Symmetric (RS) ansatz (, ) reduces the high-dimensional matrix path integral to a 2D variational free energy:
where represents the effective Gaussian scalar channel mutual information governing token-to-token attention.
4.3 Attention Spectral Phase Transitions: Marchenko-Pastur vs. BBP Emergence
The saddle-point equations yield the phase diagram of self-attention as a function of the sample ratio and sequence aspect ratio :
-
Disordered Phase (): The overlap . The empirical attention matrix is dominated by random isotropic fluctuations. The empirical spectral density of the attention logits follows the standard Marchenko-Pastur law supported on :
The attention distribution across tokens is completely uniform (), and generalization error remains at baseline chance.
-
Ordered (Retrieval) Phase (): The system undergoes a Baik-Ben Arous-Péché (BBP) spectral phase transition. A discrete set of isolated outlier eigenvalues detach from the continuous Marchenko-Pastur bulk:
The corresponding top eigenvectors encode the semantic context routing, breaking the permutation symmetry of the context window and driving generalization error down as .
5. Learning Regimes Near the Interpolation Threshold
The relationship between model capacity, training dataset size, and out-of-sample risk is governed by geometric phase transitions in high dimensions (Barbier et al., PRX 2026).
5.1 Asymptotic Regimes in High Dimensions
Let training samples be fitted by a linear or kernel model under empirical loss . In the proportional scaling limit with :
1. Under-parameterized Classical Regime (α > 1)
The system is overdetermined (). The empirical risk is strictly positive (). The solution is unique: . Generalization error follows classical bias-variance decay:
2. Critical Jamming Threshold (α → 1)
The volume of zero-loss parameter configurations undergoes a jamming phase transition. The minimum eigenvalue of the empirical Gram matrix vanishes: . The condition number diverges:
Sample-to-sample variance diverges, generating the catastrophic interpolation peak.
3. Over-parameterized Regime (α < 1)
The system is underdetermined (). There exists an infinite -dimensional manifold of interpolating solutions with . Gradient descent selects the unique Moore-Penrose pseudoinverse minimum -norm solution:
5.2 Information-Theoretic vs. Algorithmic Phase Transitions
In non-convex learning problems (such as multi-layer perceptrons, phase retrieval, and sparse coding), Barbier et al. (PRX 2026) demonstrated that the transition to perfect learning bifurcates into distinct thresholds:
- Information-Theoretic Threshold (): The theoretical minimum sample complexity where the global Bayes-optimal free energy minimum corresponds to the true ground-truth weights . Below , no algorithm can reconstruct the teacher signal.
- Algorithmic Threshold (): The practical sample complexity required for polynomial-time algorithms (Gradient Descent, Approximate Message Passing) to reach the generalizing state.
- The Computational Hard Phase (): The free energy landscape is dominated by a complex 1-step Replica Symmetry Breaking (1RSB) spin-glass phase with an exponential number of metastable local minima (traps), preventing gradient-based algorithms from discovering the global generalizing minimum.
6. Grokking as a First-Order Phase Transition in Deep Networks
Grokking (Power et al., 2022) is the dramatic phenomenon where a neural network trained on algorithmic tasks (e.g., modular arithmetic ) achieves 100% training accuracy within hundreds of gradient steps (memorization), but its validation accuracy remains at chance for hundreds of thousands of iterations before abruptly jumping to 100% (generalization).
6.1 Competing Order Parameters: Memorization vs. Generalization
Rubin et al. (ICLR 2024) formulated grokking as a first-order phase transition governed by the competition between two incompatible macroscopic order parameters:
- Memorization Order Parameter (): Measures sample-wise lookup table fitting using dense, unstructured, high-frequency weights:
- Generalization (Feature) Order Parameter (): Measures the projection of network weights onto low-rank, structured Fourier representation modes :
6.2 The Effective Free Energy of Optimization
Consider empirical risk minimization with weight decay regularization parameter :
Under Stochastic Gradient Descent (SGD) with learning rate and batch size , the discrete parameter updates can be mapped in continuous time to an overdamped Langevin equation at effective temperature :
The probability distribution over weights converges to the steady-state Gibbs-Boltzmann distribution:
The macroscopic Landau free energy of a parameter state is:
where is the parameter-space entropy (the logarithmic volume of weight configurations that implement macroscopic behavior ).
The Entropy vs. Energy Tradeoff:
- Memorization Basin (): Fits data through arbitrary, unconstrained combinations of weights. Its parameter-space volume is enormous (), but its weight norm is large: .
- Generalization Basin (): Constrained to low-dimensional circular/Fourier manifolds (), but has a very small weight norm: .
6.3 Kramers' Escape Dynamics and the Grokking Timescale
Because the memorization and generalization mechanisms rely on completely different functional representations, there is an intermediate region of weight space where neither memorization nor generalization fits the training data, creating an empirical loss barrier.
Thus, the two states are separated by a free energy barrier .
The transition from memorization to generalization is governed by Kramers' escape theory across a potential barrier under Langevin noise:
As weight decay steadily compresses the weights during training, the free energy barrier evolves as:
This produces the universal scaling law for grokking delay (Rubin et al., 2024):
When , (the model memorizes forever and never generalizes). As increases, decreases exponentially until the barrier vanishes entirely (), turning the first-order transition into a continuous spinodal descent.
7. Signal Propagation and Collapse Modes in Deep Transformers via Derrida's REM
As transformer architectures scale to extreme depth (), signal propagation through stacked self-attention and residual layers suffers from two distinct catastrophic thermodynamic failure modes (ICLR 2026).
7.1 Forward Map Dynamics
Let denote the representation of token at layer . The multi-head residual forward update is:
where the attention coefficients are given by the Boltzmann-Gibbs softmax distribution:
Here, is the effective inverse temperature set by the attention scale and layer normalization.
7.2 Mapping Attention Softmax to Derrida's Random Energy Model (REM)
Derrida's Random Energy Model (1981) is the quintessential mean-field model of disordered systems with frozen disorder.
For high-dimensional embeddings and independently initialized weights , the attention pre-activations (logits) for a fixed query are a collection of Gaussian random variables with zero mean and variance :
We map each token to a microscopic energy state:
The attention denominator is exactly the REM Partition Function:
Rigorous Analytical Derivation of the Freezing Transition
The microscopic density of states at energy level is:
The ground-state energy is the energy threshold below which the expected number of states is of order :
The microcanonical entropy as a function of energy is:
Thermodynamic temperature is defined by the fundamental relation .
Substituting into the entropy:
Because the number of microstates cannot be less than 1, the thermodynamic entropy cannot become negative (). The critical inverse temperature where the entropy vanishes is:
7.3 Phase Classification of Deep Attention
The macroscopic phase of the deep transformer is governed by whether the operational inverse temperature is above or below :
Phase 1: High-Temperature Phase () Rank Collapse
When , the attention entropy is extensive:
Attention is distributed broadly across tokens. However, in deep networks (), taking repeated convex combinations of token representations acts as a continuous diffusion process on the token manifold. By the Perron-Frobenius theorem, all token vectors converge exponentially to the dominant eigenspace:
This is Rank Collapse (Oversmoothing): tokens lose all individuality, destroying expressive capacity.
Phase 2: Low-Temperature Phase () Attention Entropy Collapse
When , the system undergoes a condensation phase transition. The Gibbs measure freezes entirely onto the single ground-state energy token:
The attention distribution collapses into a Kronecker delta function:
This is Attention Entropy Collapse (Freeze-out): attention acts as a hard permutation routing mechanism, ignoring all other context tokens.
7.4 Architectural Solutions: Critical Scaling Laws
To prevent both Rank Collapse and Attention Freeze-out, the operational inverse temperature must remain strictly invariant across layer depth :
- RMSNorm / LayerNorm Stabilization: Enforcing bounds the logit variance :
- DeepNorm Residual Scaling: Scaling residual branch weights as prevents unbounded growth of vector norms (), ensuring the system remains stably positioned in the critical edge-of-chaos regime between rank collapse and freeze-out.
8. Pedagogical Synthesis & Universal Principles
We conclude by synthesizing the unified phase transitions governing statistical mechanics and modern deep learning:
| Phenomenon | Classical Stat Mech Origin | Microscopic Order Parameter | Macroscopic Deep Learning Manifestation |
|---|---|---|---|
| Symmetry Breaking | Curie-Weiss Ferromagnetism | Magnetization | Hidden neuron feature specialization; spontaneous emergence of directional selectivity |
| Interpolation Jamming | Sphere Jamming / Perceptron Capacity | Overlap variance | Double descent peak at ; divergent Hessian condition number |
| Grokking | First-Order Nucleation / Kramers Escape | Feature alignment vs. Memorization | Delayed generalization jump from 0% to 100% after steps driven by weight decay |
| Rank Collapse | High-T Ergodic Diffusion () | Representation rank | Oversmoothing in deep transformers; tokens become collinear as |
| Attention Freeze-Out | Derrida's REM Ground-State Condensation | Attention entropy | Softmax attention collapses into a single-token winner-take-all delta distribution |
References & Further Reading
- Tiberi, L., et al. (NeurIPS 2024). Statistical Mechanics of Transformers in the Thermodynamic Limit: Replica Symmetry and Phase Diagrams of Self-Attention.
- Barbier, J., et al. (PRX 2026). Information-Theoretic and Algorithmic Phase Transitions in High-Dimensional Learning.
- Rubin, N., et al. (ICLR 2024). Grokking as a First-Order Phase Transition: Free Energy Barriers and Kramers Escape in Overparameterized Networks.
- Derrida, B. (1981). Random-Energy Model: An Exactly Solvable Model of Disordered Systems. Physical Review B, 24(5), 2613.
- Power, A., et al. (2022). Grokking: Generalization Beyond Overfitting on Small Algorithmic Datasets. arXiv:2201.02177.
- Bahri, Y., et al. (2020). Statistical Mechanics of Deep Learning. Annual Review of Condensed Matter Physics, 11, 501-528.
Lecture 4: Spin Glasses, Modern Hopfield Networks & Transformer Attention
From frustrated magnetic systems and Sherrington-Kirkpatrick spin glasses to dense associative memories, continuous modern Hopfield energy functions, exact equivalence to Transformer self-attention, in-context learning phase transitions, and Boltzmann attention mechanisms.
6. Langevin Dynamics, Score-Based SDEs & Generative Diffusion
A comprehensive statistical mechanics and stochastic calculus treatment of Brownian motion, the Fluctuation-Dissipation Theorem, Fokker-Planck evolution, DDPM, Score-SDEs, and Discrete Language Diffusion (SEDD, LLaDA).