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 . 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 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.
| Concept | Statistical Mechanics | Variational Inference (Bayesian ML) | LLM Alignment (RLHF / DPO) |
|---|---|---|---|
| State / Microstate | Microstate configuration | Latent variable (given data ) | Completion / Response (given prompt ) |
| Cost / Energy | Hamiltonian | Negative Joint Log-Likelihood | Negative Reward |
| Base / Prior Density | Uniform phase space measure | Prior distribution | Reference policy / SFT model |
| Active Distribution | Canonical Gibbs measure | Variational posterior | Fine-tuned policy |
| Normalizing Factor | Partition Function | Marginal Likelihood / Evidence | Per-prompt normalizer |
| Macroscopic Potential | Helmholtz Free Energy | Variational Free Energy | Negative regularized RL objective |
| Order vs. Disorder | Internal Energy vs. Entropy | Reconstruction fit vs. | Reward maximization vs. |
| Temperature | Thermodynamic temperature | Relaxation parameter in variational relaxations | Regularization strength (or sampling temperature ) |
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 . The microstates of the system are denoted by , and each microstate has an associated energy given by the Hamiltonian .
In the canonical ensemble, the probability of the system occupying microstate is given by the Gibbs-Boltzmann distribution:
where is the inverse temperature (we set Boltzmann's constant throughout this chapter for simplicity, hence ), and is the canonical partition function:
The partition function acts as the fundamental generating function in statistical mechanics. All macroscopic thermodynamic observables can be derived from derivatives of .
2.2 Thermodynamic Observables from the Partition Function
1. Internal Energy ()
The average or internal energy of the system is the expectation value of the Hamiltonian:
2. Heat Capacity and Energy Fluctuations
Differentiating the internal energy with respect to temperature yields the heat capacity at constant volume :
Evaluating directly:
Hence, the variance of energy fluctuations is directly proportional to the heat capacity:
3. Gibbs-Shannon Entropy ()
The statistical entropy of the canonical distribution is:
Substituting the explicit form of :
Multiplying by :
2.3 Definition of Helmholtz Free Energy
Rearranging the entropy identity yields the Helmholtz Free Energy :
Physical Significance of Helmholtz Free Energy
The Helmholtz free energy represents the maximum reversible work that a closed thermodynamic system can perform at constant temperature and volume: In any spontaneous isothermal process, the free energy monotonically decreases until reaching thermodynamic equilibrium:
3. The Variational Free Energy Formulation
In statistical mechanics and probabilistic machine learning alike, we frequently encounter an arbitrary, non-equilibrium trial distribution that differs from the true equilibrium distribution .
3.1 The Variational Free Energy Functional
For any probability distribution over the microstate space , we define the Variational Free Energy functional (also known as Gibbs free energy functional or Helmholtz functional) as:
where:
- is the expected energy under trial distribution .
- is the Shannon/Gibbs entropy of .
Expanding this definition:
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 with canonical equilibrium distribution at temperature , and for any valid probability distribution , the variational free energy satisfies:
where is the true equilibrium Helmholtz free energy.
Step-by-Step Proof:
Recall the definition of the Kullback-Leibler (KL) divergence from to :
Substitute the canonical Gibbs distribution into the second term:
Now compute :
Substitute this back into the expression for :
Multiplying both sides by :
Notice that the first two terms on the right-hand side are precisely the Variational Free Energy :
Rearranging for :
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 (, with equality if and only if almost everywhere):
The variational free energy provides an upper bound on the true equilibrium free energy .
2. Exact Equivalence of Optimizers
Since does not depend on the trial distribution :
Minimizing the physical variational free energy over any parametric family is strictly equivalent to minimizing the Kullback-Leibler divergence to the true Boltzmann distribution .
3. Uniqueness of Equilibrium
The global minimum is attained at:
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 generated by unobserved latent variables through a generative model .
| Statistical Mechanics (Physics) | Variational Inference / VAEs (Machine Learning) | Fundamental Correspondence |
|---|---|---|
| Log Partition Function () | True Marginal Log-Evidence () | |
| Variational Free Energy () | Negative Evidence Lower Bound () | (at ) |
| Equilibrium Minimizes | Training Maximizes | |
| Ground-Truth Free Energy () | Negative Evidence () |
4.1 The Intractable Posterior Problem
Computing the true posterior over latents requires the marginal likelihood (evidence):
This integral is the exact analog of the continuous partition function where the energy function is the joint negative log-likelihood:
For nonlinear deep neural networks, computing is computationally intractable due to the curse of dimensionality.
4.2 Derivation of the ELBO from Free Energy
We introduce a variational recognition network to approximate the intractable posterior . Setting (), the variational free energy of the posterior approximation is:
We define the Evidence Lower Bound (ELBO) as the negative variational free energy:
Expanding :
4.3 The Evidence Decomposition
Applying our master free energy identity with :
Rearranging:
Since , we have . Maximizing the ELBO with respect to pushes the variational distribution toward the true posterior while simultaneously maximizing the data marginal likelihood with respect to generative parameters .
5. RLHF as Free Energy Minimization
We now transition to language model alignment: training a foundation model to produce completions given a prompt 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:
- A Supervised Fine-Tuning (SFT) reference policy .
- A Reward Model parameterized by neural network .
We then optimize a parameterized policy to maximize expected reward while penalizing divergence from the reference policy :
where is the regularization coefficient.
[!WARNING] CRITICAL NOTATION WARNING: in Alignment vs. in Statistical Mechanics In statistical physics:
- is the inverse temperature. High means cold / zero exploration.
- multiplies the entropy term in free energy: .
In machine learning / RLHF literature (Rafailov et al., 2023):
- is the regularization weight multiplying the KL divergence.
- Therefore, plays the mathematical role of Temperature , not inverse temperature!
- Specifically: , and .
As , the policy is frozen to the prior (infinite temperature / infinite friction). As , 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 , the per-prompt objective to maximize is:
subject to the probability normalization constraint and .
Let us rewrite in the exact form of a Variational Free Energy:
We define the effective prompt-conditioned Hamiltonian:
Then:
with effective temperature .
By our variational free energy theorem, the distribution that minimizes (and thus maximizes ) is precisely the canonical Gibbs distribution:
Substitute :
where the per-prompt partition function is:
5.3 Alternative Direct Proof via KL Completion
To make this fundamental result unmistakable, we provide a direct algebraic completion of the KL divergence:
Since , the maximum value of is achieved if and only if , which uniquely enforces:
The corresponding maximum objective value is:
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
In standard RLHF pipelines, using directly is impossible because:
- The partition function requires summing over all possible sequences of vocabulary and length (typically states).
- Consequently, traditional pipelines train an approximate reward model , and then run Proximal Policy Optimization (PPO) (Schulman et al., 2017) to optimize .
PPO requires maintaining 4 large models in GPU memory simultaneously:
- Actor Model (active policy)
- Reference Model (frozen SFT)
- Critic / Value Model (trained online)
- Reward Model (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 contain triples where is the winning (preferred) response and is the losing (dispreferred) response for prompt .
Under the Bradley-Terry-Luce (BTL) model of choice (Bradley & Terry, 1952), the probability that a human rater prefers over given an underlying latent ground-truth reward is:
where 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 purely in terms of the optimal policy , the reference policy , and the partition function .
Take the natural logarithm of both sides of the optimal policy formula:
Rearrange for the reward :
Multiplying by :
Notice the two components of the reward:
- : The sequence-dependent log-ratio between aligned policy and base policy.
- : The free energy baseline, which depends only on the prompt and is completely independent of the response .
6.4 The Grand Cancellation of the Partition Function
Now, substitute this exact expression for into the Bradley-Terry preference probability :
The DPO Miracle: Exact Thermodynamic Cancellation
The state-dependent free energy , which represents the intractable partition function sum over all completions, cancels out completely and exactly when computing pairwise preference probabilities!
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 with our language model and formulate the maximum likelihood objective (binary cross-entropy) on the preference dataset :
We define the implicit reward modeled by the parameterized policy as:
Then the DPO loss simplifies cleanly to:
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 with respect to network parameters .
7.1 Derivation of the DPO Gradient
Let .
Recall the derivative of the log-sigmoid function:
Now apply the chain rule to differentiate with respect to :
Thus, the DPO gradient is:
7.2 Physical and Algorithmic Interpretation of the Gradient
The DPO gradient decomposes into two distinct, intuitive components:
1. Directional Force (Likelihood Push-Pull)
- : Increases the log-likelihood of every token in the winning completion .
- : Decreases the log-likelihood of every token in the losing completion .
2. Adaptive Error Weight
- High Gradient Regime (): If the current policy incorrectly rates the losing response higher than the winning response (), then , so . The model applies the maximum gradient magnitude to correct its mistake.
- Low Gradient Regime (): If the policy already strongly prefers the winning completion (), then , 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 under extreme thermodynamic limits of the regularization parameter .
8.1 High Temperature Limit ()
When the regularization parameter is extremely large:
The partition function simplifies to:
Thus:
Entropy dominates completely over the energy term. The policy remains identical to the base pre-trained/SFT model.
8.2 Zero Temperature Limit ()
When regularization approaches zero, the Boltzmann distribution concentrates all its probability mass on the ground state(s) (i.e., maximum reward completions):
Let . Then:
As :
- For any , , so .
- For , .
Therefore:
If the maximum reward completion is unique, the distribution collapses to a Dirac delta measure:
[!CAUTION] Reward Hacking as a Condensation Phase Transition In the zero-temperature regime (), 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 (typically ) 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
| Method | Loss Formulation | Key Innovation / Physical Motivation |
|---|---|---|
| DPO (Rafailov et al., 2023) | Exact analytical elimination of the partition function . | |
| IPO (Azar et al., 2024) | Regularizes the BTL log-likelihood to prevent deterministic policy saturation and overfitting to noisy preferences. | |
| KTO (Ethayarajh et al., 2024) | Optimizes binary feedback based on Kahneman-Tversky Prospect Theory | Operates directly on unpaired examples; models human loss aversion (losses loom larger than gains). |
| SimPO (Meng et al., 2024) | Eliminates entirely and normalizes by sequence length to eliminate verbosity bias. | |
| Online / Iterative DPO | Iteratively generates rollouts from current , labels with an oracle/judge, and updates | Bridges 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 is a sum of token log-probabilities:
If the per-token advantage is positive (), longer sequences accumulate a linearly larger total implicit reward . In statistical mechanics, this corresponds to an extensive thermodynamic state variable scaling with system size (or particle number ). 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_rewards11. 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
- 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.
- Gibbs, J. W. (1902). Elementary Principles in Statistical Mechanics. Yale University Press.
- Kingma, D. P., & Welling, M. (2013). Auto-Encoding Variational Bayes. arXiv:1312.6114.
- Ziegler, D. M., et al. (2019). Fine-Tuning Language Models from Human Preferences. arXiv:1909.08593.
- Ouyang, L., et al. (2022). Training language models to follow instructions with human feedback (InstructGPT). NeurIPS 2022.
- 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.
- Azar, M. G., et al. (2024). A General Theoretical Paradigm to Understand Learning from Human Preferences (IPO). ICML 2024.
- Ethayarajh, K., et al. (2024). KTO: Model Alignment as Prospect Theoretic Optimization. ICML 2024.
- Meng, Y., et al. (2024). SimPO: Simple Preference Optimization with a Reference-Free Reward. NeurIPS 2024.
- Calandriello, D., et al. (2024). Human Alignment of Large Language Models through Online Preference Optimization. ICML 2024.
1. Foundations: Gibbs Distributions, Softmax & Energy-Based Models
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.
3. Large Numbers, Self-Averaging & Infinite-Width Neural Networks
Mathematical foundations of large-N asymptotics: Stirling's approximation, high-dimensional concentration, self-averaging, Gaussian Process limits (NNGP), Neural Tangent Kernel (NTK) dynamics, non-asymptotic transport bounds, mini-batch SGD central limit theorems, and 1/N effective field theory expansions.