Buckets:
| """E2: train one (arm, direction, seed) on LIDC nodule ROIs and score every test nodule (SPEC.md "E2 scope"). | |
| Data: data/roi_job.py output (ROI .npz cubes, 112 mm at native spacing + manifest.csv). | |
| - direction "thin2thick": train/val on group thin, test on group thick; "thick2thin" the reverse. | |
| - train/val split by PATIENT (80/20, seed-fixed and identical across arms, so arms see the same data). | |
| - training sample: a 64 mm sub-cube; positives jittered +/-16 mm around the nodule, negatives anywhere; 1:1 pos/neg. | |
| - evaluation: the centred 96 mm cube in one forward pass. Per-nodule Dice is computed on the predicted components | |
| that touch the target nodule (dilated by 2 voxels), against that target only, so each nodule counts once even when | |
| neighbours share its cube. HD95 is in millimetres (surface distances with the native spacing). A missed nodule | |
| gets Dice 0 and HD95 = NaN (reported as a miss). Negative ROIs report false-positive volume (mm^3). | |
| Model selection: the validation per-nodule Dice, evaluated every EVAL_EVERY iterations; best checkpoint kept. | |
| Env / args: ARM (A|B|C|D), DIRECTION, SEED, ROI_DIR, OUT, ITERS (3000), ACCUM (2), LR (3e-4), EVAL_EVERY (250), | |
| WIDTHS (16,32,64,128), DEVICE, AMP (1), LIMIT_TEST (smoke), VAL_FRAC (0.2). | |
| Writes OUT/<arm>_<direction>_s<seed>.csv (per test ROI) and .json (config, timing, peak memory, best val Dice). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| import torch.nn.functional as F | |
| from scipy import ndimage | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from models.arms import make_arm, n_params # noqa: E402 | |
| E = os.environ.get | |
| ARM, DIRECTION, SEED = E("ARM", "C"), E("DIRECTION", "thin2thick"), int(E("SEED", "0")) | |
| ROI = Path(E("ROI_DIR", "/mnt/processed/spacing_conv/lidc_roi")) | |
| OUT = Path(E("OUT", "results/e2")); OUT.mkdir(parents=True, exist_ok=True) | |
| ITERS, ACCUM, LR, EVAL_EVERY = int(E("ITERS", "3000")), int(E("ACCUM", "2")), float(E("LR", "3e-4")), int(E("EVAL_EVERY", "250")) | |
| WIDTHS = tuple(int(w) for w in E("WIDTHS", "16,32,64,128").split(",")) | |
| DEV = torch.device(E("DEVICE", "cuda" if torch.cuda.is_available() else "cpu")) | |
| AMP = E("AMP", "1") == "1" and DEV.type == "cuda" | |
| LIMIT_TEST, VAL_FRAC = int(E("LIMIT_TEST", "0")), float(E("VAL_FRAC", "0.2")) | |
| D_TARGET = E("D_TARGET", "cohort") # cohort (SPEC) | train (nnU-Net rule) | thin (run 1) | |
| assert D_TARGET in ("cohort", "train", "thin"), D_TARGET | |
| TRAIN_MM, EVAL_MM, JITTER_MM = 64.0, 96.0, 16.0 | |
| def log(m): | |
| print(f"[e2 {ARM} {DIRECTION} s{SEED}] {m}", flush=True) | |
| def load(f): | |
| z = np.load(ROI / f) | |
| return z["image"], z["mask"], (z["target"] if "target" in z.files else z["mask"]), z["spacing"].astype(float) | |
| def norm(img): | |
| return np.clip((img.astype(np.float32) + 1000.0) / 1400.0, 0.0, 1.0) | |
| def sub(arr, centre, half): | |
| lo = [int(c) - h for c, h in zip(centre, half)] | |
| assert all(l >= 0 for l in lo) and all(l + 2 * h <= s for l, h, s in zip(lo, half, arr.shape)), "crop outside ROI" | |
| return arr[tuple(slice(l, l + 2 * h) for l, h in zip(lo, half))] | |
| def halfwidth(mm, sp): | |
| return [int(round(mm / 2 / s)) for s in sp] | |
| def splits(M): | |
| tr_g, te_g = ("thin", "thick") if DIRECTION == "thin2thick" else ("thick", "thin") | |
| pool, test = M[M.group == tr_g], M[M.group == te_g] | |
| pats = np.array(sorted(pool.patient.unique())) | |
| rng = np.random.default_rng(1234) # same split for every arm and seed | |
| val_p = set(rng.choice(pats, int(round(VAL_FRAC * len(pats))), replace=False)) | |
| tr, va = pool[~pool.patient.isin(val_p)], pool[pool.patient.isin(val_p)] | |
| assert not (set(tr.patient) & set(va.patient)) and not (set(pool.patient) & set(test.patient)), "patient leak" | |
| return tr, va, test | |
| def batch(row, rng): | |
| img, mask, _, sp = load(row.file) | |
| centre = np.array(img.shape) // 2 | |
| if row.kind == "pos": | |
| jit = rng.uniform(-JITTER_MM, JITTER_MM, 3) / sp | |
| else: | |
| jit = rng.uniform(-1, 1, 3) * (np.array(halfwidth(112 - TRAIN_MM, sp))) | |
| c = np.round(centre + jit).astype(int) | |
| h = halfwidth(TRAIN_MM, sp) | |
| c = np.clip(c, h, np.array(img.shape) - h) | |
| x = torch.from_numpy(norm(sub(img, c, h)))[None, None] | |
| y = torch.from_numpy(sub(mask, c, h).astype(np.float32))[None, None] | |
| return x, y, tuple(sp) | |
| def dice_bce(logit, y): | |
| p = torch.sigmoid(logit) | |
| inter = (p * y).sum(); den = p.sum() + y.sum() | |
| return 1 - (2 * inter + 1) / (den + 1) + F.binary_cross_entropy_with_logits(logit, y) | |
| def hd95_mm(a, b, sp): | |
| if not a.any() or not b.any(): | |
| return float("nan") | |
| sa, sb = a ^ ndimage.binary_erosion(a), b ^ ndimage.binary_erosion(b) | |
| da = ndimage.distance_transform_edt(~sb, sampling=sp)[sa] | |
| db = ndimage.distance_transform_edt(~sa, sampling=sp)[sb] | |
| return float(np.percentile(np.concatenate([da, db]), 95)) | |
| def score(model, rows): | |
| model.eval(); out = [] | |
| for r in rows.itertuples(): | |
| img, _, tgt, sp = load(r.file) | |
| h = halfwidth(EVAL_MM, sp); c = np.array(img.shape) // 2 | |
| x = torch.from_numpy(norm(sub(img, c, h)))[None, None].to(DEV) | |
| with torch.autocast("cuda", dtype=torch.float16, enabled=AMP): | |
| pred = (torch.sigmoid(model(x, tuple(sp)).float())[0, 0] > 0.5).cpu().numpy() | |
| t = sub(tgt, c, h).astype(bool) | |
| rec = {"file": r.file, "patient": r.patient, "kind": r.kind, "sz": float(sp[2]), "diam_mm": r.diam_mm} | |
| if r.kind == "pos": | |
| lab, n = ndimage.label(pred) | |
| touch = set(np.unique(lab[ndimage.binary_dilation(t, iterations=2)])) - {0} | |
| p = np.isin(lab, list(touch)) if touch else np.zeros_like(pred) | |
| rec["dice"] = float(2 * (p & t).sum() / (p.sum() + t.sum())) if (p.sum() + t.sum()) else 1.0 | |
| rec["hd95_mm"] = hd95_mm(p, t, sp) | |
| rec["detected"] = bool(touch) | |
| rec["fp_mm3"] = float((pred & ~ndimage.binary_dilation(t, iterations=2)).sum() * np.prod(sp)) | |
| out.append(rec) | |
| model.train() | |
| return pd.DataFrame(out) | |
| def main(): | |
| torch.manual_seed(SEED); rng = np.random.default_rng(SEED) | |
| M = pd.read_csv(ROI / "manifest.csv") | |
| tr, va, te = splits(M) | |
| # Arm D resampling target. SPEC section 7 registers the COHORT median. The first E2 run (2026-10-16) used the | |
| # thin-group median in both directions (a deviation: in thin->thick it equals the training spacing). "train" = | |
| # nnU-Net's training-set-median rule, reported as a labelled secondary baseline. | |
| # Medians are PER SCAN (one row per series), not per ROI: ROI rows are weighted by nodule count (thin has 971 of | |
| # 1,233 positive ROIs), which would drag a per-ROI "cohort" median back to the thin spacing. | |
| ref = {"cohort": M, "train": tr, "thin": M[M.group == "thin"]}[D_TARGET].drop_duplicates("series") | |
| target = (float(ref.sx.median()), float(ref.sy.median()), float(ref.sz.median())) | |
| model = make_arm(ARM, widths=WIDTHS, target_spacing=target).to(DEV) | |
| log(f"train {len(tr)} ROIs ({(tr.kind == 'pos').sum()} pos, {tr.patient.nunique()} patients), val {len(va)}, " | |
| f"test {len(te)}; params {n_params(model)}; D target spacing {target}") | |
| opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4) | |
| sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda i: min(1.0, (i + 1) / 100) * 0.5 * (1 + math.cos(math.pi * i / ITERS))) | |
| scaler = torch.amp.GradScaler("cuda", enabled=AMP) | |
| pos, neg = tr[tr.kind == "pos"], tr[tr.kind == "neg"] | |
| val_pos = va[va.kind == "pos"] | |
| best, best_state, t0, hist = -1.0, None, time.time(), [] | |
| if DEV.type == "cuda": | |
| torch.cuda.reset_peak_memory_stats() | |
| for it in range(ITERS): | |
| for _ in range(ACCUM): | |
| row = (pos if (rng.random() < 0.5 or not len(neg)) else neg).sample(1, random_state=int(rng.integers(1 << 31))).iloc[0] | |
| x, y, sp = batch(row, rng) | |
| with torch.autocast("cuda", dtype=torch.float16, enabled=AMP): | |
| loss = dice_bce(model(x.to(DEV), sp).float(), y.to(DEV)) / ACCUM | |
| scaler.scale(loss).backward() | |
| scaler.unscale_(opt); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| scaler.step(opt); scaler.update(); opt.zero_grad(set_to_none=True); sched.step() | |
| if (it + 1) % EVAL_EVERY == 0 or it + 1 == ITERS: | |
| v = score(model, val_pos).dice.mean() if len(val_pos) else float("nan") | |
| hist.append({"iter": it + 1, "val_dice": round(float(v), 4), "loss": round(float(loss) * ACCUM, 4)}) | |
| log(f"iter {it + 1} loss {float(loss) * ACCUM:.3f} val Dice {v:.3f} ({time.time() - t0:.0f}s)") | |
| if v > best: | |
| best, best_state = v, {k: t.detach().cpu().clone() for k, t in model.state_dict().items()} | |
| train_s = time.time() - t0 | |
| model.load_state_dict(best_state) | |
| test = te.head(LIMIT_TEST) if LIMIT_TEST else te | |
| t1 = time.time(); R = score(model, test); eval_s = time.time() - t1 | |
| R.insert(0, "arm", ARM); R.insert(1, "direction", DIRECTION); R.insert(2, "seed", SEED) | |
| tag = f"{ARM}{'' if ARM != 'D' else '-' + D_TARGET}_{DIRECTION}_s{SEED}" | |
| R.to_csv(OUT / f"{tag}.csv", index=False) | |
| info = {"arm": ARM, "direction": DIRECTION, "seed": SEED, "d_target": D_TARGET if ARM == "D" else None, | |
| "d_target_spacing": target if ARM == "D" else None, "params": n_params(model), "widths": WIDTHS, | |
| "iters": ITERS, "accum": ACCUM, "lr": LR, "best_val_dice": round(float(best), 4), "history": hist, | |
| "train_s": round(train_s), "eval_s": round(eval_s), "eval_s_per_roi": round(eval_s / max(len(test), 1), 3), | |
| "peak_mem_gb": round(torch.cuda.max_memory_allocated() / 1e9, 2) if DEV.type == "cuda" else None, | |
| "n_test_pos": int((R.kind == "pos").sum()), "test_dice": round(float(R.loc[R.kind == "pos", "dice"].mean()), 4)} | |
| (OUT / f"{tag}.json").write_text(json.dumps(info, indent=1)) | |
| print("E2_RESULT " + json.dumps({k: info[k] for k in ("arm", "direction", "seed", "best_val_dice", "test_dice", "n_test_pos")}), flush=True) | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 10.2 kB
- Xet hash:
- 8e2cbf11500511b4bdb0ebf3dc694733ac3f6daf419a7cae3666c95598166d3c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.