"""Shared training/evaluation code for amortized sliced-Wasserstein quantile estimation. Each main_*.py script defines only what is specific to its distribution (how to sample data, and how to compute the true projected quantiles) and then calls train_amortized_phi / evaluate_and_plot from this module. """ import numpy as np import torch import torch.nn as nn import torch.optim as optim import matplotlib.pyplot as plt from models import AmortizedPhiFunction def set_seed(seed=42): np.random.seed(seed) torch.manual_seed(seed) class PinballLoss(nn.Module): """Plain (unsmoothed) pinball/check loss -- no epsilon-smoothing. Useful for models like AmortizedPhiFunctionSpline / RQSpline that are already smooth and monotonic in tau by construction, so they don't need SmoothQuantileLoss's epsilon-smoothing (which was there to keep the monotonicity-penalty gradient well-behaved for the cosine-embedding MLP). """ def forward(self, preds, targets, taus): taus = taus.repeat(1, preds.shape[0]).T errors = targets - preds return torch.max(taus * errors, (taus - 1.0) * errors).mean() class SmoothQuantileLoss(nn.Module): def __init__(self, epsilon=0.01): super().__init__() self.epsilon = epsilon def forward(self, preds, targets, taus): taus = taus.repeat(1, preds.shape[0]).T errors = targets - preds a = taus * errors b = (taus - 1.0) * errors stacked = torch.stack([a, b], dim=0) loss = self.epsilon * torch.logsumexp(stacked / self.epsilon, dim=0) return loss.mean() def monotonic_loss(phi_function, tau, theta, base_loss_fn, y_true, lambda_reg=10.0): """Base quantile loss plus a monotonicity penalty computed via autograd d(phi)/d(tau).""" tau.requires_grad = True y_pred = phi_function(tau, theta) base_loss = base_loss_fn(y_pred, y_true, tau) grad_outputs = torch.ones_like(y_pred) dy_dtau = torch.autograd.grad(y_pred, tau, grad_outputs=grad_outputs, create_graph=True)[0] penalty = torch.mean(nn.functional.relu(-dy_dtau)) return base_loss + lambda_reg * penalty def monotonic_loss_sorted_taus(phi_function, tau, theta, base_loss_fn, y_true, lambda_reg=10.0): """Base quantile loss plus a monotonicity penalty from finite differences. Requires `tau` to already be sorted along dim 0. """ y_pred = phi_function(tau, theta) base_loss = base_loss_fn(y_pred, y_true, tau) diffs = y_pred[:, 1:] - y_pred[:, :-1] penalty = torch.relu(-diffs).mean() return base_loss + lambda_reg * penalty def plain_quantile_loss(phi_function, tau, theta, base_loss_fn, y_true, lambda_reg=0.0): """Base quantile loss with no monotonicity penalty, for models (e.g. AmortizedPhiFunctionSpline) that are monotonic in tau by construction.""" y_pred = phi_function(tau, theta) return base_loss_fn(y_pred, y_true, tau) def random_unit_directions(L, d, device): thetas = torch.randn((L, d), device=device) return thetas / torch.sqrt(torch.sum(thetas ** 2, dim=1, keepdim=True)) def sobol_tau_sampler(n_tau): sobol = torch.quasirandom.SobolEngine(dimension=1, scramble=True) def _sample(device): return sobol.draw(n_tau).view(n_tau, 1).to(device) return _sample def sorted_random_tau_sampler(n_tau, eps=1e-4): def _sample(device): taus = torch.rand(n_tau, 1, device=device) taus = eps + (1.0 - 2 * eps) * taus taus, _ = torch.sort(taus, dim=0) return taus return _sample def train_amortized_phi( sample_fn, d, device, n_samples=64, L=100, epochs=20000, lr=1e-4, embedding_dim=128, num_cosines=128, lambda_reg=1e-4, log_interval=1000, criterion=None, loss_fn=monotonic_loss, tau_sampler=None, model=None, ): """Train a phi-function model to estimate sliced quantile functions. sample_fn(n_samples) -> data tensor of shape (n_samples, d) on `device`. tau_sampler(device) -> tau tensor of shape (n_tau, 1); defaults to Sobol draws of size n_samples. model -> an already-constructed nn.Module taking (tau, theta); defaults to AmortizedPhiFunction(embedding_dim, num_cosines, d). Pass a different architecture (e.g. AmortizedPhiFunctionSpline) to compare against it. """ criterion = criterion or SmoothQuantileLoss() tau_sampler = tau_sampler or sobol_tau_sampler(n_samples) if model is None: model = AmortizedPhiFunction(embedding_dim=embedding_dim, num_cosines=num_cosines, d=d) model = model.to(device) optimizer = optim.Adam(model.parameters(), lr=lr) for epoch in range(epochs): optimizer.zero_grad() taus = tau_sampler(device) data = sample_fn(n_samples) thetas = random_unit_directions(L, d, device) projected_data = torch.matmul(thetas, data.T) loss = loss_fn(model, taus, thetas, criterion, projected_data, lambda_reg=lambda_reg) loss.backward() optimizer.step() if epoch % log_interval == 0: print(f"Epoch {epoch}, Loss: {loss.item()}") return model def evaluate_and_plot( model, d, device, true_quantile_fn, sample_fn, L_test=10, n_test_samples=64, title="Amortized Quantile Function", seed=None, ): """ true_quantile_fn(test_thetas, taus_test) -> array of shape (L_test, n_taus) with true quantiles. sample_fn(n_samples) -> data tensor of shape (n_samples, d), used to build empirical quantiles. seed -> if set, fixes the RNG right before drawing test_thetas/data_test, so repeated calls (e.g. across different architectures/hyperparameters) compare the same directions and test data instead of fresh random ones each time. """ if seed is not None: torch.manual_seed(seed) test_thetas = random_unit_directions(L_test, d, device) taus_test = torch.linspace(0.01, 0.99, 100).view(-1, 1) estimated_quantiles = model(taus_test.to(device), test_thetas).cpu().detach().numpy() data_test = sample_fn(n_test_samples) projected_data_test = (test_thetas @ data_test.T).cpu() true_quantiles = true_quantile_fn(test_thetas, taus_test) for l in range(L_test): empirical_quantiles = np.quantile( projected_data_test[l].numpy(), taus_test.numpy(), method='inverted_cdf' ) plt.figure(figsize=(8, 5)) plt.plot(taus_test.numpy(), true_quantiles[l], label="True Quantile", linestyle="dashed", color="black") plt.plot(taus_test.numpy(), estimated_quantiles[l], label="Estimated Quantile (Amortized)", color="blue") plt.plot(taus_test.numpy(), empirical_quantiles, label="Empirical Quantile", linestyle="dotted", color="red") plt.xlabel("Quantile Level (τ)") plt.ylabel("Quantile Value") plt.title(f"{title}, Direction {l + 1}") plt.legend() plt.show() def sample_mixture_gaussian(n_samples, means, covs, weights, n_dim, device): n_components = weights.shape[0] component_idx = np.random.choice(n_components, size=n_samples, p=weights.detach().cpu().numpy()) data = torch.zeros((n_samples, n_dim), device=device, dtype=means.dtype) for i in range(n_samples): comp_idx = component_idx[i] dist = torch.distributions.MultivariateNormal(means[comp_idx], covariance_matrix=covs[comp_idx]) data[i] = dist.sample() return data def mixture_gaussian_true_quantiles(test_thetas, taus_test, means, covs, weights, n_mc_samples=10000): """Monte-Carlo estimate of the true projected quantiles for a Gaussian mixture.""" projected_means = (test_thetas @ means.T).cpu().numpy() # (L_test, K) projected_variances = torch.einsum("li,kij,lj->lk", test_thetas, covs, test_thetas).cpu().numpy() weight_probs = (weights / torch.sum(weights)).detach().cpu().numpy() L_test = test_thetas.shape[0] true_quantiles = np.zeros((L_test, taus_test.shape[0])) for l in range(L_test): components = np.random.choice(len(weights), size=n_mc_samples, p=weight_probs) samples = np.array([ np.random.normal(projected_means[l][c], np.sqrt(projected_variances[l][c])) for c in components ]) true_quantiles[l] = np.quantile(samples, taus_test.numpy(), method='inverted_cdf').squeeze(-1) return true_quantiles