Download tests/test_idff.py from rezapop/IDFF-code: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/rezapop/IDFF-code/resolve/main/tests/test_idff.py
- Command line
-
hf download hf://rezapop/IDFF-code/tests/test_idff.py
-
curl -L -o test_idff.py https://huggingface.co/rezapop/IDFF-code/resolve/main/tests/test_idff.py
11.3 kB
| """Tests for the IDFF reference implementation. | |
| Besides unit tests, two tests check the paper's theory numerically on Gaussian data, where every | |
| quantity is available in closed form: | |
| * Theorem first_order_preservation: the K = 1 sampler with g_t^2 = 2 gamma_t^1 and the exact score | |
| reproduces the CFM marginals, while mismatched diffusion does not. | |
| * Fisher's identity: the score head trained with the IDFF objective converges to the marginal score. | |
| """ | |
| import math | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import pytest | |
| import torch | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| from idff import (JointHeadMLP, contracted_score_derivative, gamma_schedule, idff_loss, # noqa: E402 | |
| sample, sample_next, sample_sequence, sequence_training_pairs, sigma_t) | |
| from idff.datasets import TOY_DATASETS, attractor_trajectories # noqa: E402 | |
| from idff.metrics import mmd_rbf, trajectory_metrics, wrap_degrees # noqa: E402 | |
| M = torch.tensor([1.0, -2.0]) # data mean for the Gaussian tests | |
| S = 0.5 # data std | |
| class GaussianOracle(torch.nn.Module): | |
| """Exact (x1_hat, s_hat) for x0 ~ N(0, I), x1 ~ N(M, S^2 I), x_t = t x1 + (1 - t) x0 + sigma_t eps.""" | |
| def __init__(self, sigma0=0.0): | |
| super().__init__() | |
| self.sigma0 = sigma0 | |
| def variance(self, t): | |
| return t ** 2 * S ** 2 + (1 - t) ** 2 + self.sigma0 ** 2 * t * (1 - t) | |
| def forward(self, x, t): | |
| t = t.reshape(-1, 1) | |
| var = self.variance(t) | |
| x1_hat = M + (t * S ** 2 / var) * (x - t * M) | |
| score = -(x - t * M) / var | |
| return x1_hat, score | |
| # -------------------------------------------------------------------------------------------- | |
| # Unit tests | |
| # -------------------------------------------------------------------------------------------- | |
| def test_sigma_and_schedules_vanish_at_endpoints(): | |
| assert sigma_t(0.0, 0.3) == 0.0 and sigma_t(1.0, 0.3) == 0.0 | |
| assert math.isclose(sigma_t(0.5, 0.2), 0.1) | |
| for shape in ["beta22", "triangular", "sine", "beta33"]: | |
| assert gamma_schedule(0.0, 0.7, shape) == pytest.approx(0.0, abs=1e-12) | |
| assert gamma_schedule(1.0, 0.7, shape) == pytest.approx(0.0, abs=1e-12) | |
| assert gamma_schedule(0.5, 0.7, shape) > 0 | |
| assert gamma_schedule(0.5, 0.7, "beta22") == pytest.approx(0.7) | |
| def test_loss_matches_manual_computation(): | |
| torch.manual_seed(0) | |
| model = JointHeadMLP(2, hidden=16, depth=2, sigma0=0.3) | |
| x1, x0, t = torch.randn(64, 2), torch.randn(64, 2), torch.rand(64) | |
| torch.manual_seed(1) | |
| loss, stats = idff_loss(model, x1, x0=x0, t=t, sigma0=0.3) | |
| torch.manual_seed(1) | |
| eps = torch.randn_like(x1) | |
| st = 0.3 * torch.sqrt(t * (1 - t))[:, None] | |
| xt = t[:, None] * x1 + (1 - t[:, None]) * x0 + st * eps | |
| x1_hat, s_hat = model(xt, t) | |
| beta = 1 / (1 - t[:, None] + 1e-2) | |
| manual = ((beta * (x1_hat - x1)) ** 2).mean() + (st ** 2 * (s_hat + eps / st) ** 2).mean() | |
| assert loss.item() == pytest.approx(manual.item(), rel=1e-5) | |
| with pytest.raises(ValueError): | |
| idff_loss(model, x1, sigma0=0.0) | |
| def test_contracted_derivatives_match_closed_form(): | |
| torch.manual_seed(0) | |
| a = torch.randn(3, 3) | |
| def score(y): # linear part plus elementwise cubic: derivatives known in closed form | |
| return y @ a.T + 0.3 * y ** 3 | |
| x, u = torch.randn(5, 3), torch.randn(5, 3) | |
| m2 = contracted_score_derivative(score, x, u, 1) | |
| m3 = contracted_score_derivative(score, x, u, 2) | |
| m4 = contracted_score_derivative(score, x, u, 3) | |
| torch.testing.assert_close(m2, u @ a.T + 0.9 * x ** 2 * u) | |
| torch.testing.assert_close(m3, 1.8 * x * u ** 2) | |
| torch.testing.assert_close(m4, 1.8 * u ** 3) | |
| def test_network_evaluation_count_and_determinism(): | |
| class Counting(torch.nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.calls = 0 | |
| self.net = JointHeadMLP(2, hidden=16, depth=2) | |
| def forward(self, x, t): | |
| self.calls += 1 | |
| return self.net(x, t) | |
| model = Counting() | |
| x0 = torch.randn(8, 2) | |
| for nfe in [1, 2, 5]: | |
| model.calls = 0 | |
| sample(model, x0, nfe, K=1) | |
| assert model.calls == nfe | |
| model.calls = 0 | |
| sample(model, x0, 6, K=2) | |
| assert model.calls == 6 + 4 # one JVP on every step with gamma_t^1 > 0 (all but the first and last) | |
| a = sample(model, x0, 5, K=0, generator=torch.Generator().manual_seed(0)) | |
| b = sample(model, x0, 5, K=0, generator=torch.Generator().manual_seed(1)) | |
| torch.testing.assert_close(a, b) | |
| def test_sequence_training_pairs(): | |
| data = torch.arange(2 * 5 * 3, dtype=torch.float32).reshape(2, 5, 3) | |
| torch.manual_seed(0) | |
| x0, x1, n = sequence_training_pairs(data, 512, sigma0=1e-3) | |
| for i in range(len(n)): | |
| k = n[i].item() | |
| seq = [s for s in range(2) if torch.equal(x1[i], data[s, k])] | |
| assert len(seq) == 1 # x1 is a data frame at position n | |
| if k > 0: # x0 ~ N(x^{n-1}, sigma0^2 I) for the same sequence | |
| assert (x0[i] - data[seq[0], k - 1]).abs().max() < 0.01 | |
| assert x0[n == 0].std() > 0.5 # position 0 starts from N(0, I) | |
| def test_ot_coupling_shortens_pairs(): | |
| pytest.importorskip("ot") | |
| from idff import ot_coupling | |
| torch.manual_seed(0) | |
| x0, x1 = torch.randn(256, 2), TOY_DATASETS["8gaussians"](256) | |
| p0, p1 = ot_coupling(x0, x1) | |
| assert p0.shape == x0.shape and p1.shape == x1.shape | |
| assert ((p1 - p0) ** 2).sum(1).mean() < 0.6 * ((x1 - x0) ** 2).sum(1).mean() | |
| # N(0, I) -> N(m, I): W2^2 = |m|^2 = 18, while independent pairing costs |m|^2 + 2d = 22 | |
| x0, x1 = torch.randn(512, 2), torch.randn(512, 2) + 3.0 | |
| p0, p1 = ot_coupling(x0, x1) | |
| assert abs(((p1 - p0) ** 2).sum(1).mean().item() - 18.0) < 2.0 | |
| def test_metrics(): | |
| assert wrap_degrees(350.0) == pytest.approx(-10.0) | |
| true = np.stack([np.linspace(0, 10, 50), np.linspace(0, -5, 50)], 1) | |
| m = trajectory_metrics(true[:, None, :], true) | |
| assert m["MAE"] == 0 and m["RMSE"] == 0 and m["CC"] == pytest.approx(1.0) | |
| m = trajectory_metrics(np.full((3, 1, 1), 179.0), np.full((3, 1), -179.0), angles=True) | |
| assert m["MAE"] == pytest.approx(2.0) | |
| x = torch.randn(300, 2) | |
| assert mmd_rbf(x, x) == pytest.approx(0.0, abs=1e-12) | |
| assert mmd_rbf(x, x + 3.0) > 0.1 | |
| # -------------------------------------------------------------------------------------------- | |
| # Theory checks on Gaussian data | |
| # -------------------------------------------------------------------------------------------- | |
| def test_k1_sampler_preserves_marginals_with_exact_score(gamma_bar): | |
| """Theorem first_order_preservation: Langevin drift + matched diffusion leaves p_t unchanged. | |
| With sigma0 = 0 the velocity (x1_hat - x)/(1 - t) is the exact marginal field, so the only | |
| errors are Euler-Maruyama discretisation and Monte-Carlo noise. | |
| """ | |
| torch.manual_seed(0) | |
| oracle = GaussianOracle(sigma0=0.0) | |
| nfe, n = 400, 40000 | |
| x, traj = sample(oracle, torch.randn(n, 2), nfe, K=1, gamma_bar=gamma_bar, return_trajectory=True) | |
| torch.testing.assert_close(x.mean(0), M, atol=0.02, rtol=0) | |
| assert x.var(0).sub(S ** 2).abs().max() < 0.03 * S ** 2 | |
| mid = traj[nfe // 2] # t = 0.5 | |
| var_mid = oracle.variance(torch.tensor(0.5)).item() | |
| torch.testing.assert_close(mid.mean(0), 0.5 * M, atol=0.02, rtol=0) | |
| assert mid.var(0).sub(var_mid).abs().max() < 0.03 * var_mid | |
| def test_mismatched_diffusion_breaks_preservation(): | |
| """The cancellation needs g_t^2 = 2 gamma_t^1: dropping the noise shrinks the variance, and noise | |
| without the score drift inflates it.""" | |
| torch.manual_seed(0) | |
| oracle = GaussianOracle(sigma0=0.0) | |
| x0 = torch.randn(40000, 2) | |
| no_noise = sample(oracle, x0, 400, K=1, gamma_bar=1.0, diffusion_scale=0.0) | |
| noise_only = sample(oracle, x0, 400, K=1, gamma_bar=1.0, score_drift=False) | |
| assert no_noise.var(0).max() < 0.85 * S ** 2 | |
| assert noise_only.var(0).min() > 1.15 * S ** 2 | |
| def test_score_head_learns_marginal_score(): | |
| """Fisher's identity: regressing on -eps/sigma_t yields grad log p_t (and the denoiser E[x1 | x_t]).""" | |
| torch.manual_seed(0) | |
| sigma0 = 0.5 | |
| model = JointHeadMLP(2, hidden=128, depth=3, sigma0=sigma0) | |
| opt = torch.optim.Adam(model.parameters(), lr=2e-3) | |
| for _ in range(3000): | |
| x1 = M + S * torch.randn(1024, 2) | |
| loss, _ = idff_loss(model, x1, sigma0=sigma0) | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| oracle = GaussianOracle(sigma0=sigma0) | |
| for t in [0.2, 0.5, 0.8]: | |
| st = sigma0 * math.sqrt(t * (1 - t)) | |
| xt = t * (M + S * torch.randn(4000, 2)) + (1 - t) * torch.randn(4000, 2) + st * torch.randn(4000, 2) | |
| tb = torch.full((4000,), t) | |
| with torch.no_grad(): | |
| x1_hat, s_hat = model(xt, tb) | |
| x1_true, s_true = oracle(xt, tb) | |
| rel_score = ((s_hat - s_true).norm(dim=1) / s_true.norm(dim=1)).median() | |
| rel_x1 = ((x1_hat - x1_true).norm(dim=1) / x1_true.norm(dim=1)).median() | |
| assert rel_score < 0.15, (t, rel_score) | |
| assert rel_x1 < 0.05, (t, rel_x1) | |
| # -------------------------------------------------------------------------------------------- | |
| # End-to-end smoke tests | |
| # -------------------------------------------------------------------------------------------- | |
| def test_static_training_and_sampling_smoke(name): | |
| torch.manual_seed(0) | |
| model = JointHeadMLP(2, hidden=64, depth=2, sigma0=0.2) | |
| opt = torch.optim.Adam(model.parameters(), lr=1e-3) | |
| losses = [] | |
| for _ in range(200): | |
| loss, _ = idff_loss(model, TOY_DATASETS[name](256), sigma0=0.2) | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| losses.append(loss.item()) | |
| assert np.mean(losses[-20:]) < np.mean(losses[:20]) | |
| for K in [0, 1, 2, 3]: | |
| out = sample(model, torch.randn(128, 2), 5, K=K, gamma_bar=0.5, alphas={2: 1.0, 3: 1.0}) | |
| assert out.shape == (128, 2) and torch.isfinite(out).all() | |
| def test_sequence_training_and_sampling_smoke(): | |
| torch.manual_seed(0) | |
| raw = attractor_trajectories("lorenz", num_traj=4, length=30, burn_in=200, seed=0) | |
| data = torch.tensor((raw - raw.mean((0, 1))) / raw.std((0, 1)), dtype=torch.float32) | |
| model = JointHeadMLP(3, hidden=64, depth=2, sigma0=0.05, base_std=0.05, num_positions=30, residual=True) | |
| opt = torch.optim.Adam(model.parameters(), lr=1e-3) | |
| for _ in range(100): | |
| x0, x1, n = sequence_training_pairs(data, 128, sigma0=0.05) | |
| loss, _ = idff_loss(model, x1, x0=x0, sigma0=0.05, model_kwargs={"n": n}) | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| for K in [0, 1, 2]: | |
| traj = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, K=K) | |
| assert traj.shape == (30, 4, 3) and torch.isfinite(traj).all() | |
| cond = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, first_frame=data[0, 0], K=K) | |
| torch.testing.assert_close(cond[0], data[0, 0].expand(4, 3)) | |
| per_sample = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, first_frame=data[:, 0], K=K) | |
| torch.testing.assert_close(per_sample[0], data[:, 0]) | |
| nxt = sample_next(model, data[:, 3], 4, nfe=3, sigma0=0.05) | |
| assert nxt.shape == (4, 3) | |