Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ Internal cleanup plus the start of a diffusion track.
noise-conditional energies. Validated: the ancestral sampler recovers a known
Gaussian's variance; VP-DSM trains a model whose samples match it. Example
`train_diffusion.py`.
- **`nets.ContinuousNormalizingFlow`** (FFJORD) — a *trainable* neural-ODE flow,
the generalization of `eval.pf_ode_log_likelihood`: a velocity field defines an
ODE from data to a Gaussian base and the exact log-density follows the
instantaneous change of variables (Hutchinson trace), all torch-only (fixed-step
RK4, direct backprop). Trains by maximum likelihood, samples in one reverse pass,
and doubles as a self-normalized energy. Validated against a linear-field
closed form and exact rotation-invariance. Example `train_cnf.py`.

## 0.14.0 — 2026-08-17

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ returns `LossOutput(loss, metrics, x_neg)`; call `out.loss.backward()`).

| Piece | Contents |
|---|---|
| **Energies** | any callable `(B, *shape) -> (B,)`; `nets.MLPEnergy` / `ConvEnergy` / `ResNetEnergy` / `ConvClassifier` (SiLU, optional spectral norm, no batch norm), `nets.RBM` (Bernoulli RBM with exact `log_z`), `nets.IsingEnergy` / `PottsEnergy` (discrete lattices), `nets.FunnelEnergy` / `GaussianMixtureEnergy` / `BananaEnergy` (closed-form targets), `nets.AffineCouplingFlow` (RealNVP — exact-likelihood flow / self-normalized energy), noise-conditional variants for NCSN; `EnergyModel`, `ebm.score` |
| **Energies** | any callable `(B, *shape) -> (B,)`; `nets.MLPEnergy` / `ConvEnergy` / `ResNetEnergy` / `ConvClassifier` (SiLU, optional spectral norm, no batch norm), `nets.RBM` (Bernoulli RBM with exact `log_z`), `nets.IsingEnergy` / `PottsEnergy` (discrete lattices), `nets.FunnelEnergy` / `GaussianMixtureEnergy` / `BananaEnergy` (closed-form targets), `nets.AffineCouplingFlow` (RealNVP) / `nets.ContinuousNormalizingFlow` (FFJORD — trainable exact-likelihood flows / self-normalized energies), noise-conditional variants for NCSN; `EnergyModel`, `ebm.score` |
| **Samplers** | `LangevinDynamics` (ULA/SGLD), `MALA`, `HMC`, `UnderdampedLangevin` (SGHMC), `PreconditionedLangevin`, `ParallelTempering` (replica exchange), `TemperedTransitions`, `SVGD` (Stein variational), `GibbsSampler` (block Gibbs), `GibbsWithGradients` + `CategoricalGibbsWithGradients`, `AnnealedLangevinDynamics`, `ProbabilityFlowODE` / `PredictorCorrector` (score-SDE), `DDPMAncestralSampler` (VP diffusion) |
| **Losses** | `ContrastiveDivergence` (CD-k / persistent CD), `DiffusionRecoveryLikelihood` + `drl_sample`, `DenoisingScoreMatching` / `MultiSigmaDenoisingScoreMatching` (NCSN), `VPDenoisingScoreMatching` (DDPM), `SlicedScoreMatching`, `ExactScoreMatching`, `EnergyDiscrepancy` (MCMC-free), `PseudoLikelihood` / `RatioMatching` / `ConcreteScoreMatching` (MCMC-free, discrete), `NoiseContrastiveEstimation`, `JEMLoss` |
| **Composition** | `SumEnergy` (product of experts), `MixtureEnergy`, `TemperedEnergy` — energies compose like densities and nest |
Expand All @@ -66,6 +66,7 @@ Runnable scripts in [`examples/`](https://github.com/davidkhjo/ebmkit/tree/main/
- `train_diffusion.py` — a variance-preserving (DDPM) diffusion, energy-parameterized
- `exact_likelihood_ode.py` — exact bits/dim for a score model via the probability-flow ODE
- `train_flow.py` — a RealNVP normalizing flow with exact density and sampling
- `train_cnf.py` — a continuous normalizing flow (FFJORD): exact likelihood by ODE
- `train_cifar_ood.py` — energy-based OOD at color scale (CIFAR-10 vs CIFAR-100)
- `train_rbm.py` — a Bernoulli RBM on binary bars via CD-1, with the exact `log Z`
- `train_ising_pseudolikelihood.py` — recover an Ising coupling with no MCMC in the loop
Expand Down
Binary file added examples/cnf_result.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
69 changes: 69 additions & 0 deletions examples/train_cnf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""Fit two-moons with a continuous normalizing flow (FFJORD) — exact likelihood by ODE.

The trainable generalization of `eval.pf_ode_log_likelihood`: a neural velocity
field defines an ODE from data to a Gaussian base, and the exact log-density comes
from the instantaneous change of variables (Hutchinson trace), all in pure torch
(fixed-step RK4, direct backprop). Trains by maximum likelihood, samples in one
reverse pass.

Run: python examples/train_cnf.py (CPU, ~2 minutes)
Outputs cnf_result.png next to this script (needs the [viz] extra).
"""

from __future__ import annotations

from pathlib import Path

import torch

import ebm


def main() -> None:
torch.manual_seed(0)
data = ebm.datasets.two_moons(8192)
test = ebm.datasets.two_moons(4000, generator=torch.Generator().manual_seed(1))

cnf = ebm.nets.ContinuousNormalizingFlow(dim=2, hidden=(64, 64), n_steps=20)
opt = torch.optim.Adam(cnf.parameters(), lr=3e-3)
cnf.train()
for step in range(1500):
batch = data[torch.randint(0, len(data), (256,))]
loss = -cnf.log_prob(batch).mean() # exact negative log-likelihood
opt.zero_grad()
loss.backward()
opt.step()
if step % 300 == 0:
print(f"step {step:4d} NLL {loss.item():.3f}")

cnf.eval()
print(f"held-out NLL = {-cnf.log_prob(test).mean().item():.3f} nats")

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 3, figsize=(15, 5))
ebm.viz.plot_samples(data[:2000], ax=axes[0])
axes[0].set_title("data")

lin = torch.linspace(-2.5, 2.5, 80)
gy, gx = torch.meshgrid(lin, lin, indexing="ij")
grid = torch.stack([gx.reshape(-1), gy.reshape(-1)], dim=1)
dens = cnf.log_prob(grid).detach().exp().reshape(80, 80)
axes[1].imshow(
dens, extent=(-2.5, 2.5, -2.5, 2.5), origin="lower", vmax=float(dens.quantile(0.98))
)
axes[1].set_title("learned density (exact, by ODE)")

ebm.viz.plot_samples(cnf.sample(2000).detach(), ax=axes[2])
axes[2].set_title("CNF samples")

out = Path(__file__).parent / "cnf_result.png"
fig.savefig(out, dpi=120, bbox_inches="tight")
print(f"saved {out}")


if __name__ == "__main__":
main()
69 changes: 69 additions & 0 deletions src/ebm/_ode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""Fixed-step augmented-ODE integration for continuous normalizing flows (private).

Torch-only RK4 over the augmented state ``(x, log-det)``, with the divergence
``tr(∂v/∂x)`` estimated by Hutchinson (one vector-Jacobian product per probe).
"""

from __future__ import annotations

from collections.abc import Callable

import torch
from torch import Tensor

from ebm._functional import flat_sum

Field = Callable[[Tensor, float], Tensor]


def sample_eps(x: Tensor, dist: str = "rademacher") -> Tensor:
"""A Hutchinson probe vector shaped like ``x`` (Rademacher or Gaussian)."""
if dist == "rademacher":
return (torch.randint(0, 2, x.shape, device=x.device) * 2 - 1).to(x.dtype)
if dist == "gaussian":
return torch.randn_like(x)
raise ValueError("dist must be 'rademacher' or 'gaussian'")


def _vel_and_div(field: Field, x: Tensor, t: float, eps: Tensor, create_graph: bool):
v = field(x, t)
(grad_x,) = torch.autograd.grad(
v, x, grad_outputs=eps, create_graph=create_graph, retain_graph=True
)
return v, flat_sum(grad_x * eps)


def integrate_logprob(
field: Field, x0: Tensor, eps: Tensor, *, n_steps: int, create_graph: bool
) -> tuple[Tensor, Tensor]:
"""RK4 the flow from data (t=0) to base (t=1), accumulating ``∫ tr(∂v/∂x) dt``.

Returns ``(z, logdet)`` where ``z = x(1)`` and ``logdet = ∫₀¹ tr(∂v/∂x) dt`` so
that ``log p(x0) = log p_base(z) + logdet``. Requires ``x0`` to track grad.
"""
h = 1.0 / n_steps
x, logdet = x0, x0.new_zeros(x0.shape[0])
for i in range(n_steps):
t = i * h
k1v, k1t = _vel_and_div(field, x, t, eps, create_graph)
k2v, k2t = _vel_and_div(field, x + 0.5 * h * k1v, t + 0.5 * h, eps, create_graph)
k3v, k3t = _vel_and_div(field, x + 0.5 * h * k2v, t + 0.5 * h, eps, create_graph)
k4v, k4t = _vel_and_div(field, x + h * k3v, t + h, eps, create_graph)
x = x + h / 6 * (k1v + 2 * k2v + 2 * k3v + k4v)
logdet = logdet + h / 6 * (k1t + 2 * k2t + 2 * k3t + k4t)
return x, logdet


@torch.no_grad()
def integrate_reverse(field: Field, z: Tensor, *, n_steps: int) -> Tensor:
"""RK4 the flow from base (t=1) back to data (t=0); no log-det needed for sampling."""
h = 1.0 / n_steps
x = z
for i in range(n_steps):
t = 1.0 - i * h
k1 = field(x, t)
k2 = field(x - 0.5 * h * k1, t - 0.5 * h)
k3 = field(x - 0.5 * h * k2, t - 0.5 * h)
k4 = field(x - h * k3, t - h)
x = x - h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
return x
9 changes: 1 addition & 8 deletions src/ebm/eval/likelihood.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,11 @@
from torch import Tensor

from ebm._functional import standard_normal_logprob
from ebm._ode import sample_eps as _hutchinson_eps
from ebm.ais import log_likelihood
from ebm.energy import ConditionalEnergyFn, EnergyFn


def _hutchinson_eps(x: Tensor, eps_dist: str) -> Tensor:
if eps_dist == "rademacher":
return (torch.randint(0, 2, x.shape, device=x.device) * 2 - 1).to(x.dtype)
if eps_dist == "gaussian":
return torch.randn_like(x)
raise ValueError("eps_dist must be 'rademacher' or 'gaussian'")


def pf_ode_log_likelihood(
energy: ConditionalEnergyFn,
x0: Tensor,
Expand Down
2 changes: 2 additions & 0 deletions src/ebm/nets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
spectral normalization for Lipschitz control (Du & Mordatch, 2019).
"""

from ebm.nets.cnf import ContinuousNormalizingFlow
from ebm.nets.flow import AffineCouplingFlow
from ebm.nets.lattice import RBM, IsingEnergy, PottsEnergy
from ebm.nets.mlp_conv import (
Expand All @@ -27,6 +28,7 @@
"RBM",
"AffineCouplingFlow",
"BananaEnergy",
"ContinuousNormalizingFlow",
"ConvClassifier",
"ConvEnergy",
"FunnelEnergy",
Expand Down
76 changes: 76 additions & 0 deletions src/ebm/nets/cnf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Continuous normalizing flow (FFJORD) — a trainable exact-likelihood density."""

from __future__ import annotations

from collections.abc import Sequence

import torch
from torch import Tensor, nn

from ebm._functional import standard_normal_logprob
from ebm._ode import integrate_logprob, integrate_reverse, sample_eps


class _TimeMLP(nn.Module):
"""Velocity field ``v(x, t) -> (B, dim)`` conditioned on time by concatenation."""

def __init__(self, dim: int, hidden: Sequence[int]):
super().__init__()
layers: list[nn.Module] = []
in_dim = dim + 1
for h in hidden:
layers += [nn.Linear(in_dim, h), nn.SiLU()]
in_dim = h
layers.append(nn.Linear(in_dim, dim))
self.net = nn.Sequential(*layers)

def forward(self, x: Tensor, t: float) -> Tensor:
tt = x.new_full((x.shape[0], 1), float(t))
return self.net(torch.cat([x, tt], dim=1))


class ContinuousNormalizingFlow(nn.Module):
"""FFJORD continuous normalizing flow (Grathwohl et al. 2019), trainable in pure torch.

The trainable generalization of `ebm.eval.pf_ode_log_likelihood`: a neural
velocity field ``v_θ(x, t)`` defines the ODE ``ẋ = v_θ`` from data (t=0) to a
``N(0, I)`` base (t=1), and the exact log-density follows the instantaneous
change of variables ``d log p/dt = -tr(∂v/∂x)`` (Hutchinson trace). Fixed-step
RK4, direct backprop (no adjoint), so `log_prob` trains by maximum likelihood
and `sample` draws in one reverse pass. Like the coupling flow, it is a
self-normalized energy: ``forward(x) = -log_prob(x)`` with ``log Z = 0``.
Operates on vector data ``(B, dim)``. Pass a custom ``field`` to override the
default MLP (e.g. for the closed-form tests).
"""

def __init__(
self,
dim: int,
hidden: Sequence[int] = (64, 64),
n_steps: int = 20,
field: nn.Module | None = None,
eps_dist: str = "rademacher",
):
super().__init__()
if dim < 1:
raise ValueError("dim must be >= 1")
self.dim = dim
self.n_steps = n_steps
self.eps_dist = eps_dist
self.field = field if field is not None else _TimeMLP(dim, hidden)

def log_prob(self, x: Tensor) -> Tensor:
eps = sample_eps(x, self.eps_dist)
x0 = x if x.requires_grad else x.detach().requires_grad_(True)
with torch.enable_grad():
z, logdet = integrate_logprob(
self.field, x0, eps, n_steps=self.n_steps, create_graph=self.training
)
return standard_normal_logprob(z) + logdet

def sample(self, n: int) -> Tensor:
z = torch.randn(n, self.dim, device=next(self.parameters()).device)
return integrate_reverse(self.field, z, n_steps=self.n_steps)

def forward(self, x: Tensor) -> Tensor:
return -self.log_prob(x) # energy = -log p, so log Z = 0 exactly
65 changes: 65 additions & 0 deletions tests/test_cnf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Continuous normalizing flow (FFJORD): closed-form log-det, invariance, training."""

import math

import torch
from torch import nn

import ebm


class _LinearField(nn.Module):
"""Constant linear velocity ``v(x, t) = x Aᵀ`` (divergence = tr(A))."""

def __init__(self, a):
super().__init__()
self.a = nn.Parameter(a, requires_grad=False)

def forward(self, x, t):
return x @ self.a.t()


def test_cnf_matches_linear_field_closed_form():
# For v = xAᵀ the flow maps x -> e^A x with log|det| = tr(A), so
# log p(x) = log N(e^A x; 0, I) + tr(A). Hutchinson is unbiased → the mean matches.
torch.manual_seed(0)
d = 3
a = 0.2 * torch.randn(d, d)
cnf = ebm.nets.ContinuousNormalizingFlow(dim=d, n_steps=40, field=_LinearField(a)).eval()
x = torch.randn(4000, d)
lp = cnf.log_prob(x).detach()

z = x @ torch.matrix_exp(a).t()
closed = -0.5 * z.pow(2).sum(1) - 0.5 * d * math.log(2 * math.pi) + torch.trace(a)
assert abs(lp.mean().item() - closed.mean().item()) < 0.05


def test_cnf_rotation_is_measure_preserving():
# A skew-symmetric field is a rotation: tr = 0 exactly (εᵀSε = 0) and the base
# Gaussian is rotation-invariant, so log_prob(x) == log N(x; 0, I) exactly.
torch.manual_seed(0)
d = 3
a = torch.randn(d, d)
skew = a - a.t()
cnf = ebm.nets.ContinuousNormalizingFlow(dim=d, n_steps=40, field=_LinearField(skew)).eval()
x = torch.randn(500, d)
log_n = -0.5 * x.pow(2).sum(1) - 0.5 * d * math.log(2 * math.pi)
assert (cnf.log_prob(x).detach() - log_n).abs().max().item() < 1e-4


def test_cnf_trains_and_samples():
torch.manual_seed(0)
data = ebm.datasets.eight_gaussians(4000)
cnf = ebm.nets.ContinuousNormalizingFlow(dim=2, hidden=(64, 64), n_steps=20)
opt = torch.optim.Adam(cnf.parameters(), lr=3e-3)
cnf.train()
for _ in range(600):
batch = data[torch.randint(0, len(data), (256,))]
loss = -cnf.log_prob(batch).mean()
opt.zero_grad()
loss.backward()
opt.step()
cnf.eval()
samples = cnf.sample(2000)
assert samples.shape == (2000, 2)
assert ebm.eval.mmd(samples, data[:2000], bandwidth=0.3) < 0.05
Loading