diff --git a/README.md b/README.md index 254df81..7d56375 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,6 @@ [![PyPI](https://img.shields.io/pypi/v/ebmkit.svg)](https://pypi.org/project/ebmkit/) [![coverage](https://img.shields.io/badge/coverage-95%25-brightgreen.svg)](https://github.com/davidkhjo/ebmkit/actions/workflows/ci.yml) [![Python](https://img.shields.io/pypi/pyversions/ebmkit.svg)](https://pypi.org/project/ebmkit/) -[![downloads](https://img.shields.io/pypi/dm/ebmkit.svg)](https://pypi.org/project/ebmkit/) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/davidkhjo/ebmkit/blob/main/LICENSE) **Energy-based models in PyTorch** — samplers, training losses, and honest @@ -53,14 +52,6 @@ returns `LossOutput(loss, metrics, x_neg)`; call `out.loss.backward()`). | **Eval** | `ais_log_z` / `reverse_ais_log_z` (bracket `log Z`), `bits_per_dim`, `frechet_distance` (FID), `mmd`, `ood_auroc` | | **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` | -## Docs - -- [Training methods](https://github.com/davidkhjo/ebmkit/blob/main/docs/training.md) — choosing a loss; CD/PCD, NCSN, DRL, NCE, JEM -- [Samplers](https://github.com/davidkhjo/ebmkit/blob/main/docs/sampling.md) — Langevin/MALA/HMC, Gibbs-with-Gradients, annealed -- [Evaluation](https://github.com/davidkhjo/ebmkit/blob/main/docs/evaluation.md) — log-Z bracketing, FID, MMD, OOD, bits/dim -- [Composition](https://github.com/davidkhjo/ebmkit/blob/main/docs/composition.md) — products, mixtures, tempering -- [Benchmarks](https://github.com/davidkhjo/ebmkit/blob/main/docs/benchmarks.md) — every loss family scored on the eval stack - ## Examples Runnable scripts in [`examples/`](https://github.com/davidkhjo/ebmkit/tree/main/examples) (`python examples/.py`): @@ -84,7 +75,7 @@ Runnable scripts in [`examples/`](https://github.com/davidkhjo/ebmkit/tree/main/ - **The CD loss value is not a convergence signal** — it hovers near zero at equilibrium; watch `metrics["energy_gap"]` and energy histograms. -See [`docs/`](https://github.com/davidkhjo/ebmkit/tree/main/docs) and [CONTRIBUTING.md](https://github.com/davidkhjo/ebmkit/blob/main/CONTRIBUTING.md) for the rest. +See [CONTRIBUTING.md](https://github.com/davidkhjo/ebmkit/blob/main/CONTRIBUTING.md) for the rest. ## Development diff --git a/docs/assets/benchmark_result.png b/docs/assets/benchmark_result.png deleted file mode 100644 index 34144ea..0000000 Binary files a/docs/assets/benchmark_result.png and /dev/null differ diff --git a/docs/assets/cifar_ood_result.png b/docs/assets/cifar_ood_result.png deleted file mode 100644 index 55cecc2..0000000 Binary files a/docs/assets/cifar_ood_result.png and /dev/null differ diff --git a/docs/assets/composition_result.png b/docs/assets/composition_result.png deleted file mode 100644 index 204d307..0000000 Binary files a/docs/assets/composition_result.png and /dev/null differ diff --git a/docs/assets/ising_result.png b/docs/assets/ising_result.png deleted file mode 100644 index 882c041..0000000 Binary files a/docs/assets/ising_result.png and /dev/null differ diff --git a/docs/assets/jem_result.png b/docs/assets/jem_result.png deleted file mode 100644 index 6929489..0000000 Binary files a/docs/assets/jem_result.png and /dev/null differ diff --git a/docs/assets/mnist_jem_result.png b/docs/assets/mnist_jem_result.png deleted file mode 100644 index 6967a28..0000000 Binary files a/docs/assets/mnist_jem_result.png and /dev/null differ diff --git a/docs/assets/mnist_result.png b/docs/assets/mnist_result.png deleted file mode 100644 index 1bbfdc6..0000000 Binary files a/docs/assets/mnist_result.png and /dev/null differ diff --git a/docs/assets/ncsn_result.png b/docs/assets/ncsn_result.png deleted file mode 100644 index 86a137f..0000000 Binary files a/docs/assets/ncsn_result.png and /dev/null differ diff --git a/docs/assets/potts_result.png b/docs/assets/potts_result.png deleted file mode 100644 index 0668355..0000000 Binary files a/docs/assets/potts_result.png and /dev/null differ diff --git a/docs/assets/two_moons_result.png b/docs/assets/two_moons_result.png deleted file mode 100644 index b22083c..0000000 Binary files a/docs/assets/two_moons_result.png and /dev/null differ diff --git a/docs/benchmarks.md b/docs/benchmarks.md deleted file mode 100644 index 9aded20..0000000 --- a/docs/benchmarks.md +++ /dev/null @@ -1,48 +0,0 @@ -# Benchmarks - -Every training method in the library, trained on the same two-moons data and -scored with the library's own evaluation stack — `frechet_distance` and -`mmd` between test data and 4000 model samples, test log-likelihood -**bracketed** by forward and reverse AIS, and wall-clock training time -(M-series MacBook CPU). - -Reproduce with: - -```bash -python examples/benchmark_losses.py -``` - -| Method | FD ↓ | MMD² (bw 0.3) ↓ | Test log-lik (nats) | Train time | -|---|---|---|---|---| -| CD (short-run) | 0.002 | 0.0010 | [-1.16, -0.80] | 71 s | -| Persistent CD | 0.008 | 0.0013 | [-1.12, -1.11] | 70 s | -| NCE | 0.002 | 0.0016 | [-1.04, -0.92] | 6 s | -| Sliced SM | 0.038 | 0.0072 | [-1.24, -1.16] | 7 s | -| NCSN (multi-σ DSM) | 0.000 | 0.0183 | [-1.77, -1.73] | 5 s | -| DRL | 0.003 | 0.0157 | [-1.91, -1.88] | 53 s | - -![Benchmark samples](assets/benchmark_result.png) - -## Reading the results - -- **FD and MMD disagree — that's the point.** The noise-conditional methods - (NCSN, DRL) produce samples that match the data's mean and covariance - almost perfectly (tiny FD) but are visibly *blurrier* than the data; MMD at - a structure-scale bandwidth (0.3) exposes exactly that. One number is never - enough — look at samples. -- **Why the blur is structural:** annealed and recovery sampling stop at the - smallest ladder level, so their output is the σ_L-smoothed marginal — and - the σ-conditional energy is only as sharp at σ_L as training made it. - Shrinking σ_L and lengthening the ladder tightens the samples at the cost - of more sampling steps. -- **The log-likelihood is an interval, not a number.** `log p = -E - log Z`, - so the forward/reverse AIS bracket on log Z flips into a bracket on - likelihood (endpoints sorted — near convergence the two estimates can cross - within noise). A wide interval means AIS found the landscape hard to anneal - through — itself a diagnostic. -- **Score matching trains fast but samples poorly from multimodal energies.** - SSM never sees negatives, so nothing shapes the energy *between* the modes; - long-run Langevin then mixes badly. This is the textbook failure mode, and - part of why the NCSN/DRL ladder approaches exist. -- Numbers move a little run to run (MCMC training is stochastic); the - *ordering* is stable. diff --git a/docs/composition.md b/docs/composition.md deleted file mode 100644 index 0b2e72f..0000000 --- a/docs/composition.md +++ /dev/null @@ -1,44 +0,0 @@ -# Composing energies - -Energies add where densities multiply — composition is where EBMs shine, and -the composition classes are drop-in energies for every sampler, loss, and -evaluation tool. - -## Products, mixtures, tempering - -```python -product = ebm.SumEnergy(e1, e2) # p ∝ p1 · p2 (product of experts) -weighted = ebm.SumEnergy(e1, e2, weights=[2.0, 1.0]) -mixture = ebm.MixtureEnergy(e1, e2) # p ∝ (p1 + p2) / 2 -sharp = ebm.TemperedEnergy(e1, temperature=0.5) # p ∝ p1^2 (T < 1 sharpens) -nested = ebm.MixtureEnergy(product, sharp) # compose freely -``` - -- `SumEnergy` — $E = \sum_i w_i E_i$: the intersection of constraints. Two - overlapping Gaussians multiply to a tighter Gaussian between them. -- `MixtureEnergy` — $E = -\log \sum_i w_i e^{-E_i}$: the union. Exact - log-sum-exp, numerically stable. -- `TemperedEnergy` — $E / T$: tempering. A tempered standard Gaussian has - std $\sqrt{T}$ — useful both for sharpening trained models and for - building annealing paths. - -All three register component `nn.Module`s, so parameters are visible to -optimizers and frozen correctly during sampling. See -[`examples/train_composition.py`](examples.md#composing-energies-product-mixture-tempering) -for a runnable product-of-experts / mixture / tempering demo. - -## Class-conditional energies (JEM) - -`ClassifierEnergy` gives three energies from one network: - -```python -clf = ebm.ClassifierEnergy(net) # net: (B, *shape) -> (B, K) -clf(x) # marginal: E(x) = -logsumexp(logits) -clf.conditional(x, y) # joint: E(x,y) = -logits[:, y] -cond3 = clf.condition(3) # E(x | y=3) as a standalone energy module -samples = sampler.sample(cond3, x0) # class-conditional sampling -``` - -`condition(y)` returns a real `nn.Module` holding the parent, so parameter -freezing works during conditional sampling, and the result composes with -everything above — e.g. `ebm.SumEnergy(clf.condition(3), style_energy)`. diff --git a/docs/evaluation.md b/docs/evaluation.md deleted file mode 100644 index dc821e1..0000000 --- a/docs/evaluation.md +++ /dev/null @@ -1,61 +0,0 @@ -# Evaluating EBMs - -Unnormalized models make evaluation the hard part. The library gives you three -levels of rigor. - -## Log-likelihood via log-Z bracketing - -`ais_log_z` estimates $\log Z = \log \int e^{-E(x)}\,dx$ by annealed -importance sampling — a stochastic *lower* bound in expectation. -`reverse_ais_log_z` runs the same path backwards from model samples and is a -stochastic *upper* bound. Report both: - -```python -lower = ebm.ais_log_z(energy, shape=(2,), n_temps=1000, n_chains=256) -upper = ebm.reverse_ais_log_z(energy, lower.samples, n_temps=1000) - -nats = ebm.log_likelihood(energy, x_test, lower.log_z) # higher is better -bpd = ebm.eval.bits_per_dim(energy, x_test, lower.log_z) # lower is better -``` - -`log_likelihood` is higher-is-better (nats, or bits/dim with `dim=`); -`eval.bits_per_dim` returns the conventionally reported quantity — its negation, -so *lower* is better — defaulting `dim` to the per-sample element count. - -When the two agree, trust the number. When they don't, the gap tells you how -much annealing is missing — increase `n_temps` (many cheap temperatures beat -few long MCMC runs) and check `result.ess`: an effective sample size near 1 -means a few chains dominate and the estimate is unreliable. - -> **The reverse bound is only as honest as its samples.** `reverse_ais_log_z` -> assumes its inputs are (approximately) model samples — use -> `ais_log_z(...).samples` or a long MCMC run. Poor samples bias the estimate -> further *upward*, so the bracket stays conservative rather than falsely tight. - -## Sample quality: Fréchet distance / FID - -```python -fd = ebm.eval.frechet_distance(x_real, x_generated) # raw samples -fid = ebm.eval.frechet_distance(x_real, x_gen, feature_fn=inception_pool3) -``` - -Pure torch (float64, eigendecomposition matrix square root — no scipy). -`feature_fn=None` compares raw flattened samples, right for toy data; passing -an Inception embedding gives standard FID. Use a few thousand samples per side -— small sets bias the covariance term upward. - -> **Fréchet distance only sees two moments.** A *blurred* version of the data -> matches mean and covariance almost perfectly, so FD barely moves. -> `ebm.eval.mmd(x, y, bandwidth=...)` — unbiased squared MMD with an RBF -> kernel — sees all moments; pick the bandwidth at the scale of the structure -> you care about (the default median heuristic is conservative). The -> [benchmarks](benchmarks.md) page shows a case where FD and MMD genuinely -> disagree. - -## Relative diagnostics - -- `ebm.eval.ood_auroc(energy, x_in, x_out)` — AUROC for separating - in-distribution from OOD data by energy (rank statistic, no sklearn). -- `ebm.eval.energies(energy, x)` — batched energies on CPU, for histograms. -- `ebm.viz.energy_histogram(energy, {"data": x, "model": x_neg})` — the - single most useful training diagnostic: watch the two histograms merge. diff --git a/docs/examples.md b/docs/examples.md deleted file mode 100644 index d1388fa..0000000 --- a/docs/examples.md +++ /dev/null @@ -1,228 +0,0 @@ -# Examples - -The examples live in [`examples/`](https://github.com/davidkhjo/ebmkit/tree/main/examples); -the 2D ones run on CPU in a few minutes, the MNIST ones want MPS/CUDA. - -## Two moons with persistent CD - -`examples/train_two_moons.py` — the canonical smoke test. An `MLPEnergy` is -trained with `ContrastiveDivergence` + `ReplayBuffer` + `energy_reg=0.1`, -then sampled with long-run Langevin: - -![Two moons result](assets/two_moons_result.png) - -Left to right: data, the learned energy landscape (low energy on the moons), -and fresh samples from noise. The pieces that matter: - -```python -energy = ebm.nets.MLPEnergy(dim=2, hidden=(128, 128)) -loss_fn = ebm.ContrastiveDivergence( - ebm.LangevinDynamics(step_size=1e-2, steps=60), - buffer=ebm.ReplayBuffer(8192, (2,)), - energy_reg=0.1, # without this the energies drift to ±500 and diverge -) -ebm.Trainer(energy, loss_fn, lr=1e-3).fit(ebm.datasets.two_moons(8192), steps=6000) -``` - -## JEM: classify and generate with one network - -`examples/train_jem.py` — a 3-layer MLP classifier on labeled two-moons, -trained jointly with `JEMLoss` (cross-entropy + contrastive divergence on the -marginal energy). It reaches 100% accuracy *and* generates each moon on -demand: - -![JEM result](assets/jem_result.png) - -```python -energy = ebm.ClassifierEnergy(my_2_class_mlp) -loss_fn = ebm.JEMLoss(ebm.ContrastiveDivergence(sampler, buffer=buffer, energy_reg=0.1)) -trainer.fit((x, y), steps=4000, batch_size=256) # supervised batches - -moon_0 = sampler.sample(energy.condition(0), noise) # class-conditional samples -``` - -The EMA weights (`trainer.ema.module`) give visibly cleaner samples than the -raw weights — use them for anything you show to humans. - -## MNIST: the IGEBM short-run recipe - -`examples/train_mnist.py` — an image-scale EBM with no extra dependencies: -`ebm.datasets.mnist()` downloads and parses the raw IDX files itself. A small -`ConvEnergy` is trained with persistent CD using the practitioner constants -from Du & Mordatch (2019), and digits are generated by the *same* short-run -dynamics from fresh noise: - -![MNIST result](assets/mnist_result.png) - -```python -sampler = ebm.LangevinDynamics( - step_size=10.0, noise_scale=0.005, grad_clip=0.01, steps=60, clamp=(-1, 1) -) -loss_fn = ebm.ContrastiveDivergence( - sampler, - buffer=ebm.ReplayBuffer(10_000, (1, 28, 28), reinit_prob=0.05, init_fn=uniform_init), - energy_reg=1.0, -) -# generate with the training dynamics: -samples = sampler.sample(energy, uniform_init((64, 1, 28, 28)), steps=300) -``` - -Why this recipe and not recovery likelihood for a small-budget image demo? -Short-run EBMs train the *exact* process used for generation (noise → data in -60 steps), so a few thousand updates suffice. DRL's negatives start at the -tether point near data — its generation path from pure noise is never -exercised during training and only becomes reliable at paper-scale budgets. -See the note in [Training methods](training.md). - -## JEM at image scale: classify, detect OOD, and draw digits - -`examples/train_mnist_jem.py` — the previous two recipes combined: a -`ConvClassifier` wrapped in `ClassifierEnergy` and trained with `JEMLoss` -using the exact IGEBM sampler constants above. One network then does three -jobs — classifies test digits (~95% accuracy), flags Fashion-MNIST images as -out-of-distribution by their energy (~0.99 AUROC — the headline JEM -capability; `ebm.datasets.fashion_mnist` is the classic OOD counterpart from -Grathwohl et al., 2020), and draws digits of a *requested* class: - -![JEM MNIST result](assets/mnist_jem_result.png) - -Read the figure honestly: classification and OOD are strong at this budget, -and each row (one class) is visibly distinct — the conditional signal works — -but the samples themselves stay rough. Crisp digit *generation* is the -expensive part, the same budget lesson as the unconditional example above. - -```python -energy = ebm.ClassifierEnergy( - ebm.nets.ConvClassifier(num_classes=10, in_channels=1, image_size=28, channels=(32, 64, 128)) -) -loss_fn = ebm.JEMLoss( - ebm.ContrastiveDivergence(sampler, buffer=buffer, energy_reg=1.0), - conditional_negatives=True, # sample negatives per random class, JEM-style -) -trainer.fit((x, y), steps=8000, batch_size=128) # supervised batches - -sevens = sampler.sample(energy.condition(7), noise, steps=300) # row-on-demand -auroc = ebm.eval.ood_auroc(energy, mnist_test, fashion_test) # energy as OOD score -``` - -`conditional_negatives=True` matters at image scale: with plain marginal CD, -sampling a single logit at generation time explores directions CD never -trained, and `condition(k)` produces adversarial-looking textures instead of -digits — a classifier's individual logits are easy to push up off-manifold. -Steering each training chain by a random class (as the JEM reference code -does) trains exactly the per-class paths that conditional generation uses. -The loss terms stay marginal, so nothing else changes. - -## Composing energies: product, mixture, tempering - -`examples/train_composition.py` — trains two experts on crossing stripes (one -horizontal, one vertical), then combines them *without retraining*. Because -`p(x) ∝ exp(-E(x))`, arithmetic on energies is arithmetic on densities, and -every composition is itself an energy the same `LangevinDynamics` can sample: - -![Composition result](assets/composition_result.png) - -```python -product = ebm.SumEnergy(expert_h, expert_v) # p_H · p_V -> intersection -mixture = ebm.MixtureEnergy(expert_h, expert_v) # p_H + p_V -> union -sharp = ebm.TemperedEnergy(mixture, temperature=0.25) # sharpen the union -samples = ebm.LangevinDynamics(step_size=0.01, steps=500).sample(product, noise) -``` - -The product concentrates mass where **both** experts agree (the blob where the -stripes cross); the mixture covers **either** (the full plus-shape); tempering -sharpens toward the highest-density overlap. See [Composing energies](composition.md) -for the full algebra. - -## Discrete EBMs: a 2D Ising lattice - -`examples/train_ising.py` — the library's *discrete* side. `GibbsWithGradients` -is an exact Metropolis-Hastings sampler for binary data `x ∈ {0,1}^D`, and -`nets.IsingEnergy` is a 2D nearest-neighbor lattice energy -`E(x) = -J Σ_⟨i,j⟩ s_i s_j` (spins `s = 2x − 1`). Starting from a random binary -lattice and running the sampler at three coupling strengths reproduces the -ferromagnetic phase behavior — disorder at weak coupling, large aligned domains -at strong coupling (neighbor agreement 0.55 → 0.73 → 0.91): - -![Ising result](assets/ising_result.png) - -```python -energy = ebm.nets.IsingEnergy(coupling=1.0) -x0 = torch.bernoulli(torch.full((4, 48, 48), 0.5)) # random binary lattice -x = ebm.GibbsWithGradients(steps=3000).sample(energy, x0) -``` - -`IsingEnergy(..., learn_coupling=True)` makes `J` a trainable parameter, so the -same discrete `ContrastiveDivergence` + `ReplayBuffer` recipe can *recover* a -coupling from data. - -## Categorical EBMs: a Potts lattice - -`examples/train_potts.py` — the categorical counterpart. -`CategoricalGibbsWithGradients` samples one-hot data `(B, H, W, K)`, and -`nets.PottsEnergy` is the K-color generalization of `IsingEnergy`: -`E(x) = -J Σ_⟨i,j⟩ 1[c_i = c_j]`, where the indicator is the dot product of -adjacent one-hot rows. A random 5-color speckle (neighbor agreement ≈ 1/K) -condenses into same-color domains as the coupling grows (0.23 → 0.37 → 0.70): - -![Potts result](assets/potts_result.png) - -```python -energy = ebm.nets.PottsEnergy(coupling=2.0) -x0 = torch.nn.functional.one_hot(torch.randint(5, (1, 40, 40)), 5).float() -x = ebm.CategoricalGibbsWithGradients(steps=4000).sample(energy, x0) -colors = x.argmax(-1) # (1, 40, 40) category ids -``` - -## Score-based generation with NCSN - -`examples/train_ncsn.py` — a standalone tour of the noise-conditional stack -(Song & Ermon, 2019). A `NoiseConditionalMLPEnergy` is trained with -`MultiSigmaDenoisingScoreMatching` over a geometric σ ladder — no MCMC, no -negatives — and sampled with `AnnealedLangevinDynamics`, running Langevin down -the ladder from the largest σ to the smallest: - -![NCSN result](assets/ncsn_result.png) - -```python -sigmas = ebm.geometric_sigmas(2.0, 0.02, 20) -net = ebm.nets.NoiseConditionalMLPEnergy(dim=2) -ebm.Trainer(net, ebm.MultiSigmaDenoisingScoreMatching(sigmas)).fit(data, steps=8000) - -sampler = ebm.AnnealedLangevinDynamics(sigmas, step_size=4e-3, steps_per_sigma=200) -samples = sampler.sample(net, torch.randn(2000, 2)) -``` - -The middle panel is the learned score `−∇E(x, σ_min)` pointing back toward the -data. On the eight-Gaussians target the annealed sampler **covers all eight -modes** (density concentrating at each), where plain single-σ Langevin tends to -collapse onto only a few — annealing from a near-Gaussian large-σ landscape is -what lets chains cross the low-density gaps between modes. - -## Energy-based OOD at color scale (CIFAR-10 vs CIFAR-100) - -`examples/train_cifar_ood.py` — a classifier is secretly an EBM (its marginal -energy is `-logsumexp(logits)`), so one `ConvClassifier` trained on CIFAR-10 -gives both a label and an out-of-distribution score. Training is -cross-entropy-dominant with a light CD term (the stable regime — no generation), -and CIFAR-100 images are flagged as OOD purely by energy: - -![CIFAR OOD result](assets/cifar_ood_result.png) - -```python -energy = ebm.ClassifierEnergy(ebm.nets.ConvClassifier(num_classes=10, in_channels=3)) -loss_fn = ebm.JEMLoss(ebm.ContrastiveDivergence(sampler, buffer=buffer, energy_reg=1.0), - cd_weight=0.1) -trainer.fit((cifar10_x, cifar10_y), steps=8000) -auroc = ebm.eval.ood_auroc(energy, cifar10_test, cifar100_test) # energy as OOD score -``` - -Read it honestly: the classifier reaches **~61% CIFAR-10 test accuracy** (a real -classifier), but the **OOD AUROC is only ~0.57**. CIFAR-10 vs CIFAR-100 is a -*near-OOD* pair — both are natural 32×32 objects — which is genuinely hard, so -the energy histograms overlap heavily and the signal is weak-but-real, far below -MNIST-vs-FashionMNIST's ~0.99. A *far-OOD* pair like CIFAR-10 vs SVHN separates -much more cleanly, but SVHN ships as MATLAB `.mat` files and this library stays -torchvision-free. The example is about the method and API at color scale, not a -state-of-the-art number. (A heavier CD term was tried and did not improve the -near-OOD AUROC at this budget.) diff --git a/docs/sampling.md b/docs/sampling.md deleted file mode 100644 index 990ca4d..0000000 --- a/docs/sampling.md +++ /dev/null @@ -1,60 +0,0 @@ -# Sampling - -All samplers target $p(x) \propto e^{-E(x)}$ by *descending* the energy -gradient, share the interface `sampler.sample(energy, x_init, steps=..., -return_trajectory=...)`, freeze the energy network's parameters while running, -and return detached samples. - -## Catalog - -| Sampler | Exact? | Cost/step | Use for | -|---|---|---|---| -| `LangevinDynamics` (ULA/SGLD) | biased | 1 gradient | training negatives, toy sampling | -| `MALA` | exact | 2 gradients | final samples, AIS transitions | -| `HMC` | exact | L+1 gradients | smooth targets, AIS transitions | -| `GibbsWithGradients` | exact | 2 gradients | binary data `{0,1}^D` | -| `CategoricalGibbsWithGradients` | exact | 2 gradients | one-hot data `(B, *dims, K)` | -| `AnnealedLangevinDynamics` | biased | 1 gradient | NCSN generation down a noise ladder | - -## The two Langevin regimes - -One keyword apart: - -```python -# Mathematically correct: noise = sqrt(2 * step_size); targets p ∝ exp(-E). -ebm.LangevinDynamics(step_size=1e-2, steps=100) - -# Practitioner "short-run" image regime: huge step, cold decoupled noise. -ebm.LangevinDynamics(step_size=10.0, noise_scale=0.005, grad_clip=0.01, steps=60) -``` - -The first converges to the model distribution and is what you want for toy -data, MCMC diagnostics, and anything where correctness matters. The second is -an optimization-with-jitter that works empirically for image EBM training — -use it with a `ReplayBuffer` and `energy_reg`, and don't expect its samples to -be calibrated draws from $p$. - -## Tuning - -- **MALA / HMC** expose `last_accept_rate`. Aim for ~0.5–0.7 (MALA) or - ~0.65–0.9 (HMC); adjust `step_size` accordingly. AIS does this for you - automatically (`adapt_step_size=True`). -- **Gradient clipping** (`grad_clip`) is a stability tool for training - negatives, not for correct sampling — it biases the chain. -- **Discrete samplers** propose one flip / one category change per step, so - budget `steps` at a few times the number of positions; the first-order - proposal is exact for linear energies (accept rate ≈ 1), and acceptance - degrades gracefully with interaction strength. See - [`examples/train_ising.py`](examples.md#discrete-ebms-a-2d-ising-lattice) for - `GibbsWithGradients` on a 2D Ising lattice. -- **`AnnealedLangevinDynamics(sigmas, step_size, steps_per_sigma)`** follows - NCSN Algorithm 1: per level $\alpha_i = \epsilon\,\sigma_i^2/\sigma_L^2$, - update $x \leftarrow x - (\alpha_i/2)\nabla E(x,\sigma_i) + - \sqrt{\alpha_i}\,\xi$. Pair with `MultiSigmaDenoisingScoreMatching`. - -## Writing your own - -Subclass `Sampler`, implement `step(energy, x) -> x'`, and use the -`Sampler._energy_grad(energy, x)` helper for gradients — `sample()` then -handles parameter freezing, `torch.enable_grad`, detaching, and trajectories -for free. diff --git a/docs/training.md b/docs/training.md deleted file mode 100644 index d6791c2..0000000 --- a/docs/training.md +++ /dev/null @@ -1,132 +0,0 @@ -# Training methods - -Five loss families, one interface: every loss is an `nn.Module` called as -`loss_fn(energy, x)` (or `loss_fn(energy, x, y)` when supervised) and returns -`LossOutput(loss, metrics, x_neg)`. - -## Choosing a loss - -| You have | Use | Why | -|---|---|---| -| Low-dimensional / toy data | `ContrastiveDivergence` + `LangevinDynamics` | Simple, exact enough, fast to iterate | -| Images or other high-dim data | `ContrastiveDivergence` + `ReplayBuffer` (the IGEBM recipe) | Persistent chains amortize mixing | -| Unstable CD training | `DiffusionRecoveryLikelihood` | The tethered conditional is near-unimodal — short-run MCMC actually mixes | -| No MCMC budget at all | `MultiSigmaDenoisingScoreMatching` or `SlicedScoreMatching` | Score matching needs no negatives | -| A tractable noise distribution | `NoiseContrastiveEstimation` | Turns density estimation into classification; learns `log Z` as a parameter | -| Labels, and you want a classifier too | `JEMLoss` | One network that classifies and generates | - -## Contrastive divergence - -Maximum likelihood's gradient is `∇E(data) - ∇E(model samples)`; CD approximates -the model samples with a short MCMC run: - -```python -loss_fn = ebm.ContrastiveDivergence( - ebm.LangevinDynamics(step_size=1e-2, steps=60), - buffer=ebm.ReplayBuffer(8192, (2,)), # persistent CD - energy_reg=0.1, # keeps energy magnitudes bounded -) -``` - -The image-scale ("IGEBM") recipe is the same object with practitioner -constants: `LangevinDynamics(step_size=10.0, noise_scale=0.005, -grad_clip=0.01, steps=60)`, `ReplayBuffer(10_000, shape, reinit_prob=0.05)`, -`energy_reg=1.0`, samples clamped to `(-1, 1)`. - -> **The CD loss value is not a convergence signal.** `E(x⁺) - E(x⁻)` hovers -> near zero (and can go negative) at equilibrium. Watch `metrics["energy_gap"]` -> and energy histograms instead; a training run where the gap diverges to large -> negative values means the sampler can't keep up with the energy landscape — -> regularize harder or tether (see below). - -## Diffusion recovery likelihood - -The most stable known EBM training (Gao et al. 2021). Instead of sampling the -multimodal marginal, sample the *recovery posterior* between adjacent levels -of a noise ladder $\sigma_1 > \dots > \sigma_L$: - -$$ -p(x \mid \tilde{x}) \propto \exp\!\big({-E(x, \sigma_{t+1})} - - \|\tilde{x} - x\|^2 / 2s_t^2\big), -\qquad s_t^2 = \sigma_t^2 - \sigma_{t+1}^2 . -$$ - -The quadratic tether makes this near-unimodal, so 30 Langevin steps genuinely -mix. Requires a noise-conditional energy: - -```python -net = ebm.nets.NoiseConditionalMLPEnergy(dim=2) -sigmas = ebm.geometric_sigmas(3.0, 0.05, 10) -loss_fn = ebm.DiffusionRecoveryLikelihood(sigmas, mcmc_steps=30) -# ... train, then generate by walking the ladder down: -samples = ebm.drl_sample(net, sigmas, 2000, (2,)) -``` - -> **Stable training ≠ cheap generation.** DRL's negatives start at the tether -> point — always *near data* — which is exactly what makes training stable, but -> it means the generation path from pure noise down the ladder is never -> exercised during training. On small budgets the trained energy denoises -> poorly from far off-manifold and `drl_sample` output stays noisy; reaching -> paper-quality generation takes paper-scale budgets (large nets, 100k+ steps). -> For a small-budget image demo, use the short-run CD recipe instead (see the -> MNIST example) — there the training process *is* the generator. - -## Score matching - -No negatives, no MCMC — match $\nabla_x \log p$ instead. `DenoisingScoreMatching(sigma)` -for a single noise scale; `MultiSigmaDenoisingScoreMatching(sigmas)` is the -NCSN objective across a ladder (pair it with `AnnealedLangevinDynamics` for -generation); `SlicedScoreMatching` avoids noise entirely via random -projections. Note the energy's *additive constant* is invisible to the score — -the output bias never receives gradient, which is expected. - -## Noise-contrastive estimation - -`NoiseContrastiveEstimation(noise_dist, noise_ratio)` classifies data against -noise samples; `log Z` is learned as an explicit parameter, so the energy -comes out (approximately) *normalized*. Works best when the noise distribution -overlaps the data well. - -## JEM: classifier as EBM - -Any K-class classifier is secretly an EBM: `E(x) = -logsumexp(logits)`. -`ClassifierEnergy` wraps the classifier; `JEMLoss` adds cross-entropy to a CD -loss on the marginal energy: - -```python -clf = ebm.ClassifierEnergy(my_classifier) # (B, *shape) -> (B, K) -loss_fn = ebm.JEMLoss(ebm.ContrastiveDivergence(sampler), cd_weight=1.0) -trainer.fit((X, Y), ...) # supervised batches -samples_of_class_3 = sampler.sample(clf.condition(3), x0) -``` - -If class-conditional generation is the point, set -`JEMLoss(..., conditional_negatives=True)` so each negative chain targets a -random class's joint energy — otherwise `condition(k)` samples a logit whose -off-manifold shape CD never trained, which beyond toy data yields adversarial -textures rather than class samples (see the -[MNIST JEM example](examples.md#jem-at-image-scale-classify-detect-ood-and-draw-digits)). - -## Saving and resuming - -Image-scale runs take minutes; `Trainer.save(path)` / `Trainer.load(path)` -checkpoint everything needed to resume — energy weights, optimizer moments, the -EMA copy, any loss parameters (e.g. NCE's `log_z`), the PCD replay buffer, and -the step counter and metric history: - -```python -trainer.fit(data, steps=4000) -trainer.save("ckpt.pt") - -# later — reconstruct with the SAME architecture, then load into it: -resumed = ebm.Trainer(build_energy(), build_loss(), lr=1e-4, ema_decay=0.999) -resumed.load("ckpt.pt") -resumed.fit(data, steps=4000) # step_count continues from 4000 -``` - -Load restores *into* a matching trainer (the same load-into-existing pattern as -`ReplayBuffer` / `EMA`), so build the energy, loss, and buffer the same way -before calling `load`. A periodic checkpoint pairs naturally with the -`callback(step, out)` hook — see -[`examples/checkpoint_resume.py`](https://github.com/davidkhjo/ebmkit/blob/main/examples/checkpoint_resume.py) -for a runnable save-every-N-steps / resume demo. diff --git a/examples/benchmark_losses.py b/examples/benchmark_losses.py index e0a1e73..c699267 100644 --- a/examples/benchmark_losses.py +++ b/examples/benchmark_losses.py @@ -2,8 +2,7 @@ For each loss family: train on the same data, draw 4000 samples, then score with the Fréchet distance, an AIS-bracketed test log-likelihood, and wall -time. Prints a markdown table (pasted into docs/benchmarks.md) and writes -benchmark_result.png. +time. Prints a markdown table and writes benchmark_result.png. Run: python examples/benchmark_losses.py (CPU, ~15 minutes) """ diff --git a/examples/train_mnist.py b/examples/train_mnist.py index b666442..11a7b6e 100644 --- a/examples/train_mnist.py +++ b/examples/train_mnist.py @@ -8,7 +8,7 @@ which is why this recipe demos well at small budgets. (Diffusion recovery likelihood is the stabler *training* objective at scale, but its negatives start near data, so learning to generate from pure noise needs paper-scale -budgets — see docs/training.md.) +budgets.) Runs on MPS/CUDA if available (~5 min), CPU works but is slow. diff --git a/pyproject.toml b/pyproject.toml index ce9f9e7..3ae26b4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,6 @@ packages = ["src/ebm"] [tool.ruff] line-length = 100 src = ["src", "tests"] -extend-exclude = ["docs"] [tool.ruff.lint] select = ["E", "F", "W", "I", "UP", "B", "SIM"]