edschen's picture
EAGLE model u_pair_2c v1 (part 3)
473c56f verified
Raw History Blame Contribute Delete
36.2 kB
#!/usr/bin/env python
"""classifier4/B (B3 family = c4b_train_orc + --vis_floor / --mirror / --aux): train the INDEPENDENT T1 EVIDENCE network (B_LOG.md §2 design) from scratch on D331's training data.
Network: nnU-Net ResidualEncoderUNet (dynamic_network_architectures; ResEnc stage layout 32-64-128-256-320-320, blocks 1-3-4-6-6-6,
deep supervision), RANDOM init (never D331 weights). Input = T1 only (D331-preprocessed z-score, zero outside brain), 1 mm.
Data = D331 fold-0 TRAIN keys (1,086; c4b_common.train_keys), held in RAM (fp16).
Recipe (each item attacks a cause of D331's blindness, B_LOG §1):
* LESION-BALANCED sampling: p_les of patches are centred on a GT lesion picked uniformly over size bins (<0.1 / 0.1-1 / 1-5 / 5-30 /
>30 mL) then uniformly within the bin (D331: nnU-Net centres 33 % of patches on a voxel drawn uniformly from the foreground, so
tiny lesions are almost never centred); the rest are random brain locations.
* SYNTHETIC tiny / faint lesions painted into the real T1 anatomy on the GPU: volume log-uniform 3-5000 vox (0.003-5 mL), irregular
ellipsoids with soft partial-volume rims, placed in WM-like (deep / periventricular), GM-like (cortical / juxtacortical) or any
brain tissue (never on a GT lesion), contrast relative to local tissue log-uniform 0.04-1.2 of the tissue-to-CSF gap (down to
near-invisible), 10 % T1-bright; additive (keeps the tissue texture) or blended; labelled positive.
* LESION-WISE loss: CE (deep supervision, max-pooled targets so tiny lesions survive at coarse scales) + batch soft Dice + BLOB Dice
(per-instance Dice in the instance's neighbourhood, other instances ignored: every lesion weighs the same) + per-lesion
MAX-EVIDENCE term (softplus(-max fg-margin inside each instance)) balanced by a HARD-NEGATIVE term (top-k background margins).
* EXTREME domain randomisation on the GPU (renderer philosophy, breadth not realism): GIN random conv, gamma, bias field, thick
slices (resolution randomisation), blur, isotropic low-res, noise; affine (rotation / scale) + flips.
Checkpoint every --save_every iters (requeue-safe; RNG states saved).
c4b_train.py --tag b1 [--iters 30000] [--patch 128] [--bs 3] [--smoke]
"""
from __future__ import annotations
import argparse, math, os, queue, sys, threading, time, zlib
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import c4b_common as Q # noqa: E402
import torch
import torch.nn.functional as F
BINS = (0, 100, 1000, 5000, 30000, 10 ** 9)
AUX_SRC = "tissue" # tissue (SynthSeg) | tissue_gmm (label-free GMM fallback); set from --aux_src
ORC_DMIN = 3.0 # oracle up-weighting only for lesions D331 misses although VISIBLE (d' >= ORC_DMIN; set from --orc_dmin)
def log(*a):
print(time.strftime("%H:%M:%S"), *a, flush=True)
# ---------------------------------------------------------------------------------------------------------------- network
def make_net(deep_supervision=True, ncls=2, in_ch=1):
from dynamic_network_architectures.architectures.unet import ResidualEncoderUNet
return ResidualEncoderUNet(
input_channels=in_ch, n_stages=6, features_per_stage=[32, 64, 128, 256, 320, 320], conv_op=torch.nn.Conv3d,
kernel_sizes=[[3, 3, 3]] * 6, strides=[[1, 1, 1]] + [[2, 2, 2]] * 5, n_blocks_per_stage=[1, 3, 4, 6, 6, 6], num_classes=ncls,
n_conv_per_stage_decoder=[1] * 5, conv_bias=True, norm_op=torch.nn.InstanceNorm3d, norm_op_kwargs={"eps": 1e-5, "affine": True},
dropout_op=None, dropout_op_kwargs=None, nonlin=torch.nn.LeakyReLU, nonlin_kwargs={"inplace": True},
deep_supervision=deep_supervision)
# ---------------------------------------------------------------------------------------------------------------- data
class Data:
def __init__(self, keys, index, bin_w=None, faint_w=0.0, oracle=0.0, p_orc=0.0, mirror=False, aux=False):
t0 = time.time()
self.X, self.S, self.bb = [], [], []
self.M = [] if mirror else None; self.T = [] if aux else None
if mirror:
import pandas as _pd, c4b_mirror as MR
_tf = Q.OUT / "mirror" / "transforms.pkl"
trs = _pd.read_pickle(_tf).set_index("key") if _tf.exists() else _pd.DataFrame(columns=["lr", "R", "off"])
log("mirror transforms", len(trs))
for i, k in enumerate(keys):
x = Q.load_b2(Q.D331P / f"{k}.b2nd", 0); s = Q.load_b2(Q.D331P / f"{k}_seg.b2nd", 0).astype(np.int8)
br = s != -1
x = np.where(br, x, 0).astype(np.float16)
nz = (np.argwhere(br[::3, ::3, ::3]) * 3).astype(np.int16)
self.X.append(x); self.S.append(s); self.bb.append(nz)
if mirror:
self.M.append(MR.apply_mirror(x.astype(np.float32), trs.loc[k]).astype(np.float16) if k in trs.index else x.copy())
if aux:
f = Q.OUT / AUX_SRC / f"{k}.npz"
self.T.append(np.load(f)["cls"] if f.exists() else np.zeros(x.shape, np.uint8))
if i % 100 == 0:
log("load", i, len(keys), f"{time.time() - t0:.0f}s")
self.keys = keys; kpos = {k: i for i, k in enumerate(keys)}
les = index[index["key"].isin(kpos)]
self.les_case = les["key"].map(kpos).to_numpy(); self.les_vox = les["vox"].to_numpy()
self.les_xyz = [np.array(v) for v in les["vox_xyz"]]
self.bin_members = [np.nonzero((self.les_vox >= lo) & (self.les_vox < hi))[0] for lo, hi in zip(BINS[:-1], BINS[1:])]
bw = bin_w or [1.0] * len(self.bin_members)
keep = [i for i, m in enumerate(self.bin_members) if len(m)]
self.bin_p = np.array([bw[i] for i in keep], float); self.bin_p /= self.bin_p.sum()
self.bin_members = [self.bin_members[i] for i in keep]
ct = les["c_t1"].fillna(-9).to_numpy()
lw = 1.0 + faint_w * (ct > -0.5) # faint real lesions (c_t1 > -0.5 whole-brain z; ~30 %) oversampled
self.bin_lw = [lw[m] / lw[m].sum() for m in self.bin_members]
self.oracle, self.p_orc = oracle, p_orc
self.orc_dmin = ORC_DMIN
self.orc = {} # case index -> (layers, real_blind voxels)
if oracle > 0:
import json as _j
for i, k in enumerate(keys):
f = Q.OUT / "oracle" / f"{k}.npz"
if not f.exists():
continue
z = np.load(f); meta = _j.loads(str(z["meta"]))
lay = [dict(lo=np.array(m["lo"]), mask=z[f"m{j}"].astype(bool), delta=z[f"d{j}"], miss=(m["pmax"] < 0.5) and (m.get("dprime", 99) >= self.orc_dmin)) for j, m in enumerate(meta)]
self.orc[i] = (lay, z["real_blind"].astype(np.int64))
self.orc_cases = np.array(sorted(self.orc))
nm = sum(l_["miss"] for v in self.orc.values() for l_ in v[0]); na = sum(len(v[0]) for v in self.orc.values())
log("oracle cases", len(self.orc), "synthetic missed", nm, "/", na, "real D331-blind comps", sum(len(v[1]) > 0 for v in self.orc.values()))
log("data ready", len(keys), "lesions", len(les), "bins", [len(m) for m in self.bin_members], f"{time.time() - t0:.0f}s")
def patch(self, rng, P, p_les):
orc_lay = None
if self.oracle > 0 and len(self.orc) and rng.random() < self.p_orc:
ci = int(self.orc_cases[rng.integers(len(self.orc_cases))]); lay = self.orc[ci][0]
if lay:
miss = [l_ for l_ in lay if l_["miss"]]
L0 = miss[rng.integers(len(miss))] if miss and rng.random() < 0.6 else lay[rng.integers(len(lay))]
c = L0["lo"] + np.array(L0["mask"].shape) // 2 + rng.integers(-(P // 2 - 16), P // 2 - 16 + 1, 3)
orc_lay = lay
else:
bb = self.bb[ci]; c = bb[rng.integers(len(bb))]
elif rng.random() < p_les:
bi_ = rng.choice(len(self.bin_members), p=self.bin_p)
mem = self.bin_members[bi_]
j = mem[rng.choice(len(mem), p=self.bin_lw[bi_])]; ci = self.les_case[j]
c = self.les_xyz[j][rng.integers(len(self.les_xyz[j]))] + rng.integers(-(P // 2 - 12), P // 2 - 12 + 1, 3)
else:
ci = rng.integers(len(self.X)); bb = self.bb[ci]; c = bb[rng.integers(len(bb))]
x, s = self.X[ci], self.S[ci]
lo = np.array(c) - P // 2; hi = lo + P
xo = np.zeros((P,) * 3, np.float16); so = np.full((P,) * 3, -1, np.int8)
slo = np.maximum(lo, 0); shi = np.minimum(hi, x.shape)
dst = tuple(slice(a - l, b - l) for a, b, l in zip(slo, shi, lo)); src = tuple(slice(a, b) for a, b in zip(slo, shi))
xo[dst] = x[src]; so[dst] = s[src]
ex = {}
if self.M is not None:
mo = np.zeros((P,) * 3, np.float16); mo[dst] = self.M[ci][src]; ex["m"] = mo
if self.T is not None:
to = np.zeros((P,) * 3, np.uint8); to[dst] = self.T[ci][src]; ex["t"] = to
wo = np.ones((P,) * 3, np.float16)
if self.oracle > 0 and ci in self.orc:
rb = self.orc[ci][1]
if len(rb):
rr = rb - lo; ok = ((rr >= 0) & (rr < P)).all(1); rr = rr[ok]
wo[rr[:, 0], rr[:, 1], rr[:, 2]] = self.oracle # real lesions D331 misses (in-sample!) -> up-weighted
for l_ in (orc_lay or []):
a0 = l_["lo"] - lo; a1 = a0 + np.array(l_["mask"].shape)
b0 = np.maximum(a0, 0); b1 = np.minimum(a1, P)
if (b1 <= b0).any():
continue
ds = tuple(slice(u_, v_) for u_, v_ in zip(b0, b1)); ss_ = tuple(slice(u_ - w_, v_ - w_) for u_, v_, w_ in zip(b0, b1, a0))
m = l_["mask"][ss_]
xo[ds] = (xo[ds].astype(np.float32) + l_["delta"][ss_].astype(np.float32)).astype(np.float16)
so[ds][m & (so[ds] >= 0)] = 1
if l_["miss"]:
wo[ds][m] = self.oracle
return xo, so, wo, ex
def instances(seg):
import cc3d
les = (seg == 1).astype(np.uint8)
if not les.any():
return np.zeros(seg.shape, np.int16), 0
L, n = cc3d.connected_components(les, connectivity=26, return_N=True)
return L.astype(np.int16), int(n)
def producer(data, q, seed, P, bs, p_les, stop):
rng = np.random.default_rng(seed)
while not stop.is_set():
xs, ss, ins, ns, ws, exs = [], [], [], [], [], []
for _ in range(bs):
x, s, w, e = data.patch(rng, P, p_les)
L, n = instances(s)
xs.append(x); ss.append(s); ins.append(L); ns.append(n); ws.append(w); exs.append(e)
ex = {k: np.stack([e[k] for e in exs]) for k in exs[0]}
item = (np.stack(xs), np.stack(ss), np.stack(ins), ns, np.stack(ws), ex)
while not stop.is_set():
try:
q.put(item, timeout=1); break
except queue.Full:
pass
# ---------------------------------------------------------------------------------------------------------------- GPU augmentation
def u(gen, lo, hi, dev):
return float(torch.empty(1, device=dev).uniform_(lo, hi, generator=gen))
def rand(gen, dev):
return float(torch.rand(1, device=dev, generator=gen))
def spatial(x, br, ins, gen):
"""affine rotation / scale (p 0.35 each) + flips. x (B,1,P,P,P) float; br (B,1,..) float; ins (B,1,..) float (instance ids)."""
B = x.shape[0]; dev = x.device
thetas = []
for b in range(B):
R = torch.eye(3, device=dev)
if rand(gen, dev) < 0.35:
for ax in range(3):
a = u(gen, -0.35, 0.35, dev); c, s = math.cos(a), math.sin(a)
i, j = [k for k in range(3) if k != ax]
M = torch.eye(3, device=dev); M[i, i] = c; M[j, j] = c; M[i, j] = -s; M[j, i] = s
R = R @ M
if rand(gen, dev) < 0.35:
R = R * math.exp(u(gen, math.log(0.8), math.log(1.25), dev))
for ax in range(3):
if rand(gen, dev) < 0.5:
R[:, ax] = -R[:, ax]
thetas.append(torch.cat([R, torch.zeros(3, 1, device=dev)], 1))
th = torch.stack(thetas)
grid = F.affine_grid(th, x.shape, align_corners=False)
x = F.grid_sample(x, grid, mode="bilinear", padding_mode="zeros", align_corners=False)
br = F.grid_sample(br, grid, mode="bilinear", padding_mode="zeros", align_corners=False) > 0.5
ins = F.grid_sample(ins, grid, mode="nearest", padding_mode="zeros", align_corners=False)
return x, br, ins
def paint(x, br, ins, nreal, gen, a):
"""synthetic tiny / faint lesions. x (B,P,P,P) z-T1, br bool, ins float instance map (real ids 1..nreal[b]). In place."""
B, P = x.shape[0], x.shape[1]; dev = x.device
nsyn = []
edges = torch.zeros_like(br)
for b in range(B):
k = 0
if a.w_csf > 0 or a.mimic:
bv0 = x[b][br[b]]
if bv0.numel() > 5000:
q = torch.quantile(bv0[torch.randint(bv0.numel(), (20000,), device=dev, generator=gen)].float(), torch.tensor([0.03, 0.25], device=dev))
dark = (x[b] < q[0] + 0.5 * (q[1] - q[0])) & br[b]
edges[b] = (F.max_pool3d(dark.float()[None, None], 5, 1, 2)[0, 0] > 0) & br[b]
if rand(gen, dev) < a.p_syn:
n = int(torch.randint(1, a.max_syn + 1, (1,), device=dev, generator=gen))
xb = x[b]; bb = br[b]
bv = xb[bb]
if bv.numel() < 5000:
nsyn.append(0); continue
qs = torch.quantile(bv[torch.randint(bv.numel(), (20000,), device=dev, generator=gen)].float(),
torch.tensor([0.03, 0.25, 0.6], device=dev))
csf, q25, q60 = qs.tolist()
les_d = F.max_pool3d((ins[b] > 0).float()[None, None], 9, 1, 4)[0, 0] > 0
csf_near = F.max_pool3d(((xb < csf + 0.5 * (q25 - csf)) & bb).float()[None, None], 2 * a.csf_gap + 1, 1, a.csf_gap)[0, 0] > 0
for _ in range(n):
V = math.exp(u(gen, math.log(3), math.log(5000), dev))
r0 = (3 * V / (4 * math.pi)) ** (1 / 3)
ar = torch.exp(torch.empty(3, device=dev).uniform_(-0.7, 0.7, generator=gen)); ar = ar / ar.prod() ** (1 / 3)
rad = r0 * ar
half = int(math.ceil(float(rad.max()) * 1.6 + 3))
if 2 * half + 1 >= P - 8:
continue
t = rand(gen, dev)
rule = rand(gen, dev) < a.p_rule # never-CSF-dark rule applied with prob p_rule
cand = bb & ~les_d & ~(csf_near if (a.csf_gap > 0 and rule) else torch.zeros_like(bb))
if t < 0.5:
cand = cand & (xb > q60)
elif t < 0.85:
cand = cand & (xb > q25) & (xb <= q60)
m = cand[half + 2:P - half - 2, half + 2:P - half - 2, half + 2:P - half - 2]
idx = torch.nonzero(m)
if len(idx) == 0:
continue
c = idx[int(torch.randint(len(idx), (1,), device=dev, generator=gen))] + half + 2
sl = tuple(slice(int(ci) - half, int(ci) + half + 1) for ci in c)
S = 2 * half + 1
g = torch.stack(torch.meshgrid(*[torch.arange(S, device=dev, dtype=torch.float32) - half] * 3, indexing="ij"), 0)
Rm = torch.linalg.qr(torch.randn(3, 3, device=dev, generator=gen))[0]
gr = torch.einsum("ij,jxyz->ixyz", Rm, g)
d = torch.sqrt(((gr / rad.view(3, 1, 1, 1)) ** 2).sum(0))
nz = F.interpolate(torch.randn(1, 1, 4, 4, 4, device=dev, generator=gen), size=(S,) * 3, mode="trilinear",
align_corners=True)[0, 0]
d = d + nz * u(gen, 0.0, 0.4, dev)
w = u(gen, 0.05, 0.3, dev) * max(1.0, 2.0 / max(r0, 0.5))
alpha = torch.sigmoid((1 - d) / w) * bb[sl] * (~les_d[sl])
lab = alpha > 0.5
if int(lab.sum()) < 3:
continue
loc = xb[sl]; tis = loc[bb[sl] & ~lab]
T = float(tis.median()) if tis.numel() > 10 else float(q60)
gap = max(T - csf, 0.8)
cr = math.exp(u(gen, math.log(a.c_lo), math.log(1.2), dev))
if t >= 0.5 and rule:
cr = min(cr, a.gm_cmax) # cortical / any-tissue lesions never CSF-dark
shift = -cr * gap if rand(gen, dev) > 0.1 else cr * 0.6 * gap
if shift < 0 and r0 >= 1.5 and rand(gen, dev) < 0.3: # cavitation: CSF-dark core + milder gliotic rim
cf = u(gen, 0.4, 0.8, dev)
core = torch.sigmoid((cf - d) / (w * cf))
shift = shift + core * (-(u(gen, 0.7, 1.05, dev) * gap) - shift)
tex = torch.randn((S,) * 3, device=dev, generator=gen) * u(gen, 0.0, 0.25, dev) * gap * min(1.0, cr * 3)
if rand(gen, dev) < 0.5:
new = loc + alpha * (shift + tex) # additive: keeps tissue texture
else:
new = loc + alpha * ((T + shift + tex) - loc) # blended towards the target
x[b][sl] = new.to(x.dtype)
k += 1
ins[b][sl] = torch.where(lab, torch.full_like(ins[b][sl], float(nreal[b] + k)), ins[b][sl])
les_d[sl] = les_d[sl] | (F.max_pool3d(lab.float()[None, None], 9, 1, 4)[0, 0] > 0)
nsyn.append(k)
mim = torch.zeros_like(br)
if a.mimic:
for b in range(B):
bb = br[b]; xb = x[b]
bv = xb[bb]
if bv.numel() < 5000:
continue
q3, q25, q60 = torch.quantile(bv[torch.randint(bv.numel(), (20000,), device=dev, generator=gen)].float(),
torch.tensor([0.03, 0.25, 0.6], device=dev)).tolist()
far = ~(F.max_pool3d((ins[b] > 0).float()[None, None], 9, 1, 4)[0, 0] > 0)
nt = int(torch.randint(0, a.mimic + 1, (1,), device=dev, generator=gen))
for _ in range(nt):
L_ = u(gen, 6, 25, dev); r_ = u(gen, 0.6, 1.3, dev); half = int(L_ / 2 + 3)
m = (bb & far & (xb > q60))[half:P - half, half:P - half, half:P - half]
idx = torch.nonzero(m)
if len(idx) == 0:
continue
c = idx[int(torch.randint(len(idx), (1,), device=dev, generator=gen))] + half
sl = tuple(slice(int(ci) - half, int(ci) + half + 1) for ci in c); S = 2 * half + 1
g = torch.stack(torch.meshgrid(*[torch.arange(S, device=dev, dtype=torch.float32) - half] * 3, indexing="ij"), 0)
dvec = torch.randn(3, device=dev, generator=gen); dvec = dvec / dvec.norm()
along = torch.einsum("i,ixyz->xyz", dvec, g); perp = (g - along[None] * dvec.view(3, 1, 1, 1)).norm(dim=0)
alpha = torch.sigmoid((r_ - perp) / 0.3) * torch.sigmoid((L_ / 2 - along.abs()) / 0.5) * bb[sl] * far[sl]
tgt = q3 + u(gen, -0.1, 0.4, dev) * (q25 - q3) # CSF-like
x[b][sl] = (xb[sl] + alpha * (tgt - xb[sl])).to(x.dtype)
mim[b][sl] = mim[b][sl] | (alpha > 0.5)
mim[b] = mim[b] | (edges[b] & far) # sulcal CSF interface = mimic too
return x, ins, nsyn, edges, mim
def intensity_dr(x, br, gen, a):
"""extreme intensity / resolution randomisation per sample; returns z-scored (inside brain) x, zero outside. x (B,P,P,P)."""
B = x.shape[0]; dev = x.device; P = x.shape[1]
out = []
for b in range(B):
t = x[b].float(); m = br[b]
if m.sum() < 100:
out.append(t * 0); continue
v = t[m]
sub = v[torch.randint(v.numel(), (20000,), device=dev, generator=gen)]
lo, hi = torch.quantile(sub, torch.tensor([0.005, 0.995], device=dev)).tolist()
t = ((t - lo) / max(hi - lo, 1e-3)).clamp(-0.2, 1.2)
if rand(gen, dev) < a.p_aug: # GIN random conv net (mixed with the original)
C = 8; h = t[None, None]
for i in range(3):
cin = 1 if i == 0 else C; cout = 1 if i == 2 else C
k = 3 if rand(gen, dev) < 0.5 else 1
wgt = torch.randn(cout, cin, k, k, k, device=dev, generator=gen) / (cin * k ** 3) ** 0.5
h = F.conv3d(h, wgt, padding=k // 2)
if i < 2:
h = F.leaky_relu(h, 0.2)
h = h[0, 0]; hv = h[m]
h = (h - hv.mean()) / (hv.std() + 1e-6) * (t[m].std() + 1e-6) + t[m].mean()
al = u(gen, 0.2, 1.0, dev)
t = al * h + (1 - al) * t
if rand(gen, dev) < a.p_aug: # gamma
mn = t[m].min(); rg = (t[m].max() - mn).clamp(min=1e-3)
t = ((t - mn) / rg).clamp(min=0) ** math.exp(u(gen, math.log(0.5), math.log(2.0), dev)) * rg + mn
if rand(gen, dev) < a.p_aug: # multiplicative bias field
f = F.interpolate(torch.randn(1, 1, 4, 4, 4, device=dev, generator=gen), size=(P,) * 3, mode="trilinear", align_corners=True)[0, 0]
f = f / (f.abs().max() + 1e-6) * u(gen, 0.1, 0.5, dev)
mn = t[m].min(); t = (t - mn) * torch.exp(f) + mn
if rand(gen, dev) < 0.25: # thick slices along one axis (resolution randomisation)
ax = int(torch.randint(0, 3, (1,), device=dev, generator=gen)); fc = u(gen, 1.5, 4.0, dev)
sz = [P, P, P]; sz[ax] = max(int(round(P / fc)), 8)
lo_ = F.interpolate(t[None, None], size=sz, mode="area")
t = F.interpolate(lo_, size=(P,) * 3, mode="trilinear", align_corners=False)[0, 0]
if rand(gen, dev) < 0.15: # isotropic low resolution
fc = u(gen, 1.2, 2.0, dev); sz = [max(int(round(P / fc)), 8)] * 3
t = F.interpolate(F.interpolate(t[None, None], size=sz, mode="area"), size=(P,) * 3, mode="trilinear", align_corners=False)[0, 0]
if rand(gen, dev) < 0.2: # blur
s = u(gen, 0.3, 1.0, dev); r = 2; kx = torch.exp(-(torch.arange(-r, r + 1, device=dev, dtype=torch.float32) ** 2) / (2 * s * s))
kx = kx / kx.sum()
for ax in range(3):
shp = [1, 1, 1, 1, 1]; shp[2 + ax] = 2 * r + 1
pad = [0, 0, 0, 0, 0, 0]; pad[2 * (2 - ax)] = r; pad[2 * (2 - ax) + 1] = r
t = F.conv3d(F.pad(t[None, None], pad, mode="replicate"), kx.view(shp))[0, 0]
if rand(gen, dev) < 0.4: # noise (Gaussian or Rician)
sd = u(gen, 0.0, 0.08, dev)
if rand(gen, dev) < 0.5:
t = t + torch.randn_like(t) * sd
else:
t = torch.sqrt((t + torch.randn_like(t) * sd) ** 2 + (torch.randn_like(t) * sd) ** 2)
v = t[m]
t = (t - v.mean()) / (v.std() + 1e-6)
out.append(t * m)
return torch.stack(out)
def mirror_diff(x, m, br):
"""signed deviation of T1 beyond the +-1-voxel local range of the registered mirror (designer B's B3 channel); 0 = symmetric."""
mx = F.max_pool3d(m[:, None], 3, 1, 1)[:, 0]; mn = -F.max_pool3d(-m[:, None], 3, 1, 1)[:, 0]
return (x - torch.minimum(torch.maximum(x, mn), mx)) * br
def vis_ignore(x, ins, nreal, br, floor):
"""visibility-aware IGNORE (lit. review #3): per SYNTHETIC instance, d' = |mean(in) - mean(ring)| * sqrt(n) / sd(ring) in the
AUGMENTED image; d' < floor -> removed from the targets and ignored (incl. a 1-vox margin) instead of taught as positive."""
ign = torch.zeros_like(br)
for b in range(x.shape[0]):
ids = torch.unique(ins[b]); ids = ids[ids > nreal[b]]
for i in ids.tolist():
m = ins[b] == i
ring = (F.max_pool3d(m.float()[None, None], 7, 1, 3)[0, 0] > 0) & ~(F.max_pool3d(m.float()[None, None], 3, 1, 1)[0, 0] > 0) & br[b] & ~(ins[b] > 0)
if ring.sum() < 10:
continue
xi, xr = x[b][m], x[b][ring]
d = float((xi.mean() - xr.mean()).abs() * (m.sum().float().sqrt()) / (xr.std() + 1e-3))
if d < floor:
ins[b][m] = 0
ign[b] |= F.max_pool3d(m.float()[None, None], 3, 1, 1)[0, 0] > 0
return ins, ign
# ---------------------------------------------------------------------------------------------------------------- loss
def losses(outs, y, valid, ins, a, edges=None, mim=None, wmap=None):
"""outs: list of logits (B,2,...) full res first; y (B,P,P,P) bool; valid (B,..) bool (brain); ins (B,..) long instance ids."""
lo = outs[0].float()
margin = lo[:, 1] - (torch.logsumexp(lo[:, [0, 2]], 1) if lo.shape[1] == 3 else lo[:, 0])
# CE with deep supervision (targets max-pooled so tiny lesions survive at coarse scales)
ce = 0.0; wsum = 0.0
for i, o in enumerate(outs):
o = o.float(); s = o.shape[2:]
if i == 0:
yt, vt = y, valid
mt = mim if mim is not None else None
else:
f = y.shape[1] // s[0]
yt = F.max_pool3d(y.float()[:, None], f, f)[:, 0] > 0
mt = (F.max_pool3d(mim.float()[:, None], f, f)[:, 0] > 0) if mim is not None else None
vt = F.max_pool3d(valid.float()[:, None], f, f)[:, 0] > 0
w = 0.5 ** i
tgt = yt.long() if mt is None or o.shape[1] == 2 else torch.where(yt, 1, torch.where(mt, 2, 0)).long()
l = F.cross_entropy(o, tgt, reduction="none")
ce = ce + w * (l * vt).sum() / vt.sum().clamp(min=1); wsum += w
ce = ce / wsum
p = torch.softmax(lo, 1)[:, 1] * valid
yf = y.float()
dice = 1 - (2 * (p * yf).sum() + 1) / (p.sum() + yf.sum() + 1)
# instance terms
blob, det, nin, wsum = 0.0, 0.0, 0, 0.0
B = y.shape[0]
for b in range(B):
ib = ins[b]
ids = torch.unique(ib); ids = ids[ids > 0]
if len(ids) == 0:
continue
others_all = ib > 0
for i in ids.tolist():
mi = ib == i
nzi = torch.nonzero(mi)
lo_ = (nzi.min(0)[0] - 6).clamp(min=0); hi_ = nzi.max(0)[0] + 7
sl = tuple(slice(int(l_), int(h_)) for l_, h_ in zip(lo_, hi_))
m_ = mi[sl].float(); keep = (~(others_all[sl] & ~mi[sl])) & valid[b][sl]
pp = p[b][sl] * keep
wi = float(wmap[b][sl][mi[sl]].max()) if wmap is not None else 1.0
blob = blob + wi * (1 - (2 * (pp * m_).sum() + 1) / (pp.sum() + m_.sum() + 1))
mm = margin[b][sl][mi[sl]].max()
det = det + wi * F.softplus(-mm)
nin += 1; wsum += wi
blob = blob / max(wsum, 1); det = det / max(wsum, 1)
# hard negatives: top-k background margins per sample (balances the max-evidence term)
neg = margin.masked_fill(~(valid & ~(F.max_pool3d(yf[:, None], 5, 1, 2)[:, 0] > 0)), -1e4).flatten(1)
k = a.hn_k
hn = F.softplus(torch.topk(neg, k, 1)[0]).mean() if a.w_hn > 0 else margin.sum() * 0 # top-k caps the map (B_LOG §6) -> off in b2t family
tot = ce + dice + a.w_blob * blob + a.w_det * det + a.w_hn * hn
csfl = 0.0
if edges is not None and a.w_csf > 0:
em = edges & valid & ~(F.max_pool3d(yf[:, None], 7, 1, 3)[:, 0] > 0) # CSF-adjacent, away from any lesion
if a.csf_mode == "wce": # calibration-safe: weighted CE over ALL CSF-edge voxels (no top-k ceiling)
csfl = (F.softplus(margin) * em).sum() / em.sum().clamp(min=1)
else:
ne = margin.masked_fill(~em, -1e4).flatten(1)
csfl = F.softplus(torch.topk(ne, a.hn_k, 1)[0]).mean()
tot = tot + a.w_csf * csfl
return tot, dict(ce=float(ce), dice=float(dice), blob=float(blob), det=float(det), hn=float(hn), csf=float(csfl), nin=nin)
# ---------------------------------------------------------------------------------------------------------------- train
def main():
import pandas as pd
ap = argparse.ArgumentParser()
ap.add_argument("--tag", default="b1"); ap.add_argument("--iters", type=int, default=30000); ap.add_argument("--patch", type=int, default=128)
ap.add_argument("--bs", type=int, default=3); ap.add_argument("--lr", type=float, default=1e-2); ap.add_argument("--save_every", type=int, default=500)
ap.add_argument("--p_les", type=float, default=0.5); ap.add_argument("--p_syn", type=float, default=0.8); ap.add_argument("--max_syn", type=int, default=6)
ap.add_argument("--p_aug", type=float, default=0.5); ap.add_argument("--w_blob", type=float, default=1.0); ap.add_argument("--w_det", type=float, default=0.5)
ap.add_argument("--c_lo", type=float, default=0.04); ap.add_argument("--csf_mode", default="topk"); ap.add_argument("--mimic", type=int, default=0); ap.add_argument("--p_rule", type=float, default=1.0)
ap.add_argument("--vis_floor", type=float, default=0.0); ap.add_argument("--mirror", type=int, default=0)
ap.add_argument("--aux", type=int, default=0); ap.add_argument("--aux_src", default="tissue"); ap.add_argument("--w_aux", type=float, default=0.5)
ap.add_argument("--orc_dmin", type=float, default=3.0); ap.add_argument("--oracle", type=float, default=0.0); ap.add_argument("--p_orc", type=float, default=0.3)
ap.add_argument("--bin_w", default=""); ap.add_argument("--faint_w", type=float, default=0.0); ap.add_argument("--gm_cmax", type=float, default=1.2)
ap.add_argument("--csf_gap", type=int, default=0); ap.add_argument("--w_csf", type=float, default=0.0); ap.add_argument("--w_hn", type=float, default=0.5); ap.add_argument("--hn_k", type=int, default=400)
ap.add_argument("--nkeys", type=int, default=0); ap.add_argument("--smoke", action="store_true"); ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--dump", type=int, default=0, help="save N augmented batches for visual QC and exit")
a = ap.parse_args()
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.backends.cudnn.benchmark = True
if (Q.OUT / "models" / f"{a.tag}.pt").exists() and not (a.smoke or a.dump):
log("ALREADY_DONE", a.tag); return
keys = Q.train_keys()
if a.nkeys:
keys = keys[:a.nkeys]
index = pd.read_pickle(Q.OUT / "index" / "index.pkl")
global ORC_DMIN, AUX_SRC
ORC_DMIN = a.orc_dmin; AUX_SRC = a.aux_src
data = Data(keys, index, [float(v) for v in a.bin_w.split(',')] if a.bin_w else None, a.faint_w, a.oracle, a.p_orc, a.mirror, a.aux)
md = Q.OUT / "models"; md.mkdir(parents=True, exist_ok=True)
ck = md / f"{a.tag}.ckpt"
NCLS = 3 if a.mimic else 2
net = make_net(True, NCLS + (6 if a.aux else 0), 2 if a.mirror else 1).to(dev)
opt = torch.optim.SGD(net.parameters(), lr=a.lr, momentum=0.99, nesterov=True, weight_decay=3e-5)
it0 = 0
gen = torch.Generator(device=dev); gen.manual_seed(a.seed)
if ck.exists():
s = torch.load(ck, map_location=dev, weights_only=False)
net.load_state_dict(s["net"]); opt.load_state_dict(s["opt"]); it0 = s["it"]
gen.set_state(s["gen"].to(gen.get_state().device) if hasattr(s["gen"], "to") else s["gen"])
log("RESUME", it0)
q = queue.Queue(maxsize=6); stop = threading.Event()
ths = [threading.Thread(target=producer, args=(data, q, zlib.crc32(f"{a.tag}{a.seed}{it0}{w}".encode()), a.patch, a.bs, a.p_les, stop), daemon=True)
for w in range(3)]
for t in ths:
t.start()
net.train(); t0 = time.time(); run = {}
for it in range(it0, a.iters):
lr = a.lr * (1 - it / a.iters) ** 0.9
for gp in opt.param_groups:
gp["lr"] = lr
xs, ss, ins, ns, ws, ex = q.get()
x = torch.from_numpy(xs).to(dev).float()[:, None]; s = torch.from_numpy(ss).to(dev)
if a.mirror:
x = torch.cat([x, torch.from_numpy(ex["m"]).to(dev).float()[:, None]], 1) # mirror rides through the same affine
br = (s >= 0).float()[:, None]
chs = [torch.from_numpy(ins).to(dev).float()[:, None], torch.from_numpy(ws).to(dev).float()[:, None]]
if a.aux:
chs.append(torch.from_numpy(ex["t"]).to(dev).float()[:, None])
insf = torch.cat(chs, 1)
with torch.no_grad():
x, brb, insw = spatial(x, br, insf, gen)
mir = x[:, 1] if a.mirror else None
x = x[:, 0]; brb = brb[:, 0]; insf = insw[:, 0].contiguous(); wmap = insw[:, 1].clamp(min=1.0)
tis = insw[:, 2].long() if a.aux else None
x, insf, nsyn, edges, mim = paint(x, brb, insf, ns, gen, a)
if a.mirror:
dmap = mirror_diff(x, mir, brb) # after painting: painted lesions are asymmetric
x = intensity_dr(x, brb, gen, a)
ign = torch.zeros_like(brb)
if a.vis_floor > 0:
insf, ign = vis_ignore(x, insf, ns, brb, a.vis_floor)
y = insf > 0
if a.mirror:
sc = torch.empty(x.shape[0], 1, 1, 1, device=dev).uniform_(0.6, 1.4, generator=gen)
dmap = (dmap * sc + torch.randn_like(dmap) * 0.05) * brb
xin = torch.stack([x, dmap], 1)
else:
xin = x[:, None]
if a.dump:
Q.save_npz(Q.OUT / "qc" / f"{a.tag}_batch{it}.npz", x=x.cpu().numpy().astype(np.float16), y=y.cpu().numpy(), ins=insf.cpu().numpy().astype(np.int16),
nreal=np.array(ns), nsyn=np.array(nsyn))
if it - it0 + 1 >= a.dump:
break
continue
with torch.autocast(dev.type, dtype=torch.bfloat16, enabled=dev.type == "cuda"):
outs = net(xin)
outs_s = [o[:, :NCLS] for o in outs]
loss, parts = losses(outs_s, y, brb & ~ign, insf.long(), a, edges, mim if a.mimic else None, wmap if a.oracle > 0 else None)
if a.aux:
ta = tis.clone()
ign_t = (F.max_pool3d((insf > 0).float()[:, None], 7, 1, 3)[:, 0] > 0) | ~brb | (ta == 0) # SynthSeg wrong in lesions
ta = (ta - 1).clamp(min=0); ta[ign_t] = -100
la = F.cross_entropy(outs[0][:, NCLS:].float(), ta, ignore_index=-100) if (ta >= 0).any() else outs[0].sum() * 0
loss = loss + a.w_aux * la; parts["aux"] = float(la)
opt.zero_grad(set_to_none=True); loss.backward()
torch.nn.utils.clip_grad_norm_(net.parameters(), 12.0); opt.step()
for k_, v_ in dict(parts, loss=float(loss), nsyn=float(np.mean(nsyn)), nreal=float(np.mean(ns))).items():
run[k_] = 0.98 * run.get(k_, v_) + 0.02 * v_
if it % 100 == 0 or a.smoke:
log(f"it {it}/{a.iters} lr {lr:.4f} " + " ".join(f"{k_} {v_:.3f}" for k_, v_ in run.items()) + f" {time.time() - t0:.0f}s qsize {q.qsize()}")
if (it + 1) % a.save_every == 0 and it + 1 < a.iters:
tmp = str(ck) + ".tmp"
torch.save({"net": net.state_dict(), "opt": opt.state_dict(), "it": it + 1, "gen": gen.get_state()}, Q.guard_write(tmp)); os.replace(tmp, ck)
if a.smoke and it - it0 >= 20:
break
stop.set()
if not a.smoke and not a.dump:
torch.save(net.state_dict(), Q.guard_write(md / f"{a.tag}.pt"))
Q.jdump({"ncls": NCLS, "nout": NCLS + (6 if a.aux else 0), "in_ch": 2 if a.mirror else 1, "mirror": bool(a.mirror),
"patch": a.patch, "args": vars(a)}, md / f"{a.tag}.json")
if ck.exists():
ck.unlink() # storage: the final .pt is all that is kept (410 MB)
log("C4B_TRAIN_DONE", a.tag)
else:
if a.smoke:
torch.save(net.state_dict(), Q.guard_write(md / f"{a.tag}.pt"))
log("SMOKE_DONE", f"{(time.time() - t0):.0f}s")
if __name__ == "__main__":
main()