Download runtime/code/whisper_synth/src/direction2/cls2_d331feat.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 8.59 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cls2_d331feat.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/cls2_d331feat.py
-
curl -L -o cls2_d331feat.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cls2_d331feat.py
8.59 kB
| #!/usr/bin/env python | |
| """classifier2 (GPU): FROZEN D331 deep features pooled per candidate ("classification head on an nnU-Net-quality encoder"). | |
| D331 (T1-only ResEnc-L, fold 0 checkpoint_final) is OUT-OF-SAMPLE on CONTRA, DEV-A and the dev-test cohorts (never on the | |
| T1 family, which is therefore not processed). Own sliding window (patch 160x192x160, step 0.5, Gaussian weights, = nnU-Net | |
| predictor) with forward hooks on the last two decoder stages: | |
| dec1 = last decoder stage (32 ch, 1 mm) -> per candidate: mean / max inside, mean in the 1-3 voxel ring (96) | |
| dec2 = previous stage (64 ch, 2 mm) -> mean / max inside (nearest 2 mm voxels) (128) | |
| logit margin (lesion - background) -> mean / max inside, ring mean (3) | |
| Candidates = dethead_cand.candidates on each heat source (identical cids to the candidate tables). | |
| cls2_d331feat.py --pop contra|dev|test --chunk i --nchunk n -> classifier2/d331feat/<pop>/chunk_i_of_n.npz | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, sys, time | |
| from pathlib import Path | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import cls2_common as Q # noqa: E402 | |
| PATCH = (160, 192, 160) | |
| def load_net(device): | |
| import devset_common as D, cascade2_infer as I | |
| pr = I.predictor(D.model_dir("d331"), [D.model_fold("d331")], str(device)) | |
| net = pr.network.to(device).eval() | |
| return net | |
| def gaussian(device): | |
| from nnunetv2.inference.sliding_window_prediction import compute_gaussian | |
| return compute_gaussian(PATCH, sigma_scale=1. / 8, value_scaling_factor=10, device=device).float() | |
| def steps(dim, p): | |
| if dim <= p: | |
| return [0] | |
| n = int(np.ceil((dim - p) / (p * 0.5))) + 1 | |
| return [int(round(i * (dim - p) / (n - 1))) for i in range(n)] | |
| def features(net, t1, device, gw): | |
| """t1: (D,H,W) float32 preprocessed (0 outside brain). returns dec1 (32,D,H,W), dec2 (64,~D/2..), margin (D,H,W) torch on device.""" | |
| import torch | |
| shp0 = t1.shape | |
| pad = [max(0, p - s) for p, s in zip(PATCH, shp0)] | |
| x = np.pad(t1, [(0, q) for q in pad]) | |
| shp = x.shape | |
| xt = torch.from_numpy(x).to(device)[None, None] | |
| acc1 = torch.zeros((32,) + shp, device=device); acc2 = torch.zeros((64,) + tuple((s + 1) // 2 for s in shp), device=device) | |
| accl = torch.zeros((2,) + shp, device=device); wsum = torch.zeros(shp, device=device) | |
| g2 = torch.nn.functional.avg_pool3d(gw[None, None], 2)[0, 0] | |
| cap = {} | |
| dec = net.decoder | |
| h1 = dec.stages[-1].register_forward_hook(lambda m, i, o: cap.__setitem__("d1", o)) | |
| h2 = dec.stages[-2].register_forward_hook(lambda m, i, o: cap.__setitem__("d2", o)) | |
| try: | |
| with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"): | |
| for a in steps(shp[0], PATCH[0]): | |
| for b in steps(shp[1], PATCH[1]): | |
| for c in steps(shp[2], PATCH[2]): | |
| sl = (slice(a, a + PATCH[0]), slice(b, b + PATCH[1]), slice(c, c + PATCH[2])) | |
| lo = net(xt[(slice(None), slice(None)) + sl]) | |
| lo = lo[0] if isinstance(lo, (list, tuple)) else lo | |
| accl[(slice(None),) + sl] += lo[0].float() * gw | |
| acc1[(slice(None),) + sl] += cap["d1"][0].float() * gw | |
| sl2 = tuple(slice(s.start // 2, s.start // 2 + p // 2) for s, p in zip(sl, PATCH)) | |
| acc2[(slice(None),) + sl2] += cap["d2"][0].float() * g2 | |
| wsum[sl] += gw | |
| finally: | |
| h1.remove(); h2.remove() | |
| w2 = torch.nn.functional.avg_pool3d(wsum[None, None], 2, ceil_mode=True)[0, 0] | |
| acc1 /= wsum; accl /= wsum; acc2 /= w2[: acc2.shape[1], : acc2.shape[2], : acc2.shape[3]].clamp(min=1e-6) | |
| d = tuple(slice(0, s) for s in shp0) | |
| return acc1[(slice(None),) + d], acc2, (accl[1] - accl[0])[d] | |
| def pool(L, n, brain, d1, d2, mg, device): | |
| import torch, scipy.ndimage as ndi | |
| out = np.zeros((n, 32 * 3 + 64 * 2 + 3), np.float32) | |
| objs = ndi.find_objects(L) | |
| for k in range(1, n + 1): | |
| s0 = objs[k - 1] | |
| lo = [max(s.start - 3, 0) for s in s0]; hi = [min(s.stop + 3, L.shape[i]) for i, s in enumerate(s0)] | |
| sl = tuple(slice(a, b) for a, b in zip(lo, hi)) | |
| m = L[sl] == k | |
| ring = ndi.binary_dilation(m, iterations=3) & ~m & brain[sl] | |
| mt = torch.from_numpy(m).to(device); rt = torch.from_numpy(ring).to(device) | |
| f = d1[(slice(None),) + sl] | |
| fin = f[:, mt] | |
| r = [fin.mean(1), fin.amax(1), f[:, rt].mean(1) if ring.any() else fin.mean(1)] | |
| idx = np.argwhere(m) + np.array(lo) | |
| idx2 = np.unique(idx // 2, axis=0) | |
| idx2 = np.minimum(idx2, np.array(d2.shape[1:]) - 1) | |
| it = torch.from_numpy(idx2).to(device) | |
| f2 = d2[:, it[:, 0], it[:, 1], it[:, 2]] | |
| r += [f2.mean(1), f2.amax(1)] | |
| mm = mg[sl] | |
| r += [mm[mt].mean()[None], mm[mt].amax()[None], (mm[rt].mean() if ring.any() else mm[mt].mean())[None]] | |
| out[k - 1] = torch.cat(r).float().cpu().numpy() | |
| return out | |
| def pool_mirror(L, n, brain, props, d1, mg, device): | |
| """contralateral comparison: D331 dec1 features (mean, max) and logit margin (mean, max) at the left-right mirrored | |
| candidate voxels (mirror plane through the brain centre of mass along the physical L-R axis).""" | |
| import torch, diag2_common as G | |
| pa = G.phys_axes(props) | |
| lr = [a for a, (ph, sg) in enumerate(pa) if ph == 0][0] | |
| com = float(np.argwhere(brain)[:, lr].mean()) | |
| out = np.zeros((n, 32 * 2 + 2), np.float32) | |
| import scipy.ndimage as ndi | |
| objs = ndi.find_objects(L) | |
| for k in range(1, n + 1): | |
| s0 = objs[k - 1] | |
| idx = np.argwhere(L[s0] == k) + np.array([s.start for s in s0]) | |
| idx[:, lr] = np.clip(np.round(2 * com - idx[:, lr]), 0, L.shape[lr] - 1) | |
| it = torch.from_numpy(idx).to(device) | |
| f = d1[:, it[:, 0], it[:, 1], it[:, 2]]; m = mg[it[:, 0], it[:, 1], it[:, 2]] | |
| out[k - 1] = torch.cat([f.mean(1), f.amax(1), m.mean()[None], m.amax()[None]]).float().cpu().numpy() | |
| return out | |
| def iter_pop(pop, keys): | |
| import dethead_cand as K | |
| for key in keys: | |
| if pop == "contra": | |
| t1, brain, gt, props, srcs, probs = K.iter_contra(key); srcs = {s: v[0] for s, v in srcs.items()} | |
| elif pop == "dev": | |
| t1, brain, gt, props, srcs, probs = K.iter_dev(key); srcs = {s: v[0] for s, v in srcs.items()} | |
| else: | |
| import cls2_testprep as P | |
| t1, fl, h, p, brain, gt, props = P.prep(key); srcs = {"real": h} | |
| yield key, t1, brain, srcs, props | |
| def main(): | |
| import torch | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--pop", required=True); ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1) | |
| ap.add_argument("--limit", type=int, default=0); ap.add_argument("--mirror", type=int, default=0) | |
| a = ap.parse_args() | |
| import dethead_common as H, dethead_cand as K | |
| keys = {"contra": H.contra_keys, "dev": K.dev_keys, "test": Q.test_cids}[a.pop]()[a.chunk::a.nchunk] | |
| if a.limit: | |
| keys = keys[: a.limit] | |
| op = Q.OUT / (("d331feat_smoke" if a.limit else "d331feat") + ("mir" if a.mirror else "")) / a.pop / f"chunk_{a.chunk}_of_{a.nchunk}.npz" | |
| if op.exists(): | |
| print("exists", op); return | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| net = load_net(device); gw = gaussian(device) | |
| idx, feats = [], [] | |
| t0 = time.time() | |
| for key, t1, brain, srcs, props in iter_pop(a.pop, keys): | |
| t1 = np.where(brain, t1, 0).astype(np.float32) | |
| d1, d2, mg = features(net, t1, device, gw) | |
| for s, h in srcs.items(): | |
| L, n = K.candidates(h, brain) | |
| if n == 0: | |
| continue | |
| f = pool(L, n, brain, d1, d2, mg, device) | |
| if a.mirror: | |
| f = np.concatenate([f, pool_mirror(L, n, brain, props, d1, mg, device)], 1) | |
| feats.append(f) | |
| idx += [(key, s, i + 1) for i in range(n)] | |
| p05 = int((mg > 0).sum()) | |
| del d1, d2, mg; torch.cuda.empty_cache() | |
| print("D331FEAT", a.pop, key, len(idx), "vox(p>0.5)", p05, f"{time.time() - t0:.0f}s", flush=True) | |
| Q.save_npz(op, index=np.array(json.dumps(idx)), X=np.concatenate(feats).astype(np.float16) if feats else np.zeros((0, 227 + 66 * a.mirror), np.float16)) | |
| print("D331FEAT_DONE", a.pop, a.chunk, len(idx), flush=True) | |
| if __name__ == "__main__": | |
| main() | |