Microstates vs macrostates, Jaynes' Maximum Entropy derivation of the Boltzmann/Gibbs measure, exact equivalence with temperature-scaled softmax, and training Energy-Based Models in modern generative AI.
At first glance, classical statistical mechanics and modern generative machine learning appear to address disparate disciplines. The former was developed in the late 19th century by Ludwig Boltzmann, James Clerk Maxwell, and Josiah Willard Gibbs to explain how macroscopic thermodynamic observables—such as temperature, pressure, and heat capacity—emerge deterministically from the stochastic interactions of N∼1023 microscopic atoms. The latter was developed by computer scientists to model complex, high-dimensional probability distributions over natural language tokens, image pixels, protein structures, and neural network weights.
Yet beneath their domain-specific terminologies, both fields solve the exact same mathematical problem:
The Fundamental Problem of Large Systems
Given an exponentially or uncountably large configuration space S and a scalar cost/energy function E:S→R, what is the least-biased, mathematically principled probability distribution p(σ) over states σ∈S that satisfies macroscopic empirical constraints?
In physics, this question leads directly to the Boltzmann-Gibbs distributionp(σ)∝e−βE(σ). In deep learning, this identical formula appears everywhere:
The Softmax activation function with temperature T=1/β in autoregressive Transformer language models (GPT-4, Llama 3, Claude 3.7).
Energy-Based Models (EBMs) and score-based generative models where probability densities are parameterized via unnormalized deep neural networks pθ(x)=Zθ1e−Eθ(x).
The optimal policy in Reinforcement Learning from Human Feedback (RLHF) and Direct Preference Optimization (DPO), where policy distributions form exact Gibbs measures parameterized by reward functions.
Modern Discrete Diffusion Models (such as SEDD and LLaDA) operating via discrete score matching over vocabulary spaces.
This chapter establishes the rigorous foundations of statistical physics required for modern deep learning. We build from microstates and macrostates to Jaynes' Maximum Entropy Principle, derive the canonical Gibbs measure from first principles, prove its equivalence to temperature-scaled softmax, analyze the training dynamics of Energy-Based Models, and explore sequence-level residual EBMs and energy-compositional controllable generation.
A central concept in statistical mechanics is the distinction between the complete microscopic description of a system and its low-dimensional macroscopic observation.
In a lattice of N magnetic dipoles (spins), a microstateσ specifies the exact orientation of every individual spin:
σ=(s1,s2,…,sN)∈{−1,+1}N
The microstate space S={−1,+1}N contains ∣S∣=2N discrete configurations. For a macroscopic sample of matter where N∼1023, the number of microstates is 21023, a quantity vastly exceeding the number of elementary particles in the observable universe (1080).
In an autoregressive Large Language Model with vocabulary V (where typically ∣V∣≈32,000 to 128,000), a sequence y of length L represents a discrete microstate:
y=(y1,y2,…,yL)∈VL
For a context window of L=2048 tokens and ∣V∣=32,000, the discrete configuration space has cardinality:
∣S∣=∣V∣L=(32,000)2048≈109,229
No computer can enumerate, normalize, or directly evaluate all possible microstates in S.
A macrostate is defined by a small set of macroscopic observables M(σ) that summarize the system without tracking microscopic coordinates:
In physics: The total energy E(σ)=−∑⟨i,j⟩Jijsisj−∑ihisi, or the net magnetization M(σ)=∑i=1Nsi.
In NLP: The semantic topic, sentiment label y∈{+1,−1}, syntactic grammaticality, or total sequence cross-entropy loss.
The multiplicity (or discrete density of states) Ω(E) is the number of distinct microstates σ∈S that produce the identical macroscopic energy E:
Ω(E)=σ∈S∑δ(E(σ)−E)
where δ(⋅) is the Kronecker delta. Ludwig Boltzmann discovered that the thermodynamic entropyS of an isolated macrostate is proportional to the logarithm of its multiplicity:
S(E)=kBlnΩ(E)
where kB≈1.380649×10−23 J/K is Boltzmann's constant (often set to kB=1 in information theory and machine learning).
For a system of N classical point particles moving in d-dimensional Euclidean space, a microstate is a single point x=(q,p) in a 2dN-dimensional phase spaceΓ=R2dN:
q=(q1,q2,…,qN)∈RdN,p=(p1,p2,…,pN)∈RdN
where qi represents the position and pi=mvi represents the linear momentum of particle i.
The differential volume element of phase space, nondimensionalized via Planck's constant h and corrected for quantum indistinguishability of identical particles (the Gibbs factor 1/N!), is:
dΓ=hdNN!ddNqddNp
The continuous density of states g(E) for a Hamiltonian H(q,p) is defined via the Dirac delta function:
In continuous generative modeling (e.g., Score-based Diffusion Models, Continuous Normalizing Flows, and Variational Autoencoders), a microstate x∈RD represents an image, an audio waveform, or a continuous latent embedding z∈Rd:
In Image Diffusion (DDPM / Score-SDE): D=C×H×W (e.g., 3×512×512≈7.86×105 dimensions).
In Generative Flow Matching: The continuous trajectory xt∈RD is governed by a time-dependent vector field vθ(xt,t).
The macrostate corresponds to class labels (e.g., "Image of a golden retriever"), style descriptors, or clip embeddings.
To navigate the cross-disciplinary literature, we construct the exact translation table connecting physical statistical mechanics to machine learning and computer science concepts:
Concept / Quantity
Statistical Mechanics
Machine Learning & Deep Learning
Microstate
Microscopic coordinate σ∈S or (q,p)∈Γ
Token sequence y∈VL, image vector x∈RD, or model weights w
Energy Function
Hamiltonian H(σ) or potential energy E(x)
Negative logit −zi, loss function L(θ), or energy network Eθ(x)
Macrostate
Macroscopic observables (E,V,N,M)
Class labels, prompt conditioning c, semantic intent, dataset statistics
Density of States
Multiplicity Ω(E)=∑σδ(E(σ)−E)
Volume of configuration space satisfying loss L(w)≤ϵ
Inverse Temperature
β=kBT1
Inverse sampling temperature β=1/T in Softmax / LLM decoding
For a completely isolated physical system with fixed total energy in the interval [E,E+δE], total volume V, and particle number N, we possess zero information distinguishing one compatible microstate from another.
Postulate of Equal A Priori Probabilities
An isolated system in thermodynamic equilibrium is equally likely to be found in any of its accessible microstates. That is, for all microstates σ∈S compatible with macrostate (E,V,N):
p(σ)={Ω(E)10if E(σ)∈[E,E+δE]otherwise
In classical mechanics, this postulate is justified dynamically via Liouville's Theorem (which proves that phase space volume is preserved under Hamiltonian time evolution) and the Ergodic Hypothesis (which asserts that over long timescales, the time average of an observable along a single trajectory equals its phase-space ensemble average):
In two seminal 1957 papers, Edwin T. Jaynes revolutionized statistical mechanics by reinterpreting it not as a purely physical theory of mechanical trajectories, but as a general framework for optimal statistical inference under incomplete information.
Suppose we have a discrete random variable X taking values in X={x1,x2,…,xK}. We do not know the true distribution p=(p1,p2,…,pK), but we have measured M macroscopic expectation values:
Ep[fm(X)]=k=1∑Kpkfm(xk)=αm,∀m∈{1,2,…,M}
where M<K, meaning the system of equations is severely underdetermined with infinitely many valid probability distributions.
The Principle of Maximum Entropy (Jaynes, 1957)
The uniquely unbiased probability distribution p that incorporates the known constraints while remaining maximally agnostic about all other unmeasured degrees of freedom is the distribution that maximizes the Shannon entropy:
H(p)=−k=1∑Kpklnpk
Any other choice of distribution implicitly assumes extra, unjustified information.
We now present the rigorous step-by-step mathematical derivation of the Boltzmann/Gibbs distribution using the method of Lagrange multipliers under the Jaynes MaxEnt framework.
Let S={1,2,…,K} be the index set of all microstates. Each microstate i∈S has an associated microscopic energy Ei∈R.
We seek the probability vector p=(p1,p2,…,pK)T that solves:
pmaxsubject toH(p)=−i=1∑KpilnpiC1:i=1∑Kpi=1(Total probability axiom)C2:i=1∑KpiEi=U(Prescribed internal energy expectation ⟨E⟩=U)C3:pi≥0,∀i∈{1,…,K}(Non-negativity)
The partition function Z(β) is not merely an arbitrary normalization constant; it is the cumulant generating function of the energy distribution and encapsulates all thermodynamic properties of the system.
In physics, this variance is directly proportional to the heat capacity at constant volume Cv=∂T∂U:
Var(E)=∂β2∂2lnZ=−∂β∂⟨E⟩=kBT2Cv
Key Insight: Fluctuations Reveal Response
Equation Var(E)=kBT2Cv is an elementary instance of the Fluctuation-Dissipation Theorem: the equilibrium microscopic fluctuations of an observable (Var(E)) dictate the macroscopic linear response of the system to external perturbations (Cv=dU/dT).
We now establish the direct, 1-to-1 isomorphism between the Boltzmann/Gibbs measure of statistical physics and the Softmax activation function used across modern neural architectures.
Let z=(z1,z2,…,zK)T∈RK be a vector of unnormalized network outputs (logits) over K discrete classes (or tokens). Let T>0 denote the scalar temperature parameter.
Define the microscopic energy of state i as the negative logit:
Ei≡−zi
Define the thermodynamic inverse temperature as:
β≡T1(setting kB=1)
Substituting these definitions directly into the Boltzmann distribution:
In Large Language Models, when generating the next token yt∼softmax(zt/T), tuning T controls the physical thermodynamic state of the generation process:
In physics, as T→0, all thermal fluctuations freeze out, and the system condenses with probability 1 into its ground state (the configuration with minimal energy Emin=minkEk):
Having established that parameterized distributions over configurations x naturally take the form of a Gibbs measure, we now examine Energy-Based Models (EBMs) in machine learning.
An Energy-Based Model parameterizes a continuous or discrete probability distribution over data x∈RD via an unnormalized scalar energy functionEθ(x):RD→R parameterized by neural network weights θ:
Definition: Energy-Based Model
pθ(x)=Z(θ)exp(−Eθ(x))
where the partition function Z(θ) is the integral over the entire continuous data manifold:
EBMs allow Eθ(x) to be any arbitrary deep neural network mapping inputs to a scalar energy value. Crucially, EBMs allow exact compositionality: combining independent constraints amounts to simply summing their energies:
The primary challenge of EBMs is that the partition function Z(θ)=∫RDe−Eθ(x)dx is a high-dimensional integral. In dimensions D≥100, computing Z(θ) numerically via grid quadrature requires O(KD) evaluations, which is fundamentally computationally intractable (#P-hard).
Suppose we are given an empirical dataset D={x1,x2,…,xN} sampled i.i.d. from true data distribution pdata(x). We wish to train the parameters θ of Eθ(x) by maximizing the average log-likelihood:
The Positive Phase: Takes true observed data points x∼pdata and updates θ to push their energy down (Eθ(x)↓⟹pθ(x)↑).
The Negative Phase: Generates ungrounded "fantasies" or "hallucinations" x′∼pθ from the current model distribution and updates θ to pull their energy up (Eθ(x′)↑⟹pθ(x′)↓).
Stationary Equilibrium: Learning converges when the expectations match:
Running full SGLD to equilibrium at every gradient step is prohibitively slow. Contrastive Divergence (CDk, Hinton 2002) initializes the Langevin Markov chain at data points x0∼pdata and runs only k steps (k≈5−50). Modern deep EBMs (Du & Mordatch, 2019) maintain a persistent Replay Buffer of past negative samples to allow chains to mix across training iterations.
Can we train an Energy-Based Model without evaluating or approximating Z(θ) at all?
Aapo Hyvärinen (2005) introduced Score Matching, which optimizes the vector field of log-density derivatives (the score function):
sθ(x)≡∇xlnpθ(x)
Applying the definition of an EBM:
sθ(x)=∇x[−Eθ(x)−lnZ(θ)]=−∇xEθ(x)−=0 (indep. of x)∇xlnZ(θ)=−∇xEθ(x)
Fundamental Property of Score Matching
The score function sθ(x)=−∇xEθ(x) is strictly independent of the partition function Z(θ)! Differentiating with respect to the data coordinate x eliminates the normalization constant entirely.
where Tr(∇x2Eθ(x))=∑d=1D∂xd2∂2Eθ(x) is the trace of the Hessian (the Laplacian ΔEθ(x)).
This remarkable identity gave birth to modern Score-based Generative Models and Diffusion SDEs (Song & Ermon, 2019; Song et al., 2021; Ho et al., 2020), which we will explore in detail in Chapter 6.
Another approach to bypass Z(θ) is Noise Contrastive Estimation (NCE) (Gutmann & Hyvärinen, 2010). NCE treats the unnormalized model as a binary classifier trained to distinguish true data x∼pdata from synthetic noise generated by a known noise distribution y∼q(x):
where the log partition function c=lnZ(θ) is simply treated as a single scalar learnable parameter alongside θ. As the number of noise samples ν→∞, the parameter estimates θ^ and c^ converge to their true maximum likelihood values.
Standard autoregressive language models pAR(y)=∏t=1Lp(yt∣y<t) decompose text generation into a sequence of local, myopic token predictions. While highly efficient for sampling, autoregressive models struggle with global, sequence-level constraints (e.g., long-range discourse coherence, holistic semantic consistency).
Deng et al. (ICLR 2020) proposed Residual Energy-Based Models for text. Instead of training an EBM from scratch, they define the joint sequence distribution as a product of a pre-trained autoregressive base model pAR(y∣x) and a non-autoregressive residual energy function Eθ(x,y):
Division of Labor: pAR(y∣x) captures local grammar, syntax, and short-range transitions. Eθ(x,y) (parameterized via bidirectional Transformers like BERT or RoBERTa) inspects the entire sequence simultaneously to evaluate holistic coherence.
Tractable Importance Sampling: Because pAR is already close to the data distribution, we can draw candidate sequences y(1),…,y(K)∼pAR(y∣x) and compute self-normalized importance sampling estimates of the conditional partition function:
Fine-tuning a separate 70B parameter model for every possible permutation of attributes is computationally prohibitive. Statistical mechanics provides an elegant, zero-shot solution through the composition of energy functions (Product of Experts, Hinton 2002; Mireshghallah et al., ACL 2022):
Energy Composition Formula
p(y)∝exp(−Etotal(y))
where the total energy is a linear combination of independent modular energy discriminators:
A preview of Lecture 2: In Reinforcement Learning from Human Feedback (RLHF), the goal is to find an optimal policy πθ(y∣x) maximizing expected human reward r(x,y) regularized by KL-divergence to a reference model πref(y∣x):
Solving this constrained optimization problem analytically (as we will prove in Chapter 2) yields an exact Gibbs distribution:
π∗(y∣x)=Z(x)1πref(y∣x)exp(β1r(x,y))
where Z(x)=∑yπref(y∣x)exp(β1r(x,y)) is the intractable partition function.
In Direct Preference Optimization (DPO) (Rafailov et al., NeurIPS 2023), taking the logarithm of this exact Gibbs relationship allows expressing the latent reward function directly in terms of policy probabilities:
r(x,y)=βlnπref(y∣x)π∗(y∣x)+βlnZ(x)
When evaluating the pairwise Bradley-Terry preference probability p(yw≻yl∣x)=σ(r(x,yw)−r(x,yl)), the partition functions cancel each other out identically:
This allows optimizing human preferences without training a reward model and without sampling from the negative phase of the Gibbs distribution during training.
Prompt: Let X be a discrete random variable taking values in X. Suppose we measure M independent macroscopic feature functions f(X)=(f1(X),f2(X),…,fM(X))T such that E[fm(X)]=αm for m=1,…,M. Prove that the Maximum Entropy distribution is a member of the general exponential family:
pθ(x)=Z(θ)1exp(m=1∑Mθmfm(x))
where θ=(θ1,…,θM)T are the Lagrange multipliers.
Solution:
We formulate the Lagrangian with multipliers λ0 for normalization and θ=(θ1,…,θM)T for the M expectation constraints:
Prompt: Consider two sequences yw (preferred) and yl (dispreferred) conditioned on prompt x. Under the Bradley-Terry preference model, the probability that yw≻yl is given by:
Assume the optimal Gibbs policy is π∗(y∣x)=Z(x)1πref(y∣x)exp(β1r∗(x,y)). Show that the Bradley-Terry preference likelihood can be expressed entirely in terms of the ratio of policies π∗ and πref, without any dependence on the partition function Z(x).
Solution:
From the optimal Gibbs policy formula:
π∗(y∣x)=Z(x)πref(y∣x)exp(β1r∗(x,y))
Taking the natural logarithm of both sides:
lnπ∗(y∣x)=lnπref(y∣x)+β1r∗(x,y)−lnZ(x)
Rearranging to isolate the ground-truth reward r∗(x,y):
r∗(x,y)=βln(πref(y∣x)π∗(y∣x))+βlnZ(x)
Now compute the reward difference between the winning completion yw and losing completion yl: