diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a1e3cc..052b086 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 4b4f791..426d487 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/examples/energy_discrepancy_result.png b/examples/energy_discrepancy_result.png new file mode 100644 index 0000000..7619347 Binary files /dev/null and b/examples/energy_discrepancy_result.png differ diff --git a/examples/sampling_hard_targets.py b/examples/sampling_hard_targets.py new file mode 100644 index 0000000..b14c866 --- /dev/null +++ b/examples/sampling_hard_targets.py @@ -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() diff --git a/examples/sampling_hard_targets_result.png b/examples/sampling_hard_targets_result.png new file mode 100644 index 0000000..8ffdaca Binary files /dev/null and b/examples/sampling_hard_targets_result.png differ diff --git a/examples/train_energy_discrepancy.py b/examples/train_energy_discrepancy.py new file mode 100644 index 0000000..50a6aee --- /dev/null +++ b/examples/train_energy_discrepancy.py @@ -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() diff --git a/examples/train_rbm.py b/examples/train_rbm.py new file mode 100644 index 0000000..31c8486 --- /dev/null +++ b/examples/train_rbm.py @@ -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() diff --git a/examples/train_rbm_result.png b/examples/train_rbm_result.png new file mode 100644 index 0000000..70ee4b5 Binary files /dev/null and b/examples/train_rbm_result.png differ diff --git a/src/ebm/__init__.py b/src/ebm/__init__.py index 47c9e76..f472bde 100644 --- a/src/ebm/__init__.py +++ b/src/ebm/__init__.py @@ -14,6 +14,8 @@ ContrastiveDivergence, DenoisingScoreMatching, DiffusionRecoveryLikelihood, + EnergyDiscrepancy, + ExactScoreMatching, LossOutput, MultiSigmaDenoisingScoreMatching, NoiseContrastiveEstimation, @@ -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", @@ -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", diff --git a/src/ebm/eval.py b/src/ebm/eval.py index bef35bf..ccf5800 100644 --- a/src/ebm/eval.py +++ b/src/ebm/eval.py @@ -23,10 +23,110 @@ "reverse_ais_log_z", "log_likelihood", "bits_per_dim", + "effective_sample_size", + "split_rhat", + "precision_recall", + "inception_score", "AISResult", ] +def _as_chains(samples: Tensor) -> Tensor: + """Coerce MCMC output to ``(n_chains, n_samples, dim)`` in float64.""" + x = samples.detach().cpu().double() + if x.dim() == 2: + x = x.unsqueeze(-1) # (M, N) -> a single scalar quantity per draw + if x.dim() != 3: + raise ValueError("samples must be (n_chains, n_samples) or (n_chains, n_samples, dim)") + if x.shape[1] < 4: + raise ValueError("need at least 4 samples per chain for a meaningful diagnostic") + return x + + +@torch.no_grad() +def split_rhat(samples: Tensor) -> Tensor: + """Split-R̂ (Gelman–Rubin) convergence diagnostic, per dimension. + + Input is ``(n_chains, n_samples[, dim])``. Each chain is split in half (so a + single long chain still exposes non-stationarity), then + + ``R̂ = sqrt(v̂⁺ / W)``, ``v̂⁺ = (N-1)/N · W + B/N`` + + with ``W`` the mean within-chain variance and ``B`` the between-chain + variance of the half-chains. Values near ``1.0`` indicate the chains have + mixed; ``> 1.01`` is the usual "not converged" flag. Returns a ``(dim,)`` + tensor. Reference: Vehtari et al. (2021), BDA3. + """ + x = _as_chains(samples) + m, n, d = x.shape + half = n // 2 + if half < 2: + raise ValueError("need at least 4 samples per chain to split and estimate variance") + split = torch.cat([x[:, :half], x[:, half : 2 * half]], dim=0) # (2M, half, d) + means = split.mean(dim=1) # (2M, d) + within = split.var(dim=1, unbiased=True).mean(dim=0) # (d,) + between = half * means.var(dim=0, unbiased=True) # (d,) + var_plus = (half - 1) / half * within + between / half + return torch.sqrt(var_plus / within) + + +@torch.no_grad() +def effective_sample_size(samples: Tensor) -> Tensor: + """Effective sample size of an MCMC run, per dimension. + + Input is ``(n_chains, n_samples[, dim])``. Combines the within-chain + autocorrelation with the between-chain variance (Stan/BDA3 estimator) and + truncates the autocorrelation sum with Geyer's initial-monotone rule: + + ``ESS = M·N / (1 + 2 Σ_t ρ̂_t)``. + + For independent draws ``ESS → M·N``; a stuck or slowly-mixing chain gives an + ESS far below the raw draw count. Autocovariances are computed by FFT + (zero-padded past ``2N`` to avoid circular wraparound), no scipy. Returns a + ``(dim,)`` tensor. + """ + x = _as_chains(samples) + m, n, d = x.shape + + centered = x - x.mean(dim=1, keepdim=True) + n_fft = 1 + while n_fft < 2 * n: + n_fft <<= 1 + spec = torch.fft.rfft(centered, n=n_fft, dim=1) + acov = torch.fft.irfft(spec.abs().pow(2), n=n_fft, dim=1)[:, :n, :] # (M, N, d) + acov = acov / n * (n / (n - 1)) # unbiased so acov[:,0] == per-chain variance + + within = acov[:, 0, :].mean(dim=0) # (d,) == W + if m > 1: + between = n * x.mean(dim=1).var(dim=0, unbiased=True) # (d,) + else: + between = torch.zeros(d, dtype=x.dtype) + var_plus = (n - 1) / n * within + between / n + mean_acov = acov.mean(dim=0) # (N, d) + rho = 1 - (within[None, :] - mean_acov) / var_plus[None, :] # (N, d) + + ess = torch.empty(d, dtype=x.dtype) + for j in range(d): + r = rho[:, j] + # Geyer initial-monotone sequence: pair Γ_k = ρ_{2k} + ρ_{2k+1}, sum + # while positive, forcing the pairs to be non-increasing. Then + # τ = -1 + 2 Σ Γ_k (== 1 + 2 Σ_{t≥1} ρ_t untruncated). + gamma_sum = 0.0 + prev_gamma = float("inf") + k = 0 + while 2 * k + 1 < n: + gamma = float(r[2 * k] + r[2 * k + 1]) + gamma = min(gamma, prev_gamma) # enforce non-increasing pairs + if gamma <= 0: + break + gamma_sum += gamma + prev_gamma = gamma + k += 1 + tau = -1.0 + 2.0 * gamma_sum + ess[j] = m * n / max(tau, 1e-12) + return ess + + @torch.no_grad() def energies(energy: EnergyFn, x: Tensor, batch_size: int = 1024) -> Tensor: """Energies of ``x`` computed in batches, returned on CPU.""" @@ -143,6 +243,73 @@ def ood_auroc(energy: EnergyFn, x_in: Tensor, x_out: Tensor) -> float: return u / (n_in * n_out) +@torch.no_grad() +def precision_recall( + real: Tensor, + gen: Tensor, + *, + k: int = 3, + feature_fn=None, + batch_size: int = 1024, +) -> tuple[float, float]: + """Improved precision & recall (Kynkäänniemi et al., 2019). + + Estimates each set's manifold as the union of per-point k-NN hyperspheres, + then measures overlap: **precision** is the fraction of generated points that + land inside the *real* manifold (fidelity), **recall** the fraction of real + points inside the *generated* manifold (coverage/diversity). Unlike + `frechet_distance`, this separates "are the samples realistic" from "do they + cover the data" — a mode-dropping model scores high precision, low recall. + + ``feature_fn`` works exactly as in `frechet_distance` (``None`` compares the + flattened samples directly; pass an embedding for image data). Returns + ``(precision, recall)`` in ``[0, 1]``. Reference: arXiv:1904.06991. + """ + + def _features(t: Tensor) -> Tensor: + if feature_fn is None: + return t.reshape(len(t), -1).cpu().double() + chunks = [feature_fn(c).detach().cpu() for c in t.split(batch_size)] + return torch.cat(chunks).reshape(len(t), -1).double() + + fr, fg = _features(real), _features(gen) + if len(fr) <= k or len(fg) <= k: + raise ValueError(f"precision_recall needs more than k={k} samples per set") + + def _knn_radius(f: Tensor) -> Tensor: + # Column 0 of the sorted distances is the zero self-distance, so the + # k-th neighbor sits at column k. + return torch.cdist(f, f).sort(dim=1).values[:, k] + + radius_real = _knn_radius(fr) + radius_gen = _knn_radius(fg) + # A point is "inside" a manifold if it lies within some reference sphere. + precision = (torch.cdist(fg, fr) <= radius_real[None, :]).any(dim=1).double().mean() + recall = (torch.cdist(fr, fg) <= radius_gen[None, :]).any(dim=1).double().mean() + return float(precision), float(recall) + + +@torch.no_grad() +def inception_score(probs: Tensor) -> float: + """Inception score ``exp(E_x KL(p(y|x) ‖ p(y)))`` from classifier probabilities. + + ``probs`` is an ``(N, K)`` tensor of per-sample class probabilities from *any* + classifier you supply — this ships the score's formula only, not a bundled + model, so it stays torch-only and works with whatever labels are meaningful + for your data. Higher is better: it rewards confident per-sample predictions + (sharp ``p(y|x)``) that are diverse in aggregate (near-uniform marginal + ``p(y)``). ``IS = K`` for perfectly confident, perfectly balanced classes; + ``IS = 1`` when every prediction equals the marginal. + """ + p = probs.double() + if p.dim() != 2: + raise ValueError("probs must be (N, K) class probabilities") + p = p.clamp_min(1e-12) + marginal = p.mean(dim=0, keepdim=True) + kl = (p * (p.log() - marginal.log())).sum(dim=1) + return float(torch.exp(kl.mean())) + + @torch.no_grad() def bits_per_dim(energy: EnergyFn, x: Tensor, log_z: float, *, dim: int | None = None) -> Tensor: """Per-sample bits-per-dimension, the standard density-model score (lower is better). diff --git a/src/ebm/losses/__init__.py b/src/ebm/losses/__init__.py index e128b16..271d025 100644 --- a/src/ebm/losses/__init__.py +++ b/src/ebm/losses/__init__.py @@ -1,9 +1,11 @@ from ebm.losses.base import LossOutput from ebm.losses.cd import ContrastiveDivergence from ebm.losses.drl import DiffusionRecoveryLikelihood, drl_sample +from ebm.losses.energy_discrepancy import EnergyDiscrepancy from ebm.losses.nce import NoiseContrastiveEstimation from ebm.losses.score_matching import ( DenoisingScoreMatching, + ExactScoreMatching, MultiSigmaDenoisingScoreMatching, SlicedScoreMatching, geometric_sigmas, @@ -14,7 +16,9 @@ "ContrastiveDivergence", "DiffusionRecoveryLikelihood", "drl_sample", + "EnergyDiscrepancy", "DenoisingScoreMatching", + "ExactScoreMatching", "MultiSigmaDenoisingScoreMatching", "SlicedScoreMatching", "NoiseContrastiveEstimation", diff --git a/src/ebm/losses/energy_discrepancy.py b/src/ebm/losses/energy_discrepancy.py new file mode 100644 index 0000000..c18d423 --- /dev/null +++ b/src/ebm/losses/energy_discrepancy.py @@ -0,0 +1,62 @@ +"""Energy discrepancy: a sampler-free, score-free EBM loss (Schröder et al. 2023).""" + +from __future__ import annotations + +import math + +import torch +from torch import Tensor, nn + +from ebm.energy import EnergyFn +from ebm.losses.base import LossOutput + + +class EnergyDiscrepancy(nn.Module): + """Energy discrepancy loss — no MCMC, no score (Schröder et al., NeurIPS 2023). + + Perturbs each data point with Gaussian noise and contrasts its energy against + ``M`` twice-perturbed copies:: + + L = mean_i logsumexp_j( [ E(x_i) - E(x_i + √t·ξ_i + √t·ξ'_ij) ] ++ [log w] ) + + where ``ξ_i`` is shared across the ``M`` contrastive draws for point ``i`` and + ``ξ'_ij`` is drawn independently. The appended ``log w`` column is the + ``w``-stabilization: it lower-bounds the log and keeps the estimator from + diverging at small ``t``. Cost is ``M + 1`` forward energy evaluations — no + sampler to tune, no ``create_graph``, no divergence signatures. + + Args: + sigma: perturbation scale ``√t`` (the noise std). Scale to the data. + m_particles: number of contrastive draws ``M`` per point. + w_stable: stabilizer ``w`` (keep ``> 0``; ``w=0`` can diverge). + """ + + def __init__(self, sigma: float = 1.0, m_particles: int = 4, w_stable: float = 1.0): + super().__init__() + if sigma <= 0: + raise ValueError("sigma must be positive") + if m_particles < 1: + raise ValueError("m_particles must be >= 1") + if w_stable < 0: + raise ValueError("w_stable must be >= 0") + self.sigma = sigma + self.m_particles = m_particles + self.w_stable = w_stable + + def forward(self, energy: EnergyFn, x: Tensor) -> LossOutput: + b = x.shape[0] + event = x.shape[1:] + xi = torch.randn_like(x) * self.sigma # (B, *event), shared per point + xi_prime = torch.randn(b, self.m_particles, *event, device=x.device, dtype=x.dtype) + pert = x.unsqueeze(1) + xi.unsqueeze(1) + self.sigma * xi_prime # (B, M, *event) + + pos = energy(x) # (B,) + neg = energy(pert.reshape(b * self.m_particles, *event)).reshape(b, self.m_particles) + val = pos.unsqueeze(1) - neg # (B, M) + if self.w_stable > 0: + logw = val.new_full((b, 1), math.log(self.w_stable)) + val = torch.cat([val, logw], dim=1) # (B, M+1) + loss = val.logsumexp(dim=1).mean() + + x_neg = pert.reshape(b * self.m_particles, *event).detach() + return LossOutput(loss=loss, metrics={"loss": loss.item()}, x_neg=x_neg) diff --git a/src/ebm/losses/score_matching.py b/src/ebm/losses/score_matching.py index 911dc55..bc7b40d 100644 --- a/src/ebm/losses/score_matching.py +++ b/src/ebm/losses/score_matching.py @@ -90,6 +90,34 @@ def forward(self, energy, x: Tensor) -> LossOutput: return LossOutput(loss=loss, metrics={"loss": loss.item()}) +class ExactScoreMatching(nn.Module): + """Hyvärinen (2005) implicit score matching — the exact objective. + + ``L = E_x[ ½‖s(x)‖² + tr(∇_x s(x)) ]`` with ``s = -∇_x E``. The trace of the + score's Jacobian (the Hessian-diagonal term) is computed exactly by ``D`` + extra backward passes, one per input dimension, so cost is **linear in the + data dimension** — use it on small ``D`` as the ground-truth anchor for the + stochastic score-matching losses (`SlicedScoreMatching`, + `DenoisingScoreMatching`), which approximate this at fixed cost. Keeps the + graph (``create_graph=True``) so it backpropagates to the energy parameters. + """ + + def forward(self, energy: EnergyFn, x: Tensor) -> LossOutput: + x = x.detach().requires_grad_(True) + e = energy(x) + (grad_e,) = torch.autograd.grad(e.sum(), x, create_graph=True) + s = -grad_e + s_flat = s.reshape(x.shape[0], -1) + + trace = x.new_zeros(x.shape[0]) + for i in range(s_flat.shape[1]): + (grad_si,) = torch.autograd.grad(s_flat[:, i].sum(), x, create_graph=True) + trace = trace + grad_si.reshape(x.shape[0], -1)[:, i] + + loss = (0.5 * s_flat.pow(2).sum(dim=1) + trace).mean() + return LossOutput(loss=loss, metrics={"loss": loss.item()}) + + class SlicedScoreMatching(nn.Module): """Sliced score matching with random projections (Hutchinson-style). diff --git a/src/ebm/nets.py b/src/ebm/nets.py index 046e6d9..b909532 100644 --- a/src/ebm/nets.py +++ b/src/ebm/nets.py @@ -11,9 +11,17 @@ import torch from torch import Tensor, nn +from torch.nn import functional as F from torch.nn.utils.parametrizations import spectral_norm +def _binary_states(n: int, *, device=None, dtype=torch.float32) -> Tensor: + """All ``2^n`` binary vectors as a ``(2^n, n)`` tensor (for exact enumeration).""" + idx = torch.arange(2**n, device=device) + bits = (idx[:, None] >> torch.arange(n - 1, -1, -1, device=device)[None, :]) & 1 + return bits.to(dtype) + + def _maybe_sn(layer: nn.Module, enabled: bool) -> nn.Module: return spectral_norm(layer) if enabled else layer @@ -207,6 +215,73 @@ def forward(self, x: Tensor) -> Tensor: return self.head(h).squeeze(-1) +class _ResBlock(nn.Module): + """Pre-activation residual block; the second conv is zero-initialized so the + block is the identity at init (unless spectral norm reparametrizes it).""" + + def __init__( + self, c_in: int, c_out: int, *, spectral_norm: bool = False, downsample: bool = False + ): + super().__init__() + self.act = nn.SiLU() + self.conv1 = _maybe_sn(nn.Conv2d(c_in, c_out, 3, padding=1), spectral_norm) + conv2 = nn.Conv2d(c_out, c_out, 3, padding=1) + if not spectral_norm: # zero-init is incompatible with the SN parametrization + nn.init.zeros_(conv2.weight) + assert conv2.bias is not None + nn.init.zeros_(conv2.bias) + self.conv2 = _maybe_sn(conv2, spectral_norm) + self.skip: nn.Module = ( + nn.Identity() if c_in == c_out else _maybe_sn(nn.Conv2d(c_in, c_out, 1), spectral_norm) + ) + self.downsample = downsample + + def forward(self, x: Tensor) -> Tensor: + h = self.conv1(self.act(x)) + h = self.conv2(self.act(h)) + out = self.skip(x) + h + if self.downsample: + out = F.avg_pool2d(out, 2) + return out + + +class ResNetEnergy(nn.Module): + """Residual CNN energy for images ``(B, C, H, W) -> (B,)`` (IGEBM / Improved-CD). + + The standard recipe for image EBMs: a stack of pre-activation residual blocks + (SiLU, 3x3 convs, no normalization), average-pool downsampling between + stages, global-pool then a linear head. The second conv of each block is + zero-initialized so every block starts as the identity — a stable init for + the long MCMC chains contrastive divergence needs. ``spectral_norm=True`` + wraps every conv and the head for Lipschitz control (Du & Mordatch, 2019). + Works at any spatial size (the global pool removes the size dependence). + """ + + def __init__( + self, + in_channels: int = 3, + channels: Sequence[int] = (64, 128, 256), + spectral_norm: bool = False, + ): + super().__init__() + self.stem = _maybe_sn(nn.Conv2d(in_channels, channels[0], 3, padding=1), spectral_norm) + blocks: list[nn.Module] = [] + c_in = channels[0] + for c_out in channels: + blocks.append(_ResBlock(c_in, c_out, spectral_norm=spectral_norm, downsample=True)) + c_in = c_out + self.blocks = nn.ModuleList(blocks) + self.act = nn.SiLU() + self.head = _maybe_sn(nn.Linear(c_in, 1), spectral_norm) + + def forward(self, x: Tensor) -> Tensor: + h = self.stem(x) + for block in self.blocks: + h = block(h) + h = self.act(h).mean(dim=(2, 3)) # global average pool + return self.head(h).squeeze(-1) + + class IsingEnergy(nn.Module): """2D nearest-neighbor Ising lattice energy for binary data ``(B, H, W) -> (B,)``. @@ -263,3 +338,132 @@ def forward(self, x: Tensor) -> Tensor: right = (x[:, :, :-1, :] * x[:, :, 1:, :]).sum(dim=(1, 2, 3)) down = (x[:, :-1, :, :] * x[:, 1:, :, :]).sum(dim=(1, 2, 3)) return -self.coupling * (right + down) + + +class FunnelEnergy(nn.Module): + """Neal's funnel — the canonical MCMC stress test, as an energy ``(B, D) -> (B,)``. + + Coordinate 0 is the log-scale ``v ~ N(0, v_scale²)``; the remaining + ``n = D - 1`` "neck" coordinates are ``x_i | v ~ N(0, e^v)``. The negative + log density (up to a constant) is + + ``E(x) = ½[ v² / v_scale² + e^{-v} ‖x_neck‖² + n·v ]``. + + The geometry is deliberately vicious: at negative ``v`` the neck collapses to + a needle no fixed step size can navigate, so single-scale samplers fail and + the true marginals (``v ~ N(0, v_scale²)``, ``x_i | v ~ N(0, e^v)``) are the + ground truth to check against. Differentiable, so it drives any gradient + sampler. Reference: Neal (2003), "Slice Sampling". + """ + + def __init__(self, dim: int = 2, v_scale: float = 3.0): + super().__init__() + if dim < 2: + raise ValueError("funnel needs dim >= 2 (one scale coordinate + a neck)") + if v_scale <= 0: + raise ValueError("v_scale must be positive") + self.dim = dim + self.v_scale = v_scale + + def forward(self, x: Tensor) -> Tensor: + if x.dim() != 2 or x.shape[1] != self.dim: + raise ValueError(f"expected (B, {self.dim}), got {tuple(x.shape)}") + v = x[:, 0] + neck = x[:, 1:] + n = neck.shape[1] + neck_sq = neck.pow(2).sum(dim=1) + return 0.5 * (v.pow(2) / self.v_scale**2 + torch.exp(-v) * neck_sq + n * v) + + +class GaussianMixtureEnergy(nn.Module): + """Isotropic Gaussian-mixture energy with known modes ``(B, D) -> (B,)``. + + ``E(x) = -logsumexp_k( log w_k - ‖x - μ_k‖² / (2 σ²) )`` — the (unnormalized) + energy of ``p(x) ∝ Σ_k w_k N(x; μ_k, σ² I)``. A closed-form multimodal target: + with well-separated means and equal weights, a correct sampler must visit the + modes in proportion to ``w_k``, which single-chain gradient MCMC cannot do + across high barriers — exactly what `ParallelTempering` is for. + """ + + means: Tensor + log_weights: Tensor + + def __init__(self, means: Tensor, weights: Sequence[float] | None = None, std: float = 1.0): + super().__init__() + means = torch.as_tensor(means, dtype=torch.float32) + if means.dim() != 2: + raise ValueError("means must be (K, D)") + if std <= 0: + raise ValueError("std must be positive") + k = means.shape[0] + if weights is None: + weights = [1.0] * k + if len(weights) != k or any(w <= 0 for w in weights): + raise ValueError("need one positive weight per mode") + self.std = std + self.register_buffer("means", means) + self.register_buffer("log_weights", torch.log(torch.tensor([float(w) for w in weights]))) + + def forward(self, x: Tensor) -> Tensor: + if x.dim() != 2 or x.shape[1] != self.means.shape[1]: + raise ValueError(f"expected (B, {self.means.shape[1]}), got {tuple(x.shape)}") + sq = (x[:, None, :] - self.means[None, :, :]).pow(2).sum(dim=2) + log_comp = self.log_weights[None, :] - sq / (2 * self.std**2) + return -torch.logsumexp(log_comp, dim=1) + + +class RBM(nn.Module): + """Bernoulli–Bernoulli restricted Boltzmann machine as a free-energy ``(B, V) -> (B,)``. + + The joint ``E(v, h) = -bᵀv - cᵀh - hᵀW v`` marginalizes over the hidden + units in closed form, giving the free energy this module returns: + + ``F(v) = -bᵀv - Σ_j softplus(c_j + W_j·v)``, so ``p(v) ∝ exp(-F(v))``. + + Because ``F`` is a plain energy, it trains with the ordinary + `ebm.ContrastiveDivergence` loss — its gradient is exactly the RBM + maximum-likelihood gradient — using `ebm.GibbsSampler` for the block-Gibbs + negatives. For small models the partition function is available exactly via + `log_z`, which makes this the most closed-form-checkable EBM in the library. + + Input/output are binary visible vectors in ``{0, 1}`` of shape ``(B, V)``. + """ + + def __init__(self, n_visible: int, n_hidden: int): + super().__init__() + self.n_visible = n_visible + self.n_hidden = n_hidden + self.W = nn.Parameter(torch.randn(n_hidden, n_visible) * 0.01) + self.b = nn.Parameter(torch.zeros(n_visible)) + self.c = nn.Parameter(torch.zeros(n_hidden)) + + def forward(self, v: Tensor) -> Tensor: + pre = F.linear(v, self.W, self.c) # (B, H) = c + v Wᵀ + return -(v @ self.b) - F.softplus(pre).sum(dim=1) + + def p_h_given_v(self, v: Tensor) -> Tensor: + """Bernoulli means ``p(h_j = 1 | v) = σ(c_j + W_j·v)``, shape ``(B, H)``.""" + return torch.sigmoid(F.linear(v, self.W, self.c)) + + def p_v_given_h(self, h: Tensor) -> Tensor: + """Bernoulli means ``p(v_i = 1 | h) = σ(b_i + hᵀW_i)``, shape ``(B, V)``.""" + return torch.sigmoid(F.linear(h, self.W.t(), self.b)) + + @torch.no_grad() + def gibbs_step(self, v: Tensor) -> Tensor: + """One block-Gibbs transition ``v -> h -> v'`` (both layers sampled).""" + h = torch.bernoulli(self.p_h_given_v(v)) + return torch.bernoulli(self.p_v_given_h(h)) + + @torch.no_grad() + def log_z(self) -> Tensor: + """Exact ``log Z`` by enumerating the smaller layer — feasible for tiny RBMs.""" + if min(self.n_visible, self.n_hidden) > 20: + raise ValueError("exact log_z enumerates 2^min(V,H) states; keep min(V,H) <= 20") + if self.n_hidden <= self.n_visible: + h = _binary_states(self.n_hidden, device=self.c.device, dtype=self.c.dtype) + # Z = Σ_h exp(cᵀh + Σ_i softplus(b_i + (Wᵀh)_i)); marginalize v exactly. + term = h @ self.c + F.softplus(F.linear(h, self.W.t(), self.b)).sum(dim=1) + return torch.logsumexp(term, dim=0) + v = _binary_states(self.n_visible, device=self.b.device, dtype=self.b.dtype) + return torch.logsumexp(-self.forward(v), dim=0) diff --git a/src/ebm/samplers/__init__.py b/src/ebm/samplers/__init__.py index c5183c1..df3255e 100644 --- a/src/ebm/samplers/__init__.py +++ b/src/ebm/samplers/__init__.py @@ -1,15 +1,26 @@ from ebm.samplers.annealed import AnnealedLangevinDynamics from ebm.samplers.base import Sampler from ebm.samplers.discrete import CategoricalGibbsWithGradients, GibbsWithGradients +from ebm.samplers.gibbs import GibbsSampler from ebm.samplers.hmc import HMC -from ebm.samplers.langevin import MALA, LangevinDynamics +from ebm.samplers.langevin import ( + MALA, + LangevinDynamics, + PreconditionedLangevin, + UnderdampedLangevin, +) +from ebm.samplers.tempering import ParallelTempering __all__ = [ "Sampler", "LangevinDynamics", "MALA", + "UnderdampedLangevin", + "PreconditionedLangevin", "HMC", "GibbsWithGradients", "CategoricalGibbsWithGradients", + "GibbsSampler", "AnnealedLangevinDynamics", + "ParallelTempering", ] diff --git a/src/ebm/samplers/gibbs.py b/src/ebm/samplers/gibbs.py new file mode 100644 index 0000000..531725b --- /dev/null +++ b/src/ebm/samplers/gibbs.py @@ -0,0 +1,34 @@ +"""Block-Gibbs sampler for models with tractable conditionals (e.g. an RBM).""" + +from __future__ import annotations + +from typing import Protocol, runtime_checkable + +from torch import Tensor + +from ebm.energy import EnergyFn +from ebm.samplers.base import Sampler + + +@runtime_checkable +class _BlockGibbs(Protocol): + def gibbs_step(self, v: Tensor) -> Tensor: ... + + +class GibbsSampler(Sampler): + """Block Gibbs sampling via a model's own conditionals. + + Unlike the gradient-based samplers, this takes no step size: each ``step`` + delegates to the energy's ``gibbs_step`` (e.g. `ebm.nets.RBM`'s + ``v -> h -> v'`` block update), so it draws exact samples from the model's + conditionals. Running it for ``k`` steps from a data batch gives the CD-k + negatives for `ebm.ContrastiveDivergence`. + """ + + def step(self, energy: EnergyFn, x: Tensor) -> Tensor: + if not isinstance(energy, _BlockGibbs): + raise TypeError( + "GibbsSampler needs an energy exposing gibbs_step(v) -> v " + "(e.g. ebm.nets.RBM); got a plain energy function" + ) + return energy.gibbs_step(x) diff --git a/src/ebm/samplers/langevin.py b/src/ebm/samplers/langevin.py index d3e95b5..7c81962 100644 --- a/src/ebm/samplers/langevin.py +++ b/src/ebm/samplers/langevin.py @@ -59,6 +59,80 @@ def step(self, energy: EnergyFn, x: Tensor) -> Tensor: return x +class UnderdampedLangevin(Sampler): + """Underdamped (2nd-order) Langevin / SGHMC — momentum-augmented dynamics. + + Augments the state with a velocity ``v`` and integrates + + ``v ← (1 - εγ) v - ε ∇E(x) + sqrt(2γε) ξ`` , ``x ← x + ε v`` + + (symplectic Euler of Chen et al., 2014). The stationary distribution is + ``exp(-E(x) - ½‖v‖²)``, so the position marginal is exactly ``p ∝ exp(-E)``; + the momentum smooths the trajectory and mixes better than overdamped ULA on + correlated targets. The velocity is fresh state per ``sample`` call (reset to + zero), not carried between runs. + + Args: + step_size: ε, the integrator step. + friction: γ, the damping (larger → closer to overdamped Langevin). + steps: default number of transitions per ``sample`` call. + """ + + def __init__(self, step_size: float = 0.1, friction: float = 1.0, steps: int = 100): + super().__init__(steps) + self.step_size = step_size + self.friction = friction + self._v: Tensor | None = None + + def sample( + self, + energy: EnergyFn, + x_init: Tensor, + *, + steps: int | None = None, + return_trajectory: bool = False, + ) -> Tensor: + self._v = torch.zeros_like(x_init) # momentum is per-run state + return super().sample(energy, x_init, steps=steps, return_trajectory=return_trajectory) + + def step(self, energy: EnergyFn, x: Tensor) -> Tensor: + eps, gamma = self.step_size, self.friction + if self._v is None or self._v.shape != x.shape: + self._v = torch.zeros_like(x) + _, grad = self._energy_grad(energy, x) + noise = math.sqrt(2 * gamma * eps) * torch.randn_like(x) + v = (1 - eps * gamma) * self._v - eps * grad + noise + self._v = v.detach() + return x.detach() + eps * v + + +class PreconditionedLangevin(Sampler): + """Unadjusted Langevin with a fixed diagonal preconditioner ``M``. + + ``x ← x - ε (M ⊙ ∇E(x)) + sqrt(2ε) sqrt(M) ⊙ ξ``. A constant ``M`` rescales + each coordinate's step and noise together, so the chain still targets exactly + ``p ∝ exp(-E)`` (no drift-correction term is needed, unlike adaptive + preconditioners). Set ``M`` to roughly the target's per-coordinate variance + to fix the slow mixing overdamped Langevin suffers on ill-conditioned + targets. ``precond`` broadcasts against the data's event shape. + """ + + def __init__(self, precond: Tensor, step_size: float = 1e-2, steps: int = 100): + super().__init__(steps) + self.step_size = step_size + precond = torch.as_tensor(precond, dtype=torch.float32) + if (precond <= 0).any(): + raise ValueError("preconditioner entries must be positive") + self._precond = precond + + def step(self, energy: EnergyFn, x: Tensor) -> Tensor: + eps = self.step_size + m = self._precond.to(device=x.device, dtype=x.dtype) + _, grad = self._energy_grad(energy, x) + noise = torch.sqrt(2 * eps * m) * torch.randn_like(x) + return x.detach() - eps * (m * grad) + noise + + class MALA(Sampler): """Metropolis-adjusted Langevin: ULA proposals with an accept/reject step. diff --git a/src/ebm/samplers/tempering.py b/src/ebm/samplers/tempering.py new file mode 100644 index 0000000..bb71aff --- /dev/null +++ b/src/ebm/samplers/tempering.py @@ -0,0 +1,121 @@ +"""Parallel tempering (replica exchange) over a wrapped base sampler.""" + +from __future__ import annotations + +import torch +from torch import Tensor + +from ebm.energy import EnergyFn +from ebm.samplers.base import Sampler + + +class _Tempered: + """``energy(x) / T`` as a plain callable, so any base sampler targets ``exp(-E/T)``.""" + + def __init__(self, energy: EnergyFn, temperature: float): + self.energy = energy + self.temperature = temperature + + def __call__(self, x: Tensor) -> Tensor: + return self.energy(x) / self.temperature + + +class ParallelTempering(Sampler): + """Replica exchange: run a temperature ladder and swap adjacent replicas. + + Wraps a ``base_sampler`` and runs one chain per temperature + ``1 = T_0 < T_1 < …``, each targeting ``p^{1/T} ∝ exp(-E/T)``. Hot replicas + cross energy barriers a single cold chain cannot; periodic swaps carry that + mixing down to the ``T=0`` chain, whose states are returned. Each sweep + advances every replica with the base sampler, then proposes swaps of + alternating adjacent pairs, accepting ``(k, k+1)`` with + + ``log α = (1/T_k - 1/T_{k+1}) · (E(x_k) - E(x_{k+1}))`` + + (detailed balance for the joint tempered target). ``swap_rates()`` reports + the per-pair acceptance — aim for ~0.2–0.6 by spacing the ladder + geometrically; too low means insert a rung. + + Args: + base_sampler: sampler used to advance each replica one step per sweep. + temperatures: ascending ladder; ``temperatures[0]`` (the target) should + be 1.0. + swap_every: propose swaps every this many sweeps. + steps: default number of sweeps per ``sample`` call. + """ + + def __init__( + self, + base_sampler: Sampler, + temperatures: tuple[float, ...] = (1.0, 2.0, 4.0, 8.0), + swap_every: int = 1, + steps: int = 100, + ): + super().__init__(steps) + temps = [float(t) for t in temperatures] + if len(temps) < 2: + raise ValueError("need at least 2 temperatures") + if any(t <= 0 for t in temps): + raise ValueError("temperatures must be positive") + if temps != sorted(temps): + raise ValueError("temperatures must be ascending (T0 the target, then hotter)") + if swap_every < 1: + raise ValueError("swap_every must be >= 1") + self.base = base_sampler + self.temperatures = temps + self.swap_every = swap_every + self.n_replicas = len(temps) + self._replicas: list[Tensor] | None = None + self._sweep = 0 + self._swap_accept = torch.zeros(self.n_replicas - 1) + self._swap_count = torch.zeros(self.n_replicas - 1) + + def sample( + self, + energy: EnergyFn, + x_init: Tensor, + *, + steps: int | None = None, + return_trajectory: bool = False, + ) -> Tensor: + self._replicas = [x_init.detach().clone() for _ in range(self.n_replicas)] + self._sweep = 0 + self._swap_accept = torch.zeros(self.n_replicas - 1) + self._swap_count = torch.zeros(self.n_replicas - 1) + return super().sample(energy, x_init, steps=steps, return_trajectory=return_trajectory) + + def step(self, energy: EnergyFn, x: Tensor) -> Tensor: + # One sweep. The passed ``x`` is the base class's copy of the cold chain; + # the full ensemble lives in ``self._replicas`` and is what we advance. + assert self._replicas is not None, "call sample(); ParallelTempering owns its replicas" + for k in range(self.n_replicas): + tempered = _Tempered(energy, self.temperatures[k]) + self._replicas[k] = self.base.step(tempered, self._replicas[k]).detach() + self._sweep += 1 + if self._sweep % self.swap_every == 0: + self._swap(energy) + return self._replicas[0] + + def _swap(self, energy: EnergyFn) -> None: + reps = self._replicas + assert reps is not None + with torch.no_grad(): + e = [energy(r) for r in reps] # untempered energies, each (B,) + parity = self._sweep % 2 # alternate the even / odd adjacent pair sets + for k in range(parity, self.n_replicas - 1, 2): + d_beta = 1.0 / self.temperatures[k] - 1.0 / self.temperatures[k + 1] + log_alpha = d_beta * (e[k] - e[k + 1]) + accept = torch.log(torch.rand_like(log_alpha)) < log_alpha + mask = accept.reshape(-1, *([1] * (reps[k].dim() - 1))) + rk, rk1 = reps[k], reps[k + 1] + reps[k], reps[k + 1] = torch.where(mask, rk1, rk), torch.where(mask, rk, rk1) + e[k], e[k + 1] = ( + torch.where(accept, e[k + 1], e[k]), + torch.where(accept, e[k], e[k + 1]), + ) + self._swap_accept[k] += accept.float().mean().cpu() + self._swap_count[k] += 1 + + def swap_rates(self) -> list[float]: + """Mean acceptance of each adjacent swap pair over the last ``sample`` call.""" + return (self._swap_accept / self._swap_count.clamp(min=1)).tolist() diff --git a/tests/test_datasets_eval.py b/tests/test_datasets_eval.py index f526b7c..e48bf8c 100644 --- a/tests/test_datasets_eval.py +++ b/tests/test_datasets_eval.py @@ -1,11 +1,91 @@ import math +import pytest import torch import ebm from tests.conftest import quadratic_energy +def _ar1(m, n, rho): + """M chains of a stationary AR(1): x_t = ρ x_{t-1} + sqrt(1-ρ²) ε, var ≈ 1.""" + eps = torch.randn(m, n) + x = torch.empty(m, n) + x[:, 0] = eps[:, 0] + s = math.sqrt(1 - rho**2) + for t in range(1, n): + x[:, t] = rho * x[:, t - 1] + s * eps[:, t] + return x + + +def test_split_rhat_iid_near_one_and_flags_nonmixing(): + iid = torch.randn(8, 2000, 3) + rhat = ebm.eval.split_rhat(iid) + assert rhat.shape == (3,) + assert (rhat < 1.02).all() + + # Chains parked at different means never mixed → R̂ ≫ 1. + offsets = torch.arange(8).reshape(8, 1, 1).double() + stuck = 0.01 * torch.randn(8, 2000, 1) + offsets + assert ebm.eval.split_rhat(stuck).item() > 5.0 + + +def test_ess_iid_recovers_full_count(): + iid = torch.randn(8, 2000, 2) + ess = ebm.eval.effective_sample_size(iid) + assert ess.shape == (2,) + # Independent draws: ESS ≈ M·N = 16000. + assert (ess > 0.85 * 16000).all() and (ess < 1.15 * 16000).all() + + +@pytest.mark.parametrize("rho", [0.5, 0.8]) +def test_ess_matches_ar1_closed_form(rho): + m, n = 8, 4000 + x = _ar1(m, n, rho) + ess = ebm.eval.effective_sample_size(x).item() + predicted = m * n * (1 - rho) / (1 + rho) # N(1-ρ)/(1+ρ) per chain + assert abs(ess - predicted) / predicted < 0.2 + + +def test_diagnostics_reject_too_short(): + with pytest.raises(ValueError): + ebm.eval.effective_sample_size(torch.randn(4, 3, 2)) + + +def test_precision_recall_limits(): + # Two draws from the same distribution → both metrics near 1. + p, r = ebm.eval.precision_recall(torch.randn(2000, 2), torch.randn(2000, 2)) + assert p > 0.9 and r > 0.9 + + # Disjoint supports → both near 0. + p, r = ebm.eval.precision_recall(torch.randn(1500, 2), torch.randn(1500, 2) + 20.0) + assert p < 0.05 and r < 0.05 + + with pytest.raises(ValueError): + ebm.eval.precision_recall(torch.randn(3, 2), torch.randn(3, 2), k=3) + + +def test_precision_recall_detects_mode_drop(): + # Real data has two modes; the generator only covers one. + left = torch.randn(1000, 2) - torch.tensor([6.0, 0.0]) + right = torch.randn(1000, 2) + torch.tensor([6.0, 0.0]) + real = torch.cat([left, right]) + gen = torch.randn(2000, 2) + torch.tensor([6.0, 0.0]) + p, r = ebm.eval.precision_recall(real, gen) + assert p > 0.8 # generated samples are realistic (inside the real manifold) + assert r < 0.65 # but cover only ~half the data (one dropped mode) + + +def test_inception_score_bounds(): + k = 5 + confident = torch.eye(k)[torch.arange(1000) % k] # sharp and class-balanced + assert abs(ebm.eval.inception_score(confident) - k) < 1e-3 + uniform = torch.full((1000, k), 1.0 / k) # every prediction is the marginal + assert abs(ebm.eval.inception_score(uniform) - 1.0) < 1e-3 + with pytest.raises(ValueError): + ebm.eval.inception_score(torch.rand(10)) # not (N, K) + + def test_bits_per_dim_matches_gaussian_closed_form(): # Standard normal: E(x)=||x||^2/2, log Z = (D/2) log(2 pi). d = 5 diff --git a/tests/test_losses.py b/tests/test_losses.py index d3136f7..c7299b4 100644 --- a/tests/test_losses.py +++ b/tests/test_losses.py @@ -1,3 +1,4 @@ +import pytest import torch from torch import nn @@ -77,6 +78,90 @@ def test_ssm_backward_flows(): assert all(g is not None for g in grads) +class _FreeQuadratic(nn.Module): + """E(x) = ½ xᵀ M x with a full symmetric learnable M (recovers A = Σ⁻¹).""" + + def __init__(self, d): + super().__init__() + self.P = nn.Parameter(0.1 * torch.randn(d, d) + torch.eye(d)) + + def matrix(self): + return (self.P + self.P.t()) / 2 + + def forward(self, x): + return 0.5 * ((x @ self.matrix()) * x).sum(dim=1) + + +def test_exact_score_matching_recovers_precision_matrix(): + # Data N(0, Σ): the exact-SM optimum for E = ½xᵀMx is M = Σ⁻¹ = A_true. + d = 3 + a_true = torch.tensor([[2.0, 0.5, 0.0], [0.5, 1.5, 0.3], [0.0, 0.3, 1.0]]) + chol = torch.linalg.cholesky(torch.linalg.inv(a_true)) + data = torch.randn(4000, d) @ chol.t() + + energy = _FreeQuadratic(d) + esm = ebm.ExactScoreMatching() + opt = torch.optim.Adam(energy.parameters(), lr=0.02) + for _ in range(1500): + idx = torch.randint(0, len(data), (512,)) + loss = esm(energy, data[idx]).loss + opt.zero_grad() + loss.backward() + opt.step() + assert (energy.matrix().detach() - a_true).abs().max().item() < 0.1 + + +def test_exact_score_matching_agrees_with_sliced_on_a_gaussian(): + # ESM is the exact objective SSM estimates; their values match in expectation. + x = torch.randn(2000, 3) + energy = ScaledQuadratic(1.3) + exact = ebm.ExactScoreMatching()(energy, x).loss.item() + sliced = ebm.SlicedScoreMatching(n_projections=50, vr=True)(energy, x).loss.item() + assert abs(exact - sliced) < 0.1 + + +class _Quadratic1D(nn.Module): + """E(x) = a (x - b)² — its ED minimizer on N(μ, s²) is a=1/(2s²), b=μ.""" + + def __init__(self): + super().__init__() + self.a = nn.Parameter(torch.tensor(0.6)) + self.b = nn.Parameter(torch.tensor(0.0)) + + def forward(self, x): + return (self.a * (x - self.b).pow(2)).sum(dim=1) + + +def test_energy_discrepancy_recovers_gaussian(): + mu, s = 1.5, 1.2 + data = mu + s * torch.randn(8000, 1) + energy = _Quadratic1D() + ed = ebm.EnergyDiscrepancy(sigma=1.0, m_particles=16, w_stable=1.0) + opt = torch.optim.Adam(energy.parameters(), lr=0.01) + for _ in range(3000): + idx = torch.randint(0, len(data), (512,)) + loss = ed(energy, data[idx]).loss + opt.zero_grad() + loss.backward() + opt.step() + assert abs(energy.a.item() - 1 / (2 * s**2)) < 0.05 + assert abs(energy.b.item() - mu) < 0.1 + + +def test_energy_discrepancy_shapes_and_validation(): + net = ebm.nets.MLPEnergy(dim=2, hidden=(16,)) + out = ebm.EnergyDiscrepancy(m_particles=4)(net, torch.randn(8, 2)) + assert out.x_neg.shape == (8 * 4, 2) # M contrastive draws per point + out.loss.backward() + assert all(p.grad is not None for n, p in net.named_parameters() if "weight" in n) + + # No sampler, so the loss is finite with w>0 even for a wild energy. + assert torch.isfinite(ebm.EnergyDiscrepancy(w_stable=0.0)(net, torch.randn(8, 2)).loss) + for bad in (dict(sigma=0.0), dict(m_particles=0), dict(w_stable=-1.0)): + with pytest.raises(ValueError): + ebm.EnergyDiscrepancy(**bad) + + def test_nce_log_z_learns(): net = ScaledQuadratic(1.0) loss_fn = ebm.NoiseContrastiveEstimation() diff --git a/tests/test_nets.py b/tests/test_nets.py index d54160f..86a6d31 100644 --- a/tests/test_nets.py +++ b/tests/test_nets.py @@ -4,7 +4,7 @@ import torch import ebm -from ebm.nets import _GaussianFourierFeatures +from ebm.nets import _GaussianFourierFeatures, _ResBlock def test_energy_net_output_shapes(): @@ -58,3 +58,67 @@ def test_gaussian_fourier_features_shape_and_even_dim(): assert out.shape == (5, 16) with pytest.raises(ValueError): _GaussianFourierFeatures(embed_dim=15) # must be even + + +def test_funnel_energy_closed_form(): + # E(x) = 0.5 * (v^2 / v_scale^2 + e^{-v} ||neck||^2 + n * v). + energy = ebm.nets.FunnelEnergy(dim=3, v_scale=3.0) + x = torch.tensor([[0.0, 1.0, 2.0], [1.5, -1.0, 0.0]]) + v = x[:, 0] + neck_sq = x[:, 1:].pow(2).sum(dim=1) + expected = 0.5 * (v.pow(2) / 9.0 + torch.exp(-v) * neck_sq + 2 * v) + assert torch.allclose(energy(x), expected) + + # At the origin only the v-quadratic survives (e^0 * 0 + 0); here E = 0. + assert torch.allclose(energy(torch.zeros(1, 3)), torch.zeros(1)) + with pytest.raises(ValueError): + ebm.nets.FunnelEnergy(dim=1) # needs a neck + with pytest.raises(ValueError): + energy(torch.zeros(4, 2)) # wrong width + + +def test_gaussian_mixture_energy_closed_form(): + means = torch.tensor([[-4.0, 0.0], [4.0, 0.0]]) + energy = ebm.nets.GaussianMixtureEnergy(means, std=0.5) + + # Deep inside one well-separated mode the other component is negligible, so + # E(x) ≈ ||x - μ||^2 / (2σ²) - log(w) with equal unit weights (log 1 = 0). + x = torch.tensor([[-4.3, 0.2]]) + near = ((x - means[0]).pow(2).sum() / (2 * 0.5**2)).reshape(1) + assert torch.allclose( + energy(x), + -torch.logsumexp( + torch.tensor([-near.item(), -(((x - means[1]).pow(2).sum()) / (2 * 0.5**2)).item()]), 0 + ).reshape(1), + ) + + # Symmetric target: energy at mirrored points is equal. + assert torch.allclose(energy(torch.tensor([[-4.0, 0.0]])), energy(torch.tensor([[4.0, 0.0]]))) + with pytest.raises(ValueError): + ebm.nets.GaussianMixtureEnergy(means, weights=[1.0], std=1.0) # weight count + with pytest.raises(ValueError): + ebm.nets.GaussianMixtureEnergy(means, std=0.0) # bad std + + +def test_resnet_energy_shape_and_batch_independence(): + net = ebm.nets.ResNetEnergy(in_channels=1, channels=(16, 32)) + x = torch.randn(4, 1, 16, 16) + out = net(x) + assert out.shape == (4,) + # No normalization across the batch: a sample's energy is independent of the rest. + assert torch.allclose(out[2], net(x[2:3])[0], atol=1e-6) + + +def test_resnet_block_is_identity_at_init(): + # Zero-initialized second conv + identity skip → the block is the identity. + block = _ResBlock(8, 8, spectral_norm=False, downsample=False) + y = torch.randn(2, 8, 12, 12) + assert torch.allclose(block(y), y, atol=1e-6) + + +def test_resnet_energy_spectral_norm_trains(): + net = ebm.nets.ResNetEnergy(in_channels=3, channels=(16, 32), spectral_norm=True) + out = net(torch.randn(2, 3, 32, 32)) + assert out.shape == (2,) + out.sum().backward() + assert all(p.grad is not None for p in net.parameters() if p.requires_grad) diff --git a/tests/test_rbm.py b/tests/test_rbm.py new file mode 100644 index 0000000..8d3530e --- /dev/null +++ b/tests/test_rbm.py @@ -0,0 +1,105 @@ +"""RBM tests: the free-energy identity, exact log Z, Gibbs stationarity, CD training.""" + +import itertools + +import pytest +import torch + +import ebm + + +def _small_rbm(v=2, h=3, seed=0): + torch.manual_seed(seed) + rbm = ebm.nets.RBM(v, h) + with torch.no_grad(): + rbm.W.copy_(torch.randn(h, v) * 0.8) + rbm.b.copy_(torch.randn(v) * 0.5) + rbm.c.copy_(torch.randn(h) * 0.5) + return rbm + + +def _all_visibles(v): + return torch.tensor(list(itertools.product([0.0, 1.0], repeat=v))) + + +def test_free_energy_matches_brute_force_marginal(): + v, h = 2, 3 + rbm = _small_rbm(v, h) + vs = _all_visibles(v) + model_p = torch.softmax(-rbm(vs), dim=0) + + # Enumerate the full joint and marginalize the hiddens by hand. + z = 0.0 + unnorm = [] + for vv in vs: + s = 0.0 + for hh in itertools.product([0.0, 1.0], repeat=h): + hv = torch.tensor(hh) + e = -(vv @ rbm.b) - (hv @ rbm.c) - (hv @ (rbm.W @ vv)) + s = s + torch.exp(-e) + unnorm.append(s) + z += s + brute = torch.stack([u / z for u in unnorm]) + assert torch.allclose(model_p, brute.detach(), atol=1e-6) + + +def test_log_z_exact_both_enumeration_paths(): + # min(V,H) path (enumerate hiddens) must equal the visible-enumeration sum + # and the brute-force Z, exactly. + rbm = _small_rbm(2, 3) + vs = _all_visibles(2) + visible_enum = torch.logsumexp(-rbm(vs), dim=0) + assert torch.allclose(rbm.log_z(), visible_enum, atol=1e-6) + + # A wider-visible model exercises the other branch (enumerate hiddens). + rbm2 = _small_rbm(5, 3, seed=1) + vs2 = _all_visibles(5) + assert torch.allclose(rbm2.log_z(), torch.logsumexp(-rbm2(vs2), dim=0), atol=1e-5) + + with pytest.raises(ValueError): + ebm.nets.RBM(25, 25).log_z() # too large to enumerate + + +def test_block_gibbs_is_stationary_for_the_model(): + v, h = 2, 3 + rbm = _small_rbm(v, h) + model_p = torch.softmax(-rbm(_all_visibles(v)), dim=0) + + torch.manual_seed(1) + x = torch.bernoulli(torch.full((20000, v), 0.5)) + for _ in range(200): + x = rbm.gibbs_step(x) + codes = (x[:, 0] * 2 + x[:, 1]).long() + emp = torch.bincount(codes, minlength=4).float() + emp /= emp.sum() + assert (emp - model_p).abs().max().item() < 0.02 + + +def test_cd_recovers_independent_bernoulli(): + q = torch.tensor([0.2, 0.5, 0.8, 0.35]) + rbm = ebm.nets.RBM(4, 8) + opt = torch.optim.Adam(rbm.parameters(), lr=0.05) + for _ in range(1500): + v_data = torch.bernoulli(q.expand(256, 4)) + v_neg = rbm.gibbs_step(v_data) # CD-1: one block-Gibbs step from the data + loss = rbm(v_data).mean() - rbm(v_neg).mean() + opt.zero_grad() + loss.backward() + opt.step() + + samples = torch.bernoulli(torch.full((20000, 4), 0.5)) + for _ in range(300): + samples = rbm.gibbs_step(samples) + assert (samples.mean(0) - q).abs().max().item() < 0.05 + + +def test_gibbs_sampler_drives_the_rbm_and_rejects_plain_energies(): + rbm = ebm.nets.RBM(4, 6) + sampler = ebm.GibbsSampler(steps=5) + v0 = torch.bernoulli(torch.full((32, 4), 0.5)) + out = sampler.sample(rbm, v0) + assert out.shape == (32, 4) + assert torch.logical_or(out == 0, out == 1).all() # stays binary + + with pytest.raises(TypeError): + sampler.sample(lambda x: x.pow(2).sum(1), torch.randn(4, 4)) diff --git a/tests/test_samplers.py b/tests/test_samplers.py index 00194d2..c1a50ff 100644 --- a/tests/test_samplers.py +++ b/tests/test_samplers.py @@ -1,5 +1,6 @@ """Distribution-correctness tests: samplers must recover a known Gaussian.""" +import pytest import torch import ebm @@ -64,3 +65,71 @@ def test_clamp_and_grad_clip(): sampler = ebm.LangevinDynamics(step_size=0.5, steps=20, grad_clip=0.01, clamp=(-1.0, 1.0)) samples = sampler.sample(quadratic_energy, 5 * torch.randn(16, 2)) assert samples.abs().max().item() <= 1.0 + + +def test_parallel_tempering_reduces_to_base_on_gaussian(): + # With a unimodal target the cold chain must still be exactly N(0, I). + base = ebm.LangevinDynamics(step_size=0.05, steps=1) + pt = ebm.ParallelTempering(base, temperatures=(1.0, 2.0, 4.0), steps=300) + samples = pt.sample(quadratic_energy, 3 * torch.randn(3000, 2)) + _check_standard_normal(samples) + assert not samples.requires_grad + assert all(0.0 < r <= 1.0 for r in pt.swap_rates()) + + +def test_parallel_tempering_escapes_a_trapped_mode(): + means = torch.tensor([[-4.0], [4.0]]) + energy = ebm.nets.GaussianMixtureEnergy(means, std=1.0) + x0 = -4.0 + 0.3 * torch.randn(1500, 1) # every chain starts in the LEFT mode + + # A single cold Langevin chain stays trapped where it started. + single = ebm.LangevinDynamics(step_size=0.08, steps=1000).sample(energy, x0.clone()) + assert (single > 0).float().mean().item() < 0.05 + + # Parallel tempering crosses the barrier and recovers both modes ~50/50. + base = ebm.LangevinDynamics(step_size=0.08, steps=1) + pt = ebm.ParallelTempering(base, temperatures=(1.0, 4.0, 16.0, 64.0), steps=1000) + pooled = pt.sample(energy, x0.clone()) + right_mass = (pooled > 0).float().mean().item() + assert 0.3 < right_mass < 0.7 + assert all(0.1 < r < 0.95 for r in pt.swap_rates()) + + +def test_parallel_tempering_validates_ladder(): + with pytest.raises(ValueError): + ebm.ParallelTempering(ebm.LangevinDynamics(), temperatures=(4.0, 1.0)) # not ascending + with pytest.raises(ValueError): + ebm.ParallelTempering(ebm.LangevinDynamics(), temperatures=(1.0,)) # need >= 2 + + +def test_underdamped_targets_standard_normal_and_resets_momentum(): + sampler = ebm.UnderdampedLangevin(step_size=0.1, friction=1.0, steps=300) + samples = sampler.sample(quadratic_energy, 3 * torch.randn(4000, 2)) + _check_standard_normal(samples) + assert not samples.requires_grad + # A second run must not inherit stale velocity — still exactly N(0, I). + again = sampler.sample(quadratic_energy, 3 * torch.randn(4000, 2)) + _check_standard_normal(again) + + +def test_underdamped_explores_the_funnel(): + sampler = ebm.UnderdampedLangevin(step_size=0.1, friction=1.0, steps=300) + samples = sampler.sample(ebm.nets.FunnelEnergy(dim=2, v_scale=3.0), torch.randn(4000, 2)) + assert torch.isfinite(samples).all() + # The scale coordinate spreads out (a trapped chain would collapse it). + assert samples[:, 0].std().item() > 1.0 + + +def test_preconditioned_langevin_handles_anisotropy(): + # Target N(0, diag(1, 25)): per-dim std should be [1, 5]. + def aniso(x): + return 0.5 * (x[:, 0] ** 2 / 1.0 + x[:, 1] ** 2 / 25.0) + + sampler = ebm.PreconditionedLangevin( + precond=torch.tensor([1.0, 25.0]), step_size=0.05, steps=500 + ) + std = sampler.sample(aniso, torch.randn(6000, 2)).std(dim=0) + assert abs(std[0].item() - 1.0) < 0.2 + assert abs(std[1].item() - 5.0) < 0.8 + with pytest.raises(ValueError): + ebm.PreconditionedLangevin(precond=torch.tensor([1.0, -1.0]))