import math import numpy as np import pytest import torch from scipy import signal from ml_porosity.losses.rml import bank_loss, effective_lambda, gather_windows, shift_bank, window_loglik from ml_porosity.losses.softdtw import dilate_loss, dilate_loss_fast, nll_cost, softdtw_loss, softdtw_loss_fast WIN = 16 F64 = torch.float64 def bank_data(B=3, L=40, S=5, seed=0): g = torch.Generator().manual_seed(seed) mu = torch.randn(B, L, generator=g, dtype=F64) sigma = 0.5 + torch.rand(B, L, generator=g, dtype=F64) Y = mu[:, None, :] + torch.randn(B, S, L, generator=g, dtype=F64) starts = torch.tensor([[0, 6, 24]] * B) return mu, sigma, Y, starts def random_logpi(B, S, seed=1): return torch.log_softmax(torch.randn(B, S, generator=torch.Generator().manual_seed(seed), dtype=F64), -1) def gauss_nll(mu, sigma, y, starts): m, s, v = (gather_windows(a, starts, WIN) for a in (mu, sigma, y)) return (torch.log(s) + 0.5 * ((v - m) / s) ** 2 + 0.5 * math.log(2 * math.pi)).mean() def test_gather_windows_matches_slices(): _, _, Y, starts = bank_data() w = gather_windows(Y, starts, WIN) assert w.shape == (3, 3, 5, WIN) torch.testing.assert_close(w[1, 2], Y[1, :, 24: 24 + WIN]) @pytest.mark.parametrize("lam", [None, 1e-3, 1.0, 50.0]) def test_single_or_identical_members_give_gaussian_nll(lam): mu, sigma, Y, starts = bank_data() ref = gauss_nll(mu, sigma, Y[:, 0], starts) one = bank_loss(mu, sigma, Y[:, :1], torch.zeros(3, 1, dtype=F64), starts, WIN, lam) same = bank_loss(mu, sigma, Y[:, :1].expand(3, 4, -1), torch.full((3, 4), -math.log(4), dtype=F64), starts, WIN, lam) torch.testing.assert_close(one, ref) torch.testing.assert_close(same, ref) def test_rml_between_hard_min_and_mixture_mean(): # uniform π: −max ℓ/n ≤ RML_λ ≤ hard-min + log S/(λn), non-increasing in λ; λ → 0 gives −mean ℓ/n mu, sigma, Y, starts = bank_data() S = Y.shape[1] logpi = torch.full((3, S), -math.log(S), dtype=F64) hard = bank_loss(mu, sigma, Y, logpi, starts, WIN, None) mean = -(window_loglik(mu, sigma, Y, starts, WIN).mean(-1) / WIN).mean() lams = [1e-8, 0.01, 0.1, 1.0, 10.0, 1e4] v = [bank_loss(mu, sigma, Y, logpi, starts, WIN, lam) for lam in lams] assert all(a >= b - 1e-12 for a, b in zip(v, v[1:])) for lam, x in zip(lams, v): assert hard - 1e-12 <= x <= hard + math.log(S) / (lam * WIN) + 1e-12 torch.testing.assert_close(v[0], mean, rtol=0, atol=1e-6) def test_rml_small_lambda_is_pi_weighted_nll(): mu, sigma, Y, starts = bank_data() logpi = random_logpi(3, Y.shape[1]) ll = window_loglik(mu, sigma, Y, starts, WIN) ref = -((ll * logpi.exp()[:, None, :]).sum(-1) / WIN).mean() torch.testing.assert_close(bank_loss(mu, sigma, Y, logpi, starts, WIN, 1e-7), ref, rtol=0, atol=1e-6) @pytest.mark.parametrize("lam", [0.05, 1.0]) def test_rml_gradient_is_responsibility_weighted(lam): # ∇ RML = −(1/n) Σ_s r_s ∇ℓ_s with r = softmax(log π + λℓ) mu, sigma, Y, starts = bank_data() logpi = random_logpi(3, Y.shape[1]) mu.requires_grad_(True) sigma.requires_grad_(True) g = torch.autograd.grad(bank_loss(mu, sigma, Y, logpi, starts, WIN, lam), (mu, sigma)) ll = window_loglik(mu, sigma, Y, starts, WIN) r = torch.softmax(logpi[:, None, :] + lam * ll, -1).detach() g_ref = torch.autograd.grad(-((r * ll).sum(-1) / WIN).mean(), (mu, sigma)) for a, b in zip(g, g_ref): torch.testing.assert_close(a, b) def test_shift_bank_rows_are_label_shifts(): y = np.arange(10.0) bank = shift_bank(y, 2) assert bank.shape == (5, 10) np.testing.assert_array_equal(bank[2], y) np.testing.assert_array_equal(bank[3, :9], y[1:]) # k = +1: y_{i+1} np.testing.assert_array_equal(bank[0, 2:], y[:8]) # k = −2: y_{i−2} assert np.isnan(bank[3, 9]) and np.isnan(bank[0, :2]).all() def dtw_data(B=3, n=12, seed=0): g = torch.Generator().manual_seed(seed) mu = torch.randn(B, n, generator=g, dtype=F64) sigma = 0.3 + torch.rand(B, n, generator=g, dtype=F64) y = torch.roll(mu, 1, -1) + 0.3 * torch.randn(B, n, generator=g, dtype=F64) return mu, sigma, y @pytest.mark.parametrize("fast", [False, True]) def test_band0_reduces_to_nll(fast): # band 0 leaves only the diagonal: soft-DTW/(2n) = mean NLL, TDI = 0 mu, sigma, y = dtw_data() nll = torch.diagonal(nll_cost(mu, sigma, y), dim1=1, dim2=2).mean() sd, dl = (softdtw_loss_fast, dilate_loss_fast) if fast else (softdtw_loss, dilate_loss) torch.testing.assert_close(sd(mu, sigma, y, gamma=0.1, band=0), nll) torch.testing.assert_close(dl(mu, sigma, y, alpha=0.3, gamma=0.1, band=0), 0.3 * nll) @pytest.mark.parametrize("kind", ["softdtw", "dilate"]) @pytest.mark.parametrize("band", [4, None]) @pytest.mark.parametrize("gamma", [0.1, 1.0]) def test_fast_matches_autograd(kind, band, gamma): mu, sigma, y = dtw_data(seed=2) if kind == "softdtw": fns = [lambda m, s: f(m, s, y, gamma=gamma, band=band) for f in (softdtw_loss, softdtw_loss_fast)] else: fns = [lambda m, s: f(m, s, y, alpha=0.5, gamma=gamma, band=band) for f in (dilate_loss, dilate_loss_fast)] out = [] for fn in fns: m, s = mu.clone().requires_grad_(True), sigma.clone().requires_grad_(True) v = fn(m, s) out.append((v.detach(), *torch.autograd.grad(v, (m, s)))) for a, b in zip(*out): torch.testing.assert_close(b, a, rtol=1e-7, atol=1e-10) def test_effective_lambda_grows_with_correlation(): rng = np.random.default_rng(0) white = [rng.standard_normal(400) for _ in range(4)] sos = signal.butter(4, 20, fs=250, output="sos") smooth = [signal.sosfiltfilt(sos, w) for w in white] lam_w, tau_w = effective_lambda(white) lam_s, tau_s = effective_lambda(smooth) assert tau_w < 1.3 and tau_s > 2.0 assert lam_w == pytest.approx(1 / tau_w) and lam_s == pytest.approx(1 / tau_s)