Download runtime/code/whisper_synth/src/direction2/boundary2_A_nets2.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 36.5 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/boundary2_A_nets2.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/boundary2_A_nets2.py
-
curl -L -o boundary2_A_nets2.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/boundary2_A_nets2.py
36.5 kB
| """boundary2 designer A, round 2 (2026-11-18 ~18:00, replacement agent): INTERFACE-AWARE rim loss. | |
| New file (round-1 trainers in boundary2_A_nets.py are untouched). Shim: src/nnUNet/nnunetv2/training/nnUNetTrainer/ | |
| nnUNetTrainer_D2Boundary2A2.py. Log: outputs/direction2/boundary2/A_LOG.md. | |
| Motivation (FORENSICS items 2-4): the missed rim of 5-30 mL lesions is the WM-FACING outer ~1 mm (pooled offset WM-facing -1.0 mm, | |
| GM-facing -0.5 mm) while deep-CSF (ventricle) interfaces sit +0.1-0.2 mm OUTSIDE GT (leak). The bias has opposite sign per interface, | |
| so no uniform offset / threshold / size gate can fix it (Agate negative). Here the loss knows the interface: | |
| - InterfaceClassTransform (right after the prompt transform, on the UN-augmented T1): for the target lesion, local core | |
| intensity (median of the eroded lesion) and local NAWM proxy (median of the bright half of a 3-8 voxel shell, as in | |
| FaintLesionTransform); relative contrast f = (T1s - core) / (NAWM - core) (T1s = gauss 0.7 smoothed). Outer ring (2 voxels | |
| outside GT, brain, not another lesion) classes: WM-like f >= 0.7, CSF-like f <= 0.2, else intermediate (GM / partial volume). | |
| Inner rim (2 voxels inside GT) voxels take the class of their nearest outer-ring voxel. | |
| Codes: 1 = WM-facing inner rim (GT, the missed rim), 2 = CSF-like outer ring (not GT, the ventricle / sulcal leak), | |
| 3 = CSF-facing inner rim, 4 = WM-like outer ring (diagnostics only). Low-contrast lesions (NAWM - core < 0.3 sd) get no codes. | |
| - InterfaceAppendTransform appends the codes as the LAST segmentation channel (after the SDF channel if any), before mirroring. | |
| - Loss = BdALoss + W_IFACE * (L_wm + L_csf), two BALANCED, interface-specific boundary-band cross-entropies with ASYMMETRIC costs: | |
| L_wm = sum(A_FN_WM * -log p [code 1] + A_FP_WM * -log(1-p) [code 4]) / n(code 1 + code 4) (WM interface band) | |
| L_csf = sum(A_FN_CSF * -log p [code 3] + A_FP_CSF * -log(1-p) [code 2]) / n(code 2 + code 3) (CSF interface band) | |
| per sample, averaged over samples that have the band; full-resolution head; ignore voxels excluded. With cost ratio | |
| FN:FP = 1.5:1 the band's Bayes threshold moves 0.5 -> 0.4 on the WM side (include ambiguous rim, Dice-optimal for p >~ Dice/2) | |
| and 0.5 -> 0.6 on the CSF side (cut the ventricle leak). A one-sided rim term was rejected after the first smoke (-log p on | |
| the WM rim alone = a ~500x up-weight of ~500 rim voxels vs the 96^3 CE, with no counterweight on the indistinguishable WM | |
| outside -> would dilate into WM everywhere). Only re-weights voxels whose label is known; no label change, no cohort fitting. | |
| A7b nnUNetTrainer_BdA7bFaint = A0 + faint-lesion training (confidence arm, no SDF / size package). | |
| A8 nnUNetTrainer_BdA8Iface = A0 (crop control) + interface loss (W_IFACE 0.3, FN:FP 1.5:1 WM side, 1:1.5 CSF side). vs A0 (matched). | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import sys as _sys | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from torch import nn | |
| _D2 = str(Path(__file__).resolve().parent) | |
| if _D2 not in _sys.path: | |
| _sys.path.insert(0, _D2) | |
| import boundary2_A_nets as A1N # noqa: E402 | |
| from boundary2_A_nets import (_BdABase, _smoke, SDFTargetTransform, ExtremeBreadthTransform, FaintLesionTransform, # noqa: E402 | |
| IGNORE) | |
| from cascade2_prompt2 import PromptCropTransform # noqa: E402 | |
| from batchgeneratorsv2.transforms.base.basic_transform import BasicTransform # noqa: E402 | |
| IFACE_KEY = "_bda_iface" | |
| def interface_codes(x, s0, ring=2, f_wm=0.7, f_csf=0.2, min_contrast=0.3, smooth=0.7): | |
| """x: T1 (patch, z-scored), s0: segmentation channel 0 (1 = target, 0 = bg, -1 = outside brain, others = ignore/other). | |
| -> int16 codes (see module docstring).""" | |
| import scipy.ndimage as ndi | |
| out = np.zeros(s0.shape, np.int16) | |
| m = s0 == 1 | |
| if m.sum() < 3: | |
| return out | |
| idx = np.argwhere(m); lo = np.maximum(idx.min(0) - 12, 0); hi = np.minimum(idx.max(0) + 13, m.shape) | |
| sl = tuple(slice(a, b) for a, b in zip(lo, hi)) | |
| mm = m[sl]; sb = s0[sl]; bb = sb != -1 | |
| xs = ndi.gaussian_filter(x[sl].astype(np.float32), smooth) | |
| d_out = ndi.distance_transform_edt(~mm); d_in = ndi.distance_transform_edt(mm) | |
| shell = (d_out >= 3) & (d_out <= 8) & bb & (sb == 0) | |
| if shell.sum() < 20: | |
| return out | |
| sv = xs[shell]; ref = float(np.median(sv[sv >= np.median(sv)])) | |
| cm = ndi.binary_erosion(mm) | |
| core = float(np.median(xs[cm] if cm.sum() >= 3 else xs[mm])) | |
| if ref - core < min_contrast: | |
| return out | |
| f = (xs - core) / (ref - core) | |
| rg = (~mm) & (d_out <= ring) & bb & (sb == 0) | |
| if not rg.any(): | |
| return out | |
| cls = np.zeros(mm.shape, np.int8) | |
| cls[rg & (f >= f_wm)] = 1 | |
| cls[rg & (f <= f_csf)] = 2 | |
| cls[rg & (f > f_csf) & (f < f_wm)] = 3 | |
| inner = mm & (d_in <= ring) | |
| _d, ind = ndi.distance_transform_edt(~rg, return_indices=True) | |
| near = cls[tuple(ind)] | |
| o = np.zeros(mm.shape, np.int16) | |
| o[inner & (near == 1)] = 1 | |
| o[rg & (cls == 2)] = 2 | |
| o[inner & (near == 2)] = 3 | |
| o[rg & (cls == 1)] = 4 | |
| out[sl] = o | |
| return out | |
| class InterfaceClassTransform(BasicTransform): | |
| def __init__(self, **kw): | |
| super().__init__(); self.kw = kw | |
| def apply(self, data_dict, **params): | |
| seg = data_dict.get("segmentation") | |
| img = data_dict["image"] | |
| if seg is None: | |
| data_dict[IFACE_KEY] = np.zeros(tuple(img.shape[1:]), np.int16) | |
| return data_dict | |
| data_dict[IFACE_KEY] = interface_codes(img[0].numpy(), seg[0].numpy(), **self.kw) | |
| return data_dict | |
| class InterfaceAppendTransform(BasicTransform): | |
| def apply(self, data_dict, **params): | |
| seg = data_dict.get("segmentation") | |
| ifc = data_dict.pop(IFACE_KEY, None) | |
| if seg is None: | |
| return data_dict | |
| if ifc is None or tuple(ifc.shape) != tuple(seg.shape[1:]): | |
| ifc = np.zeros(tuple(seg.shape[1:]), np.int16) | |
| data_dict["segmentation"] = torch.cat([seg, torch.from_numpy(ifc)[None].to(seg.dtype)], 0) | |
| return data_dict | |
| class IfaceLoss(nn.Module): | |
| """wraps a BdALoss (inner) and adds the interface term; exposes inner.acc / inner.base (used by the trainers).""" | |
| def __init__(self, inner, iface_ch, w=0.3, costs=(1.5, 1.0, 1.0, 1.5), n_cls=3): | |
| super().__init__() | |
| self.inner, self.iface_ch, self.w, self.costs, self.n_cls = inner, iface_ch, w, costs, n_cls | |
| def acc(self): | |
| return self.inner.acc | |
| def acc(self, v): | |
| self.inner.acc = v | |
| def base(self): | |
| return self.inner.base | |
| def _log(self, k, v): | |
| return self.inner._log(k, v) | |
| def _pmean(self, x, w): | |
| num = (x * w).flatten(1).sum(1); den = w.flatten(1).sum(1); ok = den > 0 | |
| return (num[ok] / den[ok]).mean() if bool(ok.any()) else None | |
| def forward(self, outputs, targets): | |
| loss = self.inner(outputs, targets) | |
| lst = isinstance(outputs, (list, tuple)) | |
| o0 = outputs[0] if lst else outputs | |
| t0 = targets[0] if lst else targets | |
| if t0.shape[1] <= self.iface_ch: | |
| return loss | |
| ic = t0[:, self.iface_ch].round().long() | |
| valid = (t0[:, 0] != IGNORE) | |
| ls = torch.log_softmax(o0[:, :self.n_cls].float(), 1) | |
| logp = ls[:, 1] | |
| log1mp = torch.logsumexp(torch.cat([ls[:, :1], ls[:, 2:]], 1), 1) | |
| fn_wm, fp_wm, fn_csf, fp_csf = self.costs | |
| m = {c: ((ic == c) & valid).float() for c in (1, 2, 3, 4)} | |
| for nm, ci, co, a_fn, a_fp in (("if_wm", 1, 4, fn_wm, fp_wm), ("if_csf", 3, 2, fn_csf, fp_csf)): | |
| num = (a_fn * (-logp) * m[ci] + a_fp * (-log1mp) * m[co]).flatten(1).sum(1) | |
| den = (m[ci] + m[co]).flatten(1).sum(1); ok = den > 0 | |
| if bool(ok.any()): | |
| lt = (num[ok] / den[ok]).mean() | |
| loss = loss + self.w * lt; self.inner._log(nm, lt.detach()) | |
| with torch.no_grad(): | |
| p = logp.exp() | |
| for c, nm in ((1, "p_wmrim"), (2, "p_csfout"), (3, "p_csfrim"), (4, "p_wmout")): | |
| w = ((ic == c) & valid).float() | |
| if bool(w.sum() > 0): | |
| self.inner._log(nm, (p * w).sum() / w.sum()) | |
| return loss | |
| class _IfaceMixin: | |
| W_IFACE = 0.3 | |
| COSTS = (1.5, 1.0, 1.0, 1.5) # FN / FP on the WM band, FN / FP on the CSF band | |
| IFACE_KW = {} | |
| def get_training_transforms(self, *args, **kwargs): | |
| c = super().get_training_transforms(*args, **kwargs) | |
| ip = next(i for i, t in enumerate(c.transforms) if isinstance(t, PromptCropTransform)) | |
| c.transforms.insert(ip + 1, InterfaceClassTransform(**self.IFACE_KW)) | |
| kinds = (PromptCropTransform, InterfaceClassTransform, FaintLesionTransform, ExtremeBreadthTransform, SDFTargetTransform) | |
| last = max(i for i, t in enumerate(c.transforms) if isinstance(t, kinds)) | |
| c.transforms.insert(last + 1, InterfaceAppendTransform()) | |
| return c | |
| def _build_loss(self): | |
| inner = super()._build_loss() | |
| ch = 3 if self.N_EXTRA_OUT else 2 | |
| self.print_to_log_file(f"BdA8 interface loss: W_IFACE {self.W_IFACE} costs {self.COSTS} iface channel {ch} {self.IFACE_KW}") | |
| return IfaceLoss(inner, ch, self.W_IFACE, self.COSTS, n_cls=self.label_manager.num_segmentation_heads) | |
| class nnUNetTrainer_BdA8Iface(_IfaceMixin, _BdABase): | |
| """A8 = A0 crop control + interface-aware rim loss (see module docstring).""" | |
| class nnUNetTrainer_BdA7bFaint(_BdABase): | |
| """A7b = A0 crop control + FAINT-LESION training only (FaintLesionTransform p 0.7, contrast kept U(0.3, 1), smooth falloff, | |
| label fixed) = the user's CONFIDENCE arm WITHOUT A3's SDF / size package (A3's val pseudo-Dice on held-out real CONTRA | |
| collapsed to 0.03-0.30 vs A0 0.55-0.73 by epoch 36, so A7 = A3 + faint was not run). Matched control: A0.""" | |
| FAINT = True | |
| # ============================================================================== A9 size-balanced component sampling | |
| import cascade2_common as _C # noqa: E402 | |
| from cascade2_nnunet import C2DataLoader # noqa: E402 | |
| # (lo voxels, hi voxels, quota): 1 mm grid, voxels ~ uL. Default C2PCrop recipe (alpha 0.5, floor 0.1 mL) gives | |
| # <0.1 mL 51 %, 0.1-1 mL 41 %, 1-5 mL 5.4 %, 5-30 mL 1.8 %, >30 mL 0.7 % of component-centred crops (ATLAS pool, 1622 comps). | |
| SIZE_QUOTAS = ((0, 100, 0.15), (100, 1000, 0.25), (1000, 5000, 0.25), (5000, 30000, 0.25), (30000, 1 << 40, 0.10)) | |
| class QuotaLoader(C2DataLoader): | |
| """C2DataLoader with explicit size-bin quotas for the component draw (uniform within a bin) and, for components | |
| >= centre_min voxels (1 mL), the crop centred on the member voxel nearest the component's member-sample mean (comp_table | |
| keeps up to 16 random member voxels) instead of a random member, so 1-30+ mL lesions are fully inside the 96^3 crop | |
| whenever their extent allows (+-48 mm from the centroid). The centre is always a lesion voxel, so PromptCropTransform still | |
| picks this component as the target.""" | |
| def __init__(self, *args, quotas=SIZE_QUOTAS, centre_min=1000, **kwargs): | |
| super().__init__(*args, **kwargs) | |
| self.centre_min = centre_min | |
| for f, (items, _p) in list(self.pools.items()): | |
| vox = np.array([self.comp_table[_C.base_key(k)[1]][ci][0] for k, ci in items], float) | |
| w = np.zeros(len(items)) | |
| for lo, hi, q in quotas: | |
| m = (vox >= lo) & (vox < hi) | |
| if m.any(): | |
| w[m] = q / m.sum() | |
| self.pools[f] = (items, w / w.sum()) | |
| def draw(self): | |
| g = self.groups[np.random.choice(len(self.groups), p=self.gp)] | |
| f = g[0] | |
| if self.p_comp > 0 and f in self.pools and np.random.uniform() < self.p_comp: | |
| items, p = self.pools[f] | |
| k, ci = items[np.random.choice(len(items), p=p)] | |
| c = self.comp_table[_C.base_key(k)[1]][ci] | |
| mem = np.asarray(c[1]) | |
| if c[0] >= self.centre_min and len(mem) > 1: | |
| ctr = mem[int(np.argmin(((mem - mem.mean(0)) ** 2).sum(1)))] | |
| else: | |
| ctr = mem[np.random.randint(len(mem))] | |
| return k, [int(x) for x in ctr], False | |
| k = g[2][np.random.randint(len(g[2]))] | |
| force_fg = (np.random.uniform() < self.oversample_foreground_percent) if self.p_comp == 0 else False | |
| return k, None, force_fg | |
| class nnUNetTrainer_BdA9SzSample(_BdABase): | |
| """A9 = A0 crop control + SIZE-BALANCED SAMPLING ONLY (user priority 2026-11-18 ~20:10: 1-30 mL lesions are hard to draw and | |
| under-represented). Same loss as A0 (no SDF, no volume term, batch Dice as A0); component draw by explicit quotas | |
| <0.1 mL 15 % / 0.1-1 mL 25 % / 1-5 mL 25 % / 5-30 mL 25 % / >30 mL 10 %; crops of >= 1 mL components centred near the | |
| component centroid. Isolates A3's sampling factor. Matched control: A0.""" | |
| QUOTAS = SIZE_QUOTAS | |
| def _loader(self, ds, patch, final, transforms, train): | |
| if not train: | |
| return super()._loader(ds, patch, final, transforms, train) | |
| return QuotaLoader(ds, self.batch_size, patch, final, self.label_manager, self.oversample_foreground_percent, | |
| transforms, groups=self.GROUPS, comp_table=self._comp_table(), | |
| alpha=self.ALPHA, p_comp=self.P_COMP, min_vox=self.MIN_VOX, vol_floor=self.VOL_FLOOR, | |
| override=self._override_fn(), require_override=self.REQUIRE_OVERRIDE, | |
| render_hook=self._render_hook(), timing_log=self._timing_log(), | |
| decoy_codes=self._decoy_codes(), quotas=self.QUOTAS) | |
| # ============================================================================== A3m: A3 package on ALL conventions | |
| class nnUNetTrainer_BdA3mSDFSzMix(A1N.nnUNetTrainer_BdA3SDFSz): | |
| """A3m = A3 (SDF + size-aware package, seg decoder at test) trained on ALL stage-2 conventions like B0 / p2ballms: | |
| T1 family (ATLAS 655 + acute 397) 0.75 and real CONTRA (58, FLAIR-traced) 0.25 (C2Del default), minus the one non-test LAB | |
| case (syn_t1_lab_*: keeps LAB a pure generalisation guard; the mixed baselines include it). No provenance token (pilot). | |
| Question: does mixed-convention training fix the ATLAS-only arms' NORTH 5-30 mL under-drawing (vol .49 vs .74) without | |
| losing ATLAS-43 / LAB? vs A3 (ATLAS-only).""" | |
| GROUPS = {"t1": 0.75, "real": 0.25} | |
| def do_split(self): | |
| tr, va = super(_BdABase, self).do_split() | |
| tr2 = [k for k in tr if not k.startswith("syn_t1_lab_")] | |
| if not getattr(self, "_bda_logged", False): | |
| fam = {} | |
| for k in tr2: | |
| f = k.split("_sub")[0] if "_sub" in k else "_".join(k.split("_")[:2]) | |
| fam[f] = fam.get(f, 0) + 1 | |
| self.print_to_log_file(f"BdA3m: ALL conventions minus LAB: {len(tr2)} of {len(tr)} training keys {fam}; GROUPS {self.GROUPS}") | |
| self._bda_logged = True | |
| return tr2, va | |
| # ============================================================================== NO-VETO core-presence loss | |
| class CoreLoss(nn.Module): | |
| """user directive 2026-11-19 00:00 "the drawer has NO VETO, just draw": wraps a BdALoss and adds, per crop (= one prompted | |
| target lesion, seg channel 0 == 1), a CORE-PRESENCE hinge on the top-k mean of p(lesion) over the target's voxels, | |
| k = max(3, ceil(frac * n_target)): L = relu(log(tau) - log(topk_mean)). Unlike the inherited Kervadec term (mean p over the | |
| whole component >= 0.5, w 0.2, which a confident under-draw of a faint rim can satisfy or a faint lesion can fail softly), this | |
| asks that at least the core (most lesion-like ~30 %) is drawn CONFIDENTLY (p >= tau) at every prompt.""" | |
| def __init__(self, inner, w=1.0, tau=0.8, frac=0.3, n_cls=3): | |
| super().__init__() | |
| self.inner, self.w, self.tau, self.frac, self.n_cls = inner, w, tau, frac, n_cls | |
| def acc(self): | |
| return self.inner.acc | |
| def acc(self, v): | |
| self.inner.acc = v | |
| def base(self): | |
| return self.inner.base | |
| def _log(self, k, v): | |
| return self.inner._log(k, v) | |
| def forward(self, outputs, targets): | |
| loss = self.inner(outputs, targets) | |
| lst = isinstance(outputs, (list, tuple)) | |
| o0 = outputs[0] if lst else outputs | |
| t0 = targets[0] if lst else targets | |
| p = torch.softmax(o0[:, :self.n_cls].float(), 1)[:, 1].flatten(1) | |
| tg = (t0[:, 0] == 1).flatten(1) | |
| terms, fails = [], 0 | |
| for b in range(p.shape[0]): | |
| n = int(tg[b].sum()) | |
| if n == 0: | |
| continue | |
| k = max(3, int(np.ceil(self.frac * n))); k = min(k, n) | |
| tm = torch.topk(p[b][tg[b]], k).values.mean() | |
| terms.append(torch.relu(np.log(self.tau) - torch.log(tm + 1e-6))) | |
| fails += int(float(tm) < 0.5) | |
| if terms: | |
| lc = torch.stack(terms).mean() | |
| loss = loss + self.w * lc | |
| self.inner._log("core", lc.detach()); self.inner._log("core_fail", fails / len(terms)) | |
| return loss | |
| class _CoreMixin: | |
| W_CORE, CORE_TAU, CORE_FRAC = 1.0, 0.8, 0.3 | |
| def _build_loss(self): | |
| inner = super()._build_loss() | |
| self.print_to_log_file(f"BdA no-veto core loss: W {self.W_CORE} tau {self.CORE_TAU} frac {self.CORE_FRAC}") | |
| return CoreLoss(inner, self.W_CORE, self.CORE_TAU, self.CORE_FRAC, n_cls=self.label_manager.num_segmentation_heads) | |
| class nnUNetTrainer_BdA10Core(_CoreMixin, A1N.nnUNetTrainer_BdA3SDFSz): | |
| """A10 = A3 package (current best A arm) + NO-VETO core-presence loss (W 1.0, top-30 % mean p >= 0.8 at every prompt).""" | |
| nnUNetTrainer_BdA8Iface_Smoke = _smoke(nnUNetTrainer_BdA8Iface) | |
| nnUNetTrainer_BdA10Core_Smoke = _smoke(nnUNetTrainer_BdA10Core) | |
| nnUNetTrainer_BdA3mSDFSzMix_Smoke = _smoke(nnUNetTrainer_BdA3mSDFSzMix) | |
| nnUNetTrainer_BdA9SzSample_Smoke = _smoke(nnUNetTrainer_BdA9SzSample) | |
| nnUNetTrainer_BdA7bFaint_Smoke = _smoke(nnUNetTrainer_BdA7bFaint) | |
| # ============================================================================== re-seeds (drawer analyst 2026-11-19) | |
| class nnUNetTrainer_BdA3SDFSz_s2(A1N.nnUNetTrainer_BdA3SDFSz): | |
| """A3 re-seed (identical recipe, new output folder; nnU-Net does not fix seeds -> independent run). Paired A3 - p2ballms | |
| differences sit at the .01-.04 level, so selection needs seed variance.""" | |
| from cascade2_prompt2 import nnUNetTrainer_C2PBallMS as _C2PBallMS # noqa: E402 | |
| class nnUNetTrainer_C2PBallMS_s2(_C2PBallMS): | |
| """p2ballms re-seed (identical recipe: C2PBallMS, mixed conventions, 150 epochs; new output folder).""" | |
| # ============================================================================== A11: SCALE + WHOLE-LESION CONTEXT (bold, 2026-11-19 14:xx) | |
| class nnUNetTrainer_BdA11Scale(A1N.nnUNetTrainer_BdA3SDFSz): | |
| """A11 = the best A recipe (A3: signed-distance head + size-aware package, seg decoder) at p2ballms SCALE and with | |
| WHOLE-LESION CONTEXT: | |
| - ALL conventions (t1 ATLAS + acute 0.75, real CONTRA 0.25, minus the non-test LAB key) - fixes the ATLAS-only arms' NORTH | |
| 5-30 mL under-draw (vol .49 vs mixed .68-.74); | |
| - 150 epochs (p2ballms schedule; the 50-epoch pilots under-train); | |
| - 128^3 crops (batch 6): >= 30 mL lesions (where crop drawers lose to whole-volume drawers, .838-.856 vs .873-.876) fit with | |
| context, and >= 1 mL crops are centred near the lesion centroid (A9 QuotaLoader centring, A3's sampling weights kept). | |
| Expected source of gain (drawer analyst error anatomy): big-lesion under-draw and medium thick-chunk misses that need | |
| whole-lesion context; NORTH medium under-draw (mixed data); training length (A3 50 ep -> p2ballms 150 ep gap).""" | |
| EPOCHS = 150 | |
| CROP_PATCH = (128, 128, 128) | |
| CROP_BS = 6 | |
| GROUPS = {"t1": 0.75, "real": 0.25} | |
| def do_split(self): | |
| return _MixMixin.do_split(self) | |
| def _loader(self, ds, patch, final, transforms, train): | |
| if not train: | |
| return super()._loader(ds, patch, final, transforms, train) | |
| # A3's own sampling weights (alpha 0.25, floor 1 mL), with centroid-near centring for >= 1 mL components | |
| q = QuotaLoader.__new__(QuotaLoader) | |
| C2DataLoader.__init__(q, ds, self.batch_size, patch, final, self.label_manager, self.oversample_foreground_percent, | |
| transforms, groups=self.GROUPS, comp_table=self._comp_table(), alpha=self.ALPHA, p_comp=self.P_COMP, | |
| min_vox=self.MIN_VOX, vol_floor=self.VOL_FLOOR, override=self._override_fn(), | |
| require_override=self.REQUIRE_OVERRIDE, render_hook=self._render_hook(), timing_log=self._timing_log(), | |
| decoy_codes=self._decoy_codes()) | |
| q.centre_min = 1000 | |
| return q | |
| # ============================================================================== p2heatP: p2heat with PURE-detector heat | |
| from cascade2_prompt import nnUNetTrainer_C2PHeat as _C2PHeat # noqa: E402 | |
| PURE_HEAT_TAG = "det3_ivT_x" | |
| class nnUNetTrainer_C2PHeatP(_C2PHeat): | |
| """p2heatP (user-approved 2026-11-21, purity fix): IDENTICAL recipe to p2heat (nnUNetTrainer_C2PHeat: Dataset979 fold | |
| c2s2x_detA_ii_x keys, 20 held-out CONTRA, D331 warm start, 150 ep, heat-encoding prompts, bank heat + UPI ignore), but every | |
| heat comes from the PURE renderer-only ivT detector instead of the legacy MIX detector detA_ii (trained on G1 synthetic FLAIR, | |
| whose generator saw 22/26 LAB test cases): | |
| - T1-family keys: renderer heat bank HEAT_OOF/det3_ivT_x_cg_s{1,2,3} (ivT 3-fold OOF, online renderer, 3 seeds; | |
| boundary2_A_heatbank.py) instead of detA_ii_x_cg_s{1,2,3}; | |
| - CONTRA keys: real-FLAIR ivT OOF heat HEAT_OOF/det3_ivT_x instead of detA_ii_x. | |
| C2_HEAT_TAG is forced to det3_ivT_x for this trainer's process only (the Dataset979 split name stays c2s2x_detA_ii_x = same keys).""" | |
| def __init__(self, plans, configuration, fold, dataset_json, device=torch.device("cuda")): | |
| os.environ["C2_HEAT_TAG"] = PURE_HEAT_TAG | |
| super().__init__(plans, configuration, fold, dataset_json, device) | |
| assert self.heat_tag == PURE_HEAT_TAG, self.heat_tag | |
| # ============================================================================== p2heatK / p2heatE (PI-approved 2026-11-21) | |
| from cascade2_prompt import nnUNetTrainer_C2PHeatK as _C2PHeatK # noqa: E402 | |
| class nnUNetTrainer_C2PHeatKP(_C2PHeatK): | |
| """p2heatK (DRAWER GENERALISATION PLAN, PI 2026-11-21): p2heat + the ALWAYS-DRAW term (Kervadec-style log hinge, mean | |
| p_lesion >= 0.5 inside every prompted GT component, W_K 0.2 = nnUNetTrainer_C2PHeatK) on the PURE ivT heat bank (as p2heatP; | |
| G1-free). Same D979 split, 20 held-out CONTRA, D331 warm start, 150 epochs. Goal: stop the LAB speck vetoes | |
| (oracle LAB: p2heat 185/648, p2heatP 250/648 prompts undrawn) without losing borders.""" | |
| def __init__(self, plans, configuration, fold, dataset_json, device=torch.device("cuda")): | |
| os.environ["C2_HEAT_TAG"] = PURE_HEAT_TAG | |
| super().__init__(plans, configuration, fold, dataset_json, device) | |
| assert self.heat_tag == PURE_HEAT_TAG and self.W_K == 0.2, (self.heat_tag, self.W_K) | |
| EV_OOF = Path("/__EAGLE_BUNDLE_ROOT__/whisper_synth/outputs/direction2/classifier4/B/oof_ev/c2t") | |
| EV_SCALE = 250.0 | |
| class _EvStack: | |
| """lazy (C+1)-channel view of a case: nnU-Net data channels + the c2t evidence map (uint8 x250 b2nd on the same stage-2 | |
| preprocessed grid; zeros when the key has none, e.g. val_ monitors). Only slicing is materialised (crop_and_pad_nd).""" | |
| def __init__(self, data, ev_path): | |
| self.data, self.ev_path = data, ev_path | |
| self.shape = (data.shape[0] + 1, *data.shape[1:]) | |
| self.dtype = np.float32 | |
| self.ndim = len(self.shape) | |
| def __getitem__(self, sl): | |
| from cascade2_nnunet import _open_b2nd | |
| a = np.asarray(self.data[sl], dtype=np.float32) | |
| sp = tuple(sl[1:]) if isinstance(sl, tuple) else () | |
| if self.ev_path is not None: | |
| ev = _open_b2nd(self.ev_path) | |
| assert tuple(ev.shape) == tuple(self.shape[1:]), f"evidence {self.ev_path} {ev.shape} != data {self.shape[1:]}" | |
| e = np.asarray(ev[sp], dtype=np.float32) / EV_SCALE | |
| else: | |
| e = np.zeros(a.shape[1:], np.float32) | |
| return np.concatenate([a, e[None]], 0) | |
| class _EvDataset: | |
| def __init__(self, inner, ev_fn): | |
| self._inner, self._ev_fn = inner, ev_fn | |
| def __getattr__(self, n): | |
| return getattr(self._inner, n) | |
| def __getitem__(self, k): | |
| return self._inner[k] | |
| def __len__(self): | |
| return len(self._inner) | |
| def load_case(self, k): | |
| data, seg, seg_prev, props = self._inner.load_case(k) | |
| return _EvStack(data, self._ev_fn(k)), seg, seg_prev, props | |
| class nnUNetTrainer_C2PHeatE(nnUNetTrainer_C2PHeatP): | |
| """p2heatE (DRAWER GENERALISATION PLAN, PI 2026-11-21): EVIDENCE-AWARE drawer = p2heatP's recipe (pure ivT heat bank, | |
| heat prompts, D331 warm start, 150 ep) + a THIRD input channel = the c2t classifier evidence map (prob x250 -> [0, 1]). | |
| LEAKAGE: c2t was trained on the same patients as the T1 keys, so training reads OUT-OF-FOLD c2t maps (classifier4 builder | |
| B: c2t_f<f> trained on the other two cascade2 patient folds, applied to fold f; CONTRA: the full c2t, which never saw | |
| CONTRA) from EV_OOF/<key>.b2nd. Inference (DEV-A / test): the full c2t model's maps. The evidence stem starts from noise | |
| (A2S warm start 1 -> 3 channels, N(0, (0.5 sd_T1stem)^2), like the heat stem). val_ monitor keys: evidence 0. | |
| Inference: call prep_predictor_E(predictor) once (adds a NoNormalization scheme for channel 2) and feed (T1, prompt, ev).""" | |
| N_IN = 3 | |
| EV_DIR = EV_OOF | |
| def build_network_architecture(plans_manager, configuration_manager, num_input_channels, num_output_channels, | |
| enable_deep_supervision: bool = True): | |
| return nnUNetTrainer_C2PHeatP.build_network_architecture(plans_manager, configuration_manager, 3, num_output_channels, | |
| enable_deep_supervision) | |
| def initialize(self): | |
| super().initialize() | |
| self.num_input_channels = self.N_IN | |
| def _ev_fn(self): | |
| d = self.EV_DIR; allow = os.environ.get("C2E_ALLOW_MISSING", "0") == "1" | |
| def f(key): | |
| if str(key).startswith("val_"): | |
| return None | |
| p = d / f"{key}.b2nd" | |
| if p.exists(): | |
| return str(p) | |
| if allow: | |
| return None | |
| raise RuntimeError(f"p2heatE: no OOF evidence map for {key} in {d}") | |
| return f | |
| def _loader(self, ds, patch, final, transforms, train): | |
| dl = super()._loader(ds, patch, final, transforms, train) | |
| dl._data = _EvDataset(dl._data, self._ev_fn()) | |
| return dl | |
| def do_split(self): | |
| tr, va = super().do_split() | |
| if os.environ.get("C2E_ALLOW_MISSING", "0") != "1": | |
| miss = [k for k in tr if not (self.EV_DIR / f"{k}.b2nd").exists()] | |
| assert not miss, f"p2heatE: {len(miss)} of {len(tr)} training keys lack OOF c2t evidence in {self.EV_DIR}: {miss[:5]}" | |
| return tr, va | |
| def prep_predictor_E(pr): | |
| """nnU-Net predictor for nnUNetTrainer_C2PHeatE: the D979 plans list 2 normalisation schemes; channel 2 (evidence in [0, 1]) | |
| is fed un-normalised like the heat channel.""" | |
| c = pr.configuration_manager.configuration | |
| if len(c["normalization_schemes"]) == 2: | |
| c["normalization_schemes"] = list(c["normalization_schemes"]) + ["NoNormalization"] | |
| c["use_mask_for_norm"] = list(c["use_mask_for_norm"]) + [False] | |
| return pr | |
| # ============================================================================== round-3 COMBINATION factory | |
| class _MixMixin: | |
| """all stage-2 conventions (t1 ATLAS + acute 0.75, real CONTRA 0.25) minus the non-test LAB key (as A3m).""" | |
| GROUPS = {"t1": 0.75, "real": 0.25} | |
| def do_split(self): | |
| tr, va = super(_BdABase, self).do_split() | |
| tr2 = [k for k in tr if not k.startswith("syn_t1_lab_")] | |
| if not getattr(self, "_bda_logged", False): | |
| self.print_to_log_file(f"BdAX mixed: {len(tr2)} of {len(tr)} training keys; GROUPS {self.GROUPS}") | |
| self._bda_logged = True | |
| return tr2, va | |
| def _ax_class(code): | |
| """code = <base><flags>: base 0 = A0 crop control, 3 = A3 package (SDF + size-aware), 9 = A9 quota sampling; | |
| flags f = faint-lesion, i = interface rim loss, c = no-veto core loss, m = mixed conventions.""" | |
| base = {"0": A1N.nnUNetTrainer_BdA0Crop, "3": A1N.nnUNetTrainer_BdA3SDFSz, "9": nnUNetTrainer_BdA9SzSample}[code[0]] | |
| fl = code[1:] | |
| mix = [] | |
| if "i" in fl: | |
| mix.append(_IfaceMixin) | |
| if "c" in fl: | |
| mix.append(_CoreMixin) | |
| if "m" in fl: | |
| mix.append(_MixMixin) | |
| attrs = {"__module__": __name__, "__doc__": f"round-3 combination {code}: " + _ax_class.__doc__.split(':', 1)[1]} | |
| if "f" in fl: | |
| attrs["FAINT"] = True | |
| return type(f"nnUNetTrainer_BdAX_{code}", tuple(mix) + (base,), attrs) | |
| _AX_CODES = [b + "".join(f) for b in "039" for f in | |
| [(), ("f",), ("i",), ("c",), ("m",), ("f", "i"), ("f", "c"), ("i", "c"), ("f", "m"), ("i", "m"), ("c", "m"), | |
| ("f", "i", "c"), ("f", "i", "m"), ("f", "c", "m"), ("i", "c", "m"), ("f", "i", "c", "m")]] | |
| for _c in _AX_CODES: | |
| _cls = _ax_class(_c) | |
| globals()[_cls.__name__] = _cls | |
| globals()[_cls.__name__ + "_Smoke"] = _smoke(_cls) | |
| nnUNetTrainer_BdA11Scale_Smoke = _smoke(nnUNetTrainer_BdA11Scale) | |
| # ============================================================================== A12: ERROR-ANATOMY REFINER (bold, coarse-to-fine) | |
| class ErrorAnatomyPrevTransform(A1N.PrevEstimateTransform): | |
| """A4's previous-estimate channel, but the simulated first pass reproduces the drawer analyst's ERROR ANATOMY so the refiner | |
| learns to fix exactly those errors from T1 evidence + the first pass's shape (labels untouched): | |
| - medium/large lesions (>= 100 vox), p 0.7: a THICK PERIPHERAL CHUNK is removed (ball around a surface point chosen with | |
| weight ~ T1 brightness inside the lesion = the FAINT side; radius grown until 10-40 % of the lesion is gone, >= 3 vox | |
| thick), then a 0-1 voxel global erosion (conservative edge); lesions > 30 mL: 1-2 voxel erosion (big-lesion under-draw); | |
| - specks (< 100 vox), p 0.6: inflated by 1-2 voxels (speck over-draw 2-4x), else eroded/kept; | |
| - otherwise A4's perturbation (global offset + low-frequency field), empty (p_empty) or ball (p_ball). | |
| prev = sigmoid(-phi_prev / tau), tau U(0.3, 1.0).""" | |
| def __init__(self, p_anat=0.6, **kw): | |
| super().__init__(**kw); self.p_anat = p_anat | |
| def apply(self, data_dict, **params): | |
| import random as _r | |
| import scipy.ndimage as ndi | |
| rng = np.random.default_rng(_r.getrandbits(32)) | |
| seg = data_dict.get("segmentation"); img = data_dict["image"] | |
| if seg is None or rng.uniform() >= self.p_anat: | |
| return super().apply(data_dict, **params) | |
| m = seg[0].numpy() == 1 | |
| n = int(m.sum()) | |
| if n == 0: | |
| return super().apply(data_dict, **params) | |
| mp = m.copy() | |
| if n < 100: | |
| if rng.uniform() < 0.4: | |
| mp = ndi.binary_dilation(m, iterations=int(rng.integers(1, 3))) | |
| elif rng.uniform() < 0.5: | |
| e = ndi.binary_erosion(m); mp = e if e.any() else m | |
| else: | |
| if rng.uniform() < 0.6: | |
| x = img[0].numpy().astype(np.float32) | |
| surf = m & ~ndi.binary_erosion(m) | |
| pts = np.argwhere(surf) | |
| w = x[surf]; w = np.exp((w - w.mean()) / (w.std() + 1e-6)); w = w / w.sum() | |
| c = pts[rng.choice(len(pts), p=w)] | |
| d = np.sqrt(((np.indices(m.shape).reshape(3, -1).T - c) ** 2).sum(1)).reshape(m.shape) | |
| target = float(rng.uniform(0.10, 0.40)) * n | |
| for R in range(3, 40): | |
| cut = m & (d <= R) | |
| if cut.sum() >= target: | |
| break | |
| mp = m & ~cut | |
| # rim corruption SYMMETRIC in expectation (coordinator 22:50: the rim bias is site-dependent - inward on DEV-A / acute / | |
| # LAB, outward on ATLAS-43 / NORTH - so the refiner must learn to READ the T1 edge, not to push outward): | |
| # 1-voxel erosion 35 %, 1-voxel dilation 35 %, none 30 % (lesions > 30 mL: 1-2 voxels either way) | |
| u = rng.uniform(); k = int(rng.integers(1, 3)) if n > 30000 else 1 | |
| if u < 0.35: | |
| for _ in range(k): | |
| e = ndi.binary_erosion(mp) | |
| mp = e if e.sum() > 0.3 * n else mp | |
| elif u < 0.70: | |
| mp = ndi.binary_dilation(mp, iterations=k) | |
| phi = A1N.signed_distance(mp, self.clip + 4) | |
| prev = (1.0 / (1.0 + np.exp(np.clip(phi / float(rng.uniform(0.3, 1.0)), -30, 30)))).astype(np.float32) | |
| data_dict["image"] = torch.cat([img, torch.from_numpy(prev)[None].to(img.dtype)], 0) | |
| return data_dict | |
| class _A12EvoMixin(A1N._EvoMixin): | |
| P_SELF = 0.3 | |
| def get_training_transforms(self, *args, **kwargs): | |
| c = A1N._BdABase.get_training_transforms(self, *args, **kwargs) | |
| idx = next(i for i, t in enumerate(c.transforms) if isinstance(t, PromptCropTransform)) | |
| c.transforms.insert(idx + 1, ErrorAnatomyPrevTransform(p_empty=0.05, p_ball=0.05)) | |
| return c | |
| class nnUNetTrainer_BdA12Refine(_A12EvoMixin, nnUNetTrainer_BdA9SzSample): | |
| """A12 = COARSE-TO-FINE ERROR-ANATOMY REFINER on the A9 recipe (A0 loss + size-quota sampling, ATLAS-only; A9 = best A arm), | |
| 3rd input = a first-pass drawing; trained on simulated first passes with the analyst's error anatomy | |
| (ErrorAnatomyPrevTransform) + 30 % self-feedback (own detached prediction). At test the first pass is a real drawer | |
| (harness INIT_MODEL, default A9), refined K = 3 steps. Gate (coordinator): speck vol ratio in [0.7, 1.5], LAB no-veto | |
| lesion Dice >= .62, worst T1-traced cohort + shift rows.""" | |
| N_EXTRA_OUT = 0 | |
| N_IN_EXTRA = 1 | |
| nnUNetTrainer_BdA12Refine_Smoke = _smoke(nnUNetTrainer_BdA12Refine) | |
| # ============================================================================== A13: RANDOM-INIT twin of A3 (user-approved 2026-11-19) | |
| class nnUNetTrainer_BdA13Rand(A1N.nnUNetTrainer_BdA3SDFSz): | |
| """A13 = A3 recipe (same data, loss, sampling, 50 epochs, full LR from epoch 0) with RANDOM INITIALISATION instead of the D331 | |
| warm start. Rationale ("D331 does too much"): the top drawer error = thick FAINT chunks of medium lesions left out, a | |
| D331-like conservatism; D331 warm starts are known to make the T1 path dominate. Twin: A3.""" | |
| def _warm_start(self): | |
| self.print_to_log_file("BdA13: RANDOM INIT (no D331 warm start)") | |
| self.optimizer, self.lr_scheduler = self.configure_optimizers() | |
| nnUNetTrainer_BdA13Rand_Smoke = _smoke(nnUNetTrainer_BdA13Rand) | |
| class nnUNetTrainer_BdA11bScaleQ(nnUNetTrainer_BdA9SzSample): | |
| """A11b = the A9 recipe (A0 loss, SIZE-QUOTA sampling + centroid-near centring; A9 = best 50-ep A arm: primary .772, LAB .755, | |
| DEV-A .773, offset ~0) at scale: 150 epochs, 128^3 crops (batch 6), ATLAS-only like A9 (17:55: A3m showed mixed conventions | |
| cost ATLAS-43 -.014 and LAB -.023 for +.003 NORTH, net negative under the selection rule). No SDF / volume terms.""" | |
| EPOCHS = 150 | |
| CROP_PATCH = (128, 128, 128) | |
| CROP_BS = 6 | |
| nnUNetTrainer_BdA11bScaleQ_Smoke = _smoke(nnUNetTrainer_BdA11bScaleQ) | |
| TRAINER_NAMES = sorted(n for n in globals() if n.startswith(("nnUNetTrainer_BdA8", "nnUNetTrainer_BdA7b", "nnUNetTrainer_BdA9", "nnUNetTrainer_BdA3m", "nnUNetTrainer_BdA10", "nnUNetTrainer_BdAX_", "nnUNetTrainer_C2PBallMS_s2", "nnUNetTrainer_BdA11", "nnUNetTrainer_BdA12", "nnUNetTrainer_BdA13", "nnUNetTrainer_BdA3SDFSz_s2", "nnUNetTrainer_C2PHeatP", "nnUNetTrainer_C2PHeatKP", "nnUNetTrainer_C2PHeatE"))) | |