Download models.py from tonyshelby/NeuralSW: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/tonyshelby/NeuralSW/resolve/main/models.py
- Command line
-
hf download hf://tonyshelby/NeuralSW/models.py
-
curl -L -o models.py https://huggingface.co/tonyshelby/NeuralSW/resolve/main/models.py
16.5 kB
| import math | |
| import torch | |
| import torch.nn as nn | |
| import numpy as np | |
| # Define Phi Function (Quantile Embedding) | |
| class PhiFunction(nn.Module): | |
| def __init__(self, embedding_dim=64, num_cosines=64): | |
| super(PhiFunction, self).__init__() | |
| self.num_cosines = num_cosines | |
| self.fc = nn.Sequential( | |
| nn.Linear(num_cosines, embedding_dim), | |
| nn.LeakyReLU(0.2), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.LeakyReLU(0.2), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.LeakyReLU(0.2), | |
| nn.Linear(embedding_dim, 1) # Output single quantile estimate | |
| ) | |
| def forward(self, tau): | |
| k = torch.arange(1, self.num_cosines + 1, device=tau.device).float().view(1, -1) # Shape (1, num_cosines) | |
| cos_features = torch.cos(torch.pi * tau.unsqueeze(-1) * k) # Shape (batch_size, num_cosines) | |
| quantile_estimate = self.fc(cos_features) # Shape (batch_size, 1) | |
| return quantile_estimate.squeeze(-1) | |
| # class ResBlock(nn.Module): | |
| # def __init__(self, dim): | |
| # super().__init__() | |
| # self.block = nn.Sequential( | |
| # nn.Linear(dim, dim), | |
| # nn.LeakyReLU(0.2), | |
| # nn.Linear(dim, dim), | |
| # ) | |
| # self.activation = nn.LeakyReLU(0.2) | |
| # | |
| # def forward(self, x): | |
| # return self.activation(x + self.block(x)) | |
| # | |
| # | |
| # class PhiFunction(nn.Module): | |
| # def __init__(self, embedding_dim=64, num_cosines=64, num_blocks=5): | |
| # super(PhiFunction, self).__init__() | |
| # self.num_cosines = num_cosines | |
| # | |
| # self.input_layer = nn.Sequential( | |
| # nn.Linear(num_cosines, embedding_dim), | |
| # nn.LeakyReLU(0.2), | |
| # ) | |
| # | |
| # self.res_blocks = nn.Sequential( | |
| # *[ResBlock(embedding_dim) for _ in range(num_blocks)] | |
| # ) | |
| # | |
| # self.output_layer = nn.Linear(embedding_dim, 1) | |
| # | |
| # def forward(self, tau): | |
| # k = torch.arange(1, self.num_cosines + 1, device=tau.device).float().view(1, -1) | |
| # cos_features = torch.cos(torch.pi * tau.unsqueeze(-1) * k) | |
| # | |
| # x = self.input_layer(cos_features) | |
| # x = self.res_blocks(x) | |
| # quantile_estimate = self.output_layer(x) | |
| # return quantile_estimate.squeeze(-1) | |
| class AmortizedPhiFunction(nn.Module): | |
| def __init__(self, embedding_dim=64, num_cosines=64,d=3): | |
| super(AmortizedPhiFunction, self).__init__() | |
| self.num_cosines = num_cosines | |
| self.d=d | |
| self.fc1 = nn.Sequential( | |
| nn.Linear(num_cosines, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| # Output single quantile estimate | |
| ) | |
| self.fc2 = nn.Sequential( | |
| nn.Linear(d, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| ) | |
| self.fc = nn.Sequential( | |
| nn.Linear(2*embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear( embedding_dim, 1), | |
| ) | |
| def forward(self, tau,theta): | |
| k = torch.arange(1, self.num_cosines + 1, device=tau.device).float().view(1, -1) # Shape (1, num_cosines) | |
| cos_features = torch.cos(torch.pi * tau * k) # Shape (batch_size, num_cosines) | |
| cos_features = cos_features.unsqueeze(0).repeat(theta.shape[0],1,1) # L,n,num_cosine | |
| quantile_emb1 = self.fc1(cos_features) # Shape (L,batch_size, emb) | |
| quantile_emb2 = self.fc2(theta).unsqueeze(1).repeat(1,tau.shape[0],1) # Shape (L, n,emb) | |
| quantile_emb=torch.cat([quantile_emb1,quantile_emb2],dim=-1) # Shape L,n,2emb | |
| quantile_estimate=self.fc(quantile_emb) # Shape L,n,1 | |
| return quantile_estimate.squeeze(-1) # L,n, | |
| class AmortizedPhiFunctionSpline(nn.Module): | |
| """Alternative Phi function: a monotonic piecewise-linear spline over tau, | |
| conditioned on theta through a hypernetwork. | |
| Unlike AmortizedPhiFunction, tau is never passed through a fixed | |
| band-limited cosine embedding -- instead, a hypernetwork maps theta to | |
| `num_bins` bin widths (in tau) and bin heights (in Q), which are combined | |
| into knots of a monotonically increasing piecewise-linear function of tau. | |
| Because each bin's height/width ratio (its local slope) is a free | |
| parameter, this can represent an arbitrarily steep jump in a single bin | |
| without needing large weights or high-frequency features -- and the | |
| output is monotonic in tau by construction, without any penalty term. | |
| """ | |
| def __init__(self, embedding_dim=128, d=2, num_bins=32): | |
| super(AmortizedPhiFunctionSpline, self).__init__() | |
| self.num_bins = num_bins | |
| self.hyper_net = nn.Sequential( | |
| nn.Linear(d, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, 2 * num_bins + 1), # bin widths, bin heights, base offset Q(0) | |
| ) | |
| def forward(self, tau, theta): | |
| # tau: (n, 1) with values in (0, 1); theta: (L, d) | |
| params = self.hyper_net(theta) # (L, 2*num_bins + 1) | |
| width_logits = params[:, :self.num_bins] | |
| height_logits = params[:, self.num_bins:2 * self.num_bins] | |
| q0 = params[:, 2 * self.num_bins:] # (L, 1) | |
| widths = torch.softmax(width_logits, dim=-1) # (L, K), sums to 1 over tau | |
| heights = nn.functional.softplus(height_logits) + 1e-4 # (L, K), strictly positive increments | |
| zeros = torch.zeros_like(widths[:, :1]) | |
| cum_widths = torch.cat([zeros, torch.cumsum(widths, dim=-1)], dim=-1) # (L, K+1), knots in [0, 1] | |
| cum_heights = torch.cat([zeros, torch.cumsum(heights, dim=-1)], dim=-1) # (L, K+1) | |
| L, n = theta.shape[0], tau.shape[0] | |
| tau_flat = tau.view(1, n).expand(L, n) # (L, n), shared tau grid per direction | |
| bin_idx = torch.searchsorted(cum_widths.detach(), tau_flat.contiguous(), right=True) - 1 | |
| bin_idx = bin_idx.clamp(0, self.num_bins - 1) | |
| x0 = torch.gather(cum_widths, 1, bin_idx) | |
| x1 = torch.gather(cum_widths, 1, bin_idx + 1) | |
| y0 = torch.gather(cum_heights, 1, bin_idx) | |
| y1 = torch.gather(cum_heights, 1, bin_idx + 1) | |
| frac = (tau_flat - x0) / (x1 - x0).clamp_min(1e-8) | |
| quantile_estimate = q0 + y0 + frac * (y1 - y0) # (L, n) | |
| return quantile_estimate | |
| class AmortizedPhiFunctionRQSpline(nn.Module): | |
| """Monotonic rational-quadratic spline Phi function (Gregory & Delbourgo | |
| 1982; used for normalizing flows in Durkan et al. 2019, "Neural Spline | |
| Flows"). | |
| AmortizedPhiFunctionSpline (the plain piecewise-linear version) can only | |
| get a steep local slope by shrinking a softmax bin width w_k towards 0 -- | |
| and softmax saturates, so gradient descent barely moves w_k once it's | |
| already small. The rational-quadratic spline fixes this by giving every | |
| knot its own learned derivative delta_k > 0 (an unconstrained softplus | |
| output, not part of any sum-to-one normalization). A knot's local slope | |
| can be driven arbitrarily steep just by growing its delta_k, with the bin | |
| width left free to stay a comfortable, non-saturating size. | |
| For bin k, spanning tau in [x_{k-1}, x_k] with corresponding Q values | |
| [y_{k-1}, y_k] and knot derivatives delta_{k-1}, delta_k > 0, writing | |
| xi = (tau - x_{k-1}) / (x_k - x_{k-1}) and s_k = (y_k - y_{k-1}) / (x_k - x_{k-1}): | |
| Q(tau) = y_{k-1} + | |
| ((y_k - y_{k-1}) * (s_k * xi^2 + delta_{k-1} * xi * (1 - xi))) | |
| / (s_k + (delta_k + delta_{k-1} - 2 * s_k) * xi * (1 - xi)) | |
| This is guaranteed strictly increasing in tau whenever s_k > 0 and | |
| delta_{k-1}, delta_k > 0 -- no extra monotonicity penalty needed -- and by | |
| construction Q's derivative at each knot exactly equals that knot's | |
| delta, so it is continuously differentiable across bin boundaries. | |
| """ | |
| def __init__(self, embedding_dim=128, d=2, num_bins=32, init_derivative=2.0): | |
| super(AmortizedPhiFunctionRQSpline, self).__init__() | |
| self.num_bins = num_bins | |
| # widths (K), heights (K), knot derivatives (K + 1), base offset Q(0) (1) | |
| out_dim = 2 * num_bins + (num_bins + 1) + 1 | |
| self.hyper_net = nn.Sequential( | |
| nn.Linear(d, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, out_dim), | |
| ) | |
| # Derivative logits default to 0 -> softplus(0) ~ 0.69, a gentle slope | |
| # that training then has to grow for the few knots that need to spike. | |
| # Start them higher so steep local slopes are available from step 0; | |
| # gradient descent still learns which knots should stay small. | |
| K = num_bins | |
| with torch.no_grad(): | |
| self.hyper_net[-1].bias[2 * K:2 * K + (K + 1)] = init_derivative | |
| def forward(self, tau, theta): | |
| # tau: (n, 1) with values in (0, 1); theta: (L, d) | |
| K = self.num_bins | |
| params = self.hyper_net(theta) # (L, 3K + 2) | |
| width_logits = params[:, :K] | |
| height_logits = params[:, K:2 * K] | |
| deriv_logits = params[:, 2 * K:2 * K + (K + 1)] | |
| q0 = params[:, 2 * K + (K + 1):] # (L, 1) | |
| widths = torch.softmax(width_logits, dim=-1) # (L, K), sums to 1 over tau | |
| heights = nn.functional.softplus(height_logits) + 1e-4 # (L, K), strictly positive increments | |
| derivatives = nn.functional.softplus(deriv_logits) + 1e-4 # (L, K+1), one per knot, > 0 | |
| zeros = torch.zeros_like(widths[:, :1]) | |
| cum_widths = torch.cat([zeros, torch.cumsum(widths, dim=-1)], dim=-1) # (L, K+1), knots in [0, 1] | |
| cum_heights = torch.cat([zeros, torch.cumsum(heights, dim=-1)], dim=-1) # (L, K+1) | |
| L, n = theta.shape[0], tau.shape[0] | |
| tau_flat = tau.view(1, n).expand(L, n) # (L, n), shared tau grid per direction | |
| bin_idx = torch.searchsorted(cum_widths.detach(), tau_flat.contiguous(), right=True) - 1 | |
| bin_idx = bin_idx.clamp(0, K - 1) | |
| x0 = torch.gather(cum_widths, 1, bin_idx) | |
| x1 = torch.gather(cum_widths, 1, bin_idx + 1) | |
| y0 = torch.gather(cum_heights, 1, bin_idx) | |
| y1 = torch.gather(cum_heights, 1, bin_idx + 1) | |
| d0 = torch.gather(derivatives, 1, bin_idx) # delta_{k-1} | |
| d1 = torch.gather(derivatives, 1, bin_idx + 1) # delta_k | |
| bin_width = (x1 - x0).clamp_min(1e-8) | |
| bin_height = y1 - y0 | |
| s = bin_height / bin_width # average slope of the bin, > 0 | |
| xi = ((tau_flat - x0) / bin_width).clamp(0.0, 1.0) | |
| xi_1m = 1.0 - xi | |
| numerator = bin_height * (s * xi ** 2 + d0 * xi * xi_1m) | |
| denominator = s + (d1 + d0 - 2 * s) * xi * xi_1m | |
| quantile_estimate = q0 + y0 + numerator / denominator.clamp_min(1e-8) # (L, n) | |
| return quantile_estimate | |
| class AmortizedPhiFunctionMixtureCDF(nn.Module): | |
| """Phi function whose Q(tau | theta) is the inverse CDF of a learned 1D | |
| Gaussian mixture: for direction theta, a hypernetwork outputs `num_components` | |
| (mean_k, std_k, weight_k) triples, and Q(tau) is found by inverting | |
| F(x) = sum_k weight_k * Phi_std((x - mean_k) / std_k) = tau. | |
| This is a strong inductive bias specifically for mixture-of-Gaussians targets: | |
| the projection of a Gaussian-mixture random vector onto any direction theta is | |
| itself exactly a 1D Gaussian mixture (with mean_k = theta^T mu_k, | |
| var_k = theta^T Sigma_k theta, weight_k unchanged) -- so the hypernetwork only | |
| has to learn those (here linear/quadratic/constant) relationships, rather than | |
| an arbitrary quantile shape. The resulting Q is monotonic and can be as steep | |
| as needed near a low-density gap between modes, without any spline bin-width | |
| or knot-derivative machinery. | |
| A mixture's CDF has no closed-form inverse, so Q(tau) is computed by batched | |
| bisection search on F. Bisection is built entirely from `<` comparisons and | |
| torch.where, which carries NO gradient back to (mean_k, std_k, weight_k) -- | |
| so a naive implementation would silently fail to train. This is fixed with a | |
| single implicit-function-theorem correction evaluated at the converged root | |
| x*: since F(x*; params) = tau identically, | |
| dx*/dparams = -(dF/dparams) / (dF/dx) = -(dF/dparams) / f(x*), | |
| which is exactly what | |
| x* - (F(x*; params) - tau) / f(x*) | |
| differentiates to, once x* and f(x*) are detached (treated as constants) and | |
| only F(x*; params) is left attached to the autograd graph. Numerically this | |
| expression still equals x* (since F(x*) - tau ~ 0 at convergence), but its | |
| gradient is now the correct one. | |
| """ | |
| def __init__(self, embedding_dim=128, d=2, num_components=8, n_bisection_iters=50): | |
| super(AmortizedPhiFunctionMixtureCDF, self).__init__() | |
| self.num_components = num_components | |
| self.n_bisection_iters = n_bisection_iters | |
| self.hyper_net = nn.Sequential( | |
| nn.Linear(d, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, embedding_dim), | |
| nn.ReLU(), | |
| nn.Linear(embedding_dim, 3 * num_components), # means, log-stds, weight logits | |
| ) | |
| def _mixture_params(self, theta): | |
| K = self.num_components | |
| params = self.hyper_net(theta) # (L, 3K) | |
| means = params[:, :K] | |
| log_stds = params[:, K:2 * K] | |
| weight_logits = params[:, 2 * K:3 * K] | |
| stds = torch.exp(log_stds.clamp(-5.0, 5.0)) + 1e-4 | |
| weights = torch.softmax(weight_logits, dim=-1) | |
| return means, stds, weights # each (L, K) | |
| def _mixture_cdf(x, means, stds, weights): | |
| # x: (L, n); means/stds/weights: (L, K) -> broadcast to (L, n, K) | |
| z = (x.unsqueeze(-1) - means.unsqueeze(1)) / (stds.unsqueeze(1) * math.sqrt(2.0)) | |
| component_cdf = 0.5 * (1.0 + torch.erf(z)) | |
| return (weights.unsqueeze(1) * component_cdf).sum(-1) # (L, n) | |
| def _mixture_pdf(x, means, stds, weights): | |
| z = (x.unsqueeze(-1) - means.unsqueeze(1)) / stds.unsqueeze(1) | |
| component_pdf = torch.exp(-0.5 * z ** 2) / (stds.unsqueeze(1) * math.sqrt(2.0 * math.pi)) | |
| return (weights.unsqueeze(1) * component_pdf).sum(-1) # (L, n) | |
| def forward(self, tau, theta): | |
| # tau: (n, 1) with values in (0, 1); theta: (L, d) | |
| means, stds, weights = self._mixture_params(theta) # (L, K), differentiable wrt hyper_net | |
| L, n = theta.shape[0], tau.shape[0] | |
| tau_flat = tau.view(1, n).expand(L, n) | |
| with torch.no_grad(): | |
| means_d, stds_d, weights_d = means.detach(), stds.detach(), weights.detach() | |
| span = 8.0 * stds_d.max(dim=1, keepdim=True).values | |
| lo = (means_d.min(dim=1, keepdim=True).values - span).expand(L, n).clone() | |
| hi = (means_d.max(dim=1, keepdim=True).values + span).expand(L, n).clone() | |
| for _ in range(self.n_bisection_iters): | |
| mid = 0.5 * (lo + hi) | |
| cdf_mid = self._mixture_cdf(mid, means_d, stds_d, weights_d) | |
| too_low = cdf_mid < tau_flat | |
| lo = torch.where(too_low, mid, lo) | |
| hi = torch.where(too_low, hi, mid) | |
| x_star = 0.5 * (lo + hi) | |
| # implicit-function-theorem correction: numerically a no-op, but routes | |
| # the correct gradient into means/stds/weights (see class docstring). | |
| f_at_xstar = self._mixture_pdf(x_star, means, stds, weights).detach() | |
| F_at_xstar = self._mixture_cdf(x_star, means, stds, weights) # differentiable wrt params | |
| quantile_estimate = x_star - (F_at_xstar - tau_flat) / f_at_xstar.clamp_min(1e-6) | |
| return quantile_estimate | |