"""Model definitions for the CD-MSC best ensemble (frozen-embedding probes). Two architectures, both consuming a frozen foundation-model / physics embedding and emitting 9 species logits: - RP : rich Pre-LN residual probe, used for the Perch (1536-d) and BirdMAE (1024-d) members. - HarmNet : small MLP, used for the 102-d physics harmonic feature member. Both also carry an auxiliary 5-way domain head (`dm`) used only during training (domain-aux / for MMD/CORAL on the embedding); it is unused at inference. The architecture must match the training script exactly so saved checkpoints load cleanly. """ import torch, torch.nn as nn, torch.nn.functional as F class ResidualBlock(nn.Module): """Pre-LayerNorm residual MLP block: x + Dropout(W2 GELU(W1 LN(x))).""" def __init__(self, d, p=0.2): super().__init__() self.ln = nn.LayerNorm(d, eps=1e-6) self.f1 = nn.Linear(d, d * 4) self.f2 = nn.Linear(d * 4, d) self.d1 = nn.Dropout(p) self.d2 = nn.Dropout(p) def forward(self, x): return x + self.d2(self.f2(self.d1(F.gelu(self.f1(self.ln(x)))))) class RP(nn.Module): """Rich probe for high-dim FM embeddings (Perch / BirdMAE). input LayerNorm -> Linear(d->256) -> 2x ResidualBlock -> LayerNorm -> {species head, domain head}. Training-time augmentation (active only in .train()): additive Gaussian embedding noise (sigma=0.05) and feature channel-dropout (p=0.1). `e` is the L2-normalizable embedding used by SupCon/MMD/CORAL. """ def __init__(self, d, pd=256, p=0.2, noise=0.05, chdrop=0.1): super().__init__() self.iln = nn.LayerNorm(d, eps=1e-6) self.pr = nn.Linear(d, pd) self.b = nn.ModuleList([ResidualBlock(pd, p), ResidualBlock(pd, p)]) self.po = nn.LayerNorm(pd, eps=1e-6) self.sp = nn.Linear(pd, 9) # species logits self.dm = nn.Linear(pd, 5) # auxiliary domain logits (training only) self.noise = noise self.chdrop = chdrop def forward(self, x): if self.training: x = x + torch.randn_like(x) * self.noise x = x * (torch.rand(x.shape[1], device=x.device) > self.chdrop).float()[None, :] h = self.pr(self.iln(x)) for bl in self.b: h = bl(h) e = self.po(h) return self.sp(e), self.dm(e), e class HarmNet(nn.Module): """Dedicated MLP for the 102-d physics harmonic feature (device-invariant comb / f0). LN -> Linear(d->128) -> GELU -> Dropout(0.2) -> Linear(128->64) -> LN -> {species head, domain head}. Training-time additive noise sigma=0.03. """ def __init__(self, d): super().__init__() self.net = nn.Sequential( nn.LayerNorm(d, eps=1e-6), nn.Linear(d, 128), nn.GELU(), nn.Dropout(0.2), nn.Linear(128, 64), nn.LayerNorm(64, eps=1e-6), ) self.sp = nn.Linear(64, 9) self.dm = nn.Linear(64, 5) def forward(self, x): if self.training: x = x + torch.randn_like(x) * 0.03 e = self.net(x) return self.sp(e), self.dm(e), e def build(arch, d): """Factory: arch in {'rp','harm'} -> model for a d-dim input embedding.""" return HarmNet(d) if arch == "harm" else RP(d)