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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Inference + Codabench prediction.zip generator.
|
| 3 |
+
|
| 4 |
+
For each disease target:
|
| 5 |
+
- Load all best_*.pth and swa_*.pth checkpoints in the per-target results dir
|
| 6 |
+
- Run each on the {split} embeddings of that target
|
| 7 |
+
- Average softmax probabilities across checkpoints (multi-seed/multi-LR/SWA ensemble)
|
| 8 |
+
- Write {split}_per_sample_predictions.csv in the format the organizer's
|
| 9 |
+
cvpr26_organize_eval_metrics_and_predictions.py expects
|
| 10 |
+
|
| 11 |
+
Then concatenate all targets into predictions.csv and zip → prediction.zip for
|
| 12 |
+
direct Codabench submission.
|
| 13 |
+
"""
|
| 14 |
+
import argparse
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import zipfile
|
| 18 |
+
|
| 19 |
+
import h5py
|
| 20 |
+
import numpy as np
|
| 21 |
+
import pandas as pd
|
| 22 |
+
import torch
|
| 23 |
+
from torch.utils.data import DataLoader, Dataset
|
| 24 |
+
|
| 25 |
+
THIS = os.path.dirname(os.path.abspath(__file__))
|
| 26 |
+
ROOT = os.path.abspath(os.path.join(THIS, ".."))
|
| 27 |
+
sys.path.insert(0, os.path.join(ROOT, "starter"))
|
| 28 |
+
from models.attention_pooling_multilayers import MultiLayersCrossAttentionPooling # noqa: E402
|
| 29 |
+
|
| 30 |
+
# Per-disease decision thresholds, derived from val labels on the v4 multi-seed
|
| 31 |
+
# ensemble (threshold_optimize_v2 unique-prob sweep). Baked in so this single
|
| 32 |
+
# script reproduces the 0.7086 BalAcc result without needing a follow-up step.
|
| 33 |
+
# Disease not in this dict falls back to 0.5.
|
| 34 |
+
THRESHOLDS = {
|
| 35 |
+
"hydronephrosis": 0.7685199,
|
| 36 |
+
"lymphadenopathy": 0.5737428,
|
| 37 |
+
"kidney_stone": 0.80407256,
|
| 38 |
+
"covid": 0.6222638,
|
| 39 |
+
"gallstone": 0.7481811,
|
| 40 |
+
"liver_calcifications": 0.64198047,
|
| 41 |
+
"colorectal_cancer": 0.35786006,
|
| 42 |
+
"liver_lesion": 0.79084086,
|
| 43 |
+
"renal_cyst": 0.10136525,
|
| 44 |
+
"liver_cyst": 0.11666061,
|
| 45 |
+
"adrenal_hyperplasia": 0.5463961,
|
| 46 |
+
"splenomegaly": 0.37268373,
|
| 47 |
+
"lung_nodule_malignancy": 0.44977823,
|
| 48 |
+
"cholecystitis": 0.52176595,
|
| 49 |
+
"atherosclerosis": 0.5064166,
|
| 50 |
+
"fatty_liver": 0.48598397,
|
| 51 |
+
"ascites": 0.5023216,
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class SpatialFeaturesDataset(Dataset):
|
| 56 |
+
def __init__(self, embeds_dir, csv_path, split, target_column):
|
| 57 |
+
df = pd.read_csv(csv_path)
|
| 58 |
+
split_df = df[df["split"] == split].copy()
|
| 59 |
+
self.paths, self.label_mapping = [], {}
|
| 60 |
+
for _, row in split_df.iterrows():
|
| 61 |
+
case_id = str(row["case_id"])
|
| 62 |
+
base = case_id.split(".nii.gz")[0] if ".nii.gz" in case_id else case_id
|
| 63 |
+
base = base.replace(".h5", "")
|
| 64 |
+
path = os.path.join(embeds_dir, base + ".h5")
|
| 65 |
+
if os.path.exists(path):
|
| 66 |
+
self.paths.append(path)
|
| 67 |
+
self.label_mapping[base] = int(row[target_column])
|
| 68 |
+
|
| 69 |
+
def __len__(self):
|
| 70 |
+
return len(self.paths)
|
| 71 |
+
|
| 72 |
+
def __getitem__(self, i):
|
| 73 |
+
path = self.paths[i]
|
| 74 |
+
base = os.path.basename(path).replace(".h5", "")
|
| 75 |
+
with h5py.File(path, "r") as hf:
|
| 76 |
+
x = torch.tensor(hf["y_hat"][:]).float()
|
| 77 |
+
return x, torch.tensor(self.label_mapping[base]).long(), base
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def discover_target_dirs(results_root):
|
| 81 |
+
"""Find target subdirs that contain at least one .pth checkpoint."""
|
| 82 |
+
out = []
|
| 83 |
+
for name in sorted(os.listdir(results_root)):
|
| 84 |
+
d = os.path.join(results_root, name)
|
| 85 |
+
if not os.path.isdir(d):
|
| 86 |
+
continue
|
| 87 |
+
if any(f.endswith(".pth") for f in os.listdir(d)):
|
| 88 |
+
out.append(name)
|
| 89 |
+
return out
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def parse_head_hparams(ckpt):
|
| 93 |
+
"""The state dict keys look like `heads.head_lr_1e_03.<...>`. We rebuild
|
| 94 |
+
a head with the same architecture as training (defaults match starter)."""
|
| 95 |
+
sd = ckpt["state_dict"]
|
| 96 |
+
# Strip "heads.<head_name>." prefix and detect dimensions
|
| 97 |
+
stripped = {}
|
| 98 |
+
for k, v in sd.items():
|
| 99 |
+
if k.startswith("heads."):
|
| 100 |
+
parts = k.split(".", 2)
|
| 101 |
+
if len(parts) >= 3:
|
| 102 |
+
stripped[parts[2]] = v
|
| 103 |
+
|
| 104 |
+
cls_w = stripped.get("classifier.weight")
|
| 105 |
+
cq = stripped.get("class_query")
|
| 106 |
+
if cls_w is None or cq is None:
|
| 107 |
+
raise RuntimeError(f"Checkpoint missing classifier/class_query: keys={list(stripped.keys())[:5]}")
|
| 108 |
+
num_classes, q_times_d = cls_w.shape
|
| 109 |
+
query_num, embed_dim = cq.shape
|
| 110 |
+
assert q_times_d == query_num * embed_dim, (
|
| 111 |
+
f"Mismatch: classifier in_features={q_times_d} vs query_num*embed_dim={query_num*embed_dim}"
|
| 112 |
+
)
|
| 113 |
+
# num_layers = number of cross-attention layers we can find in the keys
|
| 114 |
+
num_layers = 1 + max(
|
| 115 |
+
(int(k.split(".")[1]) for k in stripped.keys() if k.startswith("layers.")),
|
| 116 |
+
default=-1,
|
| 117 |
+
)
|
| 118 |
+
if num_layers < 1:
|
| 119 |
+
num_layers = 2 # fall back to starter default
|
| 120 |
+
return stripped, dict(
|
| 121 |
+
embed_dim=embed_dim, query_num=query_num, num_classes=num_classes,
|
| 122 |
+
num_layers=num_layers, num_heads=4, dropout=0.0, ffn_mult=1,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def load_head(ckpt_path, device):
|
| 127 |
+
ckpt = torch.load(ckpt_path, map_location="cpu")
|
| 128 |
+
stripped, hp = parse_head_hparams(ckpt)
|
| 129 |
+
head = MultiLayersCrossAttentionPooling(**hp)
|
| 130 |
+
head.load_state_dict(stripped, strict=True)
|
| 131 |
+
head.to(device).eval()
|
| 132 |
+
return head, hp
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@torch.no_grad()
|
| 136 |
+
def predict_one_head(head, loader, device):
|
| 137 |
+
all_probs, all_labels, all_filenames = [], [], []
|
| 138 |
+
for xb, yb, fns in loader:
|
| 139 |
+
xb = xb.to(device)
|
| 140 |
+
logits = head(xb)
|
| 141 |
+
probs = torch.softmax(logits, dim=1).cpu()
|
| 142 |
+
all_probs.append(probs)
|
| 143 |
+
all_labels.append(yb)
|
| 144 |
+
all_filenames.extend(list(fns))
|
| 145 |
+
return torch.cat(all_probs), torch.cat(all_labels), all_filenames
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def write_per_sample_csv(probs_avg, labels, filenames, out_path, threshold=None):
|
| 149 |
+
"""Format expected by the organizer's cvpr26_organize_eval_metrics_and_predictions.py:
|
| 150 |
+
columns = filename, label, prediction, logit_class_0..C-1, prob_class_0..C-1
|
| 151 |
+
|
| 152 |
+
If `threshold` is provided and the head is binary (num_classes==2), use
|
| 153 |
+
prob_class_1 >= threshold for the prediction. Otherwise fall back to argmax.
|
| 154 |
+
"""
|
| 155 |
+
num_classes = probs_avg.shape[1]
|
| 156 |
+
if threshold is not None and num_classes == 2:
|
| 157 |
+
preds = (probs_avg[:, 1] >= float(threshold)).long()
|
| 158 |
+
else:
|
| 159 |
+
preds = probs_avg.argmax(1)
|
| 160 |
+
# We didn't track raw logits across the ensemble; use log-prob as a stand-in
|
| 161 |
+
# (the organizer's metrics never read these — only label/prediction/probs).
|
| 162 |
+
log_probs = torch.log(probs_avg.clamp_min(1e-12))
|
| 163 |
+
cols = {"filename": filenames, "label": labels.numpy(), "prediction": preds.numpy()}
|
| 164 |
+
for c in range(num_classes):
|
| 165 |
+
cols[f"logit_class_{c}"] = log_probs[:, c].numpy()
|
| 166 |
+
for c in range(num_classes):
|
| 167 |
+
cols[f"prob_class_{c}"] = probs_avg[:, c].numpy()
|
| 168 |
+
df = pd.DataFrame(cols)
|
| 169 |
+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
| 170 |
+
df.to_csv(out_path, index=False)
|
| 171 |
+
return df
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def main():
|
| 175 |
+
ap = argparse.ArgumentParser()
|
| 176 |
+
ap.add_argument("--embeds_root", required=True,
|
| 177 |
+
help="Root with {target}/embeddings/ subdirs")
|
| 178 |
+
ap.add_argument("--labels_root", required=True,
|
| 179 |
+
help="Dir with {target}.csv label files")
|
| 180 |
+
ap.add_argument("--results_root", required=True,
|
| 181 |
+
help="Dir with {target}/ subdirs containing .pth ckpts (output of run_EAO_improved.py)")
|
| 182 |
+
ap.add_argument("--split", default="val", choices=["train", "val", "test"])
|
| 183 |
+
ap.add_argument("--out_zip", default=None,
|
| 184 |
+
help="Where to write the final prediction.zip (default: results_root/prediction.zip)")
|
| 185 |
+
ap.add_argument("--batch_size", type=int, default=64)
|
| 186 |
+
ap.add_argument("--num_workers", type=int, default=2)
|
| 187 |
+
ap.add_argument("--targets", nargs="*", default=None,
|
| 188 |
+
help="Subset to predict (default: all subdirs with checkpoints)")
|
| 189 |
+
ap.add_argument("--top_k_ckpts", type=int, default=0,
|
| 190 |
+
help="If >0, only use top-K checkpoints per target by filename score")
|
| 191 |
+
args = ap.parse_args()
|
| 192 |
+
|
| 193 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 194 |
+
targets = args.targets or discover_target_dirs(args.results_root)
|
| 195 |
+
if not targets:
|
| 196 |
+
raise SystemExit(f"No target subdirs with .pth found in {args.results_root}")
|
| 197 |
+
|
| 198 |
+
aggregate_dfs = []
|
| 199 |
+
for target in targets:
|
| 200 |
+
ck_dir = os.path.join(args.results_root, target)
|
| 201 |
+
ckpts = sorted([f for f in os.listdir(ck_dir) if f.endswith(".pth")])
|
| 202 |
+
if not ckpts:
|
| 203 |
+
print(f"[skip] {target}: no checkpoints")
|
| 204 |
+
continue
|
| 205 |
+
if args.top_k_ckpts > 0:
|
| 206 |
+
# Score from filename: best_*acc{score}_*.pth
|
| 207 |
+
def score_of(fn):
|
| 208 |
+
for tag in ("balanced_acc", "auroc"):
|
| 209 |
+
if tag in fn:
|
| 210 |
+
try:
|
| 211 |
+
return float(fn.split(tag)[1].split("_")[0])
|
| 212 |
+
except Exception:
|
| 213 |
+
pass
|
| 214 |
+
return -1.0
|
| 215 |
+
ckpts = sorted(ckpts, key=score_of, reverse=True)[: args.top_k_ckpts]
|
| 216 |
+
|
| 217 |
+
embeds_dir = os.path.join(args.embeds_root, target, "embeddings")
|
| 218 |
+
labels_csv = os.path.join(args.labels_root, target + ".csv")
|
| 219 |
+
if not os.path.isdir(embeds_dir):
|
| 220 |
+
print(f"[skip] {target}: missing {embeds_dir}")
|
| 221 |
+
continue
|
| 222 |
+
if not os.path.exists(labels_csv):
|
| 223 |
+
print(f"[skip] {target}: missing {labels_csv}")
|
| 224 |
+
continue
|
| 225 |
+
|
| 226 |
+
df = pd.read_csv(labels_csv)
|
| 227 |
+
# Only the target column; if the CSV uses a slightly different name, infer it.
|
| 228 |
+
if target not in df.columns:
|
| 229 |
+
cand = [c for c in df.columns if c not in ("case_id", "split")]
|
| 230 |
+
if len(cand) != 1:
|
| 231 |
+
raise RuntimeError(f"Cannot infer target col for {target}: {df.columns.tolist()}")
|
| 232 |
+
target_col = cand[0]
|
| 233 |
+
else:
|
| 234 |
+
target_col = target
|
| 235 |
+
ds = SpatialFeaturesDataset(embeds_dir, labels_csv, args.split, target_col)
|
| 236 |
+
if len(ds) == 0:
|
| 237 |
+
print(f"[skip] {target}: empty {args.split} split (no .h5 files matched)")
|
| 238 |
+
continue
|
| 239 |
+
loader = DataLoader(ds, batch_size=args.batch_size, shuffle=False,
|
| 240 |
+
num_workers=args.num_workers, pin_memory=True)
|
| 241 |
+
|
| 242 |
+
# Average probs across all selected checkpoints
|
| 243 |
+
probs_sum = None
|
| 244 |
+
labels_keep, filenames_keep = None, None
|
| 245 |
+
for ck in ckpts:
|
| 246 |
+
head, hp = load_head(os.path.join(ck_dir, ck), device)
|
| 247 |
+
probs, labels, filenames = predict_one_head(head, loader, device)
|
| 248 |
+
if probs_sum is None:
|
| 249 |
+
probs_sum = probs
|
| 250 |
+
labels_keep, filenames_keep = labels, filenames
|
| 251 |
+
else:
|
| 252 |
+
probs_sum = probs_sum + probs
|
| 253 |
+
probs_avg = probs_sum / len(ckpts)
|
| 254 |
+
|
| 255 |
+
thr = THRESHOLDS.get(target, 0.5)
|
| 256 |
+
out_csv = os.path.join(ck_dir, f"{args.split}_per_sample_predictions.csv")
|
| 257 |
+
df_out = write_per_sample_csv(probs_avg, labels_keep, filenames_keep, out_csv, threshold=thr)
|
| 258 |
+
df_out["disease_name"] = target
|
| 259 |
+
# Quick val metric for reporting
|
| 260 |
+
from sklearn.metrics import balanced_accuracy_score, roc_auc_score
|
| 261 |
+
try:
|
| 262 |
+
bal = balanced_accuracy_score(df_out["label"], df_out["prediction"])
|
| 263 |
+
except Exception:
|
| 264 |
+
bal = float("nan")
|
| 265 |
+
try:
|
| 266 |
+
auroc = roc_auc_score(df_out["label"], df_out["prob_class_1"])
|
| 267 |
+
except Exception:
|
| 268 |
+
auroc = float("nan")
|
| 269 |
+
print(f"[{target}] ckpts={len(ckpts)} n={len(df_out)} bal_acc={bal:.4f} auroc={auroc:.4f} thr={thr:.4f}")
|
| 270 |
+
aggregate_dfs.append(df_out)
|
| 271 |
+
|
| 272 |
+
if not aggregate_dfs:
|
| 273 |
+
raise SystemExit("No predictions written.")
|
| 274 |
+
df_all = pd.concat(aggregate_dfs, ignore_index=True)
|
| 275 |
+
|
| 276 |
+
# Write aggregated predictions.csv + zip it
|
| 277 |
+
pred_csv = os.path.join(args.results_root, "predictions.csv")
|
| 278 |
+
df_all.to_csv(pred_csv, index=False)
|
| 279 |
+
out_zip = args.out_zip or os.path.join(args.results_root, "prediction.zip")
|
| 280 |
+
with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 281 |
+
zf.write(pred_csv, arcname="predictions.csv")
|
| 282 |
+
print(f"\nWrote {pred_csv} ({len(df_all)} rows, {df_all['disease_name'].nunique()} diseases)")
|
| 283 |
+
print(f"Wrote {out_zip}")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
if __name__ == "__main__":
|
| 287 |
+
main()
|