edschen's picture
EAGLE model u_pair_2c v1 (part 3)
473c56f verified
Raw History Blame Contribute Delete
17.7 kB
"""archfused (direction2, 2026-11-14): single-network architectures in which FLAIR is the DETECTOR / CONFIRMATION cue
and T1 draws the boundary. "Peek-and-Confirm" network (PACNet) and its explicit-AND variant.
Mechanism (one forward pass, no cascade):
* T1 trunk = the D331 ResEnc-L encoder + UNet decoder, 1 input channel (T1 only). Warm-started EXACTLY from D331
(same parameter names: encoder.*, decoder.*), so at initialisation the network computes D331's prediction.
* FLAIR branch = a light residual encoder that sees FLAIR ONLY (it cannot encode T1 evidence, whatever gradient it
receives) + a FLAIR-only DETECTION head: a stride-4 heatmap q of "FLAIR anomaly here" trained with TOLERANT targets
(any anomaly in a 4^3 block; a 1-coarse-voxel ring around it is not penalised; per-component balanced weights so a
0.1 mL focus counts as much as an 80 mL infarct). This unimodal head must solve its task alone (UMT/UME logic):
the branch learns to read FLAIR even when the T1 trunk already fits the training labels.
* Confirm gates ("peek"): at decoder stages /16, /8, /4, /2 the T1 decoder features h are multiplied by
1 + tanh(W[h, F_flair, q]) (an attention gate driven by FLAIR features + the detection map, zero-initialised =>
identity at start; ControlNet-style zero conv: the gate weights still get gradient, the FLAIR branch learns from
its own head regardless). The full-resolution decoder stage is NOT gated: T1 alone draws the boundary.
* T1-only pass: the same decoder run without gates gives a unimodal T1 segmentation (aux loss; keeps the T1 trunk a
complete segmenter and gives a free "fused minus T1-only" diagnostic).
* PAC-AND (explicit AND with an escape path): lesion logit z1 += log(a + (1 - a) * sigmoid(q_up)), where
a = sigmoid(conv(h_T1)) is an "escape" map computed from T1-only features. softmax then multiplies the lesion
class's unnormalised probability by g = a + (1-a) q in [a, 1]: FLAIR can only VETO (never create) lesion mass,
and strong T1 evidence can learn a -> 1 (FLAIR-silent lesions survive).
Counterfactual (cue-conflict) training is supported in two ways (see archfused_trainer.py):
* label value 2 in a training label = "FLAIR anomaly that is NOT lesion" (decoy / WMH-like): seg target 0, det
target 1 (the interface for the confirmgen agent's counterfactual cases; never trained as a segmentation class);
* built-in on-the-fly GPU ops below: FLAIR decoys (label 0, det 1), T1 attenuation of real lesions (label 1, weak
T1, FLAIR intact), T1 mimics (label 0, FLAIR normal; OFF by default, gated on the FLAIR-signal census).
"""
from __future__ import annotations
import math
from typing import Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from dynamic_network_architectures.building_blocks.residual import BasicBlockD
from dynamic_network_architectures.building_blocks.residual_encoders import ResidualEncoder
from dynamic_network_architectures.initialization.weight_init import InitWeights_He
def _guard(p):
assert "XHOLDOUT" not in str(p).upper(), f"XHOLDOUT firewall: {p}"
return p
# ------------------------------------------------------------------------------------------------------- network parts
class FlairBranch(nn.Module):
"""FLAIR-only encoder (5 stages, strides 1,2,4,8,16) + stride-4 detection head (FPN 16 -> 8 -> 4)."""
def __init__(self, conv_op, norm_op, norm_kw, nonlin, nonlin_kw, feats=(16, 32, 64, 96, 128), blocks=(1, 2, 2, 2, 2),
det_bias: float = -2.0):
super().__init__()
self.feats = tuple(feats)
self.enc = ResidualEncoder(1, 5, list(feats), conv_op, 3, [[1, 1, 1]] + [[2, 2, 2]] * 4, list(blocks), True,
norm_op, norm_kw, None, None, nonlin, nonlin_kw, BasicBlockD, return_skips=True)
c = 64
self.lat16 = conv_op(feats[4], c, 1)
self.lat8 = conv_op(feats[3], c, 1)
self.lat4 = conv_op(feats[2], c, 1)
self.det_conv = nn.Sequential(conv_op(c, c, 3, padding=1), norm_op(c, **norm_kw), nonlin(**nonlin_kw))
self.det_out = conv_op(c, 1, 1)
self._det_bias = det_bias
def init_head(self):
nn.init.zeros_(self.det_out.weight)
nn.init.constant_(self.det_out.bias, self._det_bias)
def forward(self, fl):
sk = self.enc(fl) # 5 skips at /1 /2 /4 /8 /16
p = self.lat16(sk[4])
p = F.interpolate(p, size=sk[3].shape[2:], mode="trilinear", align_corners=False) + self.lat8(sk[3])
p = F.interpolate(p, size=sk[2].shape[2:], mode="trilinear", align_corners=False) + self.lat4(sk[2])
q = self.det_out(self.det_conv(p)) # logits at /4
return sk, q
class ConfirmGate(nn.Module):
"""h <- h * (1 + tanh(W2 lrelu(W1 [P_h h, P_f F, q, sigmoid(q)]))) (zero-initialised W2 => identity)."""
def __init__(self, conv_op, c_h, c_f, hidden=32, beta=False):
super().__init__()
self.ph = conv_op(c_h, 16, 1)
self.pf = conv_op(c_f, 16, 1)
self.w1 = conv_op(16 + 16 + 2, hidden, 3, padding=1)
self.w2 = conv_op(hidden, c_h * (2 if beta else 1), 1)
self.beta = beta
def zero_init(self):
nn.init.zeros_(self.w2.weight)
nn.init.zeros_(self.w2.bias)
def forward(self, h, f, q):
if f.shape[2:] != h.shape[2:]:
f = F.interpolate(f, size=h.shape[2:], mode="trilinear", align_corners=False)
qq = F.interpolate(q, size=h.shape[2:], mode="trilinear", align_corners=False)
z = self.w1(torch.cat([self.ph(h), self.pf(f), qq, torch.sigmoid(qq)], 1))
z = self.w2(F.leaky_relu(z, 0.01))
if self.beta:
g, b = z.chunk(2, 1)
gamma = 1 + torch.tanh(g)
return h * gamma + b, gamma
gamma = 1 + torch.tanh(z)
return h * gamma, gamma
class PACNet(nn.Module):
"""Peek-and-Confirm network. forward(x) returns the fused segmentation (deep-supervision list or tensor) exactly
like an nnU-Net network, so validation / nnUNetv2_predict work unchanged. forward_train(x) returns a dict."""
GATED_DECODER_STAGES = (0, 1, 2, 3) # /16 /8 /4 /2 (stage 4 = full resolution: T1 only)
def __init__(self, base_unet: nn.Module, and_gate: bool = False, alpha_bias: float = 0.0, film_beta: bool = False,
flair_feats=(16, 32, 64, 96, 128), flair_blocks=(1, 2, 2, 2, 2)):
super().__init__()
self.encoder = base_unet.encoder # T1 trunk (same parameter names as D331)
self.decoder = base_unet.decoder
e = self.encoder
self.flair = FlairBranch(e.conv_op, e.norm_op, e.norm_op_kwargs, e.nonlin, e.nonlin_kwargs, flair_feats, flair_blocks)
n_dec = len(self.decoder.stages)
assert n_dec == 5, f"expected a 6-stage ResEnc-L (5 decoder stages), got {n_dec}"
gates = {}
for s in self.GATED_DECODER_STAGES:
c_h = e.output_channels[-(s + 2)]
c_f = flair_feats[4 - s]
gates[str(s)] = ConfirmGate(e.conv_op, c_h, c_f, beta=film_beta)
self.gates = nn.ModuleDict(gates)
self.and_gate = and_gate
if and_gate:
self.alpha_head = e.conv_op(e.output_channels[0], 1, 1)
self._alpha_bias = alpha_bias
# init new modules (the T1 trunk is overwritten by the warm start)
init = InitWeights_He(1e-2)
self.flair.apply(init)
self.gates.apply(init)
self.flair.init_head()
for g in self.gates.values():
g.zero_init()
if and_gate:
nn.init.zeros_(self.alpha_head.weight)
nn.init.constant_(self.alpha_head.bias, alpha_bias)
# names of every parameter that is NOT part of the D331 trunk
def new_param_prefixes(self):
return ("flair.", "gates.", "alpha_head.")
def _decode(self, skips, fskips=None, q=None, modulate=False, all_levels=True):
dec = self.decoder
lres = skips[-1]
outs, gammas = [], {}
x = None
for s in range(len(dec.stages)):
x = dec.transpconvs[s](lres)
x = torch.cat((x, skips[-(s + 2)]), 1)
x = dec.stages[s](x)
if modulate and str(s) in self.gates:
x, gm = self.gates[str(s)](x, fskips[4 - s], q)
gammas[s] = gm
if all_levels or s == len(dec.stages) - 1:
outs.append(dec.seg_layers[s](x))
lres = x
return outs[::-1], x, gammas
def _apply_and(self, outs, q, h_t1):
a_full = torch.sigmoid(self.alpha_head(h_t1).float())
res = []
for o in outs:
qq = torch.sigmoid(F.interpolate(q.float(), size=o.shape[2:], mode="trilinear", align_corners=False))
aa = a_full if a_full.shape[2:] == o.shape[2:] else F.interpolate(a_full, size=o.shape[2:], mode="trilinear", align_corners=False)
g = (aa + (1 - aa) * qq).clamp_min(1e-4)
o = o.float().clone()
o[:, 1:2] = o[:, 1:2] + torch.log(g)
res.append(o)
return res, a_full
def forward_train(self, x, need_t1: bool = True, flair_only: bool = False) -> Dict[str, object]:
t1, fl = x[:, :1], x[:, 1:2]
fskips, q = self.flair(fl)
if flair_only:
return {"q": q}
ds = bool(self.decoder.deep_supervision)
skips = self.encoder(t1)
seg, h_f, gammas = self._decode(skips, fskips, q, modulate=True, all_levels=ds)
out = {"q": q, "gammas": gammas}
if need_t1 or self.and_gate:
seg_t, h_t, _ = self._decode(skips, modulate=False, all_levels=ds)
out["seg_t1"] = seg_t
if self.and_gate:
seg, a = self._apply_and(seg, q, h_t)
out["alpha"] = a
out["seg"] = seg
return out
def forward(self, x):
o = self.forward_train(x, need_t1=False)
seg = o["seg"]
return seg if self.decoder.deep_supervision else seg[0]
def build_pacnet(base_unet, and_gate=False, alpha_bias=0.0, film_beta=False):
return PACNet(base_unet, and_gate=and_gate, alpha_bias=alpha_bias, film_beta=film_beta)
# ------------------------------------------------------------------------------------- tolerant FLAIR detection loss
def det_targets(anomaly: torch.Tensor, ignore: Optional[torch.Tensor], stride: int = 4, tol: int = 1):
"""anomaly/ignore: [B,1,D,H,W] bool at full res. Returns core [B,1,d,h,w] float (any anomaly in a stride^3 block),
valid mask (excludes a `tol`-voxel ring around core and blocks containing ignore), component-balanced weights."""
an = anomaly.float()
core = F.max_pool3d(an, stride, stride)
ring = F.max_pool3d(core, 2 * tol + 1, 1, tol) - core
valid = 1 - ring
if ignore is not None and ignore.any():
valid = valid * (1 - F.max_pool3d(ignore.float(), stride, stride))
w = torch.ones_like(core)
cn = core.detach().cpu().numpy() > 0.5
if cn.any():
import scipy.ndimage as ndi
st = np.ones((3, 3, 3), bool)
wn = np.ones(cn.shape, np.float32)
for b in range(cn.shape[0]):
lab, n = ndi.label(cn[b, 0], structure=st)
if n == 0:
continue
sz = np.bincount(lab.ravel())[1:].astype(np.float32)
npos = sz.sum()
per = npos / (n * sz) # each component gets equal total weight
wb = np.ones(lab.shape, np.float32)
m = lab > 0
wb[m] = 0.5 + 0.5 * per[lab[m] - 1] # half uniform, half component-balanced
wn[b, 0] = wb
w = torch.from_numpy(wn).to(core.device)
return core, valid, w
def det_loss(q: torch.Tensor, core, valid, w, alpha: float = 0.75, gamma: float = 2.0):
q = q.float()
ce = F.binary_cross_entropy_with_logits(q, core, reduction="none")
p = torch.sigmoid(q)
pt = p * core + (1 - p) * (1 - core)
at = alpha * core + (1 - alpha) * (1 - core)
fl = at * ce * (1 - pt) ** gamma * valid * w
npos = (core * valid).sum().clamp_min(1.0)
return fl.sum() / npos
# --------------------------------------------------------------------------------- on-the-fly counterfactual GPU ops
def _blob(shape, r, dev, gen=None):
"""soft irregular ellipsoid in a local box: returns (mask [d,h,w] in [0,1], half-sizes)."""
hs = [int(math.ceil(ri)) + 2 for ri in r]
zz, yy, xx = torch.meshgrid(*[torch.arange(-h, h + 1, device=dev, dtype=torch.float32) for h in hs], indexing="ij")
d = torch.sqrt((zz / r[0]) ** 2 + (yy / r[1]) ** 2 + (xx / r[2]) ** 2)
noise = torch.randn((1, 1, 4, 4, 4), device=dev)
noise = F.interpolate(noise, size=d.shape, mode="trilinear", align_corners=True)[0, 0]
d = d * (1 + 0.3 * noise)
m = torch.clamp(1.5 - d * 1.0, 0, 1) # ~1 voxel soft edge at d = 1
m = torch.where(d < 0.5, torch.ones_like(m), m)
return m, hs
def _sample_centers(cand: torch.Tensor, n: int):
idx = torch.nonzero(cand, as_tuple=False)
if idx.shape[0] == 0:
return []
sel = torch.randint(0, idx.shape[0], (n,), device=cand.device)
return [tuple(int(v) for v in idx[s]) for s in sel]
def _paste(vol, m, c, hs, val_fn):
"""vol[d,h,w] += val_fn(local vol, m) within the local box centred at c (clipped at the patch border)."""
D, H, W = vol.shape
sl_v, sl_m = [], []
for ax, (ci, hi, L) in enumerate(zip(c, hs, (D, H, W))):
a, b = ci - hi, ci + hi + 1
a0, b0 = max(a, 0), min(b, L)
sl_v.append(slice(a0, b0)); sl_m.append(slice(a0 - a, (a0 - a) + (b0 - a0)))
mm = m[sl_m[0], sl_m[1], sl_m[2]]
loc = vol[sl_v[0], sl_v[1], sl_v[2]]
vol[sl_v[0], sl_v[1], sl_v[2]] = loc + val_fn(loc, mm)
return sl_v, mm
def cf_flair_decoys(x: torch.Tensor, lesion: torch.Tensor, anomaly: torch.Tensor, b: int, n_max: int = 4,
r_rng=(1.2, 6.0), amp_rng=(1.0, 3.5)):
"""Paint 1..n_max FLAIR-hyperintense blobs (label 0, det anomaly 1) in WM-like tissue away from lesions of sample b.
x [B,2,D,H,W] (normalised, 0 outside brain); lesion/anomaly [B,1,D,H,W] bool. In place. Returns #painted."""
t1, fl = x[b, 0], x[b, 1]
brain = t1 != 0
if brain.sum() < 1000:
return 0
med = t1[brain].median()
far = F.max_pool3d(lesion[b:b + 1].float(), 7, 1, 3)[0, 0] < 0.5
er = -F.max_pool3d(-(brain.float())[None, None], 7, 1, 3)[0, 0] > 0.5 # eroded brain (no rim artefacts)
cand = brain & far & er & (t1 > med)
if fl[brain].numel() == 0:
return 0
sd = fl[brain].float().std().clamp_min(0.2)
k = int(torch.randint(1, n_max + 1, (1,)).item())
done = 0
for c in _sample_centers(cand, k):
r = [float(torch.empty(1).uniform_(*r_rng)) for _ in range(3)]
m, hs = _blob(None, r, x.device)
amp = float(torch.empty(1).uniform_(*amp_rng)) * float(sd)
sl, mm = _paste(fl, m.to(fl.dtype), c, hs, lambda loc, mm: amp * mm * (loc != 0).to(loc.dtype))
anomaly[b, 0][sl[0], sl[1], sl[2]] |= (mm > 0.5)
done += 1
return done
def cf_t1_mimics(x: torch.Tensor, lesion: torch.Tensor, b: int, n_max: int = 3, r_rng=(1.5, 6.0), depth_rng=(0.3, 0.8)):
"""Paint 1..n_max T1-HYPOintense lesion-like blobs (label 0, FLAIR untouched). OFF by default: only safe if the
FLAIR-signal census shows that T1-visible lesions essentially always carry FLAIR signal."""
t1 = x[b, 0]
brain = t1 != 0
if brain.sum() < 1000:
return 0
v = t1[brain].float()
med, lo = v.median(), torch.quantile(v[torch.randperm(v.numel(), device=v.device)[:200000]], 0.03)
far = F.max_pool3d(lesion[b:b + 1].float(), 7, 1, 3)[0, 0] < 0.5
er = -F.max_pool3d(-(brain.float())[None, None], 7, 1, 3)[0, 0] > 0.5
cand = brain & far & er & (t1 > med)
k = int(torch.randint(1, n_max + 1, (1,)).item())
done = 0
for c in _sample_centers(cand, k):
r = [float(torch.empty(1).uniform_(*r_rng)) for _ in range(3)]
m, hs = _blob(None, r, x.device)
u = float(torch.empty(1).uniform_(*depth_rng))
_paste(t1, m.to(t1.dtype), c, hs, lambda loc, mm: u * mm * (float(lo) - loc) * (loc != 0).to(loc.dtype))
done += 1
return done
def cf_t1_attenuate(x: torch.Tensor, lesion: torch.Tensor, b: int, u_rng=(0.4, 0.85), min_vox: int = 20):
"""Pull T1 inside the lesions of sample b towards the surrounding-tissue median (contrast kept 15-60%; soft edge),
FLAIR and label untouched: a 'T1-subtle, FLAIR-obvious' lesion. In place. Returns 1 if applied."""
les = lesion[b:b + 1].float()
if les.sum() < min_vox:
return 0
t1 = x[b, 0]
brain = t1 != 0
soft = F.avg_pool3d(F.max_pool3d(les, 3, 1, 1), 3, 1, 1)[0, 0] # dilate 1 + blur => soft edge
shell = (F.max_pool3d(les, 9, 1, 4)[0, 0] > 0.5) & ~(F.max_pool3d(les, 3, 1, 1)[0, 0] > 0.5) & brain
if shell.sum() < 20:
return 0
bg = t1[shell].median()
u = float(torch.empty(1).uniform_(*u_rng))
t1.add_((u * soft * (bg - t1) * brain.to(t1.dtype)).to(t1.dtype))
return 1
# ------------------------------------------------------------------------------------------------------- diagnostics
def soft_dice(p, g, eps=1e-5):
p = p.float().flatten(1); g = g.float().flatten(1)
return ((2 * (p * g).sum(1) + eps) / (p.sum(1) + g.sum(1) + eps))
def lesion_prob(seg_logits):
return torch.softmax(seg_logits.float(), 1)[:, 1:2]