Download runtime/code/whisper_synth/src/direction2/boundary2_A_nets.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 31.3 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/boundary2_A_nets.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/boundary2_A_nets.py
-
curl -L -o boundary2_A_nets.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/boundary2_A_nets.py
31.3 kB
| """boundary2 designer A (2026-11-18): boundary-NATIVE drawers (pure nnU-Net ResEnc-L, D331 warm start, crop drawer recipe). | |
| New file. Imports cascade2_prompt / cascade2_prompt2 / cascade2_nnunet read-only. Shim: | |
| src/nnUNet/nnunetv2/training/nnUNetTrainer/nnUNetTrainer_D2Boundary2A.py. Log: outputs/direction2/boundary2/A_LOG.md. | |
| All trainers inherit nnUNetTrainer_C2PCrop (96^3 crops at 1 mm centred on a lesion component, batch 10, the component nearest | |
| the centre is the only target with an offset/sized ball prompt, other lesions ignore, Kervadec non-empty term w 0.2, full-LR | |
| prompt stem, D331 warm start, Dataset979 fold c2s2x_detA_ii_x) and are restricted to ATLAS-convention keys (syn_t1_atlas_*), | |
| the ATLAS-style standard. EPOCHS = 50 for pilots. | |
| A0 nnUNetTrainer_BdA0Crop control. | |
| A1 nnUNetTrainer_BdA1SDF LEVEL-SET drawer. The network has ONE EXTRA OUTPUT CHANNEL (index 3 after bg / lesion / wmh): a | |
| signed distance to the target-lesion surface, phi_hat = CLIP * tanh(o_3) (mm, + outside). Target: SDFTargetTransform | |
| (after the prompt transform, before intensity aug) computes phi of the target mask with a half-voxel offset (zero level | |
| set between voxels), clipped to +-CLIP, stored x100 as int16 in segmentation channel 2. Loss (full-res head only for the | |
| extra terms; nnU-Net DC+CE with deep supervision on channels 0-2 as usual): | |
| L = DC+CE + W_K * Kervadec non-empty (inherited) + W_SDF * Huber(phi_hat, phi; delta 1 mm) weighted 1 + 4 exp(-|phi|/1.5) | |
| + W_BND * mean(p_lesion * phi)/CLIP (Kervadec et al. 2019/2021 boundary loss, valid voxels) | |
| + W_DTC * mean((p_lesion - sigmoid(-K_DTC * phi_hat))^2) (dual-task consistency, Luo et al. 2021) | |
| Ignore voxels (label 3) are excluded from every extra term. Decoding (eval): seg p >= 0.5, sdf phi_hat < 0, or fused. | |
| A2 nnUNetTrainer_BdA2SDFEB A1 + EXTREME-BREADTH T1 (ExtremeBreadthTransform; breadth not realism, label-free). | |
| A3 nnUNetTrainer_BdA3SDFSz A1 + size-aware loss: per-sample Dice (batch_dice False; every crop = one lesion) and per-sample | |
| normalisation of the SDF / boundary / DTC terms (mean over samples of per-sample means). | |
| """ | |
| from __future__ import annotations | |
| import copy | |
| import sys as _sys | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| _D2 = str(Path(__file__).resolve().parent) | |
| if _D2 not in _sys.path: | |
| _sys.path.insert(0, _D2) | |
| import cascade2_nnunet as N # noqa: E402 | |
| from cascade2_nnunet import IGNORE # noqa: E402 | |
| from cascade2_prompt2 import nnUNetTrainer_C2PCrop, PromptCropTransform # noqa: E402 | |
| from arch2stage_nnunet import _insert_after_spatial # noqa: E402 | |
| from batchgeneratorsv2.transforms.base.basic_transform import BasicTransform # noqa: E402 | |
| from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer # noqa: E402 | |
| SDF_SCALE = 100.0 # int16 storage: phi (voxels) * 100 | |
| # ================================================================================================= SDF target | |
| def signed_distance(m: np.ndarray, clip: float) -> np.ndarray: | |
| """phi (voxel units, + outside) with the zero level set halfway between voxels; clipped to +-clip. Computed inside the | |
| mask's bounding box + clip + 2 (outside it phi = +clip).""" | |
| import scipy.ndimage as ndi | |
| out = np.full(m.shape, clip, np.float32) | |
| if not m.any(): | |
| return out | |
| idx = np.argwhere(m) | |
| pad = int(np.ceil(clip)) + 2 | |
| lo = np.maximum(idx.min(0) - pad, 0); hi = np.minimum(idx.max(0) + pad + 1, m.shape) | |
| sl = tuple(slice(a, b) for a, b in zip(lo, hi)) | |
| mm = m[sl] | |
| d_out = ndi.distance_transform_edt(~mm) - 0.5 | |
| d_in = ndi.distance_transform_edt(mm) - 0.5 | |
| phi = np.where(mm, -d_in, d_out) | |
| out[sl] = np.clip(phi, -clip, clip) | |
| return out | |
| class SDFTargetTransform(BasicTransform): | |
| """segmentation [s0, ids] -> [s0, ids, round(phi*100)] (int16). Target = s0 == 1 (after PromptCropTransform only the | |
| prompted target lesion is label 1).""" | |
| def __init__(self, clip=6.0): | |
| super().__init__(); self.clip = clip | |
| def apply(self, data_dict, **params): | |
| seg = data_dict.get("segmentation") | |
| if seg is None: | |
| return data_dict | |
| s0 = seg[0].numpy() | |
| phi = signed_distance(s0 == 1, self.clip) | |
| ph = torch.from_numpy(np.round(phi * SDF_SCALE).astype(np.int16)).to(seg.dtype) | |
| data_dict["segmentation"] = torch.cat([seg, ph[None]], 0) | |
| return data_dict | |
| # ======================================================================================== extreme-breadth T1 | |
| class ExtremeBreadthTransform(BasicTransform): | |
| """label-free, breadth-not-realism T1 appearance randomisation (channel 0 only, inside the brain = seg != -1), then | |
| re-standardised inside the brain. With prob p: 1-3 ops drawn from {remap (monotone / non-monotone piecewise linear on | |
| brain quantiles), gin (random 3-4 layer conv net), bias (extreme low-frequency multiplicative field), thick (thick-slice | |
| average + linear upsampling along a random axis, factor 2-5), noise (Gaussian up to 0.35 sd), gamma (exp U(-1, 1))}.""" | |
| OPS = ("remap", "gin", "bias", "thick", "noise", "gamma") | |
| def __init__(self, p=0.8, n_ops=(1, 3), p_nonmono=0.3, lin_mix=0.0, gin_alpha=(0.3, 1.0), gamma_log=1.0, thick=(2, 5), | |
| noise=0.35, bias=0.8): | |
| super().__init__(); self.p, self.n_ops, self.p_nonmono = p, n_ops, p_nonmono | |
| self.lin_mix, self.gin_alpha, self.gamma_log, self.thick, self.noise, self.bias = lin_mix, gin_alpha, gamma_log, thick, noise, bias | |
| def _remap(self, v, rng): | |
| q = np.quantile(v, [0.005, 0.995]); lo, hi = float(q[0]), float(q[1]) | |
| if hi - lo < 1e-6: | |
| return v | |
| k = int(rng.integers(4, 9)) | |
| xs = np.linspace(lo, hi, k) | |
| ys = rng.uniform(0, 1, k) | |
| if rng.uniform() >= self.p_nonmono: | |
| ys = np.sort(ys) | |
| if rng.uniform() < 0.5: | |
| ys = ys[::-1].copy() # inverted contrast (still monotone) | |
| if self.lin_mix > 0: # keep a minimum slope everywhere (no flat segment can erase the rim contrast) | |
| lin = np.linspace(0, 1, k); lin = lin if ys[-1] >= ys[0] else lin[::-1] | |
| ys = (1 - self.lin_mix) * ys + self.lin_mix * lin | |
| return np.interp(v, xs, ys).astype(np.float32) | |
| def _gin(self, x, brain, rng): | |
| g = torch.Generator().manual_seed(int(rng.integers(1 << 31))) | |
| h = torch.from_numpy(x)[None, None] | |
| nl = int(rng.integers(3, 5)); C = 4 | |
| for i in range(nl): | |
| k = int([1, 3][int(rng.integers(2))]); cin = h.shape[1]; cout = 1 if i == nl - 1 else C | |
| w = torch.randn(cout, cin, k, k, k, generator=g) / (cin * k ** 3) ** 0.5 | |
| h = F.conv3d(h, w, padding=k // 2) | |
| if i < nl - 1: | |
| h = F.leaky_relu(h, 0.2) | |
| h = h[0, 0].numpy() | |
| a = float(rng.uniform(*self.gin_alpha)) | |
| hb = h[brain]; xb = x[brain] | |
| h = (h - hb.mean()) / (hb.std() + 1e-6) * (xb.std() + 1e-6) + xb.mean() | |
| return (a * h + (1 - a) * x).astype(np.float32) | |
| def _bias(self, x, rng): | |
| cs = [int(rng.integers(2, 5)) for _ in range(3)] | |
| coarse = rng.normal(0, 1, cs).astype(np.float32) | |
| f = F.interpolate(torch.from_numpy(coarse)[None, None], size=x.shape, mode="trilinear", align_corners=True)[0, 0].numpy() | |
| f = f / (np.abs(f).max() + 1e-6) * float(rng.uniform(0.2, self.bias)) | |
| return x * np.exp(f) | |
| def _thick(self, x, rng): | |
| ax = int(rng.integers(3)); fct = int(rng.integers(self.thick[0], self.thick[1] + 1)) | |
| t = torch.from_numpy(np.ascontiguousarray(x))[None, None] | |
| ks = [1, 1, 1]; ks[ax] = fct | |
| lo = F.avg_pool3d(t, ks, ks, ceil_mode=True) | |
| return F.interpolate(lo, size=x.shape, mode="trilinear", align_corners=False)[0, 0].numpy() | |
| def apply(self, data_dict, **params): | |
| import random as _r | |
| rng = np.random.default_rng(_r.getrandbits(32)) | |
| if rng.uniform() >= self.p: | |
| return data_dict | |
| img = data_dict["image"]; seg = data_dict.get("segmentation") | |
| x = img[0].numpy().astype(np.float32) | |
| brain = (seg[0].numpy() != -1) if seg is not None else (x != 0) | |
| if brain.sum() < 500: | |
| return data_dict | |
| n = int(rng.integers(self.n_ops[0], self.n_ops[1] + 1)) | |
| ops = list(rng.choice(self.OPS, size=n, replace=False)) | |
| # positive domain for multiplicative / gamma ops | |
| b = x[brain]; mn = float(b.min()); y = x - mn + 1e-3 | |
| y[~brain] = 0 | |
| for op in ops: | |
| if op == "remap": | |
| y[brain] = self._remap(y[brain], rng) + 1e-3 | |
| elif op == "gin": | |
| y = self._gin(y, brain, rng) | |
| elif op == "bias": | |
| y = self._bias(y, rng) | |
| elif op == "thick": | |
| y = self._thick(y, rng) | |
| elif op == "noise": | |
| s = float(np.std(y[brain])) * float(rng.uniform(0.02, self.noise)) | |
| y = y + rng.normal(0, s, y.shape).astype(np.float32) | |
| elif op == "gamma": | |
| yb = y[brain]; lo, hi = float(yb.min()), float(yb.max()) | |
| if hi > lo: | |
| z = np.clip((y - lo) / (hi - lo), 0, 1) | |
| y = (z ** float(np.exp(rng.uniform(-self.gamma_log, self.gamma_log))) * (hi - lo) + lo).astype(np.float32) | |
| y[~brain] = 0 | |
| yb = y[brain] | |
| y = (y - yb.mean()) / (yb.std() + 1e-6) | |
| y[~brain] = 0 | |
| img[0] = torch.from_numpy(y.astype(np.float32)).to(img.dtype) | |
| data_dict["image"] = img | |
| return data_dict | |
| # ================================================================================================ faint lesions | |
| class FaintLesionTransform(BasicTransform): | |
| """user confidence goal (2026-11-18 15:40): attenuate the TARGET lesion's contrast toward its local surroundings, label fixed, | |
| so the drawer learns to INCLUDE subtle tissue confidently as contrast drops. With prob p: keep a fraction c ~ U(c_lo, 1) of | |
| the lesion-to-surround contrast: x' = x + (1 - c) * w * (ref - x), w = Gaussian-smoothed (sigma U(0.7, 2) vox) lesion mask | |
| dilated 1 (smooth falloff, no hard edge = no label-aligned intensity step), ref = median T1 of the WM-bright half of a 3-8 | |
| voxel shell around the lesion (local NAWM proxy). Applied before nnU-Net's intensity augmentation.""" | |
| def __init__(self, p=0.7, c_lo=0.3): | |
| super().__init__(); self.p, self.c_lo = p, c_lo | |
| 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") | |
| if seg is None or rng.uniform() >= self.p: | |
| return data_dict | |
| s0 = seg[0].numpy() | |
| m = s0 == 1 | |
| if m.sum() < 3: | |
| return data_dict | |
| img = data_dict["image"]; x = img[0].numpy().astype(np.float32) | |
| brain = (s0 != -1) & (x != 0) | |
| idx = np.argwhere(m); lo = np.maximum(idx.min(0) - 10, 0); hi = np.minimum(idx.max(0) + 11, m.shape) | |
| sl = tuple(slice(a, b) for a, b in zip(lo, hi)) | |
| mm = m[sl]; xb = x[sl]; bb = brain[sl] | |
| d = ndi.distance_transform_edt(~mm) | |
| shell = (d >= 3) & (d <= 8) & bb & (s0[sl] == 0) | |
| if shell.sum() < 20: | |
| return data_dict | |
| sv = xb[shell]; ref = float(np.median(sv[sv >= np.median(sv)])) | |
| c = float(rng.uniform(self.c_lo, 1.0)) | |
| w = ndi.gaussian_filter((ndi.binary_dilation(mm) if rng.uniform() < 0.5 else mm).astype(np.float32), float(rng.uniform(0.7, 2.0))) | |
| w = np.clip(w / max(w[mm].max(), 1e-6), 0, 1) * bb | |
| xb = xb + (1.0 - c) * w * (ref - xb) | |
| x[sl] = xb | |
| img[0] = torch.from_numpy(x).to(img.dtype); data_dict["image"] = img | |
| return data_dict | |
| # ===================================================================================================== loss | |
| class BdALoss(nn.Module): | |
| """base = nnU-Net DC+CE (deep supervision wrapper) on channels 0..2; + Kervadec non-empty (ids, target ch 1); + SDF terms | |
| on the extra output channel (full-res head only, target ch 2).""" | |
| def __init__(self, base, n_cls=3, w_k=0.2, k_eps=0.5, w_sdf=0.0, w_bnd=0.0, w_dtc=0.0, clip=6.0, k_dtc=1.5, | |
| per_sample=False, w_vol=0.0): | |
| super().__init__() | |
| self.base, self.n_cls = base, n_cls | |
| self.w_k, self.k_eps, self.w_sdf, self.w_bnd, self.w_dtc = w_k, k_eps, w_sdf, w_bnd, w_dtc | |
| self.clip, self.k_dtc, self.per_sample, self.w_vol = clip, k_dtc, per_sample, w_vol | |
| self.sdf_on = (w_sdf > 0 or w_dtc > 0) | |
| self.acc = {} | |
| def _log(self, k, v): | |
| a = self.acc.setdefault(k, [0.0, 0]); a[0] += float(v); a[1] += 1 | |
| def _mean(self, x, w): | |
| """weighted mean over valid voxels: global, or per sample then averaged (per_sample).""" | |
| if self.per_sample: | |
| 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 x.sum() * 0 | |
| return (x * w).sum() / w.sum().clamp(min=1) | |
| def forward(self, outputs, targets): | |
| lst = isinstance(outputs, (list, tuple)) | |
| outs = list(outputs) if lst else [outputs] | |
| tgts = list(targets) if lst else [targets] | |
| o_seg = [o[:, :self.n_cls] for o in outs] | |
| t_seg = [t[:, :1] for t in tgts] | |
| loss = self.base(o_seg, t_seg) if lst else self.base(o_seg[0], t_seg[0]) | |
| self._log("dcce", loss.detach()) | |
| o0, t0 = outs[0], tgts[0] | |
| lab = t0[:, 0] | |
| valid = (lab != IGNORE).float() | |
| p = torch.softmax(o0[:, :self.n_cls].float(), 1)[:, 1] | |
| if self.w_k > 0 and t0.shape[1] > 1: | |
| k = self.kterm(p, t0[:, 1]) | |
| if k is not None: | |
| loss = loss + self.w_k * k; self._log("kerv", k.detach()) | |
| if self.w_vol > 0: # per-crop (= per-lesion) soft volume match, log-ratio squared (size-equalised volume bias) | |
| g = ((lab == 1).float() * valid).flatten(1).sum(1); q = (p * valid).flatten(1).sum(1) | |
| ok = g > 0 | |
| if bool(ok.any()): | |
| lv = (torch.log((q[ok] + 1) / (g[ok] + 1)) ** 2).mean() | |
| loss = loss + self.w_vol * lv; self._log("vol", lv.detach()) | |
| if t0.shape[1] > 2 and (self.sdf_on or self.w_bnd > 0): | |
| phi = t0[:, 2].float() / SDF_SCALE | |
| if self.w_bnd > 0: | |
| lb = self._mean(p * phi / self.clip, valid) | |
| loss = loss + self.w_bnd * lb; self._log("bnd", lb.detach()) | |
| if self.sdf_on and o0.shape[1] > self.n_cls: | |
| ph = self.clip * torch.tanh(o0[:, self.n_cls].float()) | |
| if self.w_sdf > 0: | |
| hub = F.smooth_l1_loss(ph, phi, reduction="none", beta=1.0) | |
| # near-surface region only (|phi| < clip: beyond it the target is the constant clip value, and for a small | |
| # lesion in a 96^3 crop those voxels would swamp the surface voxels); far voxels keep a 0.02 weight | |
| near = (phi.abs() < self.clip - 1e-3).float() | |
| w = valid * (near * (1.0 + 4.0 * torch.exp(-phi.abs() / 1.5)) + 0.02 * (1.0 - near)) | |
| ls = self._mean(hub, w) | |
| loss = loss + self.w_sdf * ls; self._log("sdf", ls.detach()) | |
| with torch.no_grad(): | |
| nb = valid * (phi.abs() <= 2).float() | |
| self._log("sdf_mae_band", self._mean((ph - phi).abs(), nb)) | |
| if self.w_dtc > 0: | |
| ld = self._mean((p - torch.sigmoid(-self.k_dtc * ph)) ** 2, valid) | |
| loss = loss + self.w_dtc * ld; self._log("dtc", ld.detach()) | |
| return loss | |
| def kterm(self, p, ids): | |
| ids = ids.long(); m = ids > 0 | |
| if not bool(m.any()): | |
| return None | |
| B = ids.shape[0] | |
| key = (torch.arange(B, device=ids.device).view(B, 1, 1, 1) * 4096 + ids)[m] | |
| uk, inv = torch.unique(key, return_inverse=True) | |
| s = torch.zeros(uk.shape[0], device=p.device).scatter_add(0, inv, p[m]) | |
| c = torch.zeros(uk.shape[0], device=p.device).scatter_add(0, inv, torch.ones_like(p[m])) | |
| return F.relu(np.log(self.k_eps) - torch.log(s / c.clamp(min=1) + 1e-6)).mean() | |
| # ================================================================================================= trainers | |
| class _BdABase(nnUNetTrainer_C2PCrop): | |
| """crop drawer recipe, ATLAS-only, pilot length. Class switches below.""" | |
| EPOCHS = 50 | |
| GROUPS = {"t1": 1.0, "real": 0.0} | |
| N_EXTRA_OUT = 0 | |
| SDF_CLIP = 6.0 | |
| W_SDF = W_BND = W_DTC = 0.0 | |
| K_DTC = 1.5 | |
| PER_SAMPLE = False | |
| W_VOL = 0.0 | |
| EB = False | |
| EB_KW = {} | |
| FAINT = False | |
| FAINT_KW = {} | |
| def do_split(self): | |
| tr, va = super().do_split() | |
| tr2 = [k for k in tr if k.startswith("syn_t1_atlas_")] | |
| if not getattr(self, "_bda_logged", False): | |
| self.print_to_log_file(f"BdA: ATLAS-only {len(tr2)} of {len(tr)} training keys; extra out {self.N_EXTRA_OUT}; " | |
| f"W_SDF {self.W_SDF} W_BND {self.W_BND} W_DTC {self.W_DTC} clip {self.SDF_CLIP} " | |
| f"per_sample {self.PER_SAMPLE} EB {self.EB} {self.EB_KW} epochs {self.num_epochs}") | |
| self._bda_logged = True | |
| return tr2, va | |
| def _n_extra(cls): | |
| return cls.N_EXTRA_OUT | |
| def get_training_transforms(self, *args, **kwargs): | |
| c = nnUNetTrainer.get_training_transforms(*args, **kwargs) | |
| extra = [self._prompt_t()] | |
| if self.FAINT: | |
| extra.append(FaintLesionTransform(**self.FAINT_KW)) | |
| if self.EB: | |
| extra.append(ExtremeBreadthTransform(**self.EB_KW)) | |
| if self.N_EXTRA_OUT: | |
| extra.append(SDFTargetTransform(self.SDF_CLIP)) | |
| for t in reversed(extra): | |
| _insert_after_spatial(c, t) | |
| return c | |
| def _build_loss(self): | |
| from nnunetv2.training.loss.compound_losses import DC_and_CE_loss | |
| from nnunetv2.training.loss.dice import MemoryEfficientSoftDiceLoss | |
| from nnunetv2.training.loss.deep_supervision import DeepSupervisionWrapper | |
| bd = self.configuration_manager.batch_dice and not self.PER_SAMPLE | |
| base = DC_and_CE_loss({'batch_dice': bd, 'smooth': 1e-5, 'do_bg': False, 'ddp': self.is_ddp}, {}, weight_ce=1, | |
| weight_dice=1, ignore_label=self.label_manager.ignore_label, dice_class=MemoryEfficientSoftDiceLoss) | |
| if self._do_i_compile(): | |
| base.dc = torch.compile(base.dc) | |
| if self.enable_deep_supervision: | |
| w = np.array([1 / (2 ** i) for i in range(len(self._get_deep_supervision_scales()))]); w[-1] = 0; w = w / w.sum() | |
| base = DeepSupervisionWrapper(base, w) | |
| return BdALoss(base, n_cls=self.label_manager.num_segmentation_heads, w_k=self.W_K, k_eps=self.K_EPS, | |
| w_sdf=self.W_SDF, w_bnd=self.W_BND, w_dtc=self.W_DTC, clip=self.SDF_CLIP, k_dtc=self.K_DTC, | |
| per_sample=self.PER_SAMPLE, w_vol=self.W_VOL) | |
| def on_train_epoch_end(self, train_outputs): | |
| a = getattr(self.loss, "acc", None) | |
| if a: | |
| self.print_to_log_file("BdA loss terms: " + ", ".join(f"{k} {v[0] / max(1, v[1]):.4f}" for k, v in a.items())) | |
| self.loss.acc = {} | |
| return super().on_train_epoch_end(train_outputs) | |
| # ---- extra output channel(s): network, warm start, validation | |
| def _warm_start(self): | |
| """_A2SBase warm start (D331, strict) generalised: seg heads 2 -> (3 + N_EXTRA_OUT) rows (rows 0-1 copied, rest zero).""" | |
| if not self.N_EXTRA_OUT: | |
| return super()._warm_start() | |
| pre = torch.load(str(self.WARM_PATH), map_location="cpu", weights_only=False)["network_weights"] | |
| mod = self._module(); sd = mod.state_dict() | |
| g = torch.Generator().manual_seed(1000 + self.SEED) | |
| copied, adapted, stem_new = 0, [], None | |
| for k, v in sd.items(): | |
| if k not in pre: | |
| raise RuntimeError(f"warm start: key {k} missing in pretrained weights") | |
| p = pre[k].to(device=v.device, dtype=v.dtype) | |
| if p.shape == v.shape: | |
| sd[k] = p.clone(); copied += 1 | |
| elif p.ndim == 5 and p.shape[0] == v.shape[0] and p.shape[1] == 1 and v.shape[1] > 1 and p.shape[2:] == v.shape[2:]: | |
| if stem_new is None: | |
| stem_new = torch.zeros_like(v); stem_new[:, :1] = p | |
| for c in range(1, v.shape[1]): | |
| sdv = float(p.float().std()) * self.NEW_STEM_REL | |
| stem_new[:, c:c + 1] = (torch.randn(p.shape, generator=g) * sdv).to(v.device, v.dtype) | |
| elif not torch.equal(stem_new[:, :1], p): | |
| raise RuntimeError(f"warm start: second 1->C conv {k} is not an alias of the stem") | |
| sd[k] = stem_new.clone(); adapted.append(k); self._new_param_names.add(k) | |
| elif ".seg_layers." in k and p.shape[0] == 2 and v.shape[0] == 3 + self.N_EXTRA_OUT and p.shape[1:] == v.shape[1:]: | |
| new = torch.zeros_like(v); new[:2] = p | |
| sd[k] = new; adapted.append(k); self._new_param_names.add(k) | |
| else: | |
| raise RuntimeError(f"warm start: unexpected shape mismatch {k}: {tuple(p.shape)} vs {tuple(v.shape)}") | |
| mod.load_state_dict(sd) | |
| self.print_to_log_file(f"BdA warm start from {self.WARM_PATH} (stem rel {self.NEW_STEM_REL}, seg heads -> {3 + self.N_EXTRA_OUT} rows): " | |
| f"copied {copied}, adapted {len(adapted)}: {adapted}") | |
| self.optimizer, self.lr_scheduler = self.configure_optimizers() | |
| def validation_step(self, batch: dict) -> dict: | |
| if not self.N_EXTRA_OUT: | |
| return super().validation_step(batch) | |
| net = self.network | |
| n = self.label_manager.num_segmentation_heads | |
| class _Slice(nn.Module): | |
| def __init__(s, m): | |
| super().__init__(); s.m = m | |
| def forward(s, x): | |
| o = s.m(x) | |
| return [t[:, :n] for t in o] if isinstance(o, (list, tuple)) else o[:, :n] | |
| loss_keep = self.loss | |
| try: | |
| self.network = _Slice(net) | |
| self.loss = lambda out, tgt: loss_keep.base(out, [t[:, :1] for t in tgt]) if isinstance(tgt, list) else loss_keep.base(out, tgt[:, :1]) | |
| batch = dict(batch) | |
| t = batch["target"] | |
| batch["target"] = [x[:, :1] for x in t] if isinstance(t, list) else t[:, :1] | |
| return nnUNetTrainer.validation_step(self, batch) | |
| finally: | |
| self.network = net; self.loss = loss_keep | |
| def _with_extra(base_cls): | |
| """build_network_architecture adding N_EXTRA_OUT output channels (static, used by nnUNetPredictor too).""" | |
| n_extra = base_cls.N_EXTRA_OUT | |
| def build_network_architecture(plans_manager, configuration_manager, num_input_channels, num_output_channels, | |
| enable_deep_supervision: bool = True): | |
| return nnUNetTrainer.build_network_architecture(plans_manager, configuration_manager, num_input_channels, | |
| num_output_channels + n_extra, enable_deep_supervision) | |
| base_cls.build_network_architecture = build_network_architecture | |
| return base_cls | |
| class nnUNetTrainer_BdA0Crop(_BdABase): | |
| """A0 control: C2PCrop recipe, ATLAS-only, 50 epochs.""" | |
| class nnUNetTrainer_BdA1SDF(_BdABase): | |
| """A1 level-set drawer (see module docstring).""" | |
| N_EXTRA_OUT = 1 | |
| W_SDF, W_BND, W_DTC = 1.0, 0.1, 0.5 | |
| class nnUNetTrainer_BdA2SDFEB(_BdABase): | |
| """A2 = A1 + extreme-breadth T1.""" | |
| N_EXTRA_OUT = 1 | |
| W_SDF, W_BND, W_DTC = 1.0, 0.1, 0.5 | |
| EB = True | |
| class nnUNetTrainer_BdA3SDFSz(_BdABase): | |
| """A3 = A1 + SIZE-AWARE package: per-sample loss (every crop = one lesion carries equal weight) AND flatter component | |
| sampling (ALPHA 0.25, floor 1 mL; the recipe's alpha 0.5 / floor 0.1 mL gives 5-30 mL lesions only ~1.8 % of crops) AND a | |
| per-crop soft-volume term (log((sum p + 1)/(sum g + 1)))^2, w 0.1 (Kervadec-style size constraint, equalised per lesion).""" | |
| N_EXTRA_OUT = 1 | |
| W_SDF, W_BND, W_DTC = 1.0, 0.1, 0.5 | |
| PER_SAMPLE = True | |
| ALPHA = 0.25 | |
| VOL_FLOOR = 1000 | |
| W_VOL = 0.1 | |
| class nnUNetTrainer_BdA0CropEB(_BdABase): | |
| """A0 + extreme-breadth T1 (the EB main effect without the SDF head; 2x2 with A0 / A1 / A2).""" | |
| EB = True | |
| class nnUNetTrainer_BdA7SzFaint(_BdABase): | |
| """A7 = A3 (size-aware package incl. SDF head) + FAINT-LESION training (FaintLesionTransform p 0.7, contrast kept U(0.3, 1), | |
| smooth falloff, label fixed). User's confidence goal; compare with A3 on the subtlety curve and the shift curve.""" | |
| N_EXTRA_OUT = 1 | |
| W_SDF, W_BND, W_DTC = 1.0, 0.1, 0.5 | |
| PER_SAMPLE = True | |
| ALPHA = 0.25 | |
| VOL_FLOOR = 1000 | |
| W_VOL = 0.1 | |
| FAINT = True | |
| EB_HYGIENIC = dict(p_nonmono=0.0, lin_mix=0.5, gin_alpha=(0.2, 0.6), gamma_log=0.6, thick=(2, 3), noise=0.2, bias=0.6) | |
| class nnUNetTrainer_BdA6CropEBh(_BdABase): | |
| """A6 = A0 + RIM-HYGIENIC breadth (LITERATURE 1.6: remaps that erase weak rim contrast while the label keeps the rim teach | |
| 'weak rim = background'): monotone remaps only, each mixed 50 % with the identity ramp (minimum slope), GIN alpha <= 0.6, | |
| gamma exp(+-0.6), thick 2-3 mm, noise <= 0.2 sd, bias <= 0.6.""" | |
| EB = True | |
| EB_KW = EB_HYGIENIC | |
| # ============================================================================================ A4 contour evolution | |
| class PrevEstimateTransform(BasicTransform): | |
| """appends image channel 2 = a PREVIOUS ESTIMATE of the target lesion (soft mask in [0, 1]) that the network must correct. | |
| Mix: p_empty -> zeros (draw from scratch); p_ball -> the prompt ball; else a perturbed GT: phi' = phi + global offset | |
| U(off) mm (biased to under-segmentation, like every model) + low-frequency random field (amplitude U(0, field) mm), | |
| prev = sigmoid(-phi' / tau), tau U(0.3, 1.5) (sharp to blurry). Target unchanged (the true outline).""" | |
| def __init__(self, p_empty=0.15, p_ball=0.15, off=(-2.5, 1.5), field=2.0, clip=6.0): | |
| super().__init__(); self.p_empty, self.p_ball, self.off, self.field, self.clip = p_empty, p_ball, off, field, clip | |
| def apply(self, data_dict, **params): | |
| import random as _r | |
| rng = np.random.default_rng(_r.getrandbits(32)) | |
| img = data_dict["image"]; seg = data_dict.get("segmentation") | |
| shp = img.shape[1:] | |
| u = rng.uniform() | |
| if seg is None or u < self.p_empty: | |
| prev = np.zeros(shp, np.float32) | |
| elif u < self.p_empty + self.p_ball: | |
| prev = img[1].numpy().astype(np.float32) | |
| else: | |
| m = seg[0].numpy() == 1 | |
| phi = signed_distance(m, self.clip + 4) | |
| cs = [int(rng.integers(2, 6)) for _ in range(3)] | |
| coarse = rng.normal(0, 1, cs).astype(np.float32) | |
| f = F.interpolate(torch.from_numpy(coarse)[None, None], size=tuple(shp), mode="trilinear", align_corners=True)[0, 0].numpy() | |
| f = f / (np.abs(f).max() + 1e-6) * float(rng.uniform(0, self.field)) | |
| ph2 = phi + float(rng.uniform(*self.off)) + f | |
| prev = 1.0 / (1.0 + np.exp(np.clip(ph2 / float(rng.uniform(0.3, 1.5)), -30, 30))) | |
| prev = prev.astype(np.float32) | |
| data_dict["image"] = torch.cat([img, torch.from_numpy(prev)[None].to(img.dtype)], 0) | |
| return data_dict | |
| class _EvoMixin: | |
| """3 input channels [T1, prompt, previous estimate]; with prob P_SELF the previous estimate is replaced in train_step by the | |
| network's OWN detached prediction from that input (one unrolled self-feedback step), so the corrector sees its own errors.""" | |
| P_SELF = 0.5 | |
| N_IN_EXTRA = 1 | |
| def get_training_transforms(self, *args, **kwargs): | |
| c = super().get_training_transforms(*args, **kwargs) | |
| # insert right after the prompt transform (it needs the prompt and the target mask) | |
| idx = next(i for i, t in enumerate(c.transforms) if isinstance(t, PromptCropTransform)) | |
| c.transforms.insert(idx + 1, PrevEstimateTransform()) | |
| return c | |
| def get_validation_transforms(self, *args, **kwargs): | |
| c = nnUNetTrainer.get_validation_transforms(*args, **kwargs) | |
| c.transforms.insert(0, PrevEstimateTransform(p_empty=1.0)) | |
| return c | |
| def train_step(self, batch: dict) -> dict: | |
| if np.random.uniform() < self.P_SELF: | |
| data = batch["data"].to(self.device, non_blocking=True) | |
| with torch.no_grad(), torch.autocast(self.device.type, enabled=self.device.type == "cuda"): | |
| o = self.network(data) | |
| o0 = o[0] if isinstance(o, (list, tuple)) else o | |
| p = torch.softmax(o0[:, :3].float(), 1)[:, 1:2] | |
| data = data.clone(); data[:, 2:3] = p.to(data.dtype) | |
| batch = dict(batch); batch["data"] = data | |
| return super().train_step(batch) | |
| def _with_io(base_cls): | |
| n_extra, n_in = base_cls.N_EXTRA_OUT, base_cls.N_IN_EXTRA | |
| def build_network_architecture(plans_manager, configuration_manager, num_input_channels, num_output_channels, | |
| enable_deep_supervision: bool = True): | |
| return nnUNetTrainer.build_network_architecture(plans_manager, configuration_manager, num_input_channels + n_in, | |
| num_output_channels + n_extra, enable_deep_supervision) | |
| base_cls.build_network_architecture = build_network_architecture | |
| return base_cls | |
| class nnUNetTrainer_BdA4Evo(_EvoMixin, _BdABase): | |
| """A4 learned contour evolution: A1 level-set drawer + previous-estimate input + self-feedback; K steps at test.""" | |
| N_EXTRA_OUT = 1 | |
| W_SDF, W_BND, W_DTC = 1.0, 0.1, 0.5 | |
| # ---------------------------------------------------------------------------------------------------- smoke classes | |
| def _smoke(base): | |
| def _init(self, plans, configuration, fold, dataset_json, device=torch.device("cuda")): | |
| base.__init__(self, plans, configuration, fold, dataset_json, device); self._smoke() | |
| return type(base.__name__ + "_Smoke", (N._C2Smoke, base), {"__init__": _init, "__module__": __name__, "BACKBONE_WARMUP_EPOCHS": 0}) | |
| nnUNetTrainer_BdA0Crop_Smoke = _smoke(nnUNetTrainer_BdA0Crop) | |
| nnUNetTrainer_BdA1SDF_Smoke = _smoke(nnUNetTrainer_BdA1SDF) | |
| nnUNetTrainer_BdA2SDFEB_Smoke = _smoke(nnUNetTrainer_BdA2SDFEB) | |
| nnUNetTrainer_BdA3SDFSz_Smoke = _smoke(nnUNetTrainer_BdA3SDFSz) | |
| nnUNetTrainer_BdA0CropEB_Smoke = _smoke(nnUNetTrainer_BdA0CropEB) | |
| nnUNetTrainer_BdA4Evo_Smoke = _smoke(nnUNetTrainer_BdA4Evo) | |
| nnUNetTrainer_BdA6CropEBh_Smoke = _smoke(nnUNetTrainer_BdA6CropEBh) | |
| nnUNetTrainer_BdA7SzFaint_Smoke = _smoke(nnUNetTrainer_BdA7SzFaint) | |
| TRAINER_NAMES = sorted(n for n in globals() if n.startswith("nnUNetTrainer_BdA")) | |