Download runtime/code/whisper_synth/src/direction2/cascade2_infer.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cascade2_infer.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/cascade2_infer.py
-
curl -L -o cascade2_infer.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cascade2_infer.py
15.2 kB
| #!/usr/bin/env python | |
| """cascade2 inference (GPU, or CPU for tests). | |
| Heat is the detector's softmax LESION probability (no blur by default: the stored OOF heat that trains stage 2 is | |
| unblurred, so test heat must be too; --blur 1.0 reproduces round 1's sigma = 1 and is recorded in heat_meta.json). | |
| oof --ds 977|978 --trainer T --fold c2_<opt>_f<k> --det_tag TAG [--smoke] | |
| held-out patients of fold k (patient_folds.json) -> heat on their PREPROCESSED stage-1 array (source key: | |
| syn_<X> (G1 FLAIR) if the option has G1, else cg0_<X> (clean render + one seeded online randomisation); | |
| r_<contra>) -> HEAT_OOF/TAG/<stage-2 key>.b2nd (uint8 x250, brain-masked, preprocessed geometry) | |
| zeroshot --arm c1|c2 --det_tag TAG [--cls sum|expansive|contractive] [--which oof,test] [--smoke] | |
| BaseExpert (Dataset320, READ ONLY) WITHOUT training. c1 = native T1 + FLAIR (heat LEAKS T1 evidence); | |
| c2 = FLAIR only (T1 zeroed after preprocessing). Heat = 1 - p(background) by default ("sum": D320 label 1 = | |
| glioma, label 2 = ISLES stroke / WMH / metastases, so neither class alone is "stroke"). Never trained on | |
| our data -> out-of-fold for EVERY stage-1 patient by construction; also writes test heat (TAG/mean). | |
| test --ds 977|978 --trainer T --folds f0,f1,f2 --det_tag TAG [--cases panel] | |
| each fold detector on the raw test pairs (D943 imagesTs, real T1 + FLAIR) -> HEAT_TEST/TAG/fold_<f>/<cid>.nii.gz (uint8) | |
| test_mean --det_tag TAG [--blur 0] mean of the fold probabilities -> HEAT_TEST/TAG/mean[_blurS]/<cid>.nii.gz (float32, /250) | |
| seg --trainer T --fold F --det_tag TAG [--variant mean] --out DIR [--zero_heat] [--cases panel] | |
| stage 2 on (T1, test heat) -> DIR/<cid>.nii.gz + DIR/prob/<cid>.nii.gz (uint8 x250) | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, os, sys, time | |
| from pathlib import Path | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import cascade2_common as C | |
| def cases(spec): | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from arch2stage_infer import cases as a2s_cases # round-1 panel definition (unchanged) | |
| return a2s_cases(spec) | |
| def predictor(model_dir, folds, device, tta=False, ckpt="checkpoint_final.pth"): | |
| import torch | |
| from nnunetv2.inference.predict_from_raw_data import nnUNetPredictor | |
| if device == "cpu": | |
| torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "4"))) | |
| p = nnUNetPredictor(tile_step_size=0.5, use_gaussian=True, use_mirroring=tta, perform_everything_on_device=device != "cpu", | |
| device=torch.device(device), verbose=False, allow_tqdm=False) | |
| p.initialize_from_trained_model_folder(str(C.guard(model_dir)), use_folds=tuple(folds), checkpoint_name=ckpt) | |
| return p | |
| def model_dir(ds, trainer): | |
| return C.RES / ds / f"{trainer}__{C.PLANS[ds]}__3d_fullres" | |
| def be_dir(): | |
| d = C.D320_RES | |
| ck = "checkpoint_best.pth" if (d / "fold_0/checkpoint_best.pth").exists() else "checkpoint_final.pth" | |
| return d, ck | |
| def heat_from_logits(logits, cls="lesion"): | |
| import torch | |
| p = torch.softmax(logits.float(), 0) | |
| if cls == "lesion": | |
| return p[1] | |
| if cls == "sum": | |
| return 1 - p[0] | |
| return p[{"expansive": 1, "contractive": 2}[cls]] | |
| def write_b2nd_u8(h, path): | |
| from cascade2_render import write_b2nd | |
| write_b2nd(np.clip(np.round(h * C.HEAT_SCALE), 0, 250).astype(np.uint8), path) | |
| def load_source(key, rtag=None, seed=0): | |
| """preprocessed stage-1 array of a source key (channel 1 swapped for cg keys).""" | |
| import blosc2, torch | |
| d, st = C.base_key(key) | |
| x = torch.from_numpy(np.asarray(blosc2.open(urlpath=str(C.guard(d / f"{st}.b2nd")), mode="r")[:]).astype(np.float32)) | |
| zero_out = os.environ.get("C2_ZERO_OUTSIDE", "0") == "1" | |
| if zero_out: # same order as training: zero outside nnU-Net's foreground mask BEFORE any rendering | |
| outside = torch.from_numpy(np.asarray(blosc2.open(urlpath=str(d / f"{st}_seg.b2nd"), mode="r")[0]) == -1) | |
| x[:, outside] = 0 | |
| if C.is_online_cg(key): | |
| import cascade2_render as R | |
| hook = R.make_online_hook(os.environ.get("C2_CG_RENDERER", "confirmgen")) | |
| les = np.asarray(blosc2.open(urlpath=str(d / f"{st}_seg.b2nd"), mode="r")[0]) == 1 | |
| x[1] = torch.from_numpy(hook(x[0].numpy(), les, key, [[0, n] for n in x.shape[1:]], np.random.default_rng(seed))) | |
| elif key.startswith("cg"): | |
| import cascade2_render as R | |
| v = key.split("_", 1)[0][2:] | |
| r = np.asarray(blosc2.open(urlpath=str(C.RENDER_DIR / rtag / f"v{v}" / f"{C.patient(key)}.b2nd"), mode="r")[:]).astype(np.float32) | |
| torch.manual_seed(seed) | |
| x[1] = R.online_randomise(torch.from_numpy(r)[None, None], (x[0] != 0)[None, None], | |
| os.environ.get("C2_CG_ONLINE", "confirmgen"))[0, 0] | |
| if zero_out: # rendered / randomised channel 1 too | |
| x[:, outside] = 0 | |
| return x | |
| def stage2_key(src_key): | |
| return f"r_{C.patient(src_key)}" if src_key.startswith("r_") else f"syn_t1_{C.patient(src_key)}" | |
| def heldout_sources(ds, fold, smoke=False, all_smoke=False): | |
| opt = fold.split("_")[1] | |
| fams = C.DATA_OPTIONS[opt] if opt in C.DATA_OPTIONS else C.DATA_OPTIONS["ii"] | |
| if smoke: | |
| sa = json.load(open(C.OUT / "smoke_assignment.json")) | |
| pats = sa["held_out_patients"] + (sa["train_patients"] if all_smoke else []) # all_smoke: SMOKE ONLY (in-sample heat) | |
| else: | |
| k = int(fold.rsplit("_f", 1)[1]) | |
| pats = [p for p, f in C.patient_folds()["assign"].items() if f == k] | |
| if fold.startswith("c2x_") or C.exclude_malformed_env(): | |
| bad = C.malformed_patients(); pats = [p for p in pats if p not in bad] | |
| src = [] | |
| for p in sorted(pats): | |
| if p.startswith("contra_"): | |
| src.append(f"r_{p}") | |
| else: | |
| online = json.load(open(C.PREP / ds / "c2_render.json")).get("cg_mode", "online") == "online" | |
| src.append(f"syn_{p}" if ("g1" in fams or smoke) else (f"cg_{p}" if online else f"cg0_{p}")) | |
| return src | |
| def run_oof_like(pr, srcs, od, cls="lesion", zero_t1=False, rtag=None): | |
| import torch | |
| od.mkdir(parents=True, exist_ok=True); man = {} | |
| for s in srcs: | |
| o = od / f"{stage2_key(s)}.b2nd" | |
| if o.exists(): | |
| continue | |
| t0 = time.time() | |
| x = load_source(s, rtag, seed=C.stable_seed("oof", s)) | |
| import blosc2 | |
| _d, _st = C.base_key(s) | |
| _sg = np.asarray(blosc2.open(urlpath=str(_d / f"{_st}_seg.b2nd"), mode="r")[0]) | |
| brain = (x[0] != 0).numpy() & (_sg != -1) # 2026-11-14: exclude nnU-Net outside mask (non-brain signal in some syn T1s) | |
| if zero_t1: | |
| x[0] = 0 | |
| with torch.no_grad(): | |
| lg = pr.predict_logits_from_preprocessed_data(x).cpu() | |
| h = heat_from_logits(lg, cls).numpy() * brain | |
| tmp = o.with_name(o.stem + f".tmp{os.getpid()}.b2nd"); write_b2nd_u8(h, tmp); os.replace(tmp, o) # 2026-11-23: atomic (requeue-safe) | |
| man[stage2_key(s)] = {"source": s, "peak": float(h.max()), "vox_ge05": int((h >= 0.5).sum()), "s": round(time.time() - t0, 1)} | |
| print("C2_OOF", stage2_key(s), json.dumps(man[stage2_key(s)]), flush=True) | |
| mp = od / "manifest.json" | |
| old = json.load(open(mp)) if mp.exists() else {} | |
| old.update(man); json.dump(old, open(mp, "w"), indent=1) | |
| def oof(a): | |
| rtag = json.load(open(C.PREP / {"977": C.DET, "978": C.DETBE}[a.ds] / "c2_render.json")).get("rtag") | |
| ds = {"977": C.DET, "978": C.DETBE}[a.ds] | |
| pr = predictor(model_dir(ds, a.trainer), [C.fold_index(ds, a.fold)], a.device) | |
| run_oof_like(pr, heldout_sources(ds, a.fold, a.smoke, a.all_smoke), C.HEAT_OOF / a.det_tag, rtag=rtag) | |
| def predict_raw(pr, files, zero_t1=False, cls="lesion"): | |
| """probability map at the raw (T1) geometry; T1 zeroed AFTER preprocessing if zero_t1 (crop/normalisation unchanged).""" | |
| import torch | |
| from nnunetv2.inference.export_prediction import convert_predicted_logits_to_segmentation_with_correct_shape | |
| pre = pr.configuration_manager.preprocessor_class(verbose=False) | |
| data, sg, props = pre.run_case(files, None, pr.plans_manager, pr.configuration_manager, pr.dataset_json) | |
| x = torch.from_numpy(data).float() | |
| if os.environ.get("C2_ZERO_OUTSIDE", "0") == "1" and sg is not None: # match the training loader | |
| x[:, torch.from_numpy(np.asarray(sg[0]) == -1)] = 0 | |
| if zero_t1: | |
| x[0] = 0 | |
| with torch.no_grad(): | |
| lg = pr.predict_logits_from_preprocessed_data(x).cpu() | |
| _, prob = convert_predicted_logits_to_segmentation_with_correct_shape(lg, pr.plans_manager, pr.configuration_manager, | |
| pr.label_manager, props, return_probabilities=True) | |
| prob = np.asarray(prob, np.float32) | |
| if cls == "lesion": | |
| return prob[1] | |
| if cls == "sum": | |
| return 1 - prob[0] | |
| return prob[{"expansive": 1, "contractive": 2}[cls]] | |
| def write_like(arr, ref_path, out, dtype): | |
| import SimpleITK as sitk | |
| ref = sitk.ReadImage(str(C.guard(ref_path))) | |
| assert arr.shape == sitk.GetArrayFromImage(ref).shape, (out, arr.shape) | |
| im = sitk.GetImageFromArray(arr.astype(dtype)); im.CopyInformation(ref) | |
| tmp = str(out) + ".tmp.nii.gz"; sitk.WriteImage(im, tmp, True); os.replace(tmp, out) | |
| def t1_brain(cid): | |
| import SimpleITK as sitk | |
| return sitk.GetArrayFromImage(sitk.ReadImage(str(C.guard(C.D943R / "imagesTs" / f"test_{cid}_0000.nii.gz")))) > 0 | |
| def run_test(pr, od, cids, zero_t1=False, cls="lesion"): | |
| od.mkdir(parents=True, exist_ok=True) | |
| for c in cids: | |
| o = od / f"{c}.nii.gz" | |
| if o.exists(): | |
| continue | |
| t0 = time.time() | |
| files = [str(C.guard(C.D943R / "imagesTs" / f"test_{c}_000{i}.nii.gz")) for i in (0, 1)] | |
| p = predict_raw(pr, files, zero_t1, cls) * t1_brain(c) | |
| write_like(np.clip(np.round(p * C.HEAT_SCALE), 0, 250), files[0], o, np.uint8) | |
| print("C2_TESTHEAT", od.name, c, f"{time.time() - t0:.0f}s", flush=True) | |
| def test(a): | |
| ds = {"977": C.DET, "978": C.DETBE}[a.ds] | |
| for f in a.folds.split(","): | |
| pr = predictor(model_dir(ds, a.trainer), [C.fold_index(ds, f)], a.device) | |
| run_test(pr, C.HEAT_TEST / a.det_tag / f"fold_{f}", cases(a.cases)) | |
| def zeroshot(a): | |
| d, ck = be_dir() | |
| pr = predictor(d, [0], a.device, ckpt=ck) | |
| zero = a.arm == "c2" | |
| which = a.which.split(",") | |
| if "oof" in which: | |
| if a.smoke: | |
| srcs = [f"syn_{p}" if not p.startswith("contra_") else f"r_{p}" for p in json.load(open(C.OUT / "smoke_assignment.json"))["held_out_patients"]] | |
| else: | |
| srcs = [f"syn_{x}" for x in C.d331_keys()] + [f"r_{c}" for c in C.contra_cids()] | |
| if C.exclude_malformed_env(): | |
| bad = C.malformed_patients(); srcs = [s for s in srcs if C.patient(s) not in bad] | |
| if a.fold is not None: # bake-off: only fold-k held-out patients first (the rest can follow) | |
| keep = {p for p, f in C.patient_folds()["assign"].items() if f == a.fold} | |
| srcs = [s for s in srcs if C.patient(s) in keep] | |
| run_oof_like(pr, srcs, C.HEAT_OOF / a.det_tag, cls=a.cls, zero_t1=zero) | |
| if "test" in which: | |
| cids = cases(a.cases) | |
| run_test(pr, C.HEAT_TEST / a.det_tag / "fold_be", cids, zero_t1=zero, cls=a.cls) | |
| a.blur = 0.0 | |
| test_mean(a) | |
| meta = {"arm": a.arm, "model": str(d), "checkpoint": ck, "cls": a.cls, "t1_zeroed": zero, | |
| "note": "C1 heat leaks T1 evidence (native T1+FLAIR input)" if not zero else "FLAIR only"} | |
| json.dump(meta, open(C.OUT / f"zeroshot_{a.det_tag}.json", "w"), indent=1) | |
| def test_mean(a): | |
| import SimpleITK as sitk, scipy.ndimage as ndi | |
| root = C.HEAT_TEST / a.det_tag | |
| fdirs = sorted(p for p in root.glob("fold_*") if p.is_dir()) | |
| assert fdirs, f"no fold heat under {root}" | |
| var = "mean" + (f"_blur{a.blur:g}" if a.blur else "") | |
| od = root / var; od.mkdir(parents=True, exist_ok=True) | |
| cids = sorted(set.intersection(*[{p.name[:-7] for p in f.glob("*.nii.gz")} for f in fdirs])) | |
| for c in cids: | |
| o = od / f"{c}.nii.gz" | |
| if o.exists(): | |
| continue | |
| ps = [sitk.GetArrayFromImage(sitk.ReadImage(str(f / f"{c}.nii.gz"))).astype(np.float32) / C.HEAT_SCALE for f in fdirs] | |
| h = np.mean(ps, 0) | |
| if a.blur: | |
| h = ndi.gaussian_filter(h, a.blur) | |
| h = np.round(np.clip(h, 0, 1) * t1_brain(c) * C.HEAT_SCALE) / C.HEAT_SCALE | |
| write_like(h, C.D943R / "imagesTs" / f"test_{c}_0000.nii.gz", o, np.float32) | |
| meta = {"det_tag": a.det_tag, "variant": var, "folds": [f.name for f in fdirs], "n_cases": len(cids), | |
| "aggregation": "mean of fold softmax lesion probabilities", "blur_sigma": a.blur or 0.0} | |
| json.dump(meta, open(root / f"heat_meta_{var}.json", "w"), indent=1) | |
| print("C2_TEST_MEAN", json.dumps(meta)) | |
| def seg(a): | |
| import torch | |
| from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO | |
| pr = predictor(model_dir(C.DEL, a.trainer), [C.fold_index(C.DEL, a.fold)], a.device, a.tta) | |
| od = Path(a.out); (od / "prob").mkdir(parents=True, exist_ok=True) | |
| hd = C.HEAT_TEST / a.det_tag / a.variant | |
| for c in cases(a.cases): | |
| o = od / f"{c}.nii.gz" | |
| if o.exists(): | |
| continue | |
| t0 = time.time() | |
| t1 = str(C.guard(C.D943R / "imagesTs" / f"test_{c}_0000.nii.gz")) | |
| img, props = SimpleITKIO().read_images([t1, str(hd / f"{c}.nii.gz") if not a.zero_heat else t1]) | |
| if a.zero_heat: | |
| img[1] = 0 | |
| s, prob = pr.predict_single_npy_array(img, props, None, None, True) | |
| write_like((s == 1).astype(np.uint8), t1, o, np.uint8) | |
| write_like(np.clip(np.round(prob[1] * 250), 0, 250), t1, od / "prob" / f"{c}.nii.gz", np.uint8) | |
| print("C2_SEG", c, int((s == 1).sum()), f"{time.time() - t0:.0f}s", flush=True) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("mode", choices=["oof", "zeroshot", "test", "test_mean", "seg"]) | |
| ap.add_argument("--ds", default="977"); ap.add_argument("--trainer"); ap.add_argument("--fold"); ap.add_argument("--folds") | |
| ap.add_argument("--det_tag"); ap.add_argument("--cases", default="panel"); ap.add_argument("--device", default="cuda") | |
| ap.add_argument("--blur", type=float, default=0.0); ap.add_argument("--arm", choices=["c1", "c2"]); ap.add_argument("--cls", default="sum") | |
| ap.add_argument("--which", default="oof,test"); ap.add_argument("--variant", default="mean"); ap.add_argument("--out") | |
| ap.add_argument("--zero_heat", action="store_true"); ap.add_argument("--tta", action="store_true"); ap.add_argument("--smoke", action="store_true") | |
| ap.add_argument("--all_smoke", action="store_true") | |
| a = ap.parse_args() | |
| if a.mode == "zeroshot" and a.fold is not None: | |
| a.fold = int(a.fold) | |
| {"oof": oof, "zeroshot": zeroshot, "test": test, "test_mean": test_mean, "seg": seg}[a.mode](a) | |
| if __name__ == "__main__": | |
| main() | |