CSE-41XX
Course Curriculum

02. Free Energy, Variational Inference & Direct Preference Optimization (DPO)

A mathematically rigorous bridge connecting Helmholtz free energy, the canonical partition function, and variational inference to modern LLM alignment via Direct Preference Optimization (DPO).

Free Energy, Variational Inference & Direct Preference Optimization (DPO)

Modern artificial intelligence and statistical physics share a profound foundational principle: the optimal state of any complex system is governed by a fundamental trade-off between energy minimization and entropy maximization.

In classical thermodynamics, this balance is quantified by the Helmholtz Free Energy F=UTSF = U - TS. In Bayesian machine learning, it manifests as the Evidence Lower Bound (ELBO) in Variational Autoencoders (VAEs). In modern large language model (LLM) alignment, it underpins the Reinforcement Learning from Human Feedback (RLHF) objective and explains the breakthrough of Direct Preference Optimization (DPO) (Rafailov et al., 2023).

This chapter presents an end-to-end, mathematically rigorous journey from 19th-century statistical mechanics to state-of-the-art generative model alignment. We demonstrate how the intractable canonical partition function ZZ that has challenged physicists for over a century is eliminated through pairwise preference modeling.


1. Conceptual Rosetta Stone: Physics vs. Deep Learning

Before diving into formal derivations, we establish the exact mapping between statistical mechanics, variational inference, and reinforcement learning / LLM alignment.

ConceptStatistical MechanicsVariational Inference (Bayesian ML)LLM Alignment (RLHF / DPO)
State / MicrostateMicrostate configuration xXx \in \mathcal{X}Latent variable zZz \in \mathcal{Z} (given data xx)Completion / Response yYy \in \mathcal{Y} (given prompt xx)
Cost / EnergyHamiltonian E(x)E(x)Negative Joint Log-Likelihood lnp(x,z)-\ln p(x, z)Negative Reward r(x,y)-r(x, y)
Base / Prior DensityUniform phase space measure dxdxPrior distribution p(z)p(z)Reference policy / SFT model πref(yx)\pi_{\mathrm{ref}}(y \mid x)
Active DistributionCanonical Gibbs measure p(x)=1ZeβE(x)p(x) = \frac{1}{Z} e^{-\beta E(x)}Variational posterior qϕ(zx)q_\phi(z \mid x)Fine-tuned policy πθ(yx)\pi_\theta(y \mid x)
Normalizing FactorPartition Function Z(β)=xeβE(x)Z(\beta) = \sum_x e^{-\beta E(x)}Marginal Likelihood / Evidence p(x)=p(x,z)dzp(x) = \int p(x,z) dzPer-prompt normalizer Z(x)=yπref(yx)er(x,y)/βZ(x) = \sum_y \pi_{\mathrm{ref}}(y\mid x) e^{r(x,y)/\beta}
Macroscopic PotentialHelmholtz Free Energy F=ETS=TlnZF = \langle E \rangle - TS = -T \ln ZVariational Free Energy F[q]=ELBO[q]\mathcal{F}[q] = -\mathrm{ELBO}[q]Negative regularized RL objective LRLHF(π)-\mathcal{L}_{\mathrm{RLHF}}(\pi)
Order vs. DisorderInternal Energy E\langle E \rangle vs. Entropy SSReconstruction fit Eq[lnp(xz)]\mathbb{E}_q[-\ln p(x\mid z)] vs. DKL(qp(z))D_{\mathrm{KL}}(q \Vert p(z))Reward maximization Eπ[r]\mathbb{E}_\pi[r] vs. DKL(ππref)D_{\mathrm{KL}}(\pi \Vert \pi_{\mathrm{ref}})
TemperatureThermodynamic temperature T=1kBβT = \frac{1}{k_B \beta}Relaxation parameter in variational relaxationsRegularization strength βKL\beta_{\mathrm{KL}} (or sampling temperature TT)

2. Thermodynamic Potentials and Helmholtz Free Energy

2.1 The Canonical Ensemble and Gibbs-Boltzmann Distribution

Consider a physical system in contact with a large thermal reservoir (heat bath) at constant absolute temperature TT. The microstates of the system are denoted by xXx \in \mathcal{X}, and each microstate has an associated energy given by the Hamiltonian E(x)RE(x) \in \mathbb{R}.

In the canonical ensemble, the probability of the system occupying microstate xx is given by the Gibbs-Boltzmann distribution:

p(x)=1Z(β)eβE(x)p(x) = \frac{1}{Z(\beta)} e^{-\beta E(x)}

where β1kBT\beta \equiv \frac{1}{k_B T} is the inverse temperature (we set Boltzmann's constant kB=1k_B = 1 throughout this chapter for simplicity, hence β=1/T\beta = 1/T), and Z(β)Z(\beta) is the canonical partition function:

Z(β)=xXeβE(x)orZ(β)=XeβE(x)dxZ(\beta) = \sum_{x \in \mathcal{X}} e^{-\beta E(x)} \quad \text{or} \quad Z(\beta) = \int_{\mathcal{X}} e^{-\beta E(x)} \, dx

The partition function acts as the fundamental generating function in statistical mechanics. All macroscopic thermodynamic observables can be derived from derivatives of lnZ(β)\ln Z(\beta).

2.2 Thermodynamic Observables from the Partition Function

1. Internal Energy (UU)

The average or internal energy of the system is the expectation value of the Hamiltonian:

UE=xXp(x)E(x)=xXeβE(x)Z(β)E(x)=1Z(β)xXβ(eβE(x))=1Z(β)Z(β)β=lnZ(β)β\begin{aligned} U \equiv \langle E \rangle &= \sum_{x \in \mathcal{X}} p(x) E(x) \\ &= \sum_{x \in \mathcal{X}} \frac{e^{-\beta E(x)}}{Z(\beta)} E(x) \\ &= -\frac{1}{Z(\beta)} \sum_{x \in \mathcal{X}} \frac{\partial}{\partial \beta} \left( e^{-\beta E(x)} \right) \\ &= -\frac{1}{Z(\beta)} \frac{\partial Z(\beta)}{\partial \beta} \\ &= -\frac{\partial \ln Z(\beta)}{\partial \beta} \end{aligned}

2. Heat Capacity and Energy Fluctuations

Differentiating the internal energy with respect to temperature yields the heat capacity at constant volume CVC_V:

CV=UT=βTUβ=(1T2)(2lnZβ2)=1T22lnZβ2C_V = \frac{\partial U}{\partial T} = \frac{\partial \beta}{\partial T} \frac{\partial U}{\partial \beta} = \left( -\frac{1}{T^2} \right) \left( -\frac{\partial^2 \ln Z}{\partial \beta^2} \right) = \frac{1}{T^2} \frac{\partial^2 \ln Z}{\partial \beta^2}

Evaluating 2lnZβ2\frac{\partial^2 \ln Z}{\partial \beta^2} directly:

2lnZβ2=Eβ=E2E2=Varp(E)\frac{\partial^2 \ln Z}{\partial \beta^2} = -\frac{\partial \langle E \rangle}{\partial \beta} = \langle E^2 \rangle - \langle E \rangle^2 = \operatorname{Var}_p(E)

Hence, the variance of energy fluctuations is directly proportional to the heat capacity:

Varp(E)=T2CV=1β2CV\operatorname{Var}_p(E) = T^2 C_V = \frac{1}{\beta^2} C_V

3. Gibbs-Shannon Entropy (SS)

The statistical entropy of the canonical distribution p(x)p(x) is:

S(p)xXp(x)lnp(x)=Ep[lnp(x)]S(p) \equiv -\sum_{x \in \mathcal{X}} p(x) \ln p(x) = -\mathbb{E}_p[\ln p(x)]

Substituting the explicit form of p(x)=1ZeβE(x)p(x) = \frac{1}{Z} e^{-\beta E(x)}:

S(p)=xXp(x)(βE(x)lnZ)=βxXp(x)E(x)+lnZxXp(x)=βE+lnZ\begin{aligned} S(p) &= -\sum_{x \in \mathcal{X}} p(x) \left( -\beta E(x) - \ln Z \right) \\ &= \beta \sum_{x \in \mathcal{X}} p(x) E(x) + \ln Z \sum_{x \in \mathcal{X}} p(x) \\ &= \beta \langle E \rangle + \ln Z \end{aligned}

Multiplying by T=1/βT = 1/\beta:

TS=E+TlnZT S = \langle E \rangle + T \ln Z

2.3 Definition of Helmholtz Free Energy

Rearranging the entropy identity yields the Helmholtz Free Energy FF:

FUTS=ETS=TlnZ=1βlnZF \equiv U - TS = \langle E \rangle - TS = -T \ln Z = -\frac{1}{\beta} \ln Z

Physical Significance of Helmholtz Free Energy

The Helmholtz free energy FF represents the maximum reversible work WmaxW_{\mathrm{max}} that a closed thermodynamic system can perform at constant temperature and volume: WrevΔFW_{\mathrm{rev}} \le -\Delta F In any spontaneous isothermal process, the free energy monotonically decreases until reaching thermodynamic equilibrium: dFdt0,with equilibrium at F=Fmin=TlnZ\frac{dF}{dt} \le 0, \quad \text{with equilibrium at } F = F_{\mathrm{min}} = -T \ln Z


3. The Variational Free Energy Formulation

In statistical mechanics and probabilistic machine learning alike, we frequently encounter an arbitrary, non-equilibrium trial distribution q(x)q(x) that differs from the true equilibrium distribution p(x)p(x).

3.1 The Variational Free Energy Functional

For any probability distribution q(x)q(x) over the microstate space X\mathcal{X}, we define the Variational Free Energy functional (also known as Gibbs free energy functional or Helmholtz functional) as:

F[q]Exq[E(x)]TS(q)\mathcal{F}[q] \equiv \mathbb{E}_{x \sim q}[E(x)] - T S(q)

where:

  • Eq[E(x)]=xq(x)E(x)\mathbb{E}_{q}[E(x)] = \sum_x q(x) E(x) is the expected energy under trial distribution qq.
  • S(q)=xq(x)lnq(x)=H(q)S(q) = -\sum_x q(x) \ln q(x) = H(q) is the Shannon/Gibbs entropy of qq.

Expanding this definition:

F[q]=xXq(x)E(x)+TxXq(x)lnq(x)\mathcal{F}[q] = \sum_{x \in \mathcal{X}} q(x) E(x) + T \sum_{x \in \mathcal{X}} q(x) \ln q(x)

3.2 Exact Equivalence between Free Energy and KL Divergence

We now prove the central theorem linking statistical mechanics to information theory.

Theorem: Variational Free Energy Identity

For any target Hamiltonian E(x)E(x) with canonical equilibrium distribution p(x)=1ZeβE(x)p(x) = \frac{1}{Z} e^{-\beta E(x)} at temperature T=1/βT = 1/\beta, and for any valid probability distribution q(x)q(x), the variational free energy satisfies:

F[q]=TDKL(qp)TlnZ=TDKL(qp)+Ftrue\mathcal{F}[q] = T D_{\mathrm{KL}}(q \,\|\, p) - T \ln Z = T D_{\mathrm{KL}}(q \,\|\, p) + F_{\mathrm{true}}

where FtrueTlnZF_{\mathrm{true}} \equiv -T \ln Z is the true equilibrium Helmholtz free energy.

Step-by-Step Proof:

Recall the definition of the Kullback-Leibler (KL) divergence from qq to pp:

DKL(qp)xXq(x)lnq(x)p(x)=xXq(x)lnq(x)xXq(x)lnp(x)D_{\mathrm{KL}}(q \,\|\, p) \equiv \sum_{x \in \mathcal{X}} q(x) \ln \frac{q(x)}{p(x)} = \sum_{x \in \mathcal{X}} q(x) \ln q(x) - \sum_{x \in \mathcal{X}} q(x) \ln p(x)

Substitute the canonical Gibbs distribution p(x)=1ZeβE(x)p(x) = \frac{1}{Z} e^{-\beta E(x)} into the second term:

lnp(x)=ln(1ZeβE(x))=βE(x)lnZ\begin{aligned} \ln p(x) &= \ln \left( \frac{1}{Z} e^{-\beta E(x)} \right) \\ &= -\beta E(x) - \ln Z \end{aligned}

Now compute xq(x)lnp(x)\sum_x q(x) \ln p(x):

xXq(x)lnp(x)=xXq(x)(βE(x)lnZ)=βxXq(x)E(x)lnZxXq(x)=βEq[E(x)]lnZ\begin{aligned} \sum_{x \in \mathcal{X}} q(x) \ln p(x) &= \sum_{x \in \mathcal{X}} q(x) \left( -\beta E(x) - \ln Z \right) \\ &= -\beta \sum_{x \in \mathcal{X}} q(x) E(x) - \ln Z \sum_{x \in \mathcal{X}} q(x) \\ &= -\beta \mathbb{E}_q[E(x)] - \ln Z \end{aligned}

Substitute this back into the expression for DKL(qp)D_{\mathrm{KL}}(q \,\|\, p):

DKL(qp)=xXq(x)lnq(x)(βEq[E(x)]lnZ)=H(q)+βEq[E(x)]+lnZ\begin{aligned} D_{\mathrm{KL}}(q \,\|\, p) &= \sum_{x \in \mathcal{X}} q(x) \ln q(x) - \left( -\beta \mathbb{E}_q[E(x)] - \ln Z \right) \\ &= -H(q) + \beta \mathbb{E}_q[E(x)] + \ln Z \end{aligned}

Multiplying both sides by T=1βT = \frac{1}{\beta}:

TDKL(qp)=TH(q)+Eq[E(x)]+TlnZT D_{\mathrm{KL}}(q \,\|\, p) = -T H(q) + \mathbb{E}_q[E(x)] + T \ln Z

Notice that the first two terms on the right-hand side are precisely the Variational Free Energy F[q]=Eq[E(x)]TH(q)\mathcal{F}[q] = \mathbb{E}_q[E(x)] - T H(q):

TDKL(qp)=F[q]+TlnZT D_{\mathrm{KL}}(q \,\|\, p) = \mathcal{F}[q] + T \ln Z

Rearranging for F[q]\mathcal{F}[q]:

F[q]=TDKL(qp)TlnZ=TDKL(qp)+Ftrue\mathcal{F}[q] = T D_{\mathrm{KL}}(q \,\|\, p) - T \ln Z = T D_{\mathrm{KL}}(q \,\|\, p) + F_{\mathrm{true}}

\blacksquare

3.3 Corollaries of the Variational Theorem

From this single identity, three profound mathematical and physical conclusions follow immediately:

1. Bogoliubov / Gibbs Free Energy Inequality

Because the KL divergence is strictly non-negative (DKL(qp)0D_{\mathrm{KL}}(q \| p) \ge 0, with equality if and only if q=pq = p almost everywhere):

F[q]TlnZ=Ftrueq\mathcal{F}[q] \ge -T \ln Z = F_{\mathrm{true}} \quad \forall q

The variational free energy F[q]\mathcal{F}[q] provides an upper bound on the true equilibrium free energy FtrueF_{\mathrm{true}}.

2. Exact Equivalence of Optimizers

Since Ftrue=TlnZF_{\mathrm{true}} = -T \ln Z does not depend on the trial distribution qq:

argminqF[q]=argminqDKL(qp)\arg\min_q \mathcal{F}[q] = \arg\min_q D_{\mathrm{KL}}(q \,\|\, p)

Minimizing the physical variational free energy F[q]\mathcal{F}[q] over any parametric family Q={qθ}\mathcal{Q} = \{ q_\theta \} is strictly equivalent to minimizing the Kullback-Leibler divergence to the true Boltzmann distribution pp.

3. Uniqueness of Equilibrium

The global minimum is attained at:

q(x)=p(x)=1ZeβE(x),at which F[q]=TlnZq^*(x) = p(x) = \frac{1}{Z} e^{-\beta E(x)}, \quad \text{at which } \mathcal{F}[q^*] = -T \ln Z

4. Variational Inference & Evidence Lower Bound (ELBO) in Deep Learning

In modern machine learning (e.g., Variational Autoencoders (Kingma & Welling, 2013), latent diffusion models), we observe high-dimensional data xpdata(x)x \sim p_{\mathrm{data}}(x) generated by unobserved latent variables zZz \in \mathcal{Z} through a generative model pθ(x,z)=p(z)pθ(xz)p_\theta(x, z) = p(z) p_\theta(x \mid z).

Statistical Mechanics (Physics)Variational Inference / VAEs (Machine Learning)Fundamental Correspondence
Log Partition Function (lnZ=FtrueT\ln Z = -\frac{F_{\text{true}}}{T})True Marginal Log-Evidence (lnp(x)\ln p(x))lnZ=lneE(x,z)dzlnp(x)\ln Z = \ln \int e^{-E(x, z)} dz \longleftrightarrow \ln p(x)
Variational Free Energy (F[q]\mathcal{F}[q])Negative Evidence Lower Bound (ELBO[q]-\text{ELBO}[q])F[q]ELBO[q]lnp(x)\mathcal{F}[q] \equiv -\text{ELBO}[q] \ge -\ln p(x) (at T=1T=1)
Equilibrium Minimizes F[q]\mathcal{F}[q]Training Maximizes ELBO[q]\text{ELBO}[q]minqF[q]maxqELBO[q]\min_q \mathcal{F}[q] \longleftrightarrow \max_q \text{ELBO}[q]
Ground-Truth Free Energy (FtrueF_{\text{true}})Negative Evidence (lnp(x)-\ln p(x))Ftruelnp(x)F_{\text{true}} \equiv -\ln p(x)

4.1 The Intractable Posterior Problem

Computing the true posterior over latents pθ(zx)=pθ(x,z)pθ(x)p_\theta(z \mid x) = \frac{p_\theta(x, z)}{p_\theta(x)} requires the marginal likelihood (evidence):

pθ(x)=Zpθ(x,z)dzp_\theta(x) = \int_{\mathcal{Z}} p_\theta(x, z) \, dz

This integral is the exact analog of the continuous partition function Z(x)=eE(x,z)dzZ(x) = \int e^{-E(x, z)} dz where the energy function is the joint negative log-likelihood:

E(x,z)lnpθ(x,z)E(x, z) \equiv -\ln p_\theta(x, z)

For nonlinear deep neural networks, computing pθ(x)p_\theta(x) is computationally intractable due to the curse of dimensionality.

4.2 Derivation of the ELBO from Free Energy

We introduce a variational recognition network qϕ(zx)q_\phi(z \mid x) to approximate the intractable posterior pθ(zx)p_\theta(z \mid x). Setting T=1T = 1 (β=1\beta = 1), the variational free energy of the posterior approximation is:

F[qϕ]=Ezqϕ(x)[E(x,z)]H(qϕ(x))=Eqϕ[lnpθ(x,z)]+Eqϕ[lnqϕ(zx)]\mathcal{F}[q_\phi] = \mathbb{E}_{z \sim q_\phi(\cdot|x)} \left[ E(x, z) \right] - H(q_\phi(\cdot \mid x)) = \mathbb{E}_{q_\phi} \left[ -\ln p_\theta(x, z) \right] + \mathbb{E}_{q_\phi} \left[ \ln q_\phi(z \mid x) \right]

We define the Evidence Lower Bound (ELBO) as the negative variational free energy:

ELBO(ϕ,θ;x)F[qϕ]\mathrm{ELBO}(\phi, \theta; x) \equiv -\mathcal{F}[q_\phi]

Expanding ELBO(ϕ,θ;x)\mathrm{ELBO}(\phi, \theta; x):

ELBO(ϕ,θ;x)=Ezqϕ(zx)[lnpθ(x,z)lnqϕ(zx)]=Ezqϕ(zx)[lnpθ(xz)+lnp(z)lnqϕ(zx)]=Ezqϕ(zx)[lnpθ(xz)]Reconstruction Fidelity (Negative Energy)DKL(qϕ(zx)p(z))Prior Regularization (Entropic Penalty)\begin{aligned} \mathrm{ELBO}(\phi, \theta; x) &= \mathbb{E}_{z \sim q_\phi(z|x)} \left[ \ln p_\theta(x, z) - \ln q_\phi(z \mid x) \right] \\ &= \mathbb{E}_{z \sim q_\phi(z|x)} \left[ \ln p_\theta(x \mid z) + \ln p(z) - \ln q_\phi(z \mid x) \right] \\ &= \underbrace{\mathbb{E}_{z \sim q_\phi(z|x)} \left[ \ln p_\theta(x \mid z) \right]}_{\text{Reconstruction Fidelity (Negative Energy)}} - \underbrace{D_{\mathrm{KL}}\left( q_\phi(z \mid x) \,\|\, p(z) \right)}_{\text{Prior Regularization (Entropic Penalty)}} \end{aligned}

4.3 The Evidence Decomposition

Applying our master free energy identity F[q]=DKL(qp)lnZ\mathcal{F}[q] = D_{\mathrm{KL}}(q \,\|\, p) - \ln Z with Z=pθ(x)Z = p_\theta(x):

ELBO(ϕ,θ;x)=DKL(qϕ(zx)pθ(zx))lnpθ(x)-\mathrm{ELBO}(\phi, \theta; x) = D_{\mathrm{KL}}\left( q_\phi(z \mid x) \,\|\, p_\theta(z \mid x) \right) - \ln p_\theta(x)

Rearranging:

lnpθ(x)=ELBO(ϕ,θ;x)+DKL(qϕ(zx)pθ(zx))\ln p_\theta(x) = \mathrm{ELBO}(\phi, \theta; x) + D_{\mathrm{KL}}\left( q_\phi(z \mid x) \,\|\, p_\theta(z \mid x) \right)

Since DKL0D_{\mathrm{KL}} \ge 0, we have lnpθ(x)ELBO(ϕ,θ;x)\ln p_\theta(x) \ge \mathrm{ELBO}(\phi, \theta; x). Maximizing the ELBO with respect to ϕ\phi pushes the variational distribution qϕ(zx)q_\phi(z|x) toward the true posterior pθ(zx)p_\theta(z|x) while simultaneously maximizing the data marginal likelihood lnpθ(x)\ln p_\theta(x) with respect to generative parameters θ\theta.


5. RLHF as Free Energy Minimization

We now transition to language model alignment: training a foundation model πθ(yx)\pi_\theta(y \mid x) to produce completions yYy \in \mathcal{Y} given a prompt xXx \in \mathcal{X} that align with human preferences.

5.1 The Standard RLHF Objective

In classical Reinforcement Learning from Human Feedback (Ziegler et al., 2019; Ouyang et al., 2022 - InstructGPT), we first train:

  1. A Supervised Fine-Tuning (SFT) reference policy πref(yx)\pi_{\mathrm{ref}}(y \mid x).
  2. A Reward Model rψ(x,y)Rr_\psi(x, y) \in \mathbb{R} parameterized by neural network ψ\psi.

We then optimize a parameterized policy πθ(yx)\pi_\theta(y \mid x) to maximize expected reward while penalizing divergence from the reference policy πref\pi_{\mathrm{ref}}:

maxπLRLHF(π)=ExD,yπ(x)[r(x,y)]βKLDKL(π(x)πref(x))\max_{\pi} \mathcal{L}_{\mathrm{RLHF}}(\pi) = \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi(\cdot|x)} \left[ r(x, y) \right] - \beta_{\mathrm{KL}} \, D_{\mathrm{KL}}\left( \pi(\cdot \mid x) \,\|\, \pi_{\mathrm{ref}}(\cdot \mid x) \right)

where βKL>0\beta_{\mathrm{KL}} > 0 is the regularization coefficient.

[!WARNING] CRITICAL NOTATION WARNING: βKL\beta_{\mathrm{KL}} in Alignment vs. β\beta in Statistical Mechanics In statistical physics:

  • β=1/T\beta = 1/T is the inverse temperature. High β\beta means cold / zero exploration.
  • TT multiplies the entropy term in free energy: F=ETSF = \langle E \rangle - T S.

In machine learning / RLHF literature (Rafailov et al., 2023):

  • βKL\beta_{\mathrm{KL}} is the regularization weight multiplying the KL divergence.
  • Therefore, βKL\beta_{\mathrm{KL}} plays the mathematical role of Temperature TT, not inverse temperature!
  • Specifically: Teffective=βKLT_{\mathrm{effective}} = \beta_{\mathrm{KL}}, and βstat=1βKL\beta_{\mathrm{stat}} = \frac{1}{\beta_{\mathrm{KL}}}.

As βKL\beta_{\mathrm{KL}} \to \infty, the policy is frozen to the prior πref\pi_{\mathrm{ref}} (infinite temperature / infinite friction). As βKL0\beta_{\mathrm{KL}} \to 0, the policy collapses onto the greedy reward-maximizing response (zero temperature ground state).

5.2 Deriving the Closed-Form Optimal RLHF Policy

For a fixed prompt xx, the per-prompt objective to maximize is:

Jx(π)=yYπ(yx)r(x,y)βKLyYπ(yx)lnπ(yx)πref(yx)J_x(\pi) = \sum_{y \in \mathcal{Y}} \pi(y \mid x) r(x, y) - \beta_{\mathrm{KL}} \sum_{y \in \mathcal{Y}} \pi(y \mid x) \ln \frac{\pi(y \mid x)}{\pi_{\mathrm{ref}}(y \mid x)}

subject to the probability normalization constraint yπ(yx)=1\sum_{y} \pi(y \mid x) = 1 and π(yx)0\pi(y \mid x) \ge 0.

Let us rewrite Jx(π)-J_x(\pi) in the exact form of a Variational Free Energy:

Jx(π)=yYπ(yx)r(x,y)+βKLyYπ(yx)lnπ(yx)βKLyYπ(yx)lnπref(yx)=yYπ(yx)[r(x,y)βKLlnπref(yx)]+βKLyYπ(yx)lnπ(yx)\begin{aligned} -J_x(\pi) &= -\sum_{y \in \mathcal{Y}} \pi(y \mid x) r(x, y) + \beta_{\mathrm{KL}} \sum_{y \in \mathcal{Y}} \pi(y \mid x) \ln \pi(y \mid x) - \beta_{\mathrm{KL}} \sum_{y \in \mathcal{Y}} \pi(y \mid x) \ln \pi_{\mathrm{ref}}(y \mid x) \\ &= \sum_{y \in \mathcal{Y}} \pi(y \mid x) \left[ -r(x, y) - \beta_{\mathrm{KL}} \ln \pi_{\mathrm{ref}}(y \mid x) \right] + \beta_{\mathrm{KL}} \sum_{y \in \mathcal{Y}} \pi(y \mid x) \ln \pi(y \mid x) \end{aligned}

We define the effective prompt-conditioned Hamiltonian:

E(x,y)r(x,y)βKLlnπref(yx)E(x, y) \equiv -r(x, y) - \beta_{\mathrm{KL}} \ln \pi_{\mathrm{ref}}(y \mid x)

Then:

Jx(π)=Eyπ(x)[E(x,y)]βKLH(π(x))=F[π(x)]-J_x(\pi) = \mathbb{E}_{y \sim \pi(\cdot|x)} \left[ E(x, y) \right] - \beta_{\mathrm{KL}} H(\pi(\cdot \mid x)) = \mathcal{F}[\pi(\cdot \mid x)]

with effective temperature T=βKLT = \beta_{\mathrm{KL}}.

By our variational free energy theorem, the distribution π(yx)\pi^*(y \mid x) that minimizes F[π]\mathcal{F}[\pi] (and thus maximizes Jx(π)J_x(\pi)) is precisely the canonical Gibbs distribution:

π(yx)=1Z(x)exp(E(x,y)βKL)\pi^*(y \mid x) = \frac{1}{Z(x)} \exp\left( -\frac{E(x, y)}{\beta_{\mathrm{KL}}} \right)

Substitute E(x,y)=r(x,y)βKLlnπref(yx)E(x, y) = -r(x, y) - \beta_{\mathrm{KL}} \ln \pi_{\mathrm{ref}}(y \mid x):

π(yx)=1Z(x)exp(r(x,y)βKLlnπref(yx)βKL)=1Z(x)exp(r(x,y)βKL+lnπref(yx))=1Z(x)πref(yx)exp(r(x,y)βKL)\begin{aligned} \pi^*(y \mid x) &= \frac{1}{Z(x)} \exp\left( -\frac{-r(x, y) - \beta_{\mathrm{KL}} \ln \pi_{\mathrm{ref}}(y \mid x)}{\beta_{\mathrm{KL}}} \right) \\ &= \frac{1}{Z(x)} \exp\left( \frac{r(x, y)}{\beta_{\mathrm{KL}}} + \ln \pi_{\mathrm{ref}}(y \mid x) \right) \\ &= \frac{1}{Z(x)} \pi_{\mathrm{ref}}(y \mid x) \exp\left( \frac{r(x, y)}{\beta_{\mathrm{KL}}} \right) \end{aligned}

where the per-prompt partition function Z(x)Z(x) is:

Z(x)yYπref(yx)exp(r(x,y)βKL)=Eyπref(x)[exp(r(x,y)βKL)]Z(x) \equiv \sum_{y \in \mathcal{Y}} \pi_{\mathrm{ref}}(y \mid x) \exp\left( \frac{r(x, y)}{\beta_{\mathrm{KL}}} \right) = \mathbb{E}_{y \sim \pi_{\mathrm{ref}}(\cdot|x)} \left[ \exp\left( \frac{r(x, y)}{\beta_{\mathrm{KL}}} \right) \right]

5.3 Alternative Direct Proof via KL Completion

To make this fundamental result unmistakable, we provide a direct algebraic completion of the KL divergence:

Jx(π)=yπ(yx)r(x,y)βKLyπ(yx)lnπ(yx)πref(yx)=βKLyπ(yx)[r(x,y)βKLlnπ(yx)πref(yx)]=βKLyπ(yx)[ln(πref(yx)exp(r(x,y)/βKL)π(yx))]=βKLyπ(yx)[ln(Z(x)1Z(x)πref(yx)exp(r(x,y)/βKL)π(yx))]=βKLyπ(yx)lnZ(x)+βKLyπ(yx)ln(π(yx)π(yx))=βKLlnZ(x)yπ(yx)=1βKLyπ(yx)ln(π(yx)π(yx))=βKLlnZ(x)βKLDKL(π(x)π(x))\begin{aligned} J_x(\pi) &= \sum_{y} \pi(y \mid x) r(x, y) - \beta_{\mathrm{KL}} \sum_y \pi(y \mid x) \ln \frac{\pi(y \mid x)}{\pi_{\mathrm{ref}}(y \mid x)} \\ &= \beta_{\mathrm{KL}} \sum_y \pi(y \mid x) \left[ \frac{r(x, y)}{\beta_{\mathrm{KL}}} - \ln \frac{\pi(y \mid x)}{\pi_{\mathrm{ref}}(y \mid x)} \right] \\ &= \beta_{\mathrm{KL}} \sum_y \pi(y \mid x) \left[ \ln \left( \frac{\pi_{\mathrm{ref}}(y \mid x) \exp(r(x, y)/\beta_{\mathrm{KL}})}{\pi(y \mid x)} \right) \right] \\ &= \beta_{\mathrm{KL}} \sum_y \pi(y \mid x) \left[ \ln \left( \frac{Z(x) \cdot \frac{1}{Z(x)} \pi_{\mathrm{ref}}(y \mid x) \exp(r(x, y)/\beta_{\mathrm{KL}})}{\pi(y \mid x)} \right) \right] \\ &= \beta_{\mathrm{KL}} \sum_y \pi(y \mid x) \ln Z(x) + \beta_{\mathrm{KL}} \sum_y \pi(y \mid x) \ln \left( \frac{\pi^*(y \mid x)}{\pi(y \mid x)} \right) \\ &= \beta_{\mathrm{KL}} \ln Z(x) \underbrace{\sum_y \pi(y \mid x)}_{=1} - \beta_{\mathrm{KL}} \sum_y \pi(y \mid x) \ln \left( \frac{\pi(y \mid x)}{\pi^*(y \mid x)} \right) \\ &= \beta_{\mathrm{KL}} \ln Z(x) - \beta_{\mathrm{KL}} D_{\mathrm{KL}}\left( \pi(\cdot \mid x) \,\|\, \pi^*(\cdot \mid x) \right) \end{aligned}

Since DKL(ππ)0D_{\mathrm{KL}}(\pi \| \pi^*) \ge 0, the maximum value of Jx(π)J_x(\pi) is achieved if and only if DKL(ππ)=0D_{\mathrm{KL}}(\pi \| \pi^*) = 0, which uniquely enforces:

π(yx)=π(yx)=1Z(x)πref(yx)exp(r(x,y)βKL)\pi(y \mid x) = \pi^*(y \mid x) = \frac{1}{Z(x)} \pi_{\mathrm{ref}}(y \mid x) \exp\left( \frac{r(x, y)}{\beta_{\mathrm{KL}}} \right)

The corresponding maximum objective value is:

Jx(π)=βKLlnZ(x)=Feq(x)J_x(\pi^*) = \beta_{\mathrm{KL}} \ln Z(x) = -F_{\mathrm{eq}}(x)

The optimal expected RLHF objective is identically the negative free energy of the aligned language model!


6. The Direct Preference Optimization (DPO) Breakthrough

6.1 Why PPO Fails in Practice: The Curse of Z(x)Z(x)

In standard RLHF pipelines, using π(yx)\pi^*(y \mid x) directly is impossible because:

  1. The partition function Z(x)=yYπref(yx)er(x,y)/βKLZ(x) = \sum_{y \in \mathcal{Y}} \pi_{\mathrm{ref}}(y \mid x) e^{r(x,y)/\beta_{\mathrm{KL}}} requires summing over all VL|\mathcal{V}|^L possible sequences of vocabulary V\mathcal{V} and length LL (typically 32000204810920032000^{2048} \approx 10^{9200} states).
  2. Consequently, traditional pipelines train an approximate reward model rψ(x,y)r_\psi(x, y), and then run Proximal Policy Optimization (PPO) (Schulman et al., 2017) to optimize πθ\pi_\theta.

PPO requires maintaining 4 large models in GPU memory simultaneously:

  1. Actor Model πθ(yx)\pi_\theta(y \mid x) (active policy)
  2. Reference Model πref(yx)\pi_{\mathrm{ref}}(y \mid x) (frozen SFT)
  3. Critic / Value Model Vϕ(x)V_\phi(x) (trained online)
  4. Reward Model rψ(x,y)r_\psi(x, y) (frozen discriminator)

This setup suffers from high variance, unstable gradient updates, high GPU memory footprints, and extreme sensitivity to reward hacking.

6.2 The Bradley-Terry Preference Model

Human preference datasets D={(x(i),yw(i),yl(i))}i=1N\mathcal{D} = \{ (x^{(i)}, y_w^{(i)}, y_l^{(i)}) \}_{i=1}^N contain triples where ywy_w is the winning (preferred) response and yly_l is the losing (dispreferred) response for prompt xx.

Under the Bradley-Terry-Luce (BTL) model of choice (Bradley & Terry, 1952), the probability that a human rater prefers ywy_w over yly_l given an underlying latent ground-truth reward r(x,y)r^*(x, y) is:

p(ywylx)=σ(r(x,yw)r(x,yl))=11+exp((r(x,yw)r(x,yl)))p^*(y_w \succ y_l \mid x) = \sigma\left( r^*(x, y_w) - r^*(x, y_l) \right) = \frac{1}{1 + \exp\left( -\left( r^*(x, y_w) - r^*(x, y_l) \right) \right)}

where σ(u)=11+eu\sigma(u) = \frac{1}{1 + e^{-u}} is the standard logistic sigmoid function.

6.3 Inverting the Gibbs Distribution for the Latent Reward

Here comes the ingenious insight of Rafailov et al. (2023): we can analytically invert the optimal policy equation to express the latent reward function r(x,y)r(x, y) purely in terms of the optimal policy π(yx)\pi^*(y \mid x), the reference policy πref(yx)\pi_{\mathrm{ref}}(y \mid x), and the partition function Z(x)Z(x).

Take the natural logarithm of both sides of the optimal policy formula:

lnπ(yx)=lnπref(yx)+r(x,y)βKLlnZ(x)\ln \pi^*(y \mid x) = \ln \pi_{\mathrm{ref}}(y \mid x) + \frac{r^*(x, y)}{\beta_{\mathrm{KL}}} - \ln Z(x)

Rearrange for the reward r(x,y)r^*(x, y):

r(x,y)βKL=lnπ(yx)πref(yx)+lnZ(x)\frac{r^*(x, y)}{\beta_{\mathrm{KL}}} = \ln \frac{\pi^*(y \mid x)}{\pi_{\mathrm{ref}}(y \mid x)} + \ln Z(x)

Multiplying by βKL\beta_{\mathrm{KL}}:

r(x,y)=βKLlnπ(yx)πref(yx)+βKLlnZ(x)r^*(x, y) = \beta_{\mathrm{KL}} \ln \frac{\pi^*(y \mid x)}{\pi_{\mathrm{ref}}(y \mid x)} + \beta_{\mathrm{KL}} \ln Z(x)

Notice the two components of the reward:

  1. βKLlnπ(yx)πref(yx)\beta_{\mathrm{KL}} \ln \frac{\pi^*(y \mid x)}{\pi_{\mathrm{ref}}(y \mid x)}: The sequence-dependent log-ratio between aligned policy and base policy.
  2. βKLlnZ(x)=Feq(x)\beta_{\mathrm{KL}} \ln Z(x) = -F_{\mathrm{eq}}(x): The free energy baseline, which depends only on the prompt xx and is completely independent of the response yy.

6.4 The Grand Cancellation of the Partition Function

Now, substitute this exact expression for r(x,y)r^*(x, y) into the Bradley-Terry preference probability p(ywylx)=σ(r(x,yw)r(x,yl))p^*(y_w \succ y_l \mid x) = \sigma\left( r^*(x, y_w) - r^*(x, y_l) \right):

r(x,yw)r(x,yl)=[βKLlnπ(ywx)πref(ywx)+βKLlnZ(x)][βKLlnπ(ylx)πref(ylx)+βKLlnZ(x)]=βKLlnπ(ywx)πref(ywx)βKLlnπ(ylx)πref(ylx)+βKLlnZ(x)βKLlnZ(x)=0=βKLln(π(ywx)πref(ywx)π(ylx)πref(ylx))\begin{aligned} r^*(x, y_w) - r^*(x, y_l) &= \left[ \beta_{\mathrm{KL}} \ln \frac{\pi^*(y_w \mid x)}{\pi_{\mathrm{ref}}(y_w \mid x)} + \beta_{\mathrm{KL}} \ln Z(x) \right] - \left[ \beta_{\mathrm{KL}} \ln \frac{\pi^*(y_l \mid x)}{\pi_{\mathrm{ref}}(y_l \mid x)} + \beta_{\mathrm{KL}} \ln Z(x) \right] \\ &= \beta_{\mathrm{KL}} \ln \frac{\pi^*(y_w \mid x)}{\pi_{\mathrm{ref}}(y_w \mid x)} - \beta_{\mathrm{KL}} \ln \frac{\pi^*(y_l \mid x)}{\pi_{\mathrm{ref}}(y_l \mid x)} + \underbrace{\beta_{\mathrm{KL}} \ln Z(x) - \beta_{\mathrm{KL}} \ln Z(x)}_{= 0} \\ &= \beta_{\mathrm{KL}} \ln \left( \frac{\frac{\pi^*(y_w \mid x)}{\pi_{\mathrm{ref}}(y_w \mid x)}}{\frac{\pi^*(y_l \mid x)}{\pi_{\mathrm{ref}}(y_l \mid x)}} \right) \end{aligned}

The DPO Miracle: Exact Thermodynamic Cancellation

The state-dependent free energy F(x)=βKLlnZ(x)-F(x) = \beta_{\mathrm{KL}} \ln Z(x), which represents the intractable partition function sum over all 10920010^{9200} completions, cancels out completely and exactly when computing pairwise preference probabilities!

p(ywylx)=σ(βKLlnπ(ywx)πref(ywx)βKLlnπ(ylx)πref(ylx))p^*(y_w \succ y_l \mid x) = \sigma \left( \beta_{\mathrm{KL}} \ln \frac{\pi^*(y_w \mid x)}{\pi_{\mathrm{ref}}(y_w \mid x)} - \beta_{\mathrm{KL}} \ln \frac{\pi^*(y_l \mid x)}{\pi_{\mathrm{ref}}(y_l \mid x)} \right)

No approximation, no Markov Chain Monte Carlo, no value network, and no normalization constants are required.

6.5 The DPO Objective Function

We can now directly parameterize π(yx)\pi^*(y \mid x) with our language model πθ(yx)\pi_\theta(y \mid x) and formulate the maximum likelihood objective (binary cross-entropy) on the preference dataset D\mathcal{D}:

LDPO(θ;πref)=E(x,yw,yl)D[lnσ(βKLlnπθ(ywx)πref(ywx)βKLlnπθ(ylx)πref(ylx))]\mathcal{L}_{\mathrm{DPO}}(\theta; \pi_{\mathrm{ref}}) = -\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \ln \sigma \left( \beta_{\mathrm{KL}} \ln \frac{\pi_\theta(y_w \mid x)}{\pi_{\mathrm{ref}}(y_w \mid x)} - \beta_{\mathrm{KL}} \ln \frac{\pi_\theta(y_l \mid x)}{\pi_{\mathrm{ref}}(y_l \mid x)} \right) \right]

We define the implicit reward modeled by the parameterized policy πθ\pi_\theta as:

r^θ(x,y)βKLlnπθ(yx)πref(yx)\hat{r}_\theta(x, y) \equiv \beta_{\mathrm{KL}} \ln \frac{\pi_\theta(y \mid x)}{\pi_{\mathrm{ref}}(y \mid x)}

Then the DPO loss simplifies cleanly to:

LDPO(θ;πref)=E(x,yw,yl)D[lnσ(r^θ(x,yw)r^θ(x,yl))]\mathcal{L}_{\mathrm{DPO}}(\theta; \pi_{\mathrm{ref}}) = -\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \ln \sigma \left( \hat{r}_\theta(x, y_w) - \hat{r}_\theta(x, y_l) \right) \right]

7. Gradient Analysis & Dynamical Mechanics of DPO

To understand how DPO updates token probabilities during stochastic gradient descent, we compute the exact analytic gradient of LDPO(θ)\mathcal{L}_{\mathrm{DPO}}(\theta) with respect to network parameters θ\theta.

7.1 Derivation of the DPO Gradient

Let ur^θ(x,yw)r^θ(x,yl)=βKLlnπθ(ywx)πref(ywx)βKLlnπθ(ylx)πref(ylx)u \equiv \hat{r}_\theta(x, y_w) - \hat{r}_\theta(x, y_l) = \beta_{\mathrm{KL}} \ln \frac{\pi_\theta(y_w \mid x)}{\pi_{\mathrm{ref}}(y_w \mid x)} - \beta_{\mathrm{KL}} \ln \frac{\pi_\theta(y_l \mid x)}{\pi_{\mathrm{ref}}(y_l \mid x)}.

Recall the derivative of the log-sigmoid function:

ddulnσ(u)=1σ(u)σ(u)(1σ(u))=1σ(u)=σ(u)\frac{d}{du} \ln \sigma(u) = \frac{1}{\sigma(u)} \cdot \sigma(u)(1 - \sigma(u)) = 1 - \sigma(u) = \sigma(-u)

Now apply the chain rule to differentiate lnσ(u)-\ln \sigma(u) with respect to θ\theta:

θLDPO(θ)=E(x,yw,yl)[σ((r^θ(x,yw)r^θ(x,yl)))θ(r^θ(x,yw)r^θ(x,yl))]=E(x,yw,yl)[σ(r^θ(x,yl)r^θ(x,yw))βKLθ(lnπθ(ywx)lnπθ(ylx))]\begin{aligned} \nabla_\theta \mathcal{L}_{\mathrm{DPO}}(\theta) &= -\mathbb{E}_{(x, y_w, y_l)} \left[ \sigma\left( -( \hat{r}_\theta(x, y_w) - \hat{r}_\theta(x, y_l) ) \right) \nabla_\theta \left( \hat{r}_\theta(x, y_w) - \hat{r}_\theta(x, y_l) \right) \right] \\ &= -\mathbb{E}_{(x, y_w, y_l)} \left[ \sigma\left( \hat{r}_\theta(x, y_l) - \hat{r}_\theta(x, y_w) \right) \cdot \beta_{\mathrm{KL}} \nabla_\theta \left( \ln \pi_\theta(y_w \mid x) - \ln \pi_\theta(y_l \mid x) \right) \right] \end{aligned}

Thus, the DPO gradient is:

θLDPO(θ)=βKLE(x,yw,yl)D[σ(r^θ(x,yl)r^θ(x,yw))Implicit Reward Error Weight w(x,yw,yl)(θlnπθ(ywx)Increase yw probabilityθlnπθ(ylx)Decrease yl probability)]\nabla_\theta \mathcal{L}_{\mathrm{DPO}}(\theta) = -\beta_{\mathrm{KL}} \, \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \underbrace{\sigma\left( \hat{r}_\theta(x, y_l) - \hat{r}_\theta(x, y_w) \right)}_{\text{Implicit Reward Error Weight } w(x, y_w, y_l)} \left( \underbrace{\nabla_\theta \ln \pi_\theta(y_w \mid x)}_{\text{Increase } y_w \text{ probability}} - \underbrace{\nabla_\theta \ln \pi_\theta(y_l \mid x)}_{\text{Decrease } y_l \text{ probability}} \right) \right]

7.2 Physical and Algorithmic Interpretation of the Gradient

DPO Loss and Implicit Reward Dynamics

The DPO gradient decomposes into two distinct, intuitive components:

1. Directional Force (Likelihood Push-Pull)

  • θlnπθ(ywx)\nabla_\theta \ln \pi_\theta(y_w \mid x): Increases the log-likelihood of every token in the winning completion ywy_w.
  • θlnπθ(ylx)-\nabla_\theta \ln \pi_\theta(y_l \mid x): Decreases the log-likelihood of every token in the losing completion yly_l.

2. Adaptive Error Weight w(x,yw,yl)=σ(r^θ(x,yl)r^θ(x,yw))w(x, y_w, y_l) = \sigma(\hat{r}_\theta(x, y_l) - \hat{r}_\theta(x, y_w))

  • High Gradient Regime (w1w \to 1): If the current policy incorrectly rates the losing response higher than the winning response (r^θ(x,yl)r^θ(x,yw)\hat{r}_\theta(x, y_l) \gg \hat{r}_\theta(x, y_w)), then r^θ(yl)r^θ(yw)0\hat{r}_\theta(y_l) - \hat{r}_\theta(y_w) \gg 0, so σ1\sigma \approx 1. The model applies the maximum gradient magnitude to correct its mistake.
  • Low Gradient Regime (w0w \to 0): If the policy already strongly prefers the winning completion (r^θ(x,yw)r^θ(x,yl)\hat{r}_\theta(x, y_w) \gg \hat{r}_\theta(x, y_l)), then σ0\sigma \approx 0, preventing gradient saturation and avoiding catastrophic forgetting.

8. Asymptotic Temperature Limits & Phase Transitions

To deepen the statistical mechanics perspective, let us analyze the behavior of the optimal aligned policy π(yx)\pi^*(y \mid x) under extreme thermodynamic limits of the regularization parameter βKL\beta_{\mathrm{KL}}.

8.1 High Temperature Limit (βKL\beta_{\mathrm{KL}} \to \infty)

When the regularization parameter is extremely large:

limβKLr(x,y)βKL=0    exp(r(x,y)βKL)1\lim_{\beta_{\mathrm{KL}} \to \infty} \frac{r(x, y)}{\beta_{\mathrm{KL}}} = 0 \implies \exp\left( \frac{r(x, y)}{\beta_{\mathrm{KL}}} \right) \to 1

The partition function simplifies to:

Z(x)yπref(yx)1=1Z(x) \to \sum_{y} \pi_{\mathrm{ref}}(y \mid x) \cdot 1 = 1

Thus:

limβKLπ(yx)=πref(yx)\lim_{\beta_{\mathrm{KL}} \to \infty} \pi^*(y \mid x) = \pi_{\mathrm{ref}}(y \mid x)

Entropy dominates completely over the energy term. The policy remains identical to the base pre-trained/SFT model.

8.2 Zero Temperature Limit (βKL0+\beta_{\mathrm{KL}} \to 0^+)

When regularization approaches zero, the Boltzmann distribution concentrates all its probability mass on the ground state(s) (i.e., maximum reward completions):

Y(x)argmaxyYr(x,y)\mathcal{Y}^*(x) \equiv \arg\max_{y \in \mathcal{Y}} r(x, y)

Let rmax(x)=maxyr(x,y)r_{\max}(x) = \max_y r(x, y). Then:

π(yx)=πref(yx)e(r(x,y)rmax(x))/βKLyπref(yx)e(r(x,y)rmax(x))/βKL\begin{aligned} \pi^*(y \mid x) &= \frac{\pi_{\mathrm{ref}}(y \mid x) e^{(r(x, y) - r_{\max}(x))/\beta_{\mathrm{KL}}}}{\sum_{y'} \pi_{\mathrm{ref}}(y' \mid x) e^{(r(x, y') - r_{\max}(x))/\beta_{\mathrm{KL}}}} \end{aligned}

As βKL0+\beta_{\mathrm{KL}} \to 0^+:

  • For any yY(x)y \notin \mathcal{Y}^*(x), r(x,y)rmax(x)<0r(x, y) - r_{\max}(x) < 0, so e(r(x,y)rmax(x))/βKL0e^{(r(x, y) - r_{\max}(x))/\beta_{\mathrm{KL}}} \to 0.
  • For yY(x)y \in \mathcal{Y}^*(x), e0=1e^0 = 1.

Therefore:

limβKL0+π(yx)={πref(yx)yY(x)πref(yx)if yY(x)0if yY(x)\lim_{\beta_{\mathrm{KL}} \to 0^+} \pi^*(y \mid x) = \begin{cases} \frac{\pi_{\mathrm{ref}}(y \mid x)}{\sum_{y' \in \mathcal{Y}^*(x)} \pi_{\mathrm{ref}}(y' \mid x)} & \text{if } y \in \mathcal{Y}^*(x) \\ 0 & \text{if } y \notin \mathcal{Y}^*(x) \end{cases}

If the maximum reward completion yy^* is unique, the distribution collapses to a Dirac delta measure:

limβKL0+π(yx)=δy,y\lim_{\beta_{\mathrm{KL}} \to 0^+} \pi^*(y \mid x) = \delta_{y, y^*}

[!CAUTION] Reward Hacking as a Condensation Phase Transition In the zero-temperature regime (βKL0\beta_{\mathrm{KL}} \to 0), the model experiences a Bose-Einstein-like condensation into the global maximum of the reward model. If the reward model has adversarial vulnerabilities (unnatural repetition, excessive verbosity, sycophancy), the policy collapses into degenerate, ungrammatical gibberish that exploits the proxy reward. Tuning βKL\beta_{\mathrm{KL}} (typically βKL[0.05,0.5]\beta_{\mathrm{KL}} \in [0.05, 0.5]) maintains the critical temperature balance between helpful alignment and linguistic entropy.


9. Modern Frontiers: Beyond Vanilla DPO (2024–2026)

Following the initial introduction of DPO, the machine learning community discovered subtleties in off-policy preference optimization that led to next-generation algorithms:

9.1 Summary of Frontier Preference Objectives

MethodLoss FormulationKey Innovation / Physical Motivation
DPO (Rafailov et al., 2023)lnσ(βlnπθ(yw)πref(yw)βlnπθ(yl)πref(yl))-\ln \sigma\left( \beta \ln \frac{\pi_\theta(y_w)}{\pi_{\mathrm{ref}}(y_w)} - \beta \ln \frac{\pi_\theta(y_l)}{\pi_{\mathrm{ref}}(y_l)} \right)Exact analytical elimination of the partition function Z(x)Z(x).
IPO (Azar et al., 2024)(lnπθ(yw)πref(yw)lnπθ(yl)πref(yl)12τ)2\left( \ln \frac{\pi_\theta(y_w)}{\pi_{\mathrm{ref}}(y_w)} - \ln \frac{\pi_\theta(y_l)}{\pi_{\mathrm{ref}}(y_l)} - \frac{1}{2\tau} \right)^2Regularizes the BTL log-likelihood to prevent deterministic policy saturation and overfitting to noisy preferences.
KTO (Ethayarajh et al., 2024)Optimizes binary (x,y,is_desirable)(x, y, \text{is\_desirable}) feedback based on Kahneman-Tversky Prospect TheoryOperates directly on unpaired examples; models human loss aversion (losses loom larger than gains).
SimPO (Meng et al., 2024)lnσ(βywlnπθ(yw)βyllnπθ(yl)γ)-\ln \sigma\left( \frac{\beta}{\mid y_w\mid } \ln \pi_\theta(y_w) - \frac{\beta}{\mid y_l\mid } \ln \pi_\theta(y_l) - \gamma \right)Eliminates πref\pi_{\mathrm{ref}} entirely and normalizes by sequence length y\mid y\mid to eliminate verbosity bias.
Online / Iterative DPOIteratively generates rollouts from current πθ\pi_\theta, labels with an oracle/judge, and updates πθ\pi_\thetaBridges the gap between offline DPO and active on-policy exploration (non-equilibrium steady state).

9.2 The Sequence Length Bias as an Entropic Volume Effect

A well-documented phenomenon in DPO alignment is length bias: models trained with DPO often generate unnecessarily long responses. Statistical mechanics provides an elegant explanation for this behavior:

The log-probability of a sequence y=(y1,,yL)y = (y_1, \dots, y_L) is a sum of LL token log-probabilities:

lnπθ(yx)=t=1Llnπθ(ytx,y<t)\ln \pi_\theta(y \mid x) = \sum_{t=1}^L \ln \pi_\theta(y_t \mid x, y_{<t})

If the per-token advantage is positive (Δlnπ>0\Delta \ln \pi > 0), longer sequences accumulate a linearly larger total implicit reward r^θ(x,y)L\hat{r}_\theta(x, y) \propto L. In statistical mechanics, this corresponds to an extensive thermodynamic state variable scaling with system size VV (or particle number NN). Without length normalization (as introduced in SimPO), the system exhibits an entropic expansion toward larger microstate volumes (longer sequences).


10. Complete PyTorch Implementation

Below is a production-grade, numerically stable implementation of the DPO loss function, demonstrating how the log-ratio arithmetic and reference policy evaluations are implemented in practice.

"""
Production-Grade Direct Preference Optimization (DPO) Loss Implementation
Includes numerical stability safeguards via logsigmoid and length masking.
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple, Optional


class DPOTrainerLoss(nn.Module):
    """
    Direct Preference Optimization (DPO) Loss Module.
    
    Mathematical Formulation:
        L_DPO(theta; pi_ref) = -E_{(x, y_w, y_l)} [ ln sigma( beta * (log_ratio_w - log_ratio_l) ) ]
        where log_ratio = ln pi_theta(y|x) - ln pi_ref(y|x)
    """
    def __init__(
        self, 
        beta: float = 0.1, 
        label_smoothing: float = 0.0,
        length_normalization: bool = False
    ):
        """
        Args:
            beta: Regularization weight (effective temperature T = beta).
            label_smoothing: Conservative label smoothing parameter epsilon.
            length_normalization: Whether to normalize log-probs by sequence length.
        """
        super().__init__()
        self.beta = beta
        self.label_smoothing = label_smoothing
        self.length_normalization = length_normalization

    def _get_batch_logps(
        self,
        logits: torch.FloatTensor,
        labels: torch.LongTensor,
        average_log_prob: bool = False,
        mask_pad_token_id: int = -100
    ) -> torch.FloatTensor:
        """
        Compute sequence-level log-probabilities from model logits.
        
        Args:
            logits: Model forward output logits of shape (batch_size, seq_len, vocab_size).
            labels: Ground-truth target token IDs of shape (batch_size, seq_len).
            average_log_prob: If True, returns mean per-token log-probability.
            mask_pad_token_id: Ignored index for padding tokens.
            
        Returns:
            Per-sequence log-probabilities of shape (batch_size,).
        """
        if logits.shape[:-1] != labels.shape:
            raise ValueError("Logits and labels must have the same batch and sequence dimensions.")

        # Shift logits and labels for autoregressive next-token prediction
        shift_logits = logits[:, :-1, :].contiguous()
        shift_labels = labels[:, 1:].contiguous()
        
        loss_mask = (shift_labels != mask_pad_token_id)
        
        # Log-softmax along vocabulary dimension for numerical precision
        log_probs = F.log_softmax(shift_logits, dim=-1)
        
        # Gather the log-probability of the actual token taken
        # Clamp negative label indices to 0 before gather to prevent index errors
        clamped_labels = shift_labels.clone()
        clamped_labels[~loss_mask] = 0
        
        per_token_logps = torch.gather(
            log_probs, 
            dim=-1, 
            index=clamped_labels.unsqueeze(-1)
        ).squeeze(-1)
        
        # Zero out padding tokens
        per_token_logps = per_token_logps * loss_mask
        
        if average_log_prob:
            seq_lens = loss_mask.sum(dim=-1).clamp(min=1)
            return per_token_logps.sum(dim=-1) / seq_lens
        else:
            return per_token_logps.sum(dim=-1)

    def forward(
        self,
        policy_chosen_logits: torch.FloatTensor,
        policy_rejected_logits: torch.FloatTensor,
        reference_chosen_logits: torch.FloatTensor,
        reference_rejected_logits: torch.FloatTensor,
        chosen_labels: torch.LongTensor,
        rejected_labels: torch.LongTensor,
    ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
        """
        Computes the forward pass of DPO loss.
        
        Returns:
            loss: Scalar tensor representing the DPO loss.
            chosen_rewards: Implicit rewards for chosen responses (detached).
            rejected_rewards: Implicit rewards for rejected responses (detached).
        """
        # 1. Compute log-probabilities under the active policy pi_theta
        pi_logps_chosen = self._get_batch_logps(
            policy_chosen_logits, chosen_labels, average_log_prob=self.length_normalization
        )
        pi_logps_rejected = self._get_batch_logps(
            policy_rejected_logits, rejected_labels, average_log_prob=self.length_normalization
        )

        # 2. Compute log-probabilities under the reference policy pi_ref (detached)
        with torch.no_grad():
            ref_logps_chosen = self._get_batch_logps(
                reference_chosen_logits, chosen_labels, average_log_prob=self.length_normalization
            )
            ref_logps_rejected = self._get_batch_logps(
                reference_rejected_logits, rejected_labels, average_log_prob=self.length_normalization
            )

        # 3. Compute log-ratios (log pi_theta - log pi_ref)
        pi_chosen_logratio = pi_logps_chosen - ref_logps_chosen
        pi_rejected_logratio = pi_logps_rejected - ref_logps_rejected

        # 4. Compute implicit rewards: r_hat(x, y) = beta * ln(pi_theta / pi_ref)
        chosen_rewards = self.beta * pi_chosen_logratio.detach()
        rejected_rewards = self.beta * pi_rejected_logratio.detach()

        # 5. Compute preference logits: beta * (logratio_w - logratio_l)
        logits = self.beta * (pi_chosen_logratio - pi_rejected_logratio)

        # 6. Numerically stable loss computation via logsigmoid
        # ln sigma(u) = F.logsigmoid(logits)
        if self.label_smoothing > 0.0:
            # Conservative smoothing: (1 - eps) * BCE + eps * BCE(reversed)
            loss = -(
                (1.0 - self.label_smoothing) * F.logsigmoid(logits)
                + self.label_smoothing * F.logsigmoid(-logits)
            ).mean()
        else:
            loss = -F.logsigmoid(logits).mean()

        return loss, chosen_rewards, rejected_rewards

11. Summary of Key Theoretical Insights

Helmholtz Free Energy

F = ⟨E⟩ - TS = -T ln Z. Equilibrium minimizes F, balancing energy minimization (fidelity) against entropy maximization (coverage).

Variational Equivalence

F[q] = T D_KL(q || p) - T ln Z. Minimizing variational free energy is mathematically identical to minimizing KL divergence to the Gibbs distribution.

ELBO in VAEs

ELBO[q] = -F[q] at T=1. Maximizing the Evidence Lower Bound minimizes the variational free energy of latent posterior approximations.

Optimal RLHF Policy

π*(y|x) ∝ π_ref(y|x) exp(r(x,y)/β). The regularized alignment objective produces a generalized Boltzmann distribution over completions.

The DPO Miracle

The per-prompt partition function Z(x) cancels out completely in pairwise preferences: r(y_w) - r(y_l) = β ln(π_w/π_ref_w) - β ln(π_l/π_ref_l).

Dynamic Push-Pull

The DPO gradient adaptively weights updates by prediction error σ(r_l - r_w), pushing winning token probabilities up and losing token probabilities down.


12. References & Further Reading

  1. Boltzmann, L. (1877). Über die Beziehung zwischen dem zweiten Hauptsatze der mechanischen Wärmetheorie und der Wahrscheinlichkeitsrechnung respektive den Sätzen über das Wärmegleichgewicht. Wiener Berichte.
  2. Gibbs, J. W. (1902). Elementary Principles in Statistical Mechanics. Yale University Press.
  3. Kingma, D. P., & Welling, M. (2013). Auto-Encoding Variational Bayes. arXiv:1312.6114.
  4. Ziegler, D. M., et al. (2019). Fine-Tuning Language Models from Human Preferences. arXiv:1909.08593.
  5. Ouyang, L., et al. (2022). Training language models to follow instructions with human feedback (InstructGPT). NeurIPS 2022.
  6. Rafailov, R., Sharma, A., Mitchell, E., Ermon, S., Manning, C. D., & Finn, C. (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model. NeurIPS 2023.
  7. Azar, M. G., et al. (2024). A General Theoretical Paradigm to Understand Learning from Human Preferences (IPO). ICML 2024.
  8. Ethayarajh, K., et al. (2024). KTO: Model Alignment as Prospect Theoretic Optimization. ICML 2024.
  9. Meng, Y., et al. (2024). SimPO: Simple Preference Optimization with a Reference-Free Reward. NeurIPS 2024.
  10. Calandriello, D., et al. (2024). Human Alignment of Large Language Models through Online Preference Optimization. ICML 2024.

On this page

Free Energy, Variational Inference & Direct Preference Optimization (DPO)1. Conceptual Rosetta Stone: Physics vs. Deep Learning2. Thermodynamic Potentials and Helmholtz Free Energy2.1 The Canonical Ensemble and Gibbs-Boltzmann Distribution2.2 Thermodynamic Observables from the Partition Function1. Internal Energy (UU)2. Heat Capacity and Energy Fluctuations3. Gibbs-Shannon Entropy (SS)2.3 Definition of Helmholtz Free Energy3. The Variational Free Energy Formulation3.1 The Variational Free Energy Functional3.2 Exact Equivalence between Free Energy and KL DivergenceStep-by-Step Proof:3.3 Corollaries of the Variational Theorem1. Bogoliubov / Gibbs Free Energy Inequality2. Exact Equivalence of Optimizers3. Uniqueness of Equilibrium4. Variational Inference & Evidence Lower Bound (ELBO) in Deep Learning4.1 The Intractable Posterior Problem4.2 Derivation of the ELBO from Free Energy4.3 The Evidence Decomposition5. RLHF as Free Energy Minimization5.1 The Standard RLHF Objective5.2 Deriving the Closed-Form Optimal RLHF Policy5.3 Alternative Direct Proof via KL Completion6. The Direct Preference Optimization (DPO) Breakthrough6.1 Why PPO Fails in Practice: The Curse of Z(x)Z(x)6.2 The Bradley-Terry Preference Model6.3 Inverting the Gibbs Distribution for the Latent Reward6.4 The Grand Cancellation of the Partition Function6.5 The DPO Objective Function7. Gradient Analysis & Dynamical Mechanics of DPO7.1 Derivation of the DPO Gradient7.2 Physical and Algorithmic Interpretation of the Gradient1. Directional Force (Likelihood Push-Pull)2. Adaptive Error Weight w(x,yw,yl)=σ(r^θ(x,yl)r^θ(x,yw))w(x, y_w, y_l) = \sigma(\hat{r}_\theta(x, y_l) - \hat{r}_\theta(x, y_w))8. Asymptotic Temperature Limits & Phase Transitions8.1 High Temperature Limit (βKL\beta_{\mathrm{KL}} \to \infty)8.2 Zero Temperature Limit (βKL0+\beta_{\mathrm{KL}} \to 0^+)9. Modern Frontiers: Beyond Vanilla DPO (2024–2026)9.1 Summary of Frontier Preference Objectives9.2 The Sequence Length Bias as an Entropic Volume Effect10. Complete PyTorch Implementation11. Summary of Key Theoretical Insights12. References & Further Reading