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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ site/

# Nia tooling config (local only)
nia.json
ebmkit-blog-post.txt
9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -63,6 +69,7 @@ source = ["ebm"]

[tool.coverage.report]
show_missing = true
fail_under = 90

[tool.pytest.ini_options]
testpaths = ["tests"]
Expand Down
70 changes: 35 additions & 35 deletions src/ebm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
3 changes: 2 additions & 1 deletion src/ebm/ais.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

from __future__ import annotations

import itertools
import math
from dataclasses import dataclass
from typing import Protocol, cast
Expand Down Expand Up @@ -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)
Expand Down
20 changes: 18 additions & 2 deletions src/ebm/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -223,20 +235,23 @@ 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)
return (centers[idx] + std * torch.randn(n, 2, generator=generator)).float()


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
return torch.stack([x1, x2], dim=1).float()


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)
Expand All @@ -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
Expand Down
22 changes: 11 additions & 11 deletions src/ebm/eval/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
3 changes: 2 additions & 1 deletion src/ebm/eval/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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.

Expand Down
4 changes: 4 additions & 0 deletions src/ebm/eval/goodness_of_fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 7 additions & 7 deletions src/ebm/losses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
4 changes: 4 additions & 0 deletions src/ebm/losses/score_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down
18 changes: 9 additions & 9 deletions src/ebm/nets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
18 changes: 9 additions & 9 deletions src/ebm/samplers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
2 changes: 2 additions & 0 deletions src/ebm/viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

from ebm.energy import EnergyFn

__all__ = ["energy_contour", "energy_histogram", "plot_samples", "show_images"]


def _require_matplotlib():
try:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading