forecasting-models / code /bifurcation /models /unet2_5ch_coord_aug.py
coarse-grained-forecasting-benchmark's picture
Add anonymous reproduction code
41dd7e0 verified
Raw History Blame Contribute Delete
5.98 kB
"""Augmented-state variant of unet2_5ch_coord: the backbone of the heterogeneous-waves models.
State x = (u, v_hat) in R^392: two independent 196-D spectral fields (coarse displacement, finite-
difference coarse velocity), each with its OWN _SpectralFieldWrapper / normalization (velocity has a
different physical scale than displacement). Everything else -- the periodic-conv trunk, coordinate
planes, channel structure -- is IDENTICAL to unet2_5ch_coord; only the input/output channel counts
differ (9 in / 2 out instead of 7 in / 1 out) to carry both fields through together.
Standard single-path dataset-norm injection (needs_dataset_norm=True, like every other backbone): the
u/v wrappers are built from TWO SUBDIRECTORIES of the one injected ``packaged_dataset_path``,
<packaged_dataset_path>/u_norm/normalization.npz (196-D, displacement)
<packaged_dataset_path>/v_norm/normalization.npz (196-D, velocity)
so the run configuration names one dataset path, as for every other model.
"""
from __future__ import annotations
import torch
import torch.nn as nn
from .spectral import K_C
from .unet2 import _PeriodicUNet2Core, _SpectralFieldWrapper, _broadcast_scalar, _upsample2, _require_packaged
from .unet2_coord import _coord_planes
class _DualHeadCore(_PeriodicUNet2Core):
"""Same trunk as _PeriodicUNet2Core; final 1x1 conv widened from 1 to 2 output channels (predict
u_next and v_next together), and _forward_core no longer squeezes the channel axis away."""
def __init__(self, in_channels: int, base_channels: int, dropout: float = 0.0):
super().__init__(in_channels=in_channels, base_channels=base_channels, dropout=dropout)
self.out = nn.Conv2d(base_channels, 2, kernel_size=1)
def _forward_core(self, x: torch.Tensor) -> torch.Tensor:
s0 = self.enc0(x)
s1 = self.enc1(self.pool(s0))
s2 = self.enc2(self.pool(s1))
u1 = self.dec1(torch.cat([_upsample2(s2), s1], dim=1))
u0 = self.dec0(torch.cat([_upsample2(u1), s0], dim=1))
return self.out(u0) # (B, 2, ng, ng) -- no squeeze
class LocalDrift2DCoordAug(nn.Module):
"""forward(x_tau, tau, x_tk, t_k, t_k1) -> (B, 392); x_tau/x_tk are (B, 392) = concat(u, v)."""
def __init__(self, D: int = 196, base_channels: int = 64, n_grid: int = 32, k_c: int = K_C,
packaged: str | None = None, dropout: float = 0.0):
super().__init__()
if packaged is None:
raise ValueError("unet2_5ch_coord_aug needs the training dataset's normalization: pass packaged")
self.core = _DualHeadCore(in_channels=9, base_channels=base_channels, dropout=dropout)
self.wrap_u = _SpectralFieldWrapper(str(packaged) + "/u_norm", n_grid, k_c)
self.wrap_v = _SpectralFieldWrapper(str(packaged) + "/v_norm", n_grid, k_c)
assert self.wrap_u.D == D and self.wrap_v.D == D
self.D = D
def forward(self, x_tau, tau, x_tk, t_k, t_k1):
B, ng, D = x_tau.shape[0], self.wrap_u.n_grid, self.D
u_tau, v_tau = x_tau[:, :D], x_tau[:, D:]
u_tk, v_tk = x_tk[:, :D], x_tk[:, D:]
xt_u = self.wrap_u.inv(u_tau).unsqueeze(1); xt_v = self.wrap_v.inv(v_tau).unsqueeze(1)
xk_u = self.wrap_u.inv(u_tk).unsqueeze(1); xk_v = self.wrap_v.inv(v_tk).unsqueeze(1)
inp = torch.cat([xt_u, xt_v, xk_u, xk_v,
_broadcast_scalar(tau, B, ng).to(xt_u),
t_k.view(B, 1, 1, 1).expand(B, 1, ng, ng).to(xt_u),
t_k1.view(B, 1, 1, 1).expand(B, 1, ng, ng).to(xt_u),
_coord_planes(B, ng, xt_u)], dim=1)
field = self.core._forward_core(inp) # (B, 2, ng, ng)
u_next = self.wrap_u.fwd(field[:, 0]); v_next = self.wrap_v.fwd(field[:, 1])
return torch.cat([u_next, v_next], dim=1)
def count_parameters(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad)
@classmethod
def from_config(cls, cfg: dict) -> "LocalDrift2DCoordAug":
return cls(D=int(cfg.get("D", 196)), base_channels=int(cfg.get("base_channels", 64)),
n_grid=int(cfg.get("n_grid", 32)), k_c=int(cfg.get("k_c", K_C)),
packaged=_require_packaged(cfg), dropout=float(cfg.get("dropout", 0.0)))
class Conditional2D5chCoordAug(LocalDrift2DCoordAug):
"""Endpoint head with the segment head's exact interface (mirrors Conditional2D5chCoord):
forward(x, sigma_embedded, x_0) fixes (t_start, t_end) = (0, T)."""
def __init__(self, *args, t_start: float = 0.0, t_end: float = 1.0, **kwargs):
super().__init__(*args, **kwargs)
self.t_start, self.t_end = float(t_start), float(t_end)
def forward(self, x, sigma_embedded, x_0):
B = x.shape[0]
tk = torch.full((B,), self.t_start, dtype=x.dtype, device=x.device)
tk1 = torch.full((B,), self.t_end, dtype=x.dtype, device=x.device)
return super().forward(x, sigma_embedded, x_0, tk, tk1)
@classmethod
def from_config(cls, cfg: dict) -> "Conditional2D5chCoordAug":
return cls(D=int(cfg.get("D", 196)), base_channels=int(cfg.get("base_channels", 64)),
n_grid=int(cfg.get("n_grid", 32)), k_c=int(cfg.get("k_c", K_C)),
packaged=_require_packaged(cfg), dropout=float(cfg.get("dropout", 0.0)),
t_start=float(cfg.get("t_start", 0.0)), t_end=float(cfg.get("t_end", 1.0)))
from ..registry import register_model # noqa: E402
register_model("unet2_5ch_coord_aug", Conditional2D5chCoordAug, LocalDrift2DCoordAug, needs_dataset_norm=True,
description="Augmented-state (u, v_hat) backbone of the heterogeneous-waves models: two "
"_SpectralFieldWrapper instances read from <packaged>/u_norm and <packaged>/v_norm; "
"otherwise identical trunk and parameter count to unet2_5ch_coord.")