edschen's picture
EAGLE model u_pair_2c v1 (part 3)
473c56f verified
Raw History Blame Contribute Delete
20.3 kB
"""archfused trainer logic (direction2, 2026-11-14). The nnU-Net trainer CLASSES are appended to
src/nnUNet/nnunetv2/training/nnUNetTrainer/nnUNetTrainer_V8xCanary.py (so nnU-Net can find them); they combine these
mixins with nnUNetTrainer_V10S (Design S: D331 warm start, GIN p 0.8 on every non-t0_ sample, 150 fused epochs).
ArchFusedMixin (PAC / PAC-AND, see archfused_net.py):
phase 1 (epochs 0 .. PRE_EPOCHS-1): FLAIR branch pre-training as a FLAIR-ONLY DETECTOR (tolerant, component-balanced
focal loss on the stride-4 heatmap). The T1 trunk is not run (no gradient, no compute). This is the fix
for the VS failure mode "FLAIR stem starts at ~0 at 0.1x LR next to a pretrained T1 pathway": both
modalities arrive at fusion as competent unimodal experts.
phase 2 (FUSED_EPOCHS, schedule identical to V10S: poly LR from 1e-2, D331 trunk at 0.1x LR for 50 epochs):
L = DS-seg(fused) + LAMBDA_T1 * DS-seg(T1-only pass) + LAMBDA_DET * det(FLAIR-only head).
Counterfactual cue-conflict ops on synthetic-FLAIR samples (keys not starting with t0_), before GIN:
CF_FDECOY_P FLAIR decoys: FLAIR-bright blobs, label 0, det target 1 ("FLAIR alone is not a lesion")
CF_T1ATT_P T1 attenuation of the real lesion: label 1, T1 contrast 15-60%, FLAIR intact
CF_T1MIMIC_P T1 mimics: T1-dark blobs, FLAIR normal, label 0 (default 0; census-gated)
label 2 in a training label (confirmgen counterfactual cases) => seg 0, det 1.
Diagnostics every DIAG_EVERY iterations -> <output_folder>/archfused_diag.jsonl and an "AF-DIAG" line per epoch:
grad-norm share of the FLAIR branch (+gates) in d L_fused / d theta; output change with FLAIR zeroed
(|dp| in brain / near lesions, soft-Dice change, flipped voxels); fused vs T1-only pass; gate |gamma-1| per
stage; detection-head voxel recall / FP rate; AND gate and escape values. A LAZY-FLAIR warning is printed
when the fused model's response to zeroing FLAIR stays negligible.
CFOnlyMixin: the same counterfactual ops on the plain single-network V10S (control: data vs architecture).
"""
from __future__ import annotations
import json
import os
import sys
import time
from typing import List
import numpy as np
import torch
import torch.nn.functional as F
from torch import autocast
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
from nnunetv2.utilities.helpers import dummy_context
from nnunetv2.utilities.get_network_from_plans import get_network_from_plans
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import archfused_net as an # noqa: E402
_WS_SRC = "/__EAGLE_BUNDLE_ROOT__/whisper_synth/src"
def _gin():
if _WS_SRC not in sys.path:
sys.path.insert(0, _WS_SRC)
import v10_gin
return v10_gin
def _apply_cf(trainer, data, target0, keys, lesion, anomaly):
"""counterfactual ops in place on synthetic-FLAIR samples; returns counts."""
st = {"t1att": 0, "fdecoy": 0, "t1mimic": 0}
if keys is None:
return st
for i, k in enumerate(keys):
if str(k).startswith("t0_"):
continue
if trainer.CF_T1ATT_P > 0 and torch.rand(1).item() < trainer.CF_T1ATT_P:
st["t1att"] += an.cf_t1_attenuate(data, lesion, i)
if trainer.CF_FDECOY_P > 0 and torch.rand(1).item() < trainer.CF_FDECOY_P:
st["fdecoy"] += an.cf_flair_decoys(data, lesion, anomaly, i)
if trainer.CF_T1MIMIC_P > 0 and torch.rand(1).item() < trainer.CF_T1MIMIC_P:
st["t1mimic"] += an.cf_t1_mimics(data, lesion, i)
return st
class ArchFusedMixin:
AND_GATE = False
ALPHA_BIAS = 0.0
FILM_BETA = False
PRE_EPOCHS = 15
FUSED_EPOCHS = 150
LAMBDA_T1 = 0.5
LAMBDA_DET = 1.0
CF_FDECOY_P = 0.5
CF_T1ATT_P = 0.25
CF_T1MIMIC_P = 0.0
DIAG_EVERY = 25
DIAG_GRAD = True
def __init__(self, plans, configuration, fold, dataset_json, device=torch.device('cuda')):
super().__init__(plans, configuration, fold, dataset_json, device)
self.num_epochs = self.PRE_EPOCHS + self.FUSED_EPOCHS
self._af_it = 0
self._af_rows: List[dict] = []
self._af_parts: List[dict] = []
self._af_lazy_epochs = 0
def _do_i_compile(self):
return False # forward_train is not the compiled forward; keep eager (also avoids graph breaks)
# ------------------------------------------------------------------------------------------------ network
@classmethod
def build_network_architecture(cls, plans_manager, configuration_manager, num_input_channels, num_output_channels,
enable_deep_supervision: bool = True):
assert num_input_channels == 2, f"archfused needs (T1, FLAIR) input, got {num_input_channels} channels"
base = get_network_from_plans(configuration_manager.network_arch_class_name,
configuration_manager.network_arch_init_kwargs,
configuration_manager.network_arch_init_kwargs_req_import,
1, num_output_channels, allow_init=True, deep_supervision=enable_deep_supervision)
return an.build_pacnet(base, and_gate=cls.AND_GATE, alpha_bias=cls.ALPHA_BIAS, film_beta=cls.FILM_BETA)
def _warm_start(self):
an._guard(self.WARM_PATH)
if not self.WARM_PATH.is_file():
raise RuntimeError(f"warm-start checkpoint missing: {self.WARM_PATH}")
pre = torch.load(str(self.WARM_PATH), map_location="cpu", weights_only=False)["network_weights"]
mod = self._module()
sd = mod.state_dict()
newp = mod.new_param_prefixes()
copied, adapted, fresh = 0, [], 0
used = set()
for k, v in sd.items():
if k.startswith(newp):
fresh += 1
continue
if k not in pre:
raise RuntimeError(f"archfused warm start: trunk key {k} missing in D331 weights")
p = pre[k].to(device=v.device, dtype=v.dtype); used.add(k)
if p.shape == v.shape:
sd[k] = p.clone(); copied += 1
elif ".seg_layers." in k and p.shape[0] == 2 and v.shape[0] == 3 and p.shape[1:] == v.shape[1:]:
new = torch.zeros_like(v); new[:2] = p
sd[k] = new; adapted.append(k)
else:
raise RuntimeError(f"archfused warm start: shape mismatch {k}: {tuple(p.shape)} vs {tuple(v.shape)}")
unused = [k for k in pre if k not in used]
if unused:
raise RuntimeError(f"archfused warm start: {len(unused)} D331 tensors unused, e.g. {unused[:3]}")
mod.load_state_dict(sd)
for n, _ in mod.named_parameters():
if n.startswith(newp) or n in adapted:
self._new_param_names.add(n)
nf = sum(p.numel() for n, p in mod.named_parameters() if n.startswith(newp))
nt = sum(p.numel() for n, p in mod.named_parameters() if not n.startswith(newp))
self.print_to_log_file(f"ARCHFUSED warm start from {self.WARM_PATH}: copied {copied} trunk tensors exactly "
f"(T1 stem 1-channel, no adaptation), adapted {adapted}, {fresh} new tensors. "
f"params: T1 trunk {nt/1e6:.2f} M, new (FLAIR branch + gates + escape) {nf/1e6:.2f} M. "
f"AND_GATE={self.AND_GATE} PRE={self.PRE_EPOCHS} FUSED={self.FUSED_EPOCHS} "
f"lambda_t1={self.LAMBDA_T1} lambda_det={self.LAMBDA_DET} CF(fdecoy={self.CF_FDECOY_P}, "
f"t1att={self.CF_T1ATT_P}, t1mimic={self.CF_T1MIMIC_P}) GIN_P={self.GIN_P}")
self.optimizer, self.lr_scheduler = self.configure_optimizers()
# -------------------------------------------------------------------------------------------- LR schedule
def on_train_epoch_start(self):
nnUNetTrainer.on_train_epoch_start(self)
e, P = self.current_epoch, self.PRE_EPOCHS
if len(self.optimizer.param_groups) == 2:
if e < P:
lr0, lr1 = self.initial_lr, 0.0
else:
f = e - P
lr0 = self.initial_lr * (1 - f / self.FUSED_EPOCHS) ** 0.9
lr1 = lr0 * (0.1 if f < self.BACKBONE_WARMUP_EPOCHS else 1.0)
self.optimizer.param_groups[0]["lr"] = lr0
self.optimizer.param_groups[1]["lr"] = lr1
if e in (0, P, P + self.BACKBONE_WARMUP_EPOCHS):
self.print_to_log_file(f"ARCHFUSED phase {'1 (FLAIR detector pre-training)' if e < P else '2 (fused)'}; "
f"lrs per group: {[g['lr'] for g in self.optimizer.param_groups]}")
# ----------------------------------------------------------------------------------------------- training
def train_step(self, batch: dict) -> dict:
mod = self._module()
keys = batch.get("keys")
data = batch["data"].to(self.device, non_blocking=True)
target = batch["target"]
target = [t.to(self.device, non_blocking=True) for t in target] if isinstance(target, list) else [target.to(self.device, non_blocking=True)]
t0 = target[0]
lesion = t0 == 1
anomaly = (t0 == 1) | (t0 == 2)
ignore = t0 == 3
with torch.no_grad():
cf = _apply_cf(self, data, t0, keys, lesion, anomaly)
if keys is not None and self.GIN_P > 0:
idx = [i for i, k in enumerate(keys) if not str(k).startswith("t0_")]
if idx:
it = torch.tensor(idx, device=self.device)
data[it] = _gin().gin_channel(data[it].clone(), ch=1, p=self.GIN_P)
seg_t = [torch.where(t == 2, torch.zeros_like(t), t) for t in target]
core, valid, w = an.det_targets(anomaly, ignore)
if keys is not None: # zero-FLAIR samples carry no FLAIR evidence: no detection target
for i, k in enumerate(keys):
if str(k).startswith("t0_"):
valid[i] = 0
phase1 = self.current_epoch < self.PRE_EPOCHS
self._af_it += 1
diag_now = (self._af_it % self.DIAG_EVERY == 0)
self.optimizer.zero_grad(set_to_none=True)
ctx = autocast(self.device.type, enabled=True) if self.device.type == 'cuda' else dummy_context()
with ctx:
if phase1:
out = mod.forward_train(data, flair_only=True)
l_det = an.det_loss(out["q"], core, valid, w)
l_f = l_t = torch.zeros((), device=self.device)
l = self.LAMBDA_DET * l_det
else:
out = mod.forward_train(data, need_t1=self.LAMBDA_T1 > 0)
l_f = self.loss(out["seg"], seg_t)
l_t = self.loss(out["seg_t1"], seg_t) if (self.LAMBDA_T1 > 0 and "seg_t1" in out) else torch.zeros((), device=self.device)
l_det = an.det_loss(out["q"], core, valid, w)
l = l_f + self.LAMBDA_T1 * l_t + self.LAMBDA_DET * l_det
row = None
if diag_now:
try:
row = self._af_diag(mod, data, seg_t, core, valid, out, l_f, phase1)
except Exception as ex: # diagnostics must never kill a training run
row = {"diag_error": repr(ex)[:300]}
if self.grad_scaler is not None:
self.grad_scaler.scale(l).backward()
self.grad_scaler.unscale_(self.optimizer)
torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)
self.grad_scaler.step(self.optimizer)
self.grad_scaler.update()
else:
l.backward()
torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)
self.optimizer.step()
self._af_parts.append({"l": float(l.detach()), "l_fused": float(l_f.detach()), "l_t1": float(l_t.detach()),
"l_det": float(l_det.detach()), **cf})
if row is not None:
row.update({"epoch": int(self.current_epoch), "it": int(self._af_it), "phase": 1 if phase1 else 2,
"l": float(l.detach()), "l_fused": float(l_f.detach()), "l_t1": float(l_t.detach()),
"l_det": float(l_det.detach()), "cf": cf, "t": time.time()})
if self.device.type == "cuda":
row["max_mem_gb"] = round(torch.cuda.max_memory_allocated() / 2 ** 30, 2)
self._af_rows.append(row)
try:
with open(os.path.join(self.output_folder, "archfused_diag.jsonl"), "a") as fh:
fh.write(json.dumps(row) + "\n")
except OSError:
pass
return {"loss": l.detach().cpu().numpy()}
# -------------------------------------------------------------------------------------------- diagnostics
def _af_diag(self, mod, data, seg_t, core, valid, out, l_f, phase1) -> dict:
r = {}
pq = torch.sigmoid(out["q"].detach().float())
pos = core * valid; neg = (1 - core) * valid
r["det_p_pos"] = float((pq * pos).sum() / pos.sum().clamp_min(1))
r["det_p_neg"] = float((pq * neg).sum() / neg.sum().clamp_min(1))
r["det_recall_vox"] = float(((pq > 0.5).float() * pos).sum() / pos.sum().clamp_min(1)) if pos.sum() > 0 else None
r["det_fp_rate_vox"] = float(((pq > 0.5).float() * neg).sum() / neg.sum().clamp_min(1))
if phase1:
return r
newp = mod.new_param_prefixes()
# (1) gradient-norm share of the FLAIR branch in d L_fused / d theta
if self.DIAG_GRAD and l_f.requires_grad:
names, params = zip(*[(n, p) for n, p in mod.named_parameters() if p.requires_grad])
scale = float(self.grad_scaler.get_scale()) if self.grad_scaler is not None else 1.0
gs = torch.autograd.grad(l_f * scale, params, retain_graph=True, allow_unused=True)
acc = {"flair": 0.0, "gates": 0.0, "alpha_head": 0.0, "trunk_enc": 0.0, "trunk_dec": 0.0}
finite = True
for n, g in zip(names, gs):
if g is None:
continue
v = float(g.float().pow(2).sum()) / scale ** 2
if not np.isfinite(v):
finite = False; break
grp = "flair" if n.startswith("flair.") else "gates" if n.startswith("gates.") else \
"alpha_head" if n.startswith("alpha_head.") else "trunk_enc" if n.startswith("encoder.") else "trunk_dec"
acc[grp] += v
if finite:
nf = (acc["flair"] + acc["gates"] + acc["alpha_head"]) ** 0.5
nt = (acc["trunk_enc"] + acc["trunk_dec"]) ** 0.5
r["gradnorm_flair_branch"] = acc["flair"] ** 0.5
r["gradnorm_gates"] = acc["gates"] ** 0.5
r["gradnorm_trunk"] = nt
r["grad_share_flair"] = nf / (nf + nt + 1e-12)
# (2) output change with FLAIR zeroed; fused vs T1-only pass
g = (seg_t[0] == 1).float()
brain = (data[:, 0:1] != 0).float()
near = F.max_pool3d(g, 5, 1, 2) * brain
p_f = an.lesion_prob(out["seg"][0].detach())
with torch.no_grad():
dz = data.clone(); dz[:, 1] = 0
ctx = autocast(self.device.type, enabled=True) if self.device.type == 'cuda' else dummy_context()
with ctx:
oz = mod.forward_train(dz, need_t1=False)
p_z = an.lesion_prob(oz["seg"][0])
def m(x, msk):
return float((x * msk).sum() / msk.sum().clamp_min(1))
r["zeroF_dp_brain"] = m((p_f - p_z).abs(), brain)
r["zeroF_dp_near_lesion"] = m((p_f - p_z).abs(), near) if near.sum() > 0 else None
r["zeroF_flip_frac_brain"] = m(((p_f > 0.5) != (p_z > 0.5)).float(), brain)
r["dice_fused"] = float(an.soft_dice(p_f, g).mean())
r["dice_zeroF"] = float(an.soft_dice(p_z, g).mean())
r["flair_usage_softdice"] = r["dice_fused"] - r["dice_zeroF"]
if "seg_t1" in out:
p_t = an.lesion_prob(out["seg_t1"][0].detach())
r["t1only_dp_brain"] = m((p_f - p_t).abs(), brain)
r["t1only_dp_near_lesion"] = m((p_f - p_t).abs(), near) if near.sum() > 0 else None
r["dice_t1only"] = float(an.soft_dice(p_t, g).mean())
# (3) gate magnitude per decoder stage; AND gate / escape
for s, gm in out.get("gammas", {}).items():
r[f"gate_dev_s{s}"] = float((gm.detach().float() - 1).abs().mean())
if "alpha" in out:
a = out["alpha"].detach()
far = brain * (1 - near)
r["alpha_near_lesion"] = m(a, near) if near.sum() > 0 else None
r["alpha_far"] = m(a, far)
qf = torch.sigmoid(F.interpolate(out["q"].detach().float(), size=a.shape[2:], mode="trilinear", align_corners=False))
gate = a + (1 - a) * qf
r["and_gate_near_lesion"] = m(gate, near) if near.sum() > 0 else None
r["and_gate_far"] = m(gate, far)
return r
def on_train_epoch_end(self, train_outputs):
super().on_train_epoch_end(train_outputs)
ep = self.current_epoch
rows = [r for r in self._af_rows if r.get("epoch") == ep and "diag_error" not in r]
parts = self._af_parts
msg = {}
if parts:
for k in parts[0]:
msg[k] = round(float(np.mean([p[k] for p in parts])), 4)
keys = ["grad_share_flair", "zeroF_dp_brain", "zeroF_dp_near_lesion", "flair_usage_softdice", "t1only_dp_near_lesion",
"det_recall_vox", "det_fp_rate_vox", "gate_dev_s0", "gate_dev_s1", "gate_dev_s2", "gate_dev_s3",
"alpha_near_lesion", "alpha_far", "and_gate_near_lesion", "and_gate_far", "max_mem_gb"]
for k in keys:
v = [r[k] for r in rows if r.get(k) is not None]
if v:
msg[k] = round(float(np.mean(v)), 5)
self.print_to_log_file("AF-DIAG epoch %d: %s" % (ep, json.dumps(msg)))
f = ep - self.PRE_EPOCHS
if f >= 0 and "zeroF_dp_near_lesion" in msg:
if msg["zeroF_dp_near_lesion"] < 0.01 and msg.get("grad_share_flair", 0) < 0.02:
self._af_lazy_epochs += 1
else:
self._af_lazy_epochs = 0
if f >= 10 and self._af_lazy_epochs >= 5:
self.print_to_log_file("AF-DIAG LAZY-FLAIR WARNING: zeroing FLAIR changes the fused prediction by < 0.01 "
"near lesions and the FLAIR branch holds < 2% of the fused-loss gradient for "
f"{self._af_lazy_epochs} consecutive epochs")
self._af_parts = []
self._af_rows = [r for r in self._af_rows if r.get("epoch", -1) >= ep]
class CFOnlyMixin:
"""Control: the same counterfactual cue-conflict ops on the plain single 2-channel network (V10S)."""
CF_FDECOY_P = 0.5
CF_T1ATT_P = 0.25
CF_T1MIMIC_P = 0.0
def train_step(self, batch: dict) -> dict:
keys = batch.get("keys")
data = batch["data"].to(self.device, non_blocking=True)
target = batch["target"]
t0 = (target[0] if isinstance(target, list) else target).to(self.device, non_blocking=True)
assert not bool((t0 == 2).any()), "CFOnly control expects binary labels (no label 2)"
with torch.no_grad():
lesion = t0 == 1
anomaly = lesion.clone()
_apply_cf(self, data, t0, keys, lesion, anomaly)
batch["data"] = data
return super().train_step(batch)
class AFSmokeMixin:
"""GPU PIPELINE SMOKE ONLY (not a result): 1 pre-training + 1 fused epoch x 6 iterations, diagnostics every 2."""
PRE_EPOCHS = 1
FUSED_EPOCHS = 1
DIAG_EVERY = 2
BACKBONE_WARMUP_EPOCHS = 1
def __init__(self, plans, configuration, fold, dataset_json, device=torch.device('cuda')):
super().__init__(plans, configuration, fold, dataset_json, device)
self.num_iterations_per_epoch = 6
self.num_val_iterations_per_epoch = 2
def perform_actual_validation(self, save_probabilities: bool = False):
self.print_to_log_file("archfused smoke: final validation skipped")