""" Inference + Codabench prediction.zip generator. For each disease target: - Load all best_*.pth and swa_*.pth checkpoints in the per-target results dir - Run each on the {split} embeddings of that target - Average softmax probabilities across checkpoints (multi-seed/multi-LR/SWA ensemble) - Write {split}_per_sample_predictions.csv in the format the organizer's cvpr26_organize_eval_metrics_and_predictions.py expects Then concatenate all targets into predictions.csv and zip → prediction.zip for direct Codabench submission. """ import argparse import os import sys import zipfile import h5py import numpy as np import pandas as pd import torch from torch.utils.data import DataLoader, Dataset THIS = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.abspath(os.path.join(THIS, "..")) sys.path.insert(0, os.path.join(ROOT, "starter")) from models.attention_pooling_multilayers import MultiLayersCrossAttentionPooling # noqa: E402 # Per-disease decision thresholds, derived from val labels on the v4 multi-seed # ensemble (threshold_optimize_v2 unique-prob sweep). Baked in so this single # script reproduces the 0.7086 BalAcc result without needing a follow-up step. # Disease not in this dict falls back to 0.5. THRESHOLDS = { "hydronephrosis": 0.7685199, "lymphadenopathy": 0.5737428, "kidney_stone": 0.80407256, "covid": 0.6222638, "gallstone": 0.7481811, "liver_calcifications": 0.64198047, "colorectal_cancer": 0.35786006, "liver_lesion": 0.79084086, "renal_cyst": 0.10136525, "liver_cyst": 0.11666061, "adrenal_hyperplasia": 0.5463961, "splenomegaly": 0.37268373, "lung_nodule_malignancy": 0.44977823, "cholecystitis": 0.52176595, "atherosclerosis": 0.5064166, "fatty_liver": 0.48598397, "ascites": 0.5023216, } class SpatialFeaturesDataset(Dataset): def __init__(self, embeds_dir, csv_path, split, target_column): df = pd.read_csv(csv_path) split_df = df[df["split"] == split].copy() self.paths, self.label_mapping = [], {} for _, row in split_df.iterrows(): case_id = str(row["case_id"]) base = case_id.split(".nii.gz")[0] if ".nii.gz" in case_id else case_id base = base.replace(".h5", "") path = os.path.join(embeds_dir, base + ".h5") if os.path.exists(path): self.paths.append(path) self.label_mapping[base] = int(row[target_column]) def __len__(self): return len(self.paths) def __getitem__(self, i): path = self.paths[i] base = os.path.basename(path).replace(".h5", "") with h5py.File(path, "r") as hf: x = torch.tensor(hf["y_hat"][:]).float() return x, torch.tensor(self.label_mapping[base]).long(), base def discover_target_dirs(results_root): """Find target subdirs that contain at least one .pth checkpoint.""" out = [] for name in sorted(os.listdir(results_root)): d = os.path.join(results_root, name) if not os.path.isdir(d): continue if any(f.endswith(".pth") for f in os.listdir(d)): out.append(name) return out def parse_head_hparams(ckpt): """The state dict keys look like `heads.head_lr_1e_03.<...>`. We rebuild a head with the same architecture as training (defaults match starter).""" sd = ckpt["state_dict"] # Strip "heads.." prefix and detect dimensions stripped = {} for k, v in sd.items(): if k.startswith("heads."): parts = k.split(".", 2) if len(parts) >= 3: stripped[parts[2]] = v cls_w = stripped.get("classifier.weight") cq = stripped.get("class_query") if cls_w is None or cq is None: raise RuntimeError(f"Checkpoint missing classifier/class_query: keys={list(stripped.keys())[:5]}") num_classes, q_times_d = cls_w.shape query_num, embed_dim = cq.shape assert q_times_d == query_num * embed_dim, ( f"Mismatch: classifier in_features={q_times_d} vs query_num*embed_dim={query_num*embed_dim}" ) # num_layers = number of cross-attention layers we can find in the keys num_layers = 1 + max( (int(k.split(".")[1]) for k in stripped.keys() if k.startswith("layers.")), default=-1, ) if num_layers < 1: num_layers = 2 # fall back to starter default return stripped, dict( embed_dim=embed_dim, query_num=query_num, num_classes=num_classes, num_layers=num_layers, num_heads=4, dropout=0.0, ffn_mult=1, ) def load_head(ckpt_path, device): ckpt = torch.load(ckpt_path, map_location="cpu") stripped, hp = parse_head_hparams(ckpt) head = MultiLayersCrossAttentionPooling(**hp) head.load_state_dict(stripped, strict=True) head.to(device).eval() return head, hp @torch.no_grad() def predict_one_head(head, loader, device): all_probs, all_labels, all_filenames = [], [], [] for xb, yb, fns in loader: xb = xb.to(device) logits = head(xb) probs = torch.softmax(logits, dim=1).cpu() all_probs.append(probs) all_labels.append(yb) all_filenames.extend(list(fns)) return torch.cat(all_probs), torch.cat(all_labels), all_filenames def write_per_sample_csv(probs_avg, labels, filenames, out_path, threshold=None): """Format expected by the organizer's cvpr26_organize_eval_metrics_and_predictions.py: columns = filename, label, prediction, logit_class_0..C-1, prob_class_0..C-1 If `threshold` is provided and the head is binary (num_classes==2), use prob_class_1 >= threshold for the prediction. Otherwise fall back to argmax. """ num_classes = probs_avg.shape[1] if threshold is not None and num_classes == 2: preds = (probs_avg[:, 1] >= float(threshold)).long() else: preds = probs_avg.argmax(1) # We didn't track raw logits across the ensemble; use log-prob as a stand-in # (the organizer's metrics never read these — only label/prediction/probs). log_probs = torch.log(probs_avg.clamp_min(1e-12)) cols = {"filename": filenames, "label": labels.numpy(), "prediction": preds.numpy()} for c in range(num_classes): cols[f"logit_class_{c}"] = log_probs[:, c].numpy() for c in range(num_classes): cols[f"prob_class_{c}"] = probs_avg[:, c].numpy() df = pd.DataFrame(cols) os.makedirs(os.path.dirname(out_path), exist_ok=True) df.to_csv(out_path, index=False) return df def main(): ap = argparse.ArgumentParser() ap.add_argument("--embeds_root", required=True, help="Root with {target}/embeddings/ subdirs") ap.add_argument("--labels_root", required=True, help="Dir with {target}.csv label files") ap.add_argument("--results_root", required=True, help="Dir with {target}/ subdirs containing .pth ckpts (output of run_EAO_improved.py)") ap.add_argument("--split", default="val", choices=["train", "val", "test"]) ap.add_argument("--out_zip", default=None, help="Where to write the final prediction.zip (default: results_root/prediction.zip)") ap.add_argument("--batch_size", type=int, default=64) ap.add_argument("--num_workers", type=int, default=2) ap.add_argument("--targets", nargs="*", default=None, help="Subset to predict (default: all subdirs with checkpoints)") ap.add_argument("--top_k_ckpts", type=int, default=0, help="If >0, only use top-K checkpoints per target by filename score") args = ap.parse_args() device = "cuda" if torch.cuda.is_available() else "cpu" targets = args.targets or discover_target_dirs(args.results_root) if not targets: raise SystemExit(f"No target subdirs with .pth found in {args.results_root}") aggregate_dfs = [] for target in targets: ck_dir = os.path.join(args.results_root, target) ckpts = sorted([f for f in os.listdir(ck_dir) if f.endswith(".pth")]) if not ckpts: print(f"[skip] {target}: no checkpoints") continue if args.top_k_ckpts > 0: # Score from filename: best_*acc{score}_*.pth def score_of(fn): for tag in ("balanced_acc", "auroc"): if tag in fn: try: return float(fn.split(tag)[1].split("_")[0]) except Exception: pass return -1.0 ckpts = sorted(ckpts, key=score_of, reverse=True)[: args.top_k_ckpts] embeds_dir = os.path.join(args.embeds_root, target, "embeddings") labels_csv = os.path.join(args.labels_root, target + ".csv") if not os.path.isdir(embeds_dir): print(f"[skip] {target}: missing {embeds_dir}") continue if not os.path.exists(labels_csv): print(f"[skip] {target}: missing {labels_csv}") continue df = pd.read_csv(labels_csv) # Only the target column; if the CSV uses a slightly different name, infer it. if target not in df.columns: cand = [c for c in df.columns if c not in ("case_id", "split")] if len(cand) != 1: raise RuntimeError(f"Cannot infer target col for {target}: {df.columns.tolist()}") target_col = cand[0] else: target_col = target ds = SpatialFeaturesDataset(embeds_dir, labels_csv, args.split, target_col) if len(ds) == 0: print(f"[skip] {target}: empty {args.split} split (no .h5 files matched)") continue loader = DataLoader(ds, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) # Average probs across all selected checkpoints probs_sum = None labels_keep, filenames_keep = None, None for ck in ckpts: head, hp = load_head(os.path.join(ck_dir, ck), device) probs, labels, filenames = predict_one_head(head, loader, device) if probs_sum is None: probs_sum = probs labels_keep, filenames_keep = labels, filenames else: probs_sum = probs_sum + probs probs_avg = probs_sum / len(ckpts) thr = THRESHOLDS.get(target, 0.5) out_csv = os.path.join(ck_dir, f"{args.split}_per_sample_predictions.csv") df_out = write_per_sample_csv(probs_avg, labels_keep, filenames_keep, out_csv, threshold=thr) df_out["disease_name"] = target # Quick val metric for reporting from sklearn.metrics import balanced_accuracy_score, roc_auc_score try: bal = balanced_accuracy_score(df_out["label"], df_out["prediction"]) except Exception: bal = float("nan") try: auroc = roc_auc_score(df_out["label"], df_out["prob_class_1"]) except Exception: auroc = float("nan") print(f"[{target}] ckpts={len(ckpts)} n={len(df_out)} bal_acc={bal:.4f} auroc={auroc:.4f} thr={thr:.4f}") aggregate_dfs.append(df_out) if not aggregate_dfs: raise SystemExit("No predictions written.") df_all = pd.concat(aggregate_dfs, ignore_index=True) # Write aggregated predictions.csv + zip it pred_csv = os.path.join(args.results_root, "predictions.csv") df_all.to_csv(pred_csv, index=False) out_zip = args.out_zip or os.path.join(args.results_root, "prediction.zip") with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf: zf.write(pred_csv, arcname="predictions.csv") print(f"\nWrote {pred_csv} ({len(df_all)} rows, {df_all['disease_name'].nunique()} diseases)") print(f"Wrote {out_zip}") if __name__ == "__main__": main()