Download runtime/code/whisper_synth/src/direction2/cascade2_render.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 29.8 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cascade2_render.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/cascade2_render.py
-
curl -L -o cascade2_render.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cascade2_render.py
29.8 kB
| #!/usr/bin/env python | |
| """cascade2 confirmation-FLAIR renderer ADAPTER (stable interface over the confirmgen agent's code, with a stub). | |
| Split pipeline (confirmgen agent's recommendation; a full numpy render costs 10-19 s per volume, far above the 0.3 s per | |
| sample DA budget, so on-the-fly numpy rendering is out): | |
| OFFLINE render_clean(): K "clean" renders per D331 training patient (structure + class intensities, lesion | |
| anomalies, label-0 decoys; NO global randomisation), made directly in the stage-1 PREPROCESSED geometry of | |
| Dataset961 dxb_<X> (channel 0 = z-scored T1, seg = binary lesion) and stored z-scored as float16 blosc2 | |
| (renders/<rtag>/v<v>/<X>.b2nd). The stage-1 loader swaps it into channel 1 for keys cg<v>_<X>. | |
| ONLINE online_randomise(): per-iteration torch global randomisation on the GPU inside train_step (GIN, gamma, | |
| bias, thick-slice / resolution, noise, rigid jitter <= 1 mm / 1.5 deg) = confirmgen_core.global_randomise_torch | |
| when importable, else the stub below. | |
| Interface contract (what cascade2 relies on; written to outputs/direction2/cascade2/renderer_interface.json): | |
| ConfirmGen(knobs, library)(t1_pos, les, sp, rng=, brain=, axial_axis=, clean_only=True) -> (flair, label, info) | |
| flair: float32, > 0 inside brain, 0 outside; label == les (decoys are label 0, never ignore); T1 untouched | |
| (knobs.p_t1mimic_implant must be 0). | |
| global_randomise_torch(x[B,1,D,H,W], brain[B,1,D,H,W] bool, knobs=None, gen=None, axial_axis=2) -> z-scored tensor. | |
| Library: | |
| ONLY library_production.json (CONTRA, WMH-challenge, BraTS/BMS; built by the confirmgen agent) or the hand-set built-in | |
| prior ("prior", tests/timing only). load_library() refuses library_all/noNORTH/noLAB/noATLASOFF and any library whose | |
| provenance includes NORTH, LAB or ATLAS-43 official. | |
| cascade2_render.py timing [--n 2] -> outputs/direction2/cascade2/render_timing.json (CPU job) | |
| cascade2_render.py render <shard> <nshard> --rtag cgv2 --K 4 [--lib production] [--stub] | |
| cascade2_render.py validate --rtag cgv2 --K 4 -> renders/<rtag>/validate.json + DONE | |
| """ | |
| 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 | |
| FORBIDDEN_LIB_COHORTS = {"north", "lab", "atlasoff", "atlas_official", "atlas43", "atlas-43"} | |
| FORBIDDEN_LIB_NAMES = {"all", "noNORTH", "noLAB", "noATLASOFF"} # built from test-cohort statistics | |
| PRODUCTION_LIB = "production" # library_production.json (CONTRA, WMH, BraTS/BMS) | |
| # ======================================================================================================= adapters | |
| def _provenance_tokens(lib): | |
| toks = set() | |
| for k in ("cohorts", "provenance", "sources", "source_cohorts"): | |
| v = lib.get(k) | |
| if isinstance(v, str): | |
| toks.add(v.lower()) | |
| elif isinstance(v, dict): | |
| toks |= {str(x).lower() for x in v} | |
| elif isinstance(v, (list, tuple)): | |
| toks |= {str(x).lower() for x in v} | |
| return toks | |
| def load_library(name=PRODUCTION_LIB): | |
| """ONLY the renderer's production library (main session, 2026-11-14) or the built-in prior ('prior', hand-set, no | |
| cohort statistics). Refuses any library whose provenance includes NORTH, LAB or ATLAS-43 official.""" | |
| if name in ("prior",): | |
| return None | |
| name = name or PRODUCTION_LIB | |
| assert name not in FORBIDDEN_LIB_NAMES, f"library_{name} contains test-cohort statistics (NORTH/LAB/ATLAS-43): refused" | |
| p = C.WS / "outputs/direction2/confirmgen" / f"library_{name}.json" | |
| assert p.exists(), f"{p} not built yet (confirmgen agent): cannot render with the production library" | |
| lib = json.load(open(C.guard(p))) | |
| assert isinstance(lib, dict), f"library_{name} is empty" | |
| toks = _provenance_tokens(lib) | |
| assert toks, f"library_{name} declares no provenance ('cohorts'/'provenance'): refused" | |
| bad = {t for t in toks if any(f in t for f in FORBIDDEN_LIB_COHORTS)} | |
| assert not bad, f"library_{name} provenance includes test cohorts {bad}: refused" | |
| if os.environ.get("C2_CG_CNR_CALIB", "0") == "1": # 2026-11-16: the confirmgen agent's data-derived CNR correction (CONTRA renders) | |
| cal = C.WS / "outputs/direction2/confirmgen/tables/cnr_calibration.json" | |
| lib = dict(lib); lib["cnr_calib"] = {k: float(v) for k, v in json.load(open(cal))["by_acq"].items()} | |
| return lib | |
| class StubRenderer: | |
| """Fast stand-in (pipeline tests only): FLAIR-like contrast from T1 (CSF dark, GM > WM), lesion = bright core + | |
| rim, label-0 bright decoys (periventricular-ish blobs). Same output contract as ConfirmGen(clean_only=True).""" | |
| def __init__(self, *a, **k): | |
| pass | |
| def __call__(self, t1, les, sp=(1, 1, 1), rng=None, brain=None, axial_axis=0, clean_only=True, **kw): | |
| import scipy.ndimage as ndi | |
| rng = rng or np.random.default_rng() | |
| brain = (t1 > 0) if brain is None else brain | |
| v = t1[brain]; z = np.zeros_like(t1, dtype=np.float32) | |
| z[brain] = (t1[brain] - np.median(v)) / (v.std() + 1e-6) | |
| fl = np.where(brain, -np.abs(z + 0.3) + 0.5 * rng.normal(size=t1.shape).astype(np.float32) * 0.05, 0).astype(np.float32) | |
| les = les.astype(bool) & brain | |
| if les.any(): | |
| fl[les] += rng.uniform(1.0, 3.0) | |
| rim = ndi.binary_dilation(les, iterations=1) & ~les & brain | |
| fl[rim] += rng.uniform(0.3, 1.5) | |
| cand = np.argwhere(brain & ~ndi.binary_dilation(les, iterations=4)) | |
| for _ in range(rng.poisson(6)): | |
| if not len(cand): | |
| break | |
| c = cand[rng.integers(len(cand))]; r = rng.uniform(1, 4) | |
| sl = tuple(slice(max(0, ci - 5), ci + 6) for ci in c) | |
| g = np.meshgrid(*[np.arange(s.start, min(s.stop, n)) for s, n in zip(sl, t1.shape)], indexing="ij") | |
| d = np.sqrt(sum((gi - ci) ** 2 for gi, ci in zip(g, c))) / r | |
| sub = tuple(slice(s.start, min(s.stop, n)) for s, n in zip(sl, t1.shape)) | |
| fl[sub] += rng.uniform(1.0, 3.0) * np.clip(1 - d, 0, 1) * brain[sub] | |
| out = np.where(brain, 1000 + 100 * fl, 0).astype(np.float32) | |
| return np.where(brain, np.maximum(out, 1.0), 0), les.astype(np.uint8), {"stub": True} | |
| def get_renderer(stub=False, knobs=None, library=None): | |
| if stub: | |
| return StubRenderer(), "stub" | |
| import confirmgen_core as G | |
| k = knobs or (G.production_knobs() if hasattr(G, "production_knobs") else G.Knobs()) | |
| assert getattr(k, "p_t1mimic_implant", 0.0) == 0.0, "renders must not modify T1 (cascade2 stores FLAIR only)" | |
| return G.ConfirmGen(k, library), "confirmgen" | |
| def knobs_for(key, v, K): | |
| """variant v of K: hardness spread 0.2..0.8 across variants (diversity of anomaly strength and decoy load).""" | |
| import confirmgen_core as G | |
| h = 0.2 + 0.6 * (v / max(1, K - 1)) | |
| try: | |
| k = G.Knobs.from_hardness(h, acute=key.startswith("acute_")) | |
| except TypeError: | |
| k = G.Knobs.from_hardness(h); k.acute = key.startswith("acute_") | |
| if hasattr(k, "p_t1mimic_implant"): | |
| k.p_t1mimic_implant = 0.0 | |
| return k | |
| def online_randomise(x, brain, mode="confirmgen"): | |
| """x [B,1,D,H,W] (clean render, z-scored), brain [B,1,D,H,W] bool -> randomised, z-scored inside brain.""" | |
| import torch | |
| if mode == "confirmgen": | |
| try: | |
| import confirmgen_core as G | |
| return G.global_randomise_torch(x, brain, None, axial_axis=0) | |
| except (ImportError, AttributeError): | |
| mode = "stub" | |
| if mode == "stub": | |
| sys.path.insert(0, str(C.WS / "src")) | |
| import v10_gin | |
| out = x.clone() | |
| for b in range(x.shape[0]): | |
| m = brain[b:b + 1] | |
| xx = torch.cat([m.float(), out[b:b + 1]], 1) | |
| v = v10_gin.gin_channel(xx, ch=1, p=0.8)[:, 1:2] | |
| v = v + 0.05 * torch.randn_like(v) | |
| mu, sd = v[m].mean(), v[m].std() + 1e-6 | |
| out[b:b + 1] = torch.where(m, (v - mu) / sd, torch.zeros_like(v)) | |
| return out | |
| return x | |
| # ================================================================================ ONLINE renderer hooks (preferred) | |
| # Expected confirmgen API (written to renderer_interface.json; the hooks raise if it is missing, never fall back silently): | |
| # CPU / DA worker : confirmgen_core.make_online_renderer(**kw) -> R ; R(t1, les, key=<case key>, bbox=[[lo,hi]]*3, rng=np.random.Generator) | |
| # t1: float32 [D,H,W] z-scored preprocessed T1 crop (0 outside brain), les: bool crop -> FLAIR crop (float32, | |
| # any scale; cascade2 z-scores it inside the brain). Precomputed per-case structures are the renderer's own | |
| # business (it gets the key and the crop box in the dxb_<X> preprocessed grid). | |
| # GPU / train_step: confirmgen_core.make_torch_renderer(device=...) -> R ; R(t1[B,1,D,H,W], les[B,1,D,H,W] bool, keys) -> [B,1,D,H,W] | |
| def _zscore_np(fl, brain): | |
| v = fl[brain] | |
| if v.size < 10: | |
| return np.zeros_like(fl, dtype=np.float32) | |
| return np.where(brain, (fl - v.mean()) / (v.std() + 1e-6), 0).astype(np.float32) | |
| STUB_CODE_TABLE = {1: {"name": "wmh_cap", "bright_parenchymal": True}, 3: {"name": "pvs_dark", "bright_parenchymal": False}, | |
| 4: {"name": "flow", "bright_parenchymal": False}} | |
| def stub_patch(t1, les, key=None, bbox=None, rng=None, negmap=None): | |
| """fast patch-level stub (tests only): FLAIR-like contrast from the z-scored T1, bright lesion core + rim, 0-6 | |
| label-0 decoys (bright 'wmh_cap' code 1, dark 'pvs' code 3, 'flow' code 4; written into `negmap` if given).""" | |
| import torch | |
| from arch2stage_nnunet import _maxpool, _bbox_slices | |
| rng = rng or np.random.default_rng() | |
| brain = t1 != 0 | |
| a = rng.uniform(0.6, 1.4) | |
| fl = np.where(brain, -a * np.abs(t1 + rng.uniform(0.0, 0.6)), 0).astype(np.float32) | |
| if les.any(): | |
| lt = torch.from_numpy(les) | |
| bb = _bbox_slices(lt, 3) | |
| rim = (_maxpool(lt[bb].float(), 1) > 0) & ~lt[bb] | |
| sub = fl[bb]; sub[les[bb]] += rng.uniform(1.0, 3.0); sub[rim.numpy() & brain[bb]] += rng.uniform(0.2, 1.2) | |
| shp = t1.shape | |
| for _ in range(rng.poisson(3)): | |
| for _t in range(30): | |
| c = [int(rng.integers(n)) for n in shp] | |
| if brain[c[0], c[1], c[2]] and not les[c[0], c[1], c[2]]: | |
| break | |
| else: | |
| continue | |
| r = rng.uniform(1.0, 4.0) | |
| sl = tuple(slice(max(0, ci - 5), min(n, ci + 6)) for ci, n in zip(c, shp)) | |
| g = np.ogrid[sl[0], sl[1], sl[2]] | |
| d = np.sqrt(sum((gi - ci) ** 2 for gi, ci in zip(g, c))) / r | |
| code = int(rng.choice([1, 3, 4])) | |
| f = np.clip(1 - d, 0, 1) * brain[sl] * ~les[sl] | |
| fl[sl] += (1 if code == 1 else -1) * rng.uniform(1.0, 3.0) * f | |
| if negmap is not None: | |
| negmap[sl] = np.where(f > 0.3, code, negmap[sl]) | |
| fl += rng.normal(0, 0.05, shp).astype(np.float32) * brain | |
| return fl | |
| CACHE_DIR = C.OUT / "cg_cache" # <key>/<array>.b2nd (volumetric, dxb_<key> preprocessed geometry) + meta.npz (tables, sites) | |
| def precompute(shard, nshard): | |
| """confirmgen_fast.precompute_case for every D331 patient, in the dxb_<X> PREPROCESSED geometry (z-scored T1 shifted | |
| positive, binary lesion, brain = T1 != 0, 1 mm). Volumetric arrays -> blosc2 (lazy crops in the DA workers).""" | |
| import confirmgen_core as G | |
| keys = os.environ["C2_RENDER_KEYS"].split(",") if os.environ.get("C2_RENDER_KEYS") else C.d331_keys() | |
| for i, key in enumerate(keys): | |
| if i % nshard != shard: | |
| continue | |
| od = CACHE_DIR / key | |
| if (od / "DONE").exists(): | |
| if (od / "BRAIN_SEGMASK").exists(): | |
| continue | |
| import shutil # cache made before the 2026-11-14 bgmask fix (brain = T1 != 0): rebuild | |
| shutil.rmtree(od) | |
| od.mkdir(parents=True, exist_ok=True) | |
| t0 = time.time() | |
| t1, seg = load_base(key) | |
| brain = (t1 != 0) & (seg != -1) # 2026-11-14: some preprocessed syn T1s carry non-brain signal where seg == -1 | |
| t1p = np.where(brain, t1 - t1[brain].min() + 1.0, 0).astype(np.float32) | |
| cache = G.precompute_case(t1p, seg == 1, (1.0, 1.0, 1.0), brain=brain) | |
| sh = tuple(int(x) for x in cache["shape"]) | |
| meta = {} | |
| for k, v in cache.items(): | |
| if isinstance(v, np.ndarray) and v.shape == sh: | |
| write_b2nd(np.ascontiguousarray(v), od / f"{k}.b2nd") | |
| else: | |
| meta[k] = np.asarray(v) | |
| meta["axial_axis"] = np.array(axial_axis_of(key)) | |
| np.savez(od / "meta.npz", **meta) | |
| (od / "BRAIN_SEGMASK").write_text("brain = (t1 != 0) & (seg != -1)\n") | |
| (od / "DONE").write_text("ok\n") | |
| print(f"[c2-precompute] {key} {time.time() - t0:.1f}s {sum(f.stat().st_size for f in od.iterdir()) / 1e6:.1f} MB", flush=True) | |
| class _CacheStore: | |
| """per-worker lazy access to the precomputed caches; crop exactly like confirmgen_fast.crop_cache.""" | |
| def __init__(self): | |
| self.open = {} | |
| def get(self, key): | |
| if key not in self.open: | |
| import blosc2 | |
| od = CACHE_DIR / key | |
| if not ((od / "DONE").exists() and (od / "BRAIN_SEGMASK").exists()): | |
| raise RuntimeError(f"no (current) confirmgen cache for {key} (run cascade2_render.py precompute)") | |
| meta = dict(np.load(od / "meta.npz")) | |
| vol = {f.name[:-5]: blosc2.open(urlpath=str(f), mode="r", dparams={"nthreads": 1}, mmap_mode="r") for f in od.glob("*.b2nd")} | |
| if len(self.open) > 64: | |
| self.open.pop(next(iter(self.open))) | |
| self.open[key] = (meta, vol) | |
| return self.open[key] | |
| def crop(self, key, sl): | |
| meta, vol = self.get(key) | |
| sh = tuple(int(x) for x in meta["shape"]) | |
| out = {k: v for k, v in meta.items() if not k.startswith("site_") and k != "axial_axis"} | |
| for k, v in vol.items(): | |
| out[k] = np.asarray(v[sl]) | |
| lo = np.array([s.start for s in sl]); hi = np.array([s.stop for s in sl]) | |
| for k, v in meta.items(): | |
| if k.startswith("site_"): | |
| c = np.stack(np.unravel_index(v, sh), 1) if len(v) else np.zeros((0, 3), int) | |
| keep = ((c >= lo) & (c < hi)).all(1) | |
| c = c[keep] - lo | |
| out[k] = np.ravel_multi_index(tuple(c.T), tuple(hi - lo)).astype(np.int32) if len(c) else np.zeros(0, np.int32) | |
| out["shape"] = np.array(hi - lo, np.int32) | |
| return out, int(meta["axial_axis"]), sh | |
| # 35n addendum, REVISED rule (user, 2026-11-15): anything that looks like a pathology must not be labelled 0 for the | |
| # FLAIR-only stage 1. THE single place to revise the stage-1 decoy mapping (renderer negmap code -> name): | |
| # DECOY_IGNORE_RULE : stage-1 seg 0 -> 3 (ignore) = every parenchymal decoy, bright or dark | |
| # DECOY_LABEL0_RULE : stays label 0 in stage 1 = CSF-space and brain-edge artefacts only | |
| # Stage 2 and all inference are unaffected (decoys are always label 0 there). Both sets are verified by name against | |
| # confirmgen_core.NEGMAP_CODES and must partition it. | |
| DECOY_IGNORE_RULE = {1: "wmh_cap", 2: "wmh_deep", 3: "pvs_dark", 7: "artefact_bright", 8: "speck", 9: "bank_bright", | |
| 10: "pvs_bright", 11: "artefact_dark", 12: "bank_dark"} | |
| DECOY_LABEL0_RULE = {4: "flow", 5: "sulcal", 6: "edge"} | |
| def decoy_ignore_codes(renderer="confirmgen"): | |
| """-> (codes, source). The registered rule above, verified against confirmgen_core.NEGMAP_CODES (names must match, so | |
| a renumbering in the renderer fails loudly). Env C2_DECOY_IGNORE_CODES ('1,2,..') overrides (tests only; logged).""" | |
| env = os.environ.get("C2_DECOY_IGNORE_CODES", "").strip() | |
| if env: | |
| return sorted(int(x) for x in env.split(",") if x.strip()), "env C2_DECOY_IGNORE_CODES (override)" | |
| assert not set(DECOY_IGNORE_RULE) & set(DECOY_LABEL0_RULE), "decoy rule sets overlap" | |
| if renderer == "stub": | |
| return sorted(DECOY_IGNORE_RULE), "registered rule (stub renderer: codes 1, 3 ignore; 4 label 0)" | |
| import confirmgen_core as G | |
| tab = {int(c): n for c, n in G.NEGMAP_CODES.items()} | |
| rule = {**DECOY_IGNORE_RULE, **DECOY_LABEL0_RULE} | |
| bad = {c: (n, tab.get(c)) for c, n in rule.items() if tab.get(c) != n} | |
| missing = sorted(set(tab) - set(rule)) | |
| assert not bad and not missing, f"confirmgen NEGMAP_CODES disagree with the registered decoy rule: {bad}, unmapped codes {missing}" | |
| return sorted(DECOY_IGNORE_RULE), "registered 35n-addendum rule (revised 2026-11-15), verified against confirmgen_core.NEGMAP_CODES" | |
| def make_online_hook(renderer="confirmgen", return_negmap=False): | |
| """DA-worker hook f(t1, les, key, bbox, rng) -> FLAIR crop (z-scored in brain). 'confirmgen': FastConfirmGen | |
| (confirmgen_fast; precomputed per-case cache + all random work at render time), production library only, | |
| skip_gin = C2_CG_SKIP_GIN (default 1: GIN is then applied on the GPU in train_step, GIN_P['cg']).""" | |
| if renderer == "stub": | |
| def hook(t1, les, key, bbox, rng): | |
| nm = np.zeros(t1.shape, np.uint8) if return_negmap else None | |
| fl = _zscore_np(np.asarray(stub_patch(t1, les, key, bbox, rng, nm), np.float32), t1 != 0) | |
| return (fl, nm) if return_negmap else fl | |
| return hook | |
| import torch | |
| import confirmgen_core as G | |
| lib = load_library(os.environ.get("C2_CG_LIBRARY", PRODUCTION_LIB)) | |
| R = G.make_online_renderer(knobs=G.production_knobs(), library=lib, device="cpu", skip_gin=os.environ.get("C2_CG_SKIP_GIN", "1") == "1") | |
| store = _CacheStore() | |
| def hook(t1, les, key, bbox, rng): | |
| pid = C.patient(key) | |
| meta, _ = store.get(pid) | |
| sh = tuple(int(x) for x in meta["shape"]) | |
| lo = np.array([b[0] for b in bbox]); hi = np.array([b[1] for b in bbox]) | |
| vlo = np.maximum(lo, 0); vhi = np.minimum(hi, sh) | |
| out = np.zeros(tuple(hi - lo), np.float32) | |
| nm = np.zeros(tuple(hi - lo), np.uint8) if return_negmap else None | |
| if (vhi <= vlo).any(): | |
| return (out, nm) if return_negmap else out | |
| cc, ax, _ = store.crop(pid, tuple(slice(int(a), int(b)) for a, b in zip(vlo, vhi))) | |
| if int(cc["brain"].sum()) < 100: | |
| return (out, nm) if return_negmap else out | |
| g = torch.Generator().manual_seed(int(rng.integers(1 << 62))) | |
| if return_negmap: # FastConfirmGen.render(..., return_negmap=True): info['negmap'] (uint8 decoy codes, crop geometry) | |
| fl, _info = R.render(cc, gen=g, axial_axis=ax, return_negmap=True) | |
| else: | |
| fl, _info = R.render(cc, gen=g, axial_axis=ax) | |
| dst = tuple(slice(int(a - l), int(b - l)) for a, b, l in zip(vlo, vhi, lo)) | |
| out[dst] = fl.detach().cpu().numpy().astype(np.float32) | |
| if return_negmap: | |
| nm[dst] = np.asarray(_info["negmap"], np.uint8) | |
| br = np.zeros(out.shape, bool); br[dst] = cc["brain"].astype(bool) # cache brain: T1 != 0 & seg != -1 | |
| out[~br] = 0 | |
| fl = _zscore_np(out, br) | |
| return (fl, nm) if return_negmap else fl | |
| return hook | |
| def make_gpu_hook(renderer="confirmgen"): | |
| import torch | |
| if renderer == "stub": | |
| def R(t1, les, keys): | |
| out = torch.empty_like(t1) | |
| for b in range(t1.shape[0]): | |
| fl = stub_patch(t1[b, 0].cpu().numpy(), les[b, 0].cpu().numpy(), keys[b], None, np.random.default_rng()) | |
| out[b, 0] = torch.from_numpy(fl).to(t1.device) | |
| return online_randomise(out, t1 != 0, "stub") | |
| return R | |
| import confirmgen_core as G | |
| if not hasattr(G, "make_torch_renderer"): | |
| raise RuntimeError("confirmgen_core.make_torch_renderer is not available yet: use C2_CG_RENDERER=stub (tests) or another CG_MODE") | |
| lib = load_library(os.environ.get("C2_CG_LIBRARY", PRODUCTION_LIB)) | |
| Rg = G.make_torch_renderer(device="cuda", library=lib) | |
| def R2(t1, les, keys): | |
| x = Rg(t1, les, keys).float(); m = t1 != 0 | |
| out = torch.zeros_like(x) | |
| for b in range(x.shape[0]): | |
| v = x[b][m[b]] | |
| out[b] = torch.where(m[b], (x[b] - v.mean()) / (v.std() + 1e-6), torch.zeros_like(x[b])) | |
| return out | |
| return R2 | |
| # =================================================================================================== offline render | |
| def write_b2nd(arr, path, patch=(160, 192, 160)): | |
| import blosc2 | |
| from nnunetv2.training.dataloading.nnunet_dataset import nnUNetDatasetBlosc2 | |
| blocks, chunks = nnUNetDatasetBlosc2.comp_blosc2_params((1,) + tuple(arr.shape), patch, arr.itemsize) | |
| tmp = str(path) + ".tmp.b2nd" | |
| if os.path.exists(tmp): | |
| os.remove(tmp) | |
| blosc2.asarray(np.ascontiguousarray(arr), urlpath=tmp, chunks=tuple(chunks[1:]), blocks=tuple(blocks[1:]), | |
| cparams={"codec": blosc2.Codec.ZSTD, "clevel": 8}) | |
| os.replace(tmp, path) | |
| def axial_axis_of(key): | |
| """array axis (SimpleITK z,y,x order of the preprocessed volume; transpose_forward is identity) closest to S-I.""" | |
| import SimpleITK as sitk | |
| r = sitk.ImageFileReader(); r.SetFileName(str(C.guard(C.B / "nnunet_raw/Dataset321_Whisper_T1Large/imagesTr" / f"{key}_0000.nii.gz"))) | |
| r.ReadImageInformation() | |
| d = np.array(r.GetDirection()).reshape(3, 3) # columns = index axes (x, y, z) in LPS world | |
| ax_xyz = int(np.argmax(np.abs(d[2, :]))) # index axis with the largest S-I component | |
| return 2 - ax_xyz # sitk array order is (z, y, x) | |
| def load_base(key): | |
| import blosc2 | |
| stem = f"dxb_{key}" | |
| d = blosc2.open(urlpath=str(C.D961P / f"{stem}.b2nd"), mode="r") | |
| s = blosc2.open(urlpath=str(C.D961P / f"{stem}_seg.b2nd"), mode="r") | |
| t1 = np.asarray(d[0]).astype(np.float32); seg = np.asarray(s[0]) | |
| return t1, seg | |
| def render_clean(gen, key, v, t1, seg, stub=False, K=4): | |
| brain = (t1 != 0) & (seg != -1) | |
| t1p = np.where(brain, t1 - t1[brain].min() + 1.0, 0).astype(np.float32) | |
| les = seg == 1 | |
| rng = np.random.default_rng(C.stable_seed("cascade2", key, v)) | |
| if not stub: | |
| import confirmgen_core as G | |
| gen.k = knobs_for(key, v, K) | |
| fl, lab, info = gen(t1p, les, (1.0, 1.0, 1.0), rng=rng, brain=brain, axial_axis=axial_axis_of(key) if not stub else 0, | |
| clean_only=True) | |
| assert np.array_equal(lab.astype(bool), les & brain), "renderer changed the label (decoys must be label 0)" | |
| vv = fl[brain] | |
| z = np.where(brain, (fl - vv.mean()) / (vv.std() + 1e-6), 0).astype(np.float16) | |
| return z, info | |
| def render(shard, nshard, rtag, K, libname, stub): | |
| lib = load_library(libname) if not stub else None | |
| gen, kind = get_renderer(stub, None, lib) | |
| od = C.RENDER_DIR / rtag | |
| for v in range(K): | |
| (od / f"v{v}").mkdir(parents=True, exist_ok=True) | |
| meta = {"rtag": rtag, "K": K, "library": libname or "prior", "renderer": kind} | |
| mp = od / "meta.json" | |
| if not mp.exists(): | |
| json.dump(meta, open(mp, "w"), indent=1) | |
| keys = C.d331_keys() | |
| if os.environ.get("C2_RENDER_KEYS"): | |
| keys = os.environ["C2_RENDER_KEYS"].split(",") | |
| for i, key in enumerate(keys): | |
| if i % nshard != shard: | |
| continue | |
| todo = [v for v in range(K) if not (od / f"v{v}" / f"{key}.b2nd").exists()] | |
| if not todo: | |
| continue | |
| t1, seg = load_base(key) | |
| for v in todo: | |
| t0 = time.time() | |
| z, info = render_clean(gen, key, v, t1, seg, stub, K) | |
| write_b2nd(z, od / f"v{v}" / f"{key}.b2nd") | |
| print(f"[c2-render] {key} v{v} {time.time() - t0:.1f}s", flush=True) | |
| def validate(rtag, K): | |
| import blosc2 | |
| od = C.RENDER_DIR / rtag; bad = []; n = 0; nbytes = 0 | |
| for key in C.d331_keys(): | |
| shp = blosc2.open(urlpath=str(C.D961P / f"dxb_{key}.b2nd"), mode="r").shape[1:] | |
| for v in range(K): | |
| f = od / f"v{v}" / f"{key}.b2nd" | |
| if not f.exists(): | |
| bad.append((key, v, "missing")); continue | |
| a = blosc2.open(urlpath=str(f), mode="r") | |
| n += 1; nbytes += f.stat().st_size | |
| if tuple(a.shape) != tuple(shp): | |
| bad.append((key, v, f"shape {a.shape} != {shp}")) | |
| res = {"rtag": rtag, "K": K, "n": n, "GB": nbytes / 1e9, "n_bad": len(bad), "bad": bad[:30]} | |
| json.dump(res, open(od / "validate.json", "w"), indent=1) | |
| if bad: | |
| raise SystemExit(f"{len(bad)} bad renders") | |
| (od / "DONE").write_text("ok\n"); print("C2_RENDER_VALIDATE_OK", json.dumps(res)) | |
| # ========================================================================================================== timing | |
| def timing(n=2): | |
| """CPU timing (Slurm job): offline clean render (full preprocessed volume) per case, stub render, storage per | |
| render (float16 b2nd), and the online torch randomisation on a 160x192x160 patch (CPU; GPU time from the smoke).""" | |
| import torch | |
| res = {"cases": []} | |
| keys = C.d331_keys() | |
| pick = [k for k in keys if k.startswith("atlas_")][:n] + [k for k in keys if k.startswith("acute_")][:1] | |
| lib = load_library("prior") | |
| try: | |
| gen, kind = get_renderer(False, None, lib) | |
| except Exception as e: # renderer not importable: stub only | |
| gen, kind = None, f"unavailable: {e!r}" | |
| res["renderer"] = kind | |
| tmpd = C.OUT / "tmp_timing"; tmpd.mkdir(exist_ok=True) | |
| for key in pick: | |
| t1, seg = load_base(key) | |
| row = {"key": key, "shape": list(t1.shape)} | |
| for nm, g, stub in (("confirmgen_clean", gen, False), ("stub", StubRenderer(), True)): | |
| if g is None: | |
| continue | |
| try: | |
| t0 = time.time(); z, info = render_clean(g, key, 0, t1, seg, stub, 4); row[f"{nm}_s"] = round(time.time() - t0, 2) | |
| f = tmpd / f"{nm}_{key}.b2nd"; write_b2nd(z, f); row[f"{nm}_MB"] = round(f.stat().st_size / 1e6, 2); f.unlink() | |
| if nm == "confirmgen_clean": | |
| row["patterns"] = [c.get("pattern") for c in info.get("comps", [])][:8]; row["n_negs"] = len(info.get("negs", [])) | |
| except Exception as e: | |
| row[f"{nm}_error"] = repr(e)[:300] | |
| res["cases"].append(row); print(json.dumps(row), flush=True) | |
| # online randomisation, patch size, CPU threads | |
| x = torch.randn(1, 1, 160, 192, 160); br = torch.ones_like(x, dtype=torch.bool); br[..., :10, :, :] = False | |
| for th in (1, 4): | |
| torch.set_num_threads(th) | |
| for mode in ("confirmgen", "stub"): | |
| ts = [] | |
| for _ in range(3): | |
| t0 = time.time(); online_randomise(x, br, mode); ts.append(round(time.time() - t0, 3)) | |
| res[f"online_{mode}_cpu{th}_s"] = ts | |
| # ONLINE hooks on a real initial-size crop (the DA worker renders the pre-spatial-transform crop, ~ 1.2x patch) | |
| t1, seg = load_base(pick[0]) | |
| crop = tuple(slice(0, min(n, m)) for n, m in zip(t1.shape, (200, 230, 200))) | |
| t1c, lesc = t1[crop], seg[crop] == 1 | |
| torch.set_num_threads(1) | |
| for nm in ("stub", "confirmgen"): | |
| try: | |
| hook = make_online_hook(nm); ts = [] | |
| for i in range(3): | |
| t0 = time.time(); hook(t1c, lesc, pick[0], [[s.start, s.stop] for s in crop], np.random.default_rng(i)); ts.append(round(time.time() - t0, 3)) | |
| res[f"online_hook_{nm}_crop{list(t1c.shape)}_s"] = ts | |
| except Exception as e: | |
| res[f"online_hook_{nm}_error"] = repr(e)[:300] | |
| tmpd.rmdir() | |
| json.dump(res, open(C.OUT / "render_timing.json", "w"), indent=1) | |
| print("C2_RENDER_TIMING", json.dumps(res)) | |
| def hooktime(n=8): | |
| """per-sample cost of the REAL online hook (FastConfirmGen, CPU, 1 thread) on initial-size crops of precomputed cases.""" | |
| import torch | |
| torch.set_num_threads(1) | |
| keys = [k for k in C.d331_keys() if (CACHE_DIR / k / "DONE").exists()][:4] | |
| res = {"keys": keys, "skip_gin": os.environ.get("C2_CG_SKIP_GIN", "1"), "s": []} | |
| hook = make_online_hook("confirmgen") | |
| for i in range(n): | |
| key = keys[i % len(keys)] | |
| t1, seg = load_base(key) | |
| bbox = [[int(s_ // 2 - 100), int(s_ // 2 + 100)] for s_ in t1.shape] | |
| bbox[1] = [t1.shape[1] // 2 - 115, t1.shape[1] // 2 + 115] | |
| from acvl_utils.cropping_and_padding.bounding_boxes import crop_and_pad_nd | |
| t1c = crop_and_pad_nd(t1, bbox, 0); lc = crop_and_pad_nd(seg, bbox, 0) == 1 | |
| t0 = time.time(); fl = hook(t1c, lc, f"cg_{key}", bbox, np.random.default_rng(i)); res["s"].append(round(time.time() - t0, 3)) | |
| res["median_s"] = float(np.median(res["s"][1:])) if len(res["s"]) > 1 else None | |
| json.dump(res, open(C.OUT / "online_hook_timing.json", "w"), indent=1) | |
| print("C2_HOOKTIME", json.dumps(res)) | |
| def main(): | |
| ap = argparse.ArgumentParser(); ap.add_argument("mode", choices=["timing", "render", "validate", "precompute", "hooktime"]) | |
| ap.add_argument("shard", nargs="?", type=int, default=0); ap.add_argument("nshard", nargs="?", type=int, default=1) | |
| ap.add_argument("--rtag", default="cgv2"); ap.add_argument("--K", type=int, default=4) | |
| ap.add_argument("--lib", default=PRODUCTION_LIB); ap.add_argument("--stub", action="store_true"); ap.add_argument("--n", type=int, default=2) | |
| a = ap.parse_args() | |
| if a.mode == "timing": | |
| timing(a.n) | |
| elif a.mode == "render": | |
| render(a.shard, a.nshard, a.rtag, a.K, a.lib, a.stub) | |
| elif a.mode == "precompute": | |
| precompute(a.shard, a.nshard) | |
| elif a.mode == "hooktime": | |
| hooktime() | |
| else: | |
| validate(a.rtag, a.K) | |
| if __name__ == "__main__": | |
| main() | |