Download runtime/code/whisper_synth/src/direction2/cascade2_det2.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cascade2_det2.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/cascade2_det2.py
-
curl -L -o cascade2_det2.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cascade2_det2.py
15.2 kB
| """cascade2_det2 (stage1x agent, 2026-11-16): NEW stage-1 detector variants. Imports cascade2_nnunet read-only; nothing | |
| there is modified. Exposed via src/nnUNet/.../nnUNetTrainer_D2Cascade2Det2.py (names nnUNetTrainer_C2D2*). | |
| All classes = detA_ii recipe (D331 warm start, ResEnc-L, FLAIR only, tolerant targets, component oversampling alpha 0.5 | |
| floor 1 mL, 150 epochs, full LR, decoy-ignore via env C2_DECOY_IGNORE=1 when the renderer family is present) unless | |
| stated. They train on Dataset977 fold c2x_ii_f0 (the main detector's fold-0 split); data-mix controls FILTER that | |
| split's training keys to their families, so every arm sees exactly the same patients. | |
| DATA-MIX CONTROLS (coordinator 2026-11-16: P1 is in-cohort; separate what each source contributes): | |
| C2D2_A_real CONTRA real FLAIR only (no synthetic) | |
| C2D2_A_g1 G1 synthetic FLAIR only | |
| C2D2_A_g1real G1 + CONTRA 50/50 (= option i on the c2x split; no renderer) | |
| C2D2_A_r25 option ii with CONTRA down-weighted: g1 0.375 / renderer 0.375 / real 0.25 | |
| LOSS SCREENS (option ii data): | |
| C2D2_A_ii_mil02 CE + per-lesion blob Dice + 0.2 * MIL lesion-max term mean_k -log(max_{i in C_k} p_i) (CATMIL) | |
| C2D2_A_ii_bicc CE (deep supervision) + BiCC alpha 1/4 in place of the blob term: | |
| (1 - a) * mean_k DiceCE(P n R_k, C_k) over GT cells + a * mean_j [mean_{i in B_j} p_i + CE(R_j)] | |
| over prediction-only (false-positive) cells; R = Voronoi partition of the patch seeded by GT | |
| components (>= 10 vox) and by predicted components (p > 0.5) that touch no GT; Dice non-smooth (eps 0). | |
| Voronoi approximated on the GPU at half resolution (max-pool id propagation; GT wins ties); | |
| predicted components labelled with cc3d at half resolution. FP cells capped at 64 per sample. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import sys as _sys | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| _D2 = str(Path(__file__).resolve().parent) | |
| if _D2 not in _sys.path: | |
| _sys.path.insert(0, _D2) | |
| import cascade2_common as C # noqa: E402 | |
| import cascade2_nnunet as N # noqa: E402 | |
| from cascade2_nnunet import _C2DetBase, _C2Smoke, C2DetLoss, IGNORE # noqa: E402 | |
| # =========================================================================================================== losses | |
| class C2D2Loss(C2DetLoss): | |
| """C2DetLoss (CE + w_blob * blob) + w_mil * MIL + w_cc * BiCC(alpha). Extra terms on the full-resolution head only.""" | |
| def __init__(self, ds_weights=None, w_ce=1.0, w_blob=1.0, mode="dice", margin=8, w_mil=0.0, w_cc=0.0, alpha=0.25, | |
| max_fp=64, cc_min_vox=10): | |
| super().__init__(ds_weights, w_ce, w_blob, mode, margin) | |
| self.w_mil, self.w_cc, self.alpha, self.max_fp, self.cc_min_vox = w_mil, w_cc, alpha, max_fp, cc_min_vox | |
| def forward(self, outputs, targets): | |
| tot = super().forward(outputs, targets) | |
| o0 = outputs[0] if isinstance(outputs, (list, tuple)) else outputs | |
| t0 = targets[0] if isinstance(targets, (list, tuple)) else targets | |
| if self.w_mil > 0 and t0.shape[1] > 1: | |
| m = self.mil(o0, t0); tot = tot + self.w_mil * m; self.last["mil"] = float(m.detach()) | |
| if self.w_cc > 0 and t0.shape[1] > 1: | |
| g, p, nfp = self.bicc(o0, t0) | |
| cc = (1 - self.alpha) * g + self.alpha * p | |
| tot = tot + self.w_cc * cc | |
| self.last.update({"ccgt": float(g.detach()), "ccfp": float(p.detach()), "nfp": float(nfp)}) | |
| return tot | |
| def mil(self, out, tgt): | |
| cid = tgt[:, 1].long() | |
| sel = cid > 0 | |
| if not bool(sel.any()): | |
| return torch.zeros((), device=out.device) | |
| lp = F.log_softmax(out.float(), 1)[:, self.lesion_ch] | |
| b = torch.arange(cid.shape[0], device=out.device).view(-1, 1, 1, 1).expand_as(cid) | |
| key = (b * (1 << 15) + cid)[sel] | |
| uk, inv = torch.unique(key, return_inverse=True) | |
| mx = torch.full((uk.shape[0],), -1e4, device=out.device).scatter_reduce(0, inv, lp[sel], "amax", include_self=True) | |
| return (-mx).mean() | |
| def _voronoi(seeds: torch.Tensor, max_iter=256): | |
| """seeds [B, X, Y, Z] long (0 = none) -> nearest-seed id map (approx., half resolution; ties -> larger id).""" | |
| s = seeds.float()[:, None] | |
| h = F.max_pool3d(s, 2, 2, ceil_mode=True) | |
| for _ in range(max_iter): | |
| z = h == 0 | |
| if not bool(z.any()) or not bool((h > 0).any()): | |
| break | |
| h = torch.where(z, F.max_pool3d(h, 3, 1, 1), h) | |
| up = F.interpolate(h, scale_factor=2, mode="nearest")[..., :s.shape[2], :s.shape[3], :s.shape[4]] | |
| v = torch.where(s > 0, s, up)[:, 0].long() | |
| return v | |
| def bicc(self, out, tgt): | |
| import cc3d | |
| lab = tgt[:, 0].long(); cid = tgt[:, 1].long() | |
| B = lab.shape[0] | |
| logits = out.float() | |
| prob = torch.softmax(logits, 1)[:, self.lesion_ch] | |
| ce = F.cross_entropy(logits, torch.where(lab == self.ignore, 0, lab).clamp(min=0), reduction="none") # ignore voxels masked by valid | |
| valid = (lab != self.ignore) & (lab >= 0) | |
| gtany = (lab == 1) | (cid > 0) | |
| # predicted components (half resolution labelling), keep those touching no GT and >= cc_min_vox (full res) | |
| pm = (prob.detach() > 0.5) | |
| pm_h = (F.max_pool3d(pm.float()[:, None], 2, 2, ceil_mode=True)[:, 0].bool().cpu().numpy() if self.alpha > 0 | |
| else np.zeros((B, 1, 1, 1), bool)) # alpha 0 = CC-DiceCE: no FP cells | |
| seeds = torch.zeros_like(lab); fpmap = torch.zeros_like(lab); kinds = [] | |
| for b in range(B): | |
| ng = int(cid[b].max()) | |
| nfp = 0 | |
| if pm_h[b].any(): | |
| lh = cc3d.connected_components(pm_h[b].astype(np.uint8), connectivity=26) | |
| lfull = torch.from_numpy(lh.astype(np.int64)).to(lab.device) | |
| lfull = lfull.repeat_interleave(2, 0).repeat_interleave(2, 1).repeat_interleave(2, 2)[:lab.shape[1], :lab.shape[2], :lab.shape[3]] | |
| lfull = torch.where(pm[b], lfull, torch.zeros_like(lfull)) | |
| n = int(lh.max()) | |
| if n: | |
| cnt = torch.bincount(lfull.reshape(-1), minlength=n + 1) | |
| touch = torch.bincount(lfull[gtany[b]].reshape(-1), minlength=n + 1) > 0 | |
| ok = torch.nonzero((cnt >= self.cc_min_vox) & ~touch).reshape(-1) | |
| ok = ok[ok > 0] | |
| if ok.numel() > self.max_fp: | |
| ok = ok[torch.randperm(ok.numel(), device=ok.device)[:self.max_fp]] | |
| nfp = int(ok.numel()) | |
| if nfp: | |
| remap = torch.zeros(n + 1, dtype=torch.long, device=lab.device) | |
| remap[ok] = torch.arange(1, nfp + 1, device=lab.device) | |
| fpmap[b] = remap[lfull] | |
| # FP cells get ids 1..nfp, GT cells nfp+1..nfp+ng (GT wins Voronoi ties) | |
| sb = fpmap[b].clone() | |
| sb[cid[b] > 0] = cid[b][cid[b] > 0] + nfp | |
| seeds[b] = sb | |
| kinds.append((nfp, ng)) | |
| V = self._voronoi(seeds) | |
| OFF = 1 << 12 | |
| g = (V + torch.arange(B, device=lab.device).view(-1, 1, 1, 1) * OFF).reshape(-1) | |
| w = (valid & (V > 0)).float().reshape(-1) | |
| t = (lab == 1).float().reshape(-1); p = prob.reshape(-1); cev = ce.reshape(-1) | |
| nb = B * OFF | |
| def S(x): | |
| return torch.zeros(nb, device=lab.device).index_add_(0, g, x) | |
| s_pt, s_p, s_t, s_ce, s_n = S(p * t * w), S(p * w), S(t * w), S(cev * w), S(w) | |
| fpb = (fpmap > 0).float().reshape(-1) | |
| s_pb, s_nb = S(p * fpb), S(fpb) | |
| gl, fl = [], [] | |
| for b, (nfp, ng) in enumerate(kinds): | |
| base = b * OFF | |
| for k in range(nfp + 1, nfp + ng + 1): | |
| i = base + k | |
| if s_t[i] <= 0 or s_n[i] <= 0: | |
| continue | |
| dice = 1 - 2 * s_pt[i] / (s_p[i] + s_t[i]).clamp(min=1e-8) | |
| gl.append(dice + s_ce[i] / s_n[i]) | |
| for j in range(1, nfp + 1): | |
| i = base + j | |
| if s_nb[i] <= 0: | |
| continue | |
| fl.append(s_pb[i] / s_nb[i] + s_ce[i] / s_n[i].clamp(min=1)) | |
| z = torch.zeros((), device=lab.device) | |
| return (torch.stack(gl).mean() if gl else z), (torch.stack(fl).mean() if fl else z), sum(k[0] for k in kinds) | |
| # ========================================================================================================= trainers | |
| class _C2D2Base(_C2DetBase): | |
| """detA_ii recipe + optional family filter (GROUPS_OVERRIDE) and extra loss terms.""" | |
| DATA_OPTION = "ii" | |
| WARM = "d331" | |
| OVERSAMPLE = True | |
| GROUPS_OVERRIDE = None # dict family -> fraction; the fold's training keys are filtered to these families | |
| W_MIL = 0.0 | |
| W_CC = 0.0 | |
| CC_ALPHA = 0.25 | |
| def __init__(self, plans, configuration, fold, dataset_json, device=torch.device("cuda")): | |
| super().__init__(plans, configuration, fold, dataset_json, device) | |
| if self.GROUPS_OVERRIDE is not None: | |
| self.GROUPS = dict(self.GROUPS_OVERRIDE) | |
| def do_split(self): | |
| tr, va = super(_C2DetBase, self).do_split() | |
| n0 = len(tr) | |
| tr = [k for k in tr if C.family(k) in self.GROUPS and self.GROUPS[C.family(k)] > 0] | |
| fams = {C.family(k) for k in tr} | |
| assert fams == {f for f, v in self.GROUPS.items() if v > 0}, f"fold families {fams} != {self.GROUPS}" | |
| cg = [k for k in tr if C.family(k) == "cg"] | |
| if cg: | |
| assert {C.is_online_cg(k) for k in cg} == {self.CG_MODE != "offline"}, "CG_MODE / cg key mismatch" | |
| for k in tr: | |
| C.assert_train_key(k) | |
| self.print_to_log_file(f"C2D2 split: {n0} -> {len(tr)} training keys after family filter {self.GROUPS}; " | |
| f"per family {{{', '.join(f'{f}: {sum(C.family(k) == f for k in tr)}' for f in sorted(fams))}}}") | |
| return tr, va | |
| def _build_loss(self): | |
| w = None | |
| if self.enable_deep_supervision: | |
| n = len(self._get_deep_supervision_scales()) | |
| w = np.array([1 / (2 ** i) for i in range(n)]); w[-1] = 0; w = (w / w.sum()).tolist() | |
| return C2D2Loss(w, self.W_CE, self.W_BLOB, self.BLOB_MODE, self.BLOB_MARGIN, w_mil=self.W_MIL, w_cc=self.W_CC, | |
| alpha=self.CC_ALPHA) | |
| def on_train_epoch_end(self, train_outputs): | |
| if train_outputs: | |
| extra = [k for k in train_outputs[0] if k.startswith("l_") and k not in ("l_ce", "l_blob", "l_tgpu", "l_ngpu")] | |
| if extra: | |
| self.print_to_log_file("C2D2 extra loss parts: " + " ".join( | |
| f"{k[2:]} {np.mean([o[k] for o in train_outputs if k in o]):.4f}" for k in extra)) | |
| return super().on_train_epoch_end(train_outputs) | |
| class _C2D2Robust(_C2D2Base): | |
| """SITE-ROBUSTNESS screen (stage1x, from the OOC-ISLES diagnosis: unseen-site FPs are high-confidence, mostly NOT | |
| FLAIR-bright, and ISLES FLAIR is thick-slice-interpolated, through-plane gradient 0.57 vs 0.82 for CONTRA): | |
| * GIN on the REAL CONTRA FLAIR too (base recipe: real 0.0), p GIN_REAL; | |
| * slice-thickness simulation on the FLAIR channel of every family with p ANISO_P: along one random axis, | |
| area-downsample by a factor U(ANISO_K) and trilinear-upsample back (label untouched; geometry unchanged).""" | |
| GIN_REAL = 0.6 | |
| ANISO_P = 0.0 | |
| ANISO_K = (2.0, 5.0) | |
| def __init__(self, plans, configuration, fold, dataset_json, device=torch.device("cuda")): | |
| super().__init__(plans, configuration, fold, dataset_json, device) | |
| self.GIN_P = dict(self.GIN_P, real=self.GIN_REAL) | |
| def _aniso(self, x): | |
| if self.ANISO_P <= 0: | |
| return x | |
| for i in range(x.shape[0]): | |
| if np.random.uniform() >= self.ANISO_P: | |
| continue | |
| ax = np.random.randint(3); k = np.random.uniform(*self.ANISO_K) | |
| v = x[i:i + 1, 1:2].float(); size = list(v.shape[2:]); small = list(size) | |
| small[ax] = max(2, int(round(size[ax] / k))) | |
| v2 = F.interpolate(F.interpolate(v, size=small, mode="area"), size=size, mode="trilinear", align_corners=False) | |
| x[i, 1] = v2[0, 0].to(x.dtype) | |
| return x | |
| def train_step(self, batch: dict) -> dict: | |
| batch["data"] = self._aniso(batch["data"].to(self.device, non_blocking=True)) | |
| return super().train_step(batch) | |
| def _mk(name, **attrs): | |
| doc = attrs.pop("doc", "") | |
| return type(name, (_C2D2Base,), dict(attrs, __module__=__name__, __doc__=doc)) | |
| _GEN = { | |
| "nnUNetTrainer_C2D2_A_real": _mk("nnUNetTrainer_C2D2_A_real", GROUPS_OVERRIDE={"real": 1.0}, | |
| doc="data-mix control: CONTRA real FLAIR only"), | |
| "nnUNetTrainer_C2D2_A_g1": _mk("nnUNetTrainer_C2D2_A_g1", GROUPS_OVERRIDE={"g1": 1.0}, | |
| doc="data-mix control: G1 synthetic FLAIR only"), | |
| "nnUNetTrainer_C2D2_A_g1real": _mk("nnUNetTrainer_C2D2_A_g1real", GROUPS_OVERRIDE={"g1": 0.5, "real": 0.5}, | |
| doc="data-mix control: G1 + CONTRA 50/50 (no renderer)"), | |
| "nnUNetTrainer_C2D2_A_r25": _mk("nnUNetTrainer_C2D2_A_r25", GROUPS_OVERRIDE={"g1": 0.375, "cg": 0.375, "real": 0.25}, | |
| doc="option ii with CONTRA down-weighted to 25 %"), | |
| "nnUNetTrainer_C2D2_A_ii_mil02": _mk("nnUNetTrainer_C2D2_A_ii_mil02", W_MIL=0.2, | |
| doc="option ii + 0.2 * MIL lesion-max term"), | |
| "nnUNetTrainer_C2D2_A_ii_ginreal": type("nnUNetTrainer_C2D2_A_ii_ginreal", (_C2D2Robust,), dict( | |
| GIN_REAL=0.6, ANISO_P=0.0, __module__=__name__, __doc__="option ii + GIN on real CONTRA FLAIR (p 0.6)")), | |
| "nnUNetTrainer_C2D2_A_ii_robust": type("nnUNetTrainer_C2D2_A_ii_robust", (_C2D2Robust,), dict( | |
| GIN_REAL=0.6, ANISO_P=0.3, __module__=__name__, | |
| __doc__="option ii + GIN on real CONTRA FLAIR (p 0.6) + slice-thickness simulation (p 0.3, factor 2-5)")), | |
| "nnUNetTrainer_C2D2_A_ii_cc": _mk("nnUNetTrainer_C2D2_A_ii_cc", W_BLOB=0.0, W_CC=1.0, CC_ALPHA=0.0, | |
| doc="option ii, CC-DiceCE (per-lesion Voronoi DiceCE, eps 0; BiCC alpha 0) in place of the blob term"), | |
| "nnUNetTrainer_C2D2_A_ii_bicc": _mk("nnUNetTrainer_C2D2_A_ii_bicc", W_BLOB=0.0, W_CC=1.0, CC_ALPHA=0.25, | |
| doc="option ii, BiCC alpha 1/4 in place of the blob term"), | |
| } | |
| def _mk_smoke_init(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 __init__ | |
| for _n, _c in list(_GEN.items()): | |
| _GEN[_n + "_Smoke"] = type(_n + "_Smoke", (_C2Smoke, _c), {"__init__": _mk_smoke_init(_c), "__module__": __name__}) | |
| globals().update(_GEN) | |