"""Isolation controls used to debug the v2 backbone. ``AblationProbe`` reproduces the AGILE predictor exactly (GINE + descriptor + context, concatenated) inside the same training harness, and then switches on one component of the proposed architecture at a time: flat -> AGILE-equivalent reference +set -> adds the hierarchical formulation set and its attention pooling +set+bias -> adds the pairwise physical interaction bias +rank -> adds the within-study pairwise ranking loss Running the ladder on the same fold answers the only question that matters for the architecture: *which component costs cross-study accuracy?* """ from __future__ import annotations from typing import Sequence import torch import torch.nn as nn import torch.nn.functional as F from ..featurize import ATOM_DIM, BOND_DIM from ..store import FeatureStore from ..trainer import NeuralModel, TrainConfig from .backbone import FormulationEncoder from .blocks import GINEEncoder class ProbeModule(nn.Module): def __init__(self, desc_dim: int, ctx_dim: int, fp_dim: int, hidden: int = 192, desc_hidden: int = 128, dropout: float = 0.1, use_set: bool = False, use_bias: bool = False, lam_rank: float = 0.0, node_mode: str = "fp", rank_gamma: float = 2.0): super().__init__() self.use_set = use_set self.lam_rank = lam_rank self.rank_gamma = rank_gamma self.gnn = GINEEncoder(ATOM_DIM, BOND_DIM, hidden, 3, dropout) self.desc_enc = nn.Sequential( nn.Linear(desc_dim, desc_hidden), nn.SiLU(), nn.Linear(desc_hidden, desc_hidden) ) self.ctx_enc = nn.Sequential(nn.Linear(ctx_dim, 64), nn.SiLU(), nn.Linear(64, 64)) if use_set: self.enc = FormulationEncoder( fp_dim=fp_dim, ctx_dim=ctx_dim, desc_dim=desc_dim, d_model=hidden, n_heads=6, n_layers=3, dropout=dropout, use_physics=use_bias, cond_mode="concat", node_mode=node_mode, ) head_in = self.enc.out_dim + hidden + desc_hidden + 64 else: head_in = hidden + desc_hidden + 64 self.head = nn.Sequential( nn.Linear(head_in, 256), nn.SiLU(), nn.Dropout(dropout), nn.Linear(256, 1) ) def forward(self, batch): zs = self.gnn(batch["graph"]) zd = self.desc_enc(batch["desc"]) zc = self.ctx_enc(batch["ctx"]) parts = [zs, zd, zc] if self.use_set: e = self.enc.encode(batch) parts = [e["z_form"], e["g_il"], e["d_il"]] + parts return {"y_hat": self.head(torch.cat(parts, dim=-1)).squeeze(-1)} def compute_loss(self, batch, out, epoch=0, n_epochs=1): reg = F.mse_loss(out["y_hat"], batch["y"]) if self.lam_rank <= 0: return reg, {"mse": float(reg.detach())} study = batch["study_id"] same = study[:, None] == study[None, :] diff = batch["y"][:, None] - batch["y"][None, :] valid = same & (diff > 1e-4) if not bool(valid.any()): return reg, {"mse": float(reg.detach())} pd_ = out["y_hat"][:, None] - out["y_hat"][None, :] rank = F.softplus(-self.rank_gamma * pd_[valid]).mean() return reg + self.lam_rank * rank, {"mse": float(reg.detach()), "rank": float(rank.detach())} class _Probe(NeuralModel): kwargs_default: dict = {} def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module: kw = dict(self.kwargs_default) kw.update(self.kwargs) return ProbeModule( desc_dim=store.il_desc.shape[1], ctx_dim=store.ctx_dim, fp_dim=store.il_fp.shape[1], **kw, ) def need(self) -> Sequence[str]: base = ("y", "ctx", "desc", "graph", "study_id") if self.kwargs_default.get("use_set") or self.kwargs.get("use_set"): return base + ("ratios", "nodes", "helpers") return base class ProbeFlat(_Probe): name = "probe_flat" kwargs_default = {"use_set": False, "use_bias": False, "lam_rank": 0.0} class ProbeSet(_Probe): name = "probe_set" kwargs_default = {"use_set": True, "use_bias": False, "lam_rank": 0.0} class ProbeSetBias(_Probe): name = "probe_set_bias" kwargs_default = {"use_set": True, "use_bias": True, "lam_rank": 0.0} class ProbeSetBiasRank(_Probe): name = "probe_set_bias_rank" kwargs_default = {"use_set": True, "use_bias": True, "lam_rank": 0.5} class ProbePhysSet(_Probe): """Identity-free set: nodes carry physics only, plus the graph embedding.""" name = "probe_physset" kwargs_default = {"use_set": True, "use_bias": True, "lam_rank": 0.0, "node_mode": "phys"} class ProbePhysSetRank(_Probe): name = "probe_physset_rank" kwargs_default = {"use_set": True, "use_bias": True, "lam_rank": 0.5, "node_mode": "phys"} class ProbeFlatRank(_Probe): name = "probe_flat_rank" kwargs_default = {"use_set": False, "use_bias": False, "lam_rank": 0.5}