edschen's picture
EAGLE model u_pair_2c v1 (part 3)
473c56f verified
Raw History Blame Contribute Delete
20.8 kB
"""prompt2 (direction2, 2026-11-16): a DRAW-ONLY stage 2 ("where", not "whether") trained on TRUTHFUL prompts.
New file. Imports cascade2_nnunet read-only (never edits it). Exposed to nnU-Net through the shim
src/nnUNet/nnunetv2/training/nnUNetTrainer/nnUNetTrainer_D2Cascade2Prompt.py (names nnUNetTrainer_C2P*).
Why (cascade2/REPORT.md "Why stage 2 vetoes or ignores the heat"): realistic heat contains false blobs labelled background,
so stage 2 learned "heat here, answer = nothing" (veto) or ignored the heat (greedy learner). Promptable segmenters
(nnInteractive, LesionLocator, VISTA3D) generate EVERY training prompt from a ground-truth object. Here:
PromptTransform (DA worker, right after nnU-Net's SpatialTransform; channel 1 = loaded heat = bank / real OOF heat):
1. IGNORE: unlabelled heat-positive tissue (stored heat >= ign_thr, label 0, > ign_near voxels from any GT lesion; dilated
1 voxel but never into the near-lesion zone) -> label 3. The near-lesion zone keeps its label 0 so the BOUNDARY stays
supervised (no licence to copy the heat halo).
2. PROMPTS from GT components only (26-conn, >= min_vox voxels in the patch). Each component is prompted with p_prompt
(whole sample unprompted with p_none). Channel 1 is REPLACED by the prompt map (false heat never reaches the input):
mode "heat" (encoding a): the stored heat restricted to dilate(component, nb_r); if the heat missed the component
(peak < mark_thr in dilate(c, 2)) or with p_syn anyway, a synthetic heat-like blob (component dilated 0-2, Gaussian
blur sigma 0.7-1.8, amplitude 0.5-1, low-frequency multiplicative noise); then shape jitter: grey dilation /
erosion (morph range), fragmentation (p_frag), gamma, integer shift (+-shift).
mode "ball" (encoding b, LesionLocator): a binary ball, radius U(ball_r), at a random interior voxel (eroded component
when possible), shifted 1-2 voxels with p_ball_out (inference centres come from heat candidates, not from the GT).
3. UNPROMPTED lesions: label 3 (ignore, dilated 1) with prob 1 - p_unprompted_target, else kept as targets (label 1).
Components < min_vox voxels: ignore.
4. FADE (R14-style, hard-edged): prompted lesions < fade_max_vox (5 mL) voxels get, with prob fade_p each, their T1 contrast faded
30-70 % toward their ring (HeatPerturbTransform._fade, reused), so presence must come from the prompt and extent from
the residual T1.
5. Target channel 1 (emit_ids) = prompted component id (for the Kervadec-style term; sliced off for nnU-Net's loss).
PromptLoss = nnU-Net DC+CE (deep supervision, ignore 3) on target channel 0 + W_K * mean over prompted components of
relu(log eps - log(mean_{v in c} p_lesion(v))): a Kervadec-2020-style lower size bound ("the prompted region cannot be
empty", mean probability >= eps inside the prompted GT component), in log form so the gradient does not vanish at p ~ 0,
one term per component (small lesions weigh as much as big ones).
Trainers (Dataset979, fold c2s2x_detA_ii_x, D331 warm start, bank heat override, small-lesion component sampling: all
inherited from nnUNetTrainer_C2DelBankConv). The CONTRA patients of stage-1 fold 0 (20) are HELD OUT of training so a
label-safe real-FLAIR-heat evaluation exists (their OOF heat comes from the fold-0 detector, which never saw them either).
"""
from __future__ import annotations
import json
import os
import random as _random
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 (HeatPerturbTransform, nnUNetTrainer_C2DelBankConv, _label26, _mf, IGNORE) # noqa: E402
from arch2stage_nnunet import _insert_after_spatial, _bbox_slices # noqa: E402
from batchgeneratorsv2.transforms.base.basic_transform import BasicTransform # noqa: E402
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer # noqa: E402
C = N.C
# ===================================================================================================== prompt rendering
def ball_mask(shape, centre, r):
"""binary ball (Euclidean, voxel units) of radius r at centre (may lie outside the box; clipped)."""
out = np.zeros(shape, np.float32)
ri = int(np.ceil(r))
sl = tuple(slice(max(0, int(c) - ri), min(s, int(c) + ri + 1)) for c, s in zip(centre, shape))
if any(s.stop <= s.start for s in sl):
return out
g = np.meshgrid(*[np.arange(s.start, s.stop) for s in sl], indexing="ij")
d2 = sum((gi - float(ci)) ** 2 for gi, ci in zip(g, centre))
out[sl] = (d2 <= r * r + 1e-6).astype(np.float32)
return out
def synth_heat_blob(m: np.ndarray, rng) -> np.ndarray:
"""heat-like blob from a GT component mask (local box): dilate 0-2, blur, amplitude, low-frequency noise."""
import scipy.ndimage as ndi
r = int(rng.integers(0, 3))
mm = _mf(m.astype(np.uint8), r, "max") > 0 if r else m
g = ndi.gaussian_filter(mm.astype(np.float32), float(rng.uniform(0.7, 1.8)))
if g.max() <= 0:
return g
g = np.clip(g / g.max() * 1.3, 0, 1) * float(rng.uniform(0.5, 1.0))
cs = int(rng.integers(3, 7))
coarse = rng.uniform(0.6, 1.0, size=[max(1, int(np.ceil(n / cs))) for n in g.shape]).astype(np.float32)
field = F.interpolate(torch.from_numpy(coarse)[None, None], size=tuple(g.shape), mode="trilinear", align_corners=False)[0, 0].numpy()
g = g * field
g[g < 0.05] = 0
return g
class PromptTransform(BasicTransform):
def __init__(self, mode="heat", p_prompt=0.8, p_none=0.1, p_unprompted_target=0.3, ign_thr=0.3, ign_near=2, nb_r=4,
mark_thr=0.3, p_syn=0.15, morph=(-1, 3), p_morph=0.6, p_frag=0.25, frag_keep=(0.6, 0.9), p_gamma=0.5,
gamma=(0.7, 1.4), p_shift=0.5, shift=2, ball_r=(3.0, 5.0), p_ball_out=0.25, fade_p=0.3, fade=(0.3, 0.7),
fade_max_vox=5000, min_vox=3, emit_ids=True, max_comp=40):
super().__init__()
assert mode in ("heat", "ball", "both"), mode
self.__dict__.update({k: v for k, v in locals().items() if k not in ("self", "__class__")})
self._fader = HeatPerturbTransform(fade_p=fade_p, fade=fade, fade_max_vox=fade_max_vox, mark_thr=0.5, keep_thr=0.5,
fade_hard=True, max_fade=max_comp)
# ---- pieces
def _ignore_unlabelled_heat(self, s0: np.ndarray, stored: np.ndarray) -> np.ndarray:
cand = (stored >= self.ign_thr) & (s0 == 0)
if not cand.any():
return s0
# work inside the heat bounding box (+ margin): lesions farther away cannot be 'near' a candidate voxel (speed only)
bb = _bbox_slices(torch.from_numpy(cand), self.ign_near + 2)
sb = s0[bb]
les = sb == 1
near = _mf(les.astype(np.uint8), self.ign_near, "max") > 0 if les.any() else np.zeros_like(les)
cm = cand[bb] & ~near
if not cm.any():
return s0
cm = (_mf(cm.astype(np.uint8), 1, "max") > 0) & ~near & (sb == 0)
s0 = s0.copy(); v = s0[bb]; v[cm] = IGNORE; s0[bb] = v
return s0
def _heat_prompt(self, m_loc, st_loc, rng):
nb = _mf(m_loc.astype(np.uint8), self.nb_r, "max") > 0
hc = st_loc * nb
near2 = _mf(m_loc.astype(np.uint8), 2, "max") > 0
marked = float(hc[near2].max()) >= self.mark_thr if near2.any() else False
if (not marked) or rng.uniform() < self.p_syn:
h = synth_heat_blob(m_loc, rng); src = "syn"
else:
h = hc.astype(np.float32); src = "heat"
if rng.uniform() < self.p_morph:
r = int(rng.integers(self.morph[0], self.morph[1] + 1))
if r > 0:
h = _mf(h, r, "max")
elif r < 0:
he = _mf(h, -r, "min")
if (he > 0.05).sum() >= 3:
h = he
if rng.uniform() < self.p_frag and (h > 0.05).sum() > 20:
cs = int(rng.integers(3, 8))
coarse = rng.uniform(size=[max(1, int(np.ceil(n / cs))) for n in h.shape]).astype(np.float32)
field = F.interpolate(torch.from_numpy(coarse)[None, None], size=tuple(h.shape), mode="trilinear", align_corners=False)[0, 0].numpy()
sup = h > 0.05
thr = np.quantile(field[sup], 1 - rng.uniform(*self.frag_keep))
h2 = h * (field >= thr)
if (h2 > 0.05).sum() >= 3:
h = h2
if rng.uniform() < self.p_gamma and h.max() > 0:
h = np.clip(h, 0, 1) ** float(rng.uniform(*self.gamma))
if rng.uniform() < self.p_shift:
sh = [int(rng.integers(-self.shift, self.shift + 1)) for _ in range(3)]
if any(sh):
h = np.roll(h, sh, axis=(0, 1, 2))
return np.clip(h, 0, 1).astype(np.float32), src
def _ball_prompt(self, m_loc, rng):
er = _mf(m_loc.astype(np.uint8), 1, "min") > 0
pool = er if (er.any() and rng.uniform() < 0.7) else m_loc
idx = np.argwhere(pool)
c = idx[rng.integers(len(idx))].astype(float)
if rng.uniform() < self.p_ball_out:
c = c + rng.integers(-2, 3, size=3)
return ball_mask(m_loc.shape, c, float(rng.uniform(*self.ball_r)))
# ---- main
def apply(self, data_dict, **params):
img = data_dict["image"]; seg = data_dict.get("segmentation")
if seg is None:
return data_dict
rng = np.random.default_rng(_random.getrandbits(32))
t1 = img[0]; stored = img[1].clamp(0, 1).numpy()
s0 = seg[0].numpy().astype(np.int16)
s0 = self._ignore_unlabelled_heat(s0, stored)
prompt = np.zeros(s0.shape, np.float32)
ids = np.zeros(s0.shape, np.int16)
les = s0 == 1
if les.any():
bb = _bbox_slices(torch.from_numpy(les), 0)
lab, n = _label26(les[bb])
sizes = np.bincount(lab.ravel(), minlength=n + 1)
import scipy.ndimage as ndi
objs = ndi.find_objects(lab)
none = rng.uniform() < self.p_none
order = list(range(1, n + 1)); rng.shuffle(order)
k = 0
off = [s.start for s in bb]
for c in order:
o = objs[c - 1]
if o is None:
continue
pad = max(self.nb_r, 6) + self.shift + 2
sl = tuple(slice(max(0, s.start + a - pad), min(dim, s.stop + a + pad)) for s, a, dim in zip(o, off, s0.shape))
lsl = tuple(slice(s.start - a, s.stop - a) for s, a in zip(sl, off))
# local component mask in the full-patch local box (lab lives in the bbox frame)
m_loc = np.zeros([s.stop - s.start for s in sl], bool)
inner = tuple(slice(max(0, ls.start), min(lab.shape[d], ls.stop)) for d, ls in enumerate(lsl))
tgt = tuple(slice(i.start - ls.start, i.stop - ls.start) for i, ls in zip(inner, lsl))
m_loc[tgt] = lab[inner] == c
prompted = (not none) and sizes[c] >= self.min_vox and k < self.max_comp and rng.uniform() < self.p_prompt
if prompted:
k += 1
mode = self.mode if self.mode != "both" else ("heat" if rng.uniform() < 0.5 else "ball")
if mode == "heat":
p, _src = self._heat_prompt(m_loc, stored[sl], rng)
else:
p = self._ball_prompt(m_loc, rng)
prompt[sl] = np.maximum(prompt[sl], p)
v = ids[sl]; v[m_loc] = k; ids[sl] = v
elif sizes[c] < self.min_vox or rng.uniform() >= self.p_unprompted_target:
d1 = _mf(m_loc.astype(np.uint8), 1, "max") > 0
v = s0[sl]; v[d1 & (v != -1) & ~((v == 1) & ~m_loc)] = IGNORE; s0[sl] = v
if k and self.fade_p > 0:
pm = torch.from_numpy((ids > 0).astype(np.float32))
img[0] = self._fader._fade(t1, torch.from_numpy((s0 == 1).astype(np.int16)), pm, pm, t1 != 0)
img[1] = torch.from_numpy(prompt).to(img.dtype)
data_dict["image"] = img
s0t = torch.from_numpy(s0).to(seg.dtype)
if self.emit_ids:
data_dict["segmentation"] = torch.stack([s0t, torch.from_numpy(ids).to(seg.dtype)])
else:
data_dict["segmentation"] = s0t[None]
return data_dict
# ============================================================================================================== loss
class PromptLoss(nn.Module):
def __init__(self, base, w_k=0.0, eps=0.5, lesion_ch=1):
super().__init__()
self.base, self.w_k, self.eps, self.lesion_ch = base, w_k, eps, lesion_ch
self.acc = {"n": 0, "k": 0.0, "nk": 0}
def forward(self, outputs, targets):
lst = isinstance(targets, (list, tuple))
t0 = targets[0] if lst else targets
tb = [t[:, :1] for t in targets] if lst else targets[:, :1]
loss = self.base(outputs, tb)
if self.w_k > 0 and t0.shape[1] > 1:
k = self.kterm(outputs[0] if lst else outputs, t0[:, 1])
if k is not None:
loss = loss + self.w_k * k
self.acc["k"] += float(k.detach()); self.acc["nk"] += 1
self.acc["n"] += 1
return loss
def kterm(self, out, ids):
ids = ids.long()
m = ids > 0
if not bool(m.any()):
return None
p = torch.softmax(out.float(), 1)[:, self.lesion_ch]
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]))
mean = s / c.clamp(min=1)
return F.relu(np.log(self.eps) - torch.log(mean + 1e-6)).mean()
# ========================================================================================================== trainers
class _C2PBase(nnUNetTrainer_C2DelBankConv):
"""draw-only stage 2 (see module docstring). Class attributes are the switches."""
PROMPT_KW = {}
W_K = 0.0
K_EPS = 0.5
HOLDOUT_CONTRA_FOLD = 0
def do_split(self):
tr, va = super().do_split()
assign = C.patient_folds()["assign"]
hold = {p for p, f in assign.items() if f == self.HOLDOUT_CONTRA_FOLD and p.startswith("contra")}
tr2 = [k for k in tr if not (k.startswith("r_") and C.patient(k) in hold)]
if not getattr(self, "_p2_logged", False):
self.print_to_log_file(f"C2P: held out {len(tr) - len(tr2)} CONTRA patients of stage-1 fold {self.HOLDOUT_CONTRA_FOLD} "
f"(label-safe real-heat evaluation); {len(tr2)} training keys; prompt {json.dumps(self.PROMPT_KW)}; "
f"W_K {self.W_K} eps {self.K_EPS}")
self._p2_logged = True
return tr2, va
def _prompt_t(self):
return PromptTransform(**self.PROMPT_KW)
def get_training_transforms(self, *args, **kwargs):
return _insert_after_spatial(nnUNetTrainer.get_training_transforms(*args, **kwargs), self._prompt_t())
def _build_loss(self):
return PromptLoss(super()._build_loss(), self.W_K, self.K_EPS)
def on_train_epoch_end(self, train_outputs):
a = getattr(self.loss, "acc", None)
if a and a["n"]:
self.print_to_log_file(f"C2P loss: kervadec term mean {a['k'] / max(1, a['nk']):.4f} over {a['nk']} of {a['n']} steps (w {self.W_K})")
self.loss.acc = {"n": 0, "k": 0.0, "nk": 0}
return super().on_train_epoch_end(train_outputs)
class nnUNetTrainer_C2PHeat(_C2PBase):
"""encoding (a): GT-restricted bank/real heat + synthetic blobs for heat-missed lesions, shape jitter."""
PROMPT_KW = dict(mode="heat")
class nnUNetTrainer_C2PBall(_C2PBase):
"""encoding (b): LesionLocator ball (r 3-5) at a jittered interior point; extent must come from T1."""
PROMPT_KW = dict(mode="ball")
class nnUNetTrainer_C2PBallK(_C2PBase):
"""encoding (b) + Kervadec-style non-empty-inside-prompt term (log hinge, eps 0.5, weight 0.2)."""
PROMPT_KW = dict(mode="ball")
W_K = 0.2
class nnUNetTrainer_C2PHeatK(_C2PBase):
"""encoding (a) + Kervadec-style term."""
PROMPT_KW = dict(mode="heat")
W_K = 0.2
# ---------------------------------------------------------------------------------------------------- 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_C2PHeat_Smoke = _smoke(nnUNetTrainer_C2PHeat)
nnUNetTrainer_C2PBall_Smoke = _smoke(nnUNetTrainer_C2PBall)
nnUNetTrainer_C2PBallK_Smoke = _smoke(nnUNetTrainer_C2PBallK)
TRAINER_NAMES = sorted(n for n in globals() if n.startswith("nnUNetTrainer_C2P"))
class nnUNetTrainer_C2PBallNoContra(nnUNetTrainer_C2PBall):
"""Main session 2026-11-16: training-source ablation of the draw-only stage 2: ball prompts, NO CONTRA (100 % T1-family,
T1-traced masks). For a pure boundary drawer, CONTRA's FLAIR-traced envelopes may teach non-T1-style edges."""
GROUPS = {"t1": 1.0, "real": 0.0}
class nnUNetTrainer_C2PBallPO(_C2PBase):
"""Main session 2026-11-17 (user: 'why not enforce always draw? will we fight the warm-started weights?'). Round-2 drawer:
PROMPT-ONLY (every GT component prompted, no prompt-free patches, unprompted components always ignore, so the network is
never asked to decide 'whether'), ball encoding, Kervadec non-empty term, and NO warm-start protection: prompt stem at full
T1-stem scale and full LR from epoch 0 (D331 init kept for the T1 boundary style, but free to change)."""
PROMPT_KW = dict(mode="ball", p_prompt=1.0, p_none=0.0, p_unprompted_target=0.0)
W_K = 0.2
NEW_STEM_REL = 1.0
BACKBONE_WARMUP_EPOCHS = 0
# ---- 2026-11-17 main session: PLACEMENT-OFFSET ball drawer (user approved). Training balls follow the measured test-time
# placement (prompt2/ball_offset: candidate heat-centroid vs GT lesion over DEV-A + CONTRA + dev-test, 1,386 lesion-overlapping
# candidates): inside the lesion 72 %; when outside, distance (vox) 1:44 % 2:21 % 3:15 % 4:8 % 5:4 % 6:2 % 7:2 % 8-10:3 %.
# Radius sized like the inference rule (cls2_drawer_test 'sized'): r = clip(0.6 * equivalent-sphere radius of a heat-like
# envelope, 2, 5), envelope volume = lesion volume x U(0.6, 3.5) (measured envelope/lesion ratio IQR 0.6-3.4 for < 5 mL).
_OFF_P = np.array([.444, .214, .152, .078, .039, .018, .023, .010, .005, .016]); _OFF_P = _OFF_P / _OFF_P.sum()
def sized_ball_radius(env_vox):
return float(np.clip(0.6 * (3.0 * float(env_vox) / (4.0 * np.pi)) ** (1.0 / 3.0), 2.0, 5.0))
class PromptTransformOffset(PromptTransform):
def __init__(self, p_inside=0.72, env_ratio=(0.6, 3.5), **kw):
super().__init__(**kw); self.p_inside = p_inside; self.env_ratio = env_ratio
def _ball_prompt(self, m_loc, rng):
import scipy.ndimage as ndi
r = sized_ball_radius(m_loc.sum() * rng.uniform(*self.env_ratio))
if rng.uniform() < self.p_inside:
er = _mf(m_loc.astype(np.uint8), 1, "min") > 0
pool = er if (er.any() and rng.uniform() < 0.5) else m_loc
idx = np.argwhere(pool); c = idx[rng.integers(len(idx))].astype(float)
else:
d = 1 + int(rng.choice(len(_OFF_P), p=_OFF_P))
dist = ndi.distance_transform_edt(~m_loc)
ring = (np.abs(dist - d) <= 0.5)
if not ring.any():
ring = (dist > 0) & (dist <= d + 0.5)
idx = np.argwhere(ring); c = idx[rng.integers(len(idx))].astype(float)
return ball_mask(m_loc.shape, c, r)
class nnUNetTrainer_C2PBallOff(_C2PBase):
"""Round-2b drawer: placement-offset + candidate-sized ball prompts (test-realistic), prompt-only (every lesion prompted),
Kervadec term, full-scale prompt stem, full LR from epoch 0. Inference must use the 'sized' ball radius rule."""
PROMPT_KW = dict(mode="ball", p_prompt=1.0, p_none=0.0, p_unprompted_target=0.0)
W_K = 0.2
NEW_STEM_REL = 1.0
BACKBONE_WARMUP_EPOCHS = 0
def _prompt_t(self):
return PromptTransformOffset(**self.PROMPT_KW)