diff --git a/.gitignore b/.gitignore index aac7da5..7519796 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ site/ # Nia tooling config (local only) nia.json +ebmkit-blog-post.txt diff --git a/pyproject.toml b/pyproject.toml index 3ae26b4..406e894 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,7 +52,13 @@ line-length = 100 src = ["src", "tests"] [tool.ruff.lint] -select = ["E", "F", "W", "I", "UP", "B", "SIM"] +select = ["E", "F", "W", "I", "UP", "B", "SIM", "C4", "PIE", "PERF", "RUF"] +# The library uses mathematical Unicode (σ, ε, ρ, μ, …) throughout its docs and +# comments on purpose; the "ambiguous character" rules would fight that. +ignore = ["RUF001", "RUF002", "RUF003"] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E731"] # lambdas are fine in tests [tool.mypy] files = ["src/ebm"] @@ -63,6 +69,7 @@ source = ["ebm"] [tool.coverage.report] show_missing = true +fail_under = 90 [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/src/ebm/__init__.py b/src/ebm/__init__.py index 7ec7c00..8aac29e 100644 --- a/src/ebm/__init__.py +++ b/src/ebm/__init__.py @@ -49,54 +49,54 @@ __version__ = "0.14.0" __all__ = [ - "EnergyFn", - "ConditionalEnergyFn", - "EnergyModel", - "score", - "ClassifierEnergy", - "ConditionalEnergy", - "JEMLoss", - "SumEnergy", - "MixtureEnergy", - "TemperedEnergy", - "Sampler", - "LangevinDynamics", - "MALA", - "UnderdampedLangevin", - "PreconditionedLangevin", + "EMA", "HMC", - "GibbsWithGradients", - "CategoricalGibbsWithGradients", - "GibbsSampler", - "AnnealedLangevinDynamics", - "ParallelTempering", + "MALA", "SVGD", - "ProbabilityFlowODE", - "PredictorCorrector", - "TemperedTransitions", - "ReplayBuffer", - "LossOutput", + "AISResult", + "AnnealedLangevinDynamics", + "CategoricalGibbsWithGradients", + "ClassifierEnergy", + "ConcreteScoreMatching", + "ConditionalEnergy", + "ConditionalEnergyFn", "ContrastiveDivergence", "DenoisingScoreMatching", "DiffusionRecoveryLikelihood", - "drl_sample", "EnergyDiscrepancy", - "PseudoLikelihood", - "RatioMatching", - "ConcreteScoreMatching", + "EnergyFn", + "EnergyModel", "ExactScoreMatching", + "GibbsSampler", + "GibbsWithGradients", + "JEMLoss", + "LangevinDynamics", + "LossOutput", + "MixtureEnergy", "MultiSigmaDenoisingScoreMatching", - "SlicedScoreMatching", "NoiseContrastiveEstimation", - "geometric_sigmas", + "ParallelTempering", + "PreconditionedLangevin", + "PredictorCorrector", + "ProbabilityFlowODE", + "PseudoLikelihood", + "RatioMatching", + "ReplayBuffer", + "Sampler", + "SlicedScoreMatching", + "SumEnergy", + "TemperedEnergy", + "TemperedTransitions", "Trainer", - "EMA", + "UnderdampedLangevin", "ais_log_z", - "reverse_ais_log_z", - "log_likelihood", - "AISResult", "datasets", + "drl_sample", "eval", + "geometric_sigmas", + "log_likelihood", "nets", + "reverse_ais_log_z", + "score", "viz", ] diff --git a/src/ebm/ais.py b/src/ebm/ais.py index 2a39a83..52c809e 100644 --- a/src/ebm/ais.py +++ b/src/ebm/ais.py @@ -18,6 +18,7 @@ from __future__ import annotations +import itertools import math from dataclasses import dataclass from typing import Protocol, cast @@ -107,7 +108,7 @@ def _anneal( try: with frozen_params(module): - for beta_prev, beta_next in zip(betas[:-1], betas[1:], strict=True): + for beta_prev, beta_next in itertools.pairwise(betas): with torch.no_grad(): # log γ_{β'}(x) - log γ_β(x) = Δβ (-E(x) - log p₀(x)). delta = float(beta_next - beta_prev) diff --git a/src/ebm/datasets.py b/src/ebm/datasets.py index 250fd01..3230b00 100644 --- a/src/ebm/datasets.py +++ b/src/ebm/datasets.py @@ -17,6 +17,18 @@ import torch from torch import Tensor +__all__ = [ + "checkerboard", + "cifar10", + "cifar100", + "eight_gaussians", + "fashion_mnist", + "mnist", + "rings", + "spirals", + "two_moons", +] + def two_moons( n: int, @@ -72,7 +84,7 @@ def _load_mnist_like( name = f"{prefix}-{kind}-ubyte.gz" path = root / (cache_prefix + name) if not path.exists(): - urllib.request.urlretrieve(mirror + name, path) # noqa: S310 + urllib.request.urlretrieve(mirror + name, path) tensors.append(_parse_idx(gzip.decompress(path.read_bytes()))) images, labels = tensors @@ -148,7 +160,7 @@ def _load_cifar_like(url, archive_name, members, parser, root, return_labels): root.mkdir(parents=True, exist_ok=True) archive = root / archive_name if not archive.exists(): - urllib.request.urlretrieve(url, archive) # noqa: S310 + urllib.request.urlretrieve(url, archive) images, labels = [], [] with tarfile.open(archive, "r:gz") as tar: @@ -223,6 +235,7 @@ def cifar100( def eight_gaussians(n: int, std: float = 0.15, generator: torch.Generator | None = None) -> Tensor: + """``n`` points from a ring of 8 isotropic Gaussians (a classic mode-coverage toy).""" angles = torch.arange(8) * (2 * math.pi / 8) centers = 2.0 * torch.stack([torch.cos(angles), torch.sin(angles)], dim=1) idx = torch.randint(8, (n,), generator=generator) @@ -230,6 +243,7 @@ def eight_gaussians(n: int, std: float = 0.15, generator: torch.Generator | None def checkerboard(n: int, generator: torch.Generator | None = None) -> Tensor: + """``n`` points uniform on a 2D checkerboard of alternating squares.""" x1 = 4 * torch.rand(n, generator=generator) - 2 offset = 2 * torch.randint(2, (n,), generator=generator).float() x2 = torch.rand(n, generator=generator) + torch.floor(x1) % 2 + offset - 2 @@ -237,6 +251,7 @@ def checkerboard(n: int, generator: torch.Generator | None = None) -> Tensor: def rings(n: int, noise: float = 0.05, generator: torch.Generator | None = None) -> Tensor: + """``n`` points on three concentric noisy rings.""" radii = torch.tensor([0.7, 1.4, 2.1]) idx = torch.randint(3, (n,), generator=generator) theta = 2 * math.pi * torch.rand(n, generator=generator) @@ -245,6 +260,7 @@ def rings(n: int, noise: float = 0.05, generator: torch.Generator | None = None) def spirals(n: int, noise: float = 0.08, generator: torch.Generator | None = None) -> Tensor: + """``n`` points on two interleaved noisy spiral arms.""" n_a = n // 2 n_b = n - n_a t_a = torch.sqrt(torch.rand(n_a, generator=generator)) * 3 * math.pi diff --git a/src/ebm/eval/__init__.py b/src/ebm/eval/__init__.py index e39c37a..0e71b7f 100644 --- a/src/ebm/eval/__init__.py +++ b/src/ebm/eval/__init__.py @@ -27,22 +27,22 @@ ) __all__ = [ - "energies", - "frechet_distance", - "mmd", - "ood_auroc", + "AISResult", "ais_log_z", - "reverse_ais_log_z", - "log_likelihood", "bits_per_dim", + "classifier_two_sample_test", "effective_sample_size", - "split_rhat", - "precision_recall", + "energies", + "fisher_divergence", + "frechet_distance", "inception_score", "kernel_stein_discrepancy", - "classifier_two_sample_test", - "fisher_divergence", + "log_likelihood", + "mmd", "mutual_information", + "ood_auroc", "pf_ode_log_likelihood", - "AISResult", + "precision_recall", + "reverse_ais_log_z", + "split_rhat", ] diff --git a/src/ebm/eval/diagnostics.py b/src/ebm/eval/diagnostics.py index 8d5ad8f..46301c9 100644 --- a/src/ebm/eval/diagnostics.py +++ b/src/ebm/eval/diagnostics.py @@ -35,7 +35,7 @@ def split_rhat(samples: Tensor) -> Tensor: tensor. Reference: Vehtari et al. (2021), BDA3. """ x = _as_chains(samples) - m, n, d = x.shape + _, n, _ = x.shape half = n // 2 if half < 2: raise ValueError("need at least 4 samples per chain to split and estimate variance") @@ -111,6 +111,7 @@ def energies(energy: EnergyFn, x: Tensor, batch_size: int = 1024) -> Tensor: return torch.cat(out) +@torch.no_grad() def ood_auroc(energy: EnergyFn, x_in: Tensor, x_out: Tensor) -> float: """AUROC for separating in-distribution from OOD data by energy. diff --git a/src/ebm/eval/goodness_of_fit.py b/src/ebm/eval/goodness_of_fit.py index f342e70..98d9b94 100644 --- a/src/ebm/eval/goodness_of_fit.py +++ b/src/ebm/eval/goodness_of_fit.py @@ -66,8 +66,12 @@ def classifier_two_sample_test( separated. A single-number, interpretable complement to `frechet_distance` / `mmd`. Pure torch; samples are flattened and standardized. """ + if not 0 < test_frac < 1: + raise ValueError("test_frac must be in (0, 1)") rf = real.detach().reshape(len(real), -1).float() gf = gen.detach().reshape(len(gen), -1).float() + if len(rf) < 2 or len(gf) < 2: + raise ValueError("classifier_two_sample_test needs at least 2 samples per set") x = torch.cat([rf, gf]) y = torch.cat([x.new_zeros(len(rf)), x.new_ones(len(gf))]) x = (x - x.mean(0)) / x.std(0).clamp_min(1e-8) diff --git a/src/ebm/losses/__init__.py b/src/ebm/losses/__init__.py index cbe8337..11717ea 100644 --- a/src/ebm/losses/__init__.py +++ b/src/ebm/losses/__init__.py @@ -13,18 +13,18 @@ ) __all__ = [ - "LossOutput", + "ConcreteScoreMatching", "ContrastiveDivergence", + "DenoisingScoreMatching", "DiffusionRecoveryLikelihood", - "drl_sample", "EnergyDiscrepancy", - "PseudoLikelihood", - "RatioMatching", - "ConcreteScoreMatching", - "DenoisingScoreMatching", "ExactScoreMatching", + "LossOutput", "MultiSigmaDenoisingScoreMatching", - "SlicedScoreMatching", "NoiseContrastiveEstimation", + "PseudoLikelihood", + "RatioMatching", + "SlicedScoreMatching", + "drl_sample", "geometric_sigmas", ] diff --git a/src/ebm/losses/score_matching.py b/src/ebm/losses/score_matching.py index 65d8384..ee91031 100644 --- a/src/ebm/losses/score_matching.py +++ b/src/ebm/losses/score_matching.py @@ -39,6 +39,8 @@ class DenoisingScoreMatching(nn.Module): def __init__(self, sigma: float = 0.1): super().__init__() + if sigma <= 0: + raise ValueError("sigma must be positive") self.sigma = sigma def forward(self, energy: EnergyFn, x: Tensor) -> LossOutput: @@ -124,6 +126,8 @@ class SlicedScoreMatching(nn.Module): def __init__(self, n_projections: int = 1, vr: bool = True): super().__init__() + if n_projections < 1: + raise ValueError("n_projections must be >= 1") self.n_projections = n_projections self.vr = vr diff --git a/src/ebm/nets/__init__.py b/src/ebm/nets/__init__.py index 733ae86..b4e76ea 100644 --- a/src/ebm/nets/__init__.py +++ b/src/ebm/nets/__init__.py @@ -24,17 +24,17 @@ from ebm.nets.targets import BananaEnergy, FunnelEnergy, GaussianMixtureEnergy __all__ = [ - "MLPEnergy", + "RBM", + "AffineCouplingFlow", + "BananaEnergy", "ConvClassifier", "ConvEnergy", - "ResNetEnergy", - "NoiseConditionalMLPEnergy", - "NoiseConditionalConvEnergy", - "IsingEnergy", - "PottsEnergy", - "RBM", "FunnelEnergy", "GaussianMixtureEnergy", - "BananaEnergy", - "AffineCouplingFlow", + "IsingEnergy", + "MLPEnergy", + "NoiseConditionalConvEnergy", + "NoiseConditionalMLPEnergy", + "PottsEnergy", + "ResNetEnergy", ] diff --git a/src/ebm/samplers/__init__.py b/src/ebm/samplers/__init__.py index 07ee52f..8684743 100644 --- a/src/ebm/samplers/__init__.py +++ b/src/ebm/samplers/__init__.py @@ -14,19 +14,19 @@ from ebm.samplers.tempering import ParallelTempering, TemperedTransitions __all__ = [ - "Sampler", - "LangevinDynamics", - "MALA", - "UnderdampedLangevin", - "PreconditionedLangevin", "HMC", - "GibbsWithGradients", + "MALA", + "SVGD", + "AnnealedLangevinDynamics", "CategoricalGibbsWithGradients", "GibbsSampler", - "AnnealedLangevinDynamics", + "GibbsWithGradients", + "LangevinDynamics", "ParallelTempering", - "SVGD", - "ProbabilityFlowODE", + "PreconditionedLangevin", "PredictorCorrector", + "ProbabilityFlowODE", + "Sampler", "TemperedTransitions", + "UnderdampedLangevin", ] diff --git a/src/ebm/viz.py b/src/ebm/viz.py index f6e3b33..b2cc9b2 100644 --- a/src/ebm/viz.py +++ b/src/ebm/viz.py @@ -9,6 +9,8 @@ from ebm.energy import EnergyFn +__all__ = ["energy_contour", "energy_histogram", "plot_samples", "show_images"] + def _require_matplotlib(): try: diff --git a/tests/test_buffer.py b/tests/test_buffer.py index 54717dd..8354fe6 100644 --- a/tests/test_buffer.py +++ b/tests/test_buffer.py @@ -19,7 +19,7 @@ def test_push_writes_back_to_sampled_slots(): def test_reinit_prob_one_always_reinitializes(): - init_fn = lambda shape: torch.full(shape, 42.0) # noqa: E731 + init_fn = lambda shape: torch.full(shape, 42.0) buf = ebm.ReplayBuffer(capacity=20, shape=(2,), reinit_prob=1.0, init_fn=init_fn) buf.data.zero_() x = buf.sample(10) diff --git a/tests/test_datasets_eval.py b/tests/test_datasets_eval.py index 4b79fcf..4f3db38 100644 --- a/tests/test_datasets_eval.py +++ b/tests/test_datasets_eval.py @@ -86,8 +86,8 @@ def test_fisher_divergence_matches_two_gaussian_closed_form(): closed = torch.trace(m @ s1 @ m.t()) + (b @ (mu1 - mu2)).pow(2).sum() x = torch.randn(20000, 2) @ torch.linalg.cholesky(s1).t() + mu1 - e_a = lambda z: 0.5 * (((z - mu1) @ a) * (z - mu1)).sum(dim=1) # noqa: E731 - e_b = lambda z: 0.5 * (((z - mu2) @ b) * (z - mu2)).sum(dim=1) # noqa: E731 + e_a = lambda z: 0.5 * (((z - mu1) @ a) * (z - mu1)).sum(dim=1) + e_b = lambda z: 0.5 * (((z - mu2) @ b) * (z - mu2)).sum(dim=1) assert abs(ebm.eval.fisher_divergence(e_a, e_b, x) - closed.item()) < 0.05 # Identical models → zero. assert ebm.eval.fisher_divergence(e_a, e_a, x) < 1e-6 @@ -430,3 +430,10 @@ def test_two_moons_labels(): assert set(y.unique().tolist()) == {0, 1} # Upper moon (label 0) sits higher on average than the lower moon. assert x[y == 0][:, 1].mean() > x[y == 1][:, 1].mean() + + +def test_classifier_two_sample_test_validation(): + with pytest.raises(ValueError): + ebm.eval.classifier_two_sample_test(torch.randn(100, 2), torch.randn(100, 2), test_frac=0.0) + with pytest.raises(ValueError): + ebm.eval.classifier_two_sample_test(torch.randn(1, 2), torch.randn(1, 2)) diff --git a/tests/test_discrete.py b/tests/test_discrete.py index c92166c..5195558 100644 --- a/tests/test_discrete.py +++ b/tests/test_discrete.py @@ -13,7 +13,7 @@ def bernoulli_init(shape): def test_gwg_recovers_independent_bernoulli_marginals(): # E(x) = -theta.x => p(x_i = 1) = sigmoid(theta_i), independent bits. theta = torch.tensor([2.0, 0.0, -1.0, 0.5]) - energy = lambda x: -(x * theta).sum(dim=1) # noqa: E731 + energy = lambda x: -(x * theta).sum(dim=1) sampler = ebm.GibbsWithGradients(steps=60) samples = sampler.sample(energy, bernoulli_init((2000, 4))) assert torch.allclose(samples.mean(0), torch.sigmoid(theta), atol=0.05) @@ -22,7 +22,7 @@ def test_gwg_recovers_independent_bernoulli_marginals(): def test_gwg_pairwise_coupling(): # Ising pair: E = -J s1 s2 with s = 2x - 1 => P(x1 == x2) = sigmoid(2J). j = 1.0 - energy = lambda x: -j * (2 * x[:, 0] - 1) * (2 * x[:, 1] - 1) # noqa: E731 + energy = lambda x: -j * (2 * x[:, 0] - 1) * (2 * x[:, 1] - 1) sampler = ebm.GibbsWithGradients(steps=40) samples = sampler.sample(energy, bernoulli_init((4000, 2))) agree = (samples[:, 0] == samples[:, 1]).float().mean() @@ -32,7 +32,7 @@ def test_gwg_pairwise_coupling(): def test_gwg_output_binary_and_accept_rate(): theta = torch.tensor([1.0, -1.0, 0.5, 0.0]) - energy = lambda x: -(x * theta).sum(dim=1) # noqa: E731 + energy = lambda x: -(x * theta).sum(dim=1) sampler = ebm.GibbsWithGradients(steps=20) samples = sampler.sample(energy, bernoulli_init((500, 4))) assert set(samples.unique().tolist()) <= {0.0, 1.0} @@ -59,7 +59,7 @@ def onehot_init(n, d, k, generator=None): def test_categorical_gwg_recovers_independent_marginals(): # E(x) = -sum theta * x over one-hot x => p(x_i = k) = softmax(theta_i)_k. theta = torch.tensor([[1.0, 0.0, -1.0], [0.5, 0.5, -0.5]]) - energy = lambda x: -(x * theta).sum(dim=(1, 2)) # noqa: E731 + energy = lambda x: -(x * theta).sum(dim=(1, 2)) sampler = ebm.CategoricalGibbsWithGradients(steps=60) samples = sampler.sample(energy, onehot_init(2000, 2, 3)) marginals = samples.mean(0) @@ -70,7 +70,7 @@ def test_categorical_gwg_pairwise_coupling(): # Potts pair: E = -J * 1[c1 == c2] with K categories => # P(c1 == c2) = e^J / (e^J + K - 1). j, k = 1.0, 3 - energy = lambda x: -j * (x[:, 0] * x[:, 1]).sum(dim=1) # noqa: E731 + energy = lambda x: -j * (x[:, 0] * x[:, 1]).sum(dim=1) sampler = ebm.CategoricalGibbsWithGradients(steps=50) samples = sampler.sample(energy, onehot_init(4000, 2, k)) agree = (samples[:, 0].argmax(1) == samples[:, 1].argmax(1)).float().mean() @@ -80,7 +80,7 @@ def test_categorical_gwg_pairwise_coupling(): def test_categorical_gwg_output_onehot_and_accept_rate(): theta = torch.tensor([[1.0, -1.0, 0.0], [0.0, 0.5, -0.5]]) - energy = lambda x: -(x * theta).sum(dim=(1, 2)) # noqa: E731 + energy = lambda x: -(x * theta).sum(dim=(1, 2)) sampler = ebm.CategoricalGibbsWithGradients(steps=20) samples = sampler.sample(energy, onehot_init(500, 2, 3)) assert set(samples.unique().tolist()) <= {0.0, 1.0} diff --git a/tests/test_losses.py b/tests/test_losses.py index 88106b6..e19bd0f 100644 --- a/tests/test_losses.py +++ b/tests/test_losses.py @@ -157,7 +157,7 @@ def test_energy_discrepancy_shapes_and_validation(): # 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)): + for bad in ({"sigma": 0.0}, {"m_particles": 0}, {"w_stable": -1.0}): with pytest.raises(ValueError): ebm.EnergyDiscrepancy(**bad) @@ -316,3 +316,10 @@ def test_nce_optimum_for_matching_model_and_noise(): loss_fn.log_z.fill_(math.log(2 * math.pi)) # log Z of N(0, I) in 2D out = loss_fn(net, torch.randn(2000, 2)) assert abs(out.loss.item() - 2 * math.log(2)) < 0.05 + + +def test_score_matching_validation_guards(): + with pytest.raises(ValueError): + ebm.DenoisingScoreMatching(sigma=0.0) + with pytest.raises(ValueError): + ebm.SlicedScoreMatching(n_projections=0) diff --git a/tests/test_viz.py b/tests/test_viz.py index 6a58950..ca48f49 100644 --- a/tests/test_viz.py +++ b/tests/test_viz.py @@ -31,3 +31,26 @@ def test_show_images_rejects_bad_shape(): ebm.viz.show_images(torch.rand(4, 2, 8, 8)) # C=2 unsupported with pytest.raises(ValueError): ebm.viz.show_images(torch.rand(4, 8, 8)) # not 4D + + +def test_energy_contour_plot_samples_and_histogram(): + import matplotlib + + matplotlib.use("Agg") + from tests.conftest import quadratic_energy + + # energy_contour renders a filled contour of a 2D energy. + ax = ebm.viz.energy_contour(quadratic_energy, bounds=(-2.0, 2.0), resolution=40) + assert len(ax.collections) > 0 + + # plot_samples scatters 2D points onto (optionally shared) axes. + ax2 = ebm.viz.plot_samples(torch.randn(200, 2)) + assert len(ax2.collections) == 1 + assert ebm.viz.plot_samples(torch.randn(50, 2), ax=ax2) is ax2 # reuses the axes + + # energy_histogram overlays one histogram per labelled batch. + ax3 = ebm.viz.energy_histogram( + quadratic_energy, {"data": torch.randn(300, 2), "model": torch.randn(300, 2) + 1} + ) + assert ax3.get_xlabel() == "energy" + assert len(ax3.get_legend().get_texts()) == 2