""" Enhanced RemizovNet variants for crypto direction prediction. 4 enhancements from arxiv research: 1. Neural SDE — learnable σ(x) noise in Chernoff steps 2. Learnable FNO — spectral correction on top of physics kernel 3. Diagonal SSM — state space regime encoder 4. GBM augmentation — heteroskedastic data augmentation (in experiment.py) All enhancements are toggleable via flags for clean ablation. """ from __future__ import annotations import math import torch import torch.nn as nn import torch.nn.functional as f_nn from torch import Tensor # --------------------------------------------------------------------------- # 1. Diagonal SSM — regime encoder # --------------------------------------------------------------------------- class DiagonalSSM(nn.Module): """Diagonal State Space Model for regime detection. Captures long-range dependencies via learned decay rates. Computed efficiently via FFT convolution (not sequential). Architecture: S4D-style diagonal SSM with skip connection. y[n] = sum_d C[d] * A[d]^n * B[d] (conv with input) + D * x[n] """ def __init__(self, d_state: int = 8): super().__init__() self.d_state = d_state # Decay rates in log-space (negative → stable, in (0,1) after exp) # HiPPO-inspired initialization: different timescales self.log_A = nn.Parameter(torch.linspace(-0.1, -2.0, d_state)) # Input-to-state and state-to-output projections self.B = nn.Parameter(torch.randn(d_state) * 0.1) self.C = nn.Parameter(torch.randn(d_state) * 0.1) # Skip connection (initialized to 1 = identity at start) self.D = nn.Parameter(torch.ones(1)) def forward(self, x: Tensor) -> Tensor: """ Args: x: (batch, seq_len) — input sequence. Returns: (batch, seq_len) — regime-modulated output. """ L = x.shape[1] device = x.device A = torch.exp(self.log_A) # decay rates in (0, 1) # Build causal convolution kernel: K[n] = sum_d C[d] * A[d]^n * B[d] n = torch.arange(L, device=device, dtype=x.dtype) # A^n for each state dim: (L, d_state) A_powers = A.unsqueeze(0) ** n.unsqueeze(1) # K[n] = sum over d_state CB = self.C * self.B # (d_state,) K = (A_powers * CB.unsqueeze(0)).sum(dim=1) # (L,) # Causal convolution via FFT (pad to avoid circular) fft_size = 2 * L K_f = torch.fft.rfft(K, n=fft_size) x_f = torch.fft.rfft(x, n=fft_size, dim=-1) y = torch.fft.irfft(x_f * K_f.unsqueeze(0), n=fft_size, dim=-1)[..., :L] return y + self.D * x # --------------------------------------------------------------------------- # 2+3. Enhanced Chernoff Layer (FNO + SDE) # --------------------------------------------------------------------------- class EnhancedRemizovLayer(nn.Module): """Chernoff step with optional FNO spectral correction and SDE noise. Base physics: S(τ) = S₃(τ) · S₂(τ) + FNO: learnable spectral correction on S₂ kernel + SDE: learnable σ(x)·√τ·ε noise injection after S₃ """ def __init__( self, grid_size: int, tau: float = 0.1, dx: float = 1.0, use_fno: bool = False, use_sde: bool = False, ): super().__init__() self.grid_size = grid_size self.tau = tau self.dx = dx self.use_fno = use_fno self.use_sde = use_sde # --- ODE coefficients (same as original) --- self.log_a = nn.Parameter(torch.zeros(grid_size)) self.b = nn.Parameter(torch.zeros(grid_size)) self.c = nn.Parameter(torch.zeros(grid_size)) # --- FNO: learnable spectral correction --- if use_fno: # Correction applied as: kernel = physics_kernel * (1 + correction) # Initialized to 0 → starts exactly as physics kernel self.fno_real = nn.Parameter(torch.zeros(grid_size)) self.fno_imag = nn.Parameter(torch.zeros(grid_size)) # --- SDE: learnable volatility --- if use_sde: # Start with small noise: softplus(-3) ≈ 0.05 self.log_sigma = nn.Parameter(torch.full((grid_size,), -3.0)) @property def a(self) -> Tensor: return f_nn.softplus(self.log_a) + 1e-6 @property def potential(self) -> Tensor: return self.c - self.b ** 2 / (4.0 * self.a) @property def sigma(self) -> Tensor: return f_nn.softplus(self.log_sigma) + 1e-6 def _apply_s2(self, f: Tensor) -> Tensor: """S₂ with optional FNO spectral correction.""" a_mean = self.a.mean() b_mean = self.b.mean() sigma2 = 4.0 * self.tau * a_mean k = torch.fft.fftfreq(self.grid_size, d=self.dx, device=f.device) # Physics-based kernel gauss_ft = torch.exp(-sigma2 * (math.pi * k) ** 2) drift_ft = torch.exp(2j * math.pi * k * b_mean * self.tau) kernel = gauss_ft * drift_ft # FNO correction: kernel *= (1 + learned_correction) if self.use_fno: correction = torch.complex( 1.0 + self.fno_real, self.fno_imag, ) kernel = kernel * correction f_ft = torch.fft.fft(f, dim=-1) result = torch.fft.ifft(f_ft * kernel.unsqueeze(0), dim=-1).real # Completion-of-square factor completion = torch.exp(self.b ** 2 * self.tau / (4.0 * self.a)) result = result * completion.unsqueeze(0) return result def _apply_s3(self, f: Tensor) -> Tensor: return f * torch.exp(self.tau * self.potential).unsqueeze(0) def forward(self, f: Tensor, stochastic: bool = True) -> Tensor: """One Chernoff step: S₃ · S₂ + optional noise.""" f = self._apply_s2(f) f = self._apply_s3(f) # SDE noise injection: σ(x) · √τ · ε if self.use_sde and stochastic: noise = torch.randn_like(f) * self.sigma.unsqueeze(0) * math.sqrt(self.tau) f = f + noise return f # --------------------------------------------------------------------------- # Combined model # --------------------------------------------------------------------------- class EnhancedRemizovNet(nn.Module): """RemizovNet with configurable SSM/FNO/SDE enhancements. Architecture: [SSM encoder] → [EnhancedChernoffLayer × n_steps] → output Each enhancement is toggleable for clean ablation studies. """ def __init__( self, grid_size: int, n_steps: int = 20, total_time: float = 0.5, dx: float = 1.0, use_ssm: bool = False, use_fno: bool = False, use_sde: bool = False, d_state: int = 8, ): super().__init__() self.grid_size = grid_size self.n_steps = n_steps self.use_ssm = use_ssm tau = total_time / n_steps # SSM regime encoder if use_ssm: self.ssm = DiagonalSSM(d_state=d_state) # Shared Chernoff layer (all steps share weights) self.layer = EnhancedRemizovLayer( grid_size, tau=tau, dx=dx, use_fno=use_fno, use_sde=use_sde, ) def forward(self, g: Tensor, stochastic: bool = True) -> Tensor: """ Args: g: (batch, grid_size) — input windows. stochastic: whether to inject SDE noise. Returns: (batch, grid_size) — predicted evolved windows. """ f = g # SSM pre-processing if self.use_ssm: f = self.ssm(f) # Chernoff composition for _ in range(self.n_steps): f = self.layer(f, stochastic=stochastic) return f def get_coefficients(self) -> dict[str, Tensor]: return { "a": self.layer.a.detach(), "b": self.layer.b.detach(), "c": self.layer.c.detach(), } def equation_string(self, precision: int = 3) -> str: coeffs = self.get_coefficients() a_m = coeffs["a"].mean().item() b_m = coeffs["b"].mean().item() c_m = coeffs["c"].mean().item() parts = [f"{a_m:.{precision}f}*y''", f"{b_m:.{precision}f}*y'", f"({c_m:.{precision}f})*y"] eq = " + ".join(parts) + " = g(x)" if hasattr(self.layer, "log_sigma"): s_m = self.layer.sigma.mean().item() eq += f" [sigma={s_m:.{precision}f}]" return eq def param_count(self) -> int: return sum(p.numel() for p in self.parameters()) # --------------------------------------------------------------------------- # GBM-style data augmentation # --------------------------------------------------------------------------- def gbm_augment( g_windows: Tensor, y_windows: Tensor, labels: Tensor, n_aug: int = 2, noise_scale: float = 0.15, ) -> tuple[Tensor, Tensor, Tensor]: """Heteroskedastic data augmentation mimicking GBM properties. Noise magnitude is proportional to local price changes (volatility), matching the heteroskedasticity of financial time series. Args: g_windows: input windows (n, grid). y_windows: target windows (n, grid). labels: direction labels (n,). n_aug: number of augmented copies. noise_scale: base noise magnitude. Returns: Augmented (g, y, labels) with (1 + n_aug) × n samples. """ aug_g = [g_windows] aug_y = [y_windows] aug_labels = [labels] for _ in range(n_aug): # Local volatility: |diff| of window, with floor diff_g = torch.diff(g_windows, dim=-1, prepend=g_windows[..., :1]) local_vol = torch.abs(diff_g).clamp(min=0.05) # Additive noise scaled by local volatility (heteroskedastic) noise_g = torch.randn_like(g_windows) * local_vol * noise_scale noise_y = torch.randn_like(y_windows) * local_vol * noise_scale aug_g.append(g_windows + noise_g) aug_y.append(y_windows + noise_y) aug_labels.append(labels.clone()) return torch.cat(aug_g), torch.cat(aug_y), torch.cat(aug_labels)