Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
ce614ef
Add FunnelEnergy and GaussianMixtureEnergy test targets
davidkhjo Aug 15, 2026
5cedcf6
Test funnel and GMM energies against their closed forms
davidkhjo Aug 15, 2026
8658603
Add ESS and split-R̂ MCMC convergence diagnostics
davidkhjo Aug 15, 2026
b757d60
Test ESS against the AR(1) closed form and R̂ on stuck chains
davidkhjo Aug 15, 2026
501de43
Add ParallelTempering (replica-exchange) sampler
davidkhjo Aug 15, 2026
e3b58d2
Test parallel tempering: N(0,I) reduction and 50/50 mode recovery fro…
davidkhjo Aug 15, 2026
76d90f5
Add Bernoulli RBM energy, block-Gibbs sampler, and exact log Z
davidkhjo Aug 15, 2026
3e9726b
Test RBM: free-energy identity, exact log Z, Gibbs stationarity, CD r…
davidkhjo Aug 15, 2026
7339bd4
Add ExactScoreMatching (Hyvärinen 2005) loss
davidkhjo Aug 15, 2026
b4729cd
Test exact score matching recovers Σ⁻¹ and matches sliced SM
davidkhjo Aug 15, 2026
99db92d
Add EnergyDiscrepancy loss (Schröder et al. 2023)
davidkhjo Aug 15, 2026
832d9ff
Test energy discrepancy recovers a Gaussian and validates its args
davidkhjo Aug 15, 2026
cd4ae7b
Add precision_recall and inception_score eval metrics
davidkhjo Aug 15, 2026
f9451f9
Test precision/recall limits + mode-drop and inception-score bounds
davidkhjo Aug 15, 2026
b9f6f14
Add ResNetEnergy: residual image energy (IGEBM / Improved-CD recipe)
davidkhjo Aug 15, 2026
ed50fb6
Test ResNetEnergy shape, batch independence, identity init, and SN tr…
davidkhjo Aug 15, 2026
9b80e16
Add UnderdampedLangevin (SGHMC) and PreconditionedLangevin samplers
davidkhjo Aug 15, 2026
134560d
Test underdamped N(0,I) + momentum reset and preconditioned anisotropy
davidkhjo Aug 15, 2026
85ab3a0
Type-narrow the ResNet block zero-init to satisfy mypy
davidkhjo Aug 15, 2026
a683833
Add examples: hard-target sampling, RBM bars, MCMC-free energy discre…
davidkhjo Aug 15, 2026
e7040e7
Document the new samplers, losses, energies, and eval metrics
davidkhjo Aug 15, 2026
6008de4
Bump version to 0.13.0
davidkhjo Aug 15, 2026
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
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
# Changelog

## 0.13.0 — 2026-08-15

Research-feature expansion — every addition validated against a closed-form or
known distribution, torch-only at runtime.

- **Samplers.** `ParallelTempering` (replica exchange over any base sampler —
escapes multimodal traps single-chain Langevin can't), `UnderdampedLangevin`
(SGHMC; momentum for better mixing, exact `exp(-E)` position marginal),
`PreconditionedLangevin` (fixed diagonal preconditioner for ill-conditioned
targets), and `GibbsSampler` (block Gibbs for models with tractable
conditionals, e.g. the RBM).
- **Losses.** `ExactScoreMatching` (Hyvärinen 2005 — the O(D) exact objective
the sliced/denoising variants approximate) and `EnergyDiscrepancy` (Schröder
et al. 2023 — a sampler-free, score-free objective).
- **Energies.** `RBM` (Bernoulli RBM as a free energy, with block-Gibbs and an
exact `log_z`), `ResNetEnergy` (the IGEBM / Improved-CD residual image net),
and the closed-form test targets `FunnelEnergy` (Neal's funnel) and
`GaussianMixtureEnergy`.
- **Eval.** `effective_sample_size` and `split_rhat` (MCMC convergence
diagnostics), `precision_recall` (Kynkäänniemi et al. 2019 — fidelity vs
coverage), and `inception_score` (formula over user-supplied classifier probs).
- **Examples.** `sampling_hard_targets.py`, `train_rbm.py`,
`train_energy_discrepancy.py`.

## 0.12.0 — 2026-08-14

- Renamed the distribution to **`ebmkit`** (`pip install ebmkit`). The import
Expand Down
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ returns `LossOutput(loss, metrics, x_neg)`; call `out.loss.backward()`).

| Piece | Contents |
|---|---|
| **Energies** | any callable `(B, *shape) -> (B,)`; `nets.MLPEnergy` / `ConvEnergy` / `ConvClassifier` (SiLU, optional spectral norm, no batch norm), `nets.IsingEnergy` / `PottsEnergy` (discrete lattices), noise-conditional variants for NCSN; `EnergyModel`, `ebm.score` |
| **Samplers** | `LangevinDynamics` (ULA/SGLD), `MALA`, `HMC`, `GibbsWithGradients` + `CategoricalGibbsWithGradients`, `AnnealedLangevinDynamics` |
| **Losses** | `ContrastiveDivergence` (CD-k / persistent CD), `DiffusionRecoveryLikelihood` + `drl_sample`, `DenoisingScoreMatching` / `MultiSigmaDenoisingScoreMatching` (NCSN), `SlicedScoreMatching`, `NoiseContrastiveEstimation`, `JEMLoss` |
| **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` (closed-form targets), noise-conditional variants for NCSN; `EnergyModel`, `ebm.score` |
| **Samplers** | `LangevinDynamics` (ULA/SGLD), `MALA`, `HMC`, `UnderdampedLangevin` (SGHMC), `PreconditionedLangevin`, `ParallelTempering` (replica exchange), `GibbsSampler` (block Gibbs), `GibbsWithGradients` + `CategoricalGibbsWithGradients`, `AnnealedLangevinDynamics` |
| **Losses** | `ContrastiveDivergence` (CD-k / persistent CD), `DiffusionRecoveryLikelihood` + `drl_sample`, `DenoisingScoreMatching` / `MultiSigmaDenoisingScoreMatching` (NCSN), `SlicedScoreMatching`, `ExactScoreMatching`, `EnergyDiscrepancy` (MCMC-free), `NoiseContrastiveEstimation`, `JEMLoss` |
| **Composition** | `SumEnergy` (product of experts), `MixtureEnergy`, `TemperedEnergy` — energies compose like densities and nest |
| **Training** | thin `Trainer` (device, EMA, supervised batches, `save`/`load` checkpointing), `ReplayBuffer`, `EMA` |
| **Eval** | `ais_log_z` / `reverse_ais_log_z` (bracket `log Z`), `bits_per_dim`, `frechet_distance` (FID), `mmd`, `ood_auroc` |
| **Eval** | `ais_log_z` / `reverse_ais_log_z` (bracket `log Z`), `bits_per_dim`, `frechet_distance` (FID), `mmd`, `precision_recall`, `inception_score`, `ood_auroc`, `effective_sample_size` / `split_rhat` (MCMC diagnostics) |
| **Data & viz** | 2D toys (`two_moons`, `eight_gaussians`, `checkerboard`, `rings`, `spirals`) and torchvision-free image loaders (`mnist`, `fashion_mnist`, `cifar10`, `cifar100`); `viz.energy_contour` / `plot_samples` / `energy_histogram` / `show_images` |

## Examples
Expand All @@ -63,6 +63,9 @@ Runnable scripts in [`examples/`](https://github.com/davidkhjo/ebmkit/tree/main/
- `train_ising.py` / `train_potts.py` — discrete lattices via (categorical) Gibbs-with-Gradients
- `train_ncsn.py` — score-based generation: multi-sigma denoising + annealed Langevin
- `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_energy_discrepancy.py` — two-moons trained MCMC-free (energy discrepancy)
- `sampling_hard_targets.py` — parallel tempering escapes a trapped mode; ESS / R̂ diagnostics
- `checkpoint_resume.py` — save a run and resume it in a fresh process

## Conventions
Expand Down
Binary file added examples/energy_discrepancy_result.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
64 changes: 64 additions & 0 deletions examples/sampling_hard_targets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Hard-target sampling: parallel tempering vs a single chain, with diagnostics.

A single Langevin chain started in one mode of a well-separated mixture stays
trapped there; parallel tempering crosses the barrier and recovers both modes.
We then run several independent chains and report the ESS / split-R̂ convergence
diagnostics — the honest way to tell whether a sampler actually mixed.

Run: python examples/sampling_hard_targets.py
Outputs sampling_hard_targets_result.png next to this script (needs [viz]).
"""

from __future__ import annotations

from pathlib import Path

import torch

import ebm


def main() -> None:
torch.manual_seed(0)

means = torch.tensor([[-4.0], [4.0]])
energy = ebm.nets.GaussianMixtureEnergy(means, std=1.0)
x0 = -4.0 + 0.3 * torch.randn(2000, 1) # every chain starts in the LEFT mode

single = ebm.LangevinDynamics(step_size=0.08, steps=1000).sample(energy, x0.clone())
base = ebm.LangevinDynamics(step_size=0.08, steps=1)
pt = ebm.ParallelTempering(base, temperatures=(1.0, 4.0, 16.0, 64.0), steps=1000)
tempered = pt.sample(energy, x0.clone())

print(f"single chain P(x>0) = {(single > 0).float().mean():.3f} (trapped)")
print(f"tempered chain P(x>0) = {(tempered > 0).float().mean():.3f} (both modes)")
print("swap rates: " + ", ".join(f"{r:.2f}" for r in pt.swap_rates()))

# Convergence diagnostics: many chains on a standard normal, drawn as a
# (n_chains, n_samples, dim) trajectory tensor.
traj = ebm.MALA(step_size=0.5, steps=400).sample(
lambda x: 0.5 * x.pow(2).sum(1), torch.randn(16, 1), return_trajectory=True
)
chains = traj.transpose(0, 1) # (16, 401, 1)
total = chains.shape[0] * chains.shape[1]
print(f"ESS = {ebm.eval.effective_sample_size(chains).item():.0f} of {total}")
print(f"R-hat = {ebm.eval.split_rhat(chains).item():.3f}")

import matplotlib

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

fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
for ax, s, title in ((axes[0], single, "single chain"), (axes[1], tempered, "tempered")):
ax.hist(s.flatten().numpy(), bins=60, range=(-7, 7), color="#5c50c9", alpha=0.8)
ax.set_title(f"{title} — P(x>0)={(s > 0).float().mean():.2f}")
ax.set_xlabel("x")
fig.suptitle("Escaping a trapped mode: single Langevin chain vs parallel tempering")
out = Path(__file__).parent / "sampling_hard_targets_result.png"
fig.savefig(out, dpi=120, bbox_inches="tight")
print(f"saved {out}")


if __name__ == "__main__":
main()
Binary file added examples/sampling_hard_targets_result.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
54 changes: 54 additions & 0 deletions examples/train_energy_discrepancy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""MCMC-free EBM training on two-moons with the energy-discrepancy loss.

Energy discrepancy needs no sampler during training — just perturbed-energy
contrasts — so this whole training loop runs without a single MCMC chain. We
still sample at the end (with Langevin) purely to visualize the learned energy.

Run: python examples/train_energy_discrepancy.py
Outputs energy_discrepancy_result.png next to this script (needs [viz]).
"""

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)

energy = ebm.nets.MLPEnergy(dim=2, hidden=(128, 128))
loss_fn = ebm.EnergyDiscrepancy(sigma=0.3, m_particles=16, w_stable=1.0)
# No sampler, no buffer — the Trainer just backprops the loss each step.
trainer = ebm.Trainer(energy, loss_fn, lr=1e-3, ema_decay=0.999)
trainer.fit(data, steps=6000, batch_size=256)

model = trainer.ema.module
samples = ebm.LangevinDynamics(step_size=0.01, steps=500).sample(
model, torch.randn(2000, 2, device=trainer.device)
)

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")
ebm.viz.energy_contour(model, bounds=(-2.5, 2.5), device=trainer.device, ax=axes[1])
axes[1].set_title("learned energy (MCMC-free)")
ebm.viz.plot_samples(samples, ax=axes[2])
axes[2].set_title("samples")

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


if __name__ == "__main__":
main()
73 changes: 73 additions & 0 deletions examples/train_rbm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Train a Bernoulli RBM on binary "bars" images with CD-1, exactly.

Generates simple horizontal/vertical bar patterns on a small grid, fits an RBM
by contrastive divergence (the free-energy gradient *is* the RBM ML gradient),
then draws samples by block Gibbs. Because the model is small, we also print the
exact log-partition function — the closed-form check that makes RBMs the most
verifiable EBM.

Run: python examples/train_rbm.py
Outputs train_rbm_result.png next to this script (needs the [viz] extra).
"""

from __future__ import annotations

from pathlib import Path

import torch

import ebm

GRID = 6 # 6x6 images -> 36 visible units


def bars_dataset(n: int) -> torch.Tensor:
"""Random single horizontal or vertical bars on a GRID x GRID canvas."""
imgs = torch.zeros(n, GRID, GRID)
vertical = torch.rand(n) < 0.5
idx = torch.randint(0, GRID, (n,))
for i in range(n):
if vertical[i]:
imgs[i, :, idx[i]] = 1.0
else:
imgs[i, idx[i], :] = 1.0
return imgs.reshape(n, GRID * GRID)


def main() -> None:
torch.manual_seed(0)
data = bars_dataset(4096)

# 16 hidden units: enough for the 12 bar patterns, and small enough that the
# exact log Z (which enumerates the smaller layer, 2^16 states) is tractable.
rbm = ebm.nets.RBM(n_visible=GRID * GRID, n_hidden=16)
opt = torch.optim.Adam(rbm.parameters(), lr=1e-2)
for step in range(3000):
batch = data[torch.randint(0, len(data), (128,))]
v_neg = rbm.gibbs_step(batch) # CD-1: one block-Gibbs step from the data
loss = rbm(batch).mean() - rbm(v_neg).mean()
opt.zero_grad()
loss.backward()
opt.step()
if step % 500 == 0:
print(f"step {step:4d} energy_gap {loss.item():+.3f}")

print(f"exact log Z = {rbm.log_z().item():.3f}")

# Sample from the model by a longer Gibbs chain started from noise.
v = torch.bernoulli(torch.full((64, GRID * GRID), 0.5))
for _ in range(500):
v = rbm.gibbs_step(v)
samples = v.reshape(64, 1, GRID, GRID)

import matplotlib

matplotlib.use("Agg")
ax = ebm.viz.show_images(samples, nrow=8, title="RBM samples (block Gibbs from noise)")
out = Path(__file__).parent / "train_rbm_result.png"
ax.figure.savefig(out, dpi=150, bbox_inches="tight")
print(f"saved {out}")


if __name__ == "__main__":
main()
Binary file added examples/train_rbm_result.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 13 additions & 1 deletion src/ebm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
ContrastiveDivergence,
DenoisingScoreMatching,
DiffusionRecoveryLikelihood,
EnergyDiscrepancy,
ExactScoreMatching,
LossOutput,
MultiSigmaDenoisingScoreMatching,
NoiseContrastiveEstimation,
Expand All @@ -26,14 +28,18 @@
MALA,
AnnealedLangevinDynamics,
CategoricalGibbsWithGradients,
GibbsSampler,
GibbsWithGradients,
LangevinDynamics,
ParallelTempering,
PreconditionedLangevin,
Sampler,
UnderdampedLangevin,
)
from ebm.training import Trainer
from ebm.utils import EMA

__version__ = "0.12.0"
__version__ = "0.13.0"

__all__ = [
"EnergyFn",
Expand All @@ -49,16 +55,22 @@
"Sampler",
"LangevinDynamics",
"MALA",
"UnderdampedLangevin",
"PreconditionedLangevin",
"HMC",
"GibbsWithGradients",
"CategoricalGibbsWithGradients",
"GibbsSampler",
"AnnealedLangevinDynamics",
"ParallelTempering",
"ReplayBuffer",
"LossOutput",
"ContrastiveDivergence",
"DenoisingScoreMatching",
"DiffusionRecoveryLikelihood",
"drl_sample",
"EnergyDiscrepancy",
"ExactScoreMatching",
"MultiSigmaDenoisingScoreMatching",
"SlicedScoreMatching",
"NoiseContrastiveEstimation",
Expand Down
Loading
Loading