procodec commited on
Commit
1a04429
·
verified ·
1 Parent(s): 4f980e9

Upload predict_eao_ensemble.py

Browse files
Files changed (1) hide show
  1. predict_eao_ensemble.py +248 -71
predict_eao_ensemble.py CHANGED
@@ -1,18 +1,41 @@
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
 
@@ -27,10 +50,8 @@ 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,
@@ -51,12 +72,79 @@ THRESHOLDS = {
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
@@ -65,6 +153,9 @@ class SpatialFeaturesDataset(Dataset):
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)
@@ -89,17 +180,32 @@ def discover_target_dirs(results_root):
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")
@@ -110,22 +216,21 @@ def parse_head_hparams(ckpt):
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()
@@ -145,65 +250,116 @@ def predict_one_head(head, loader, device):
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:
@@ -224,26 +380,34 @@ def main():
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
@@ -251,32 +415,45 @@ def main():
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)")
 
1
  """
2
+ Ensemble inference for Team Aviral (CVPR 2026 3D CT FM challenge, Task 2 EAO, vision-only).
3
+
4
+ Per disease target, this script:
5
+ 1. loads this team's checkpoints in the target's checkpoint dir (best_auroc*, best_balanced_acc*
6
+ and swa_* files with a _seed tag; any other .pth file in the dir is ignored and listed),
7
+ 2. runs each head on the {split} embeddings and averages the softmax probabilities,
8
+ 3. applies the per-disease decision threshold below (fitted on the validation split only),
9
+ 4. writes {split}_per_sample_predictions.csv and {split}_metrics.csv into the checkpoint dir,
10
+ with the same columns as the organizer's cvpr26_inference_EAO.py.
11
+ Only torch, numpy, pandas and h5py are needed (no scikit-learn).
12
+
13
+ How the threshold reaches every output column
14
+ The organizer's evaluation takes argmax over the logit_class_* columns; other scorers may read the
15
+ prediction or prob_class_* columns. For a binary target with threshold t, and m = logit(p1) - logit(t):
16
+ prediction = 1 if p1 >= t else 0
17
+ logit_class_0/1 = -m'/2, +m'/2
18
+ prob_class_0/1 = sigmoid(-m'), sigmoid(m') (= softmax of the two logits)
19
+ where m' = m + 1e-6 if p1 >= t and m' = m - 1e-6 otherwise, so m' is never 0. Hence
20
+ prediction == argmax(logits) == argmax(probs) for every case. This equals shifting the classifier
21
+ bias by -logit(t). m' is a strictly increasing function of p1, so the AUROC is exactly the AUROC of
22
+ the raw ensemble probability (checked and printed for every target). With t = 0.5 the probabilities
23
+ are the raw ones (up to the 1e-6 step).
24
+
25
+ Usage
26
+ organizer style, one target per call (same arguments as cvpr26_inference_EAO.py):
27
+ python predict_eao_ensemble.py --embeds_root R --labels_root L --target T --split test --ckpt_dir D \
28
+ [--query_num 2 --num_heads 4 --num_layers 2 --dropout 0.0 --ffn_mult 1 --batch_size 256 --num_workers 4]
29
+ all targets at once (also writes predictions.csv and prediction.zip):
30
+ python predict_eao_ensemble.py --embeds_root R --labels_root L --results_root checkpoints --split test
31
+
32
+ The thresholds are built in, so no further step is needed. threshold_optimize_v2.py must NOT be run
33
+ on test predictions: it fits thresholds on whatever labels it is given.
34
  """
35
  import argparse
36
+ import math
37
  import os
38
+ import re
39
  import sys
40
  import zipfile
41
 
 
50
  sys.path.insert(0, os.path.join(ROOT, "starter"))
51
  from models.attention_pooling_multilayers import MultiLayersCrossAttentionPooling # noqa: E402
52
 
53
+ # Per-disease decision thresholds, derived from val labels on the v4 multi-seed ensemble
54
+ # (threshold_optimize_v2 unique-prob sweep, rule p1 >= t). A disease not listed here falls back to 0.5.
 
 
55
  THRESHOLDS = {
56
  "hydronephrosis": 0.7685199,
57
  "lymphadenopathy": 0.5737428,
 
72
  "ascites": 0.5023216,
73
  }
74
 
75
+ # Other names a dataset may use for the same disease (e.g. external test sets). Values are THRESHOLDS keys.
76
+ ALIASES = {
77
+ "kidney_cyst": "renal_cyst", "kidney_cysts": "renal_cyst", "renal_cysts": "renal_cyst",
78
+ "liver_tumor": "liver_lesion", "liver_tumour": "liver_lesion", "liver_tumors": "liver_lesion",
79
+ "liver_lesions": "liver_lesion",
80
+ "liver_calcification": "liver_calcifications",
81
+ "kidney_stones": "kidney_stone", "renal_stone": "kidney_stone", "renal_stones": "kidney_stone",
82
+ "gallstones": "gallstone",
83
+ "liver_cysts": "liver_cyst",
84
+ }
85
+
86
+ # Targets for which threshold_optimize_v2.py flipped the probabilities (it does so when val AUROC < 0.5 and
87
+ # reports it in the 'inverted' column of --report_csv). Their thresholds were fitted on 1 - p1, so the same
88
+ # flip must be applied here. Empty = no target was flipped. Example: INVERTED = {"liver_cyst"}
89
+ INVERTED = set()
90
+
91
+ # This team's checkpoint file names, e.g. best_auroc0.6890_bal0.5714_head_lr_1e_04_ep4_seed50.pth,
92
+ # best_balanced_acc0.6143_head_lr_5e_04_ep7_seed42.pth, swa_balanced_acc0.6029_head_lr_5e_04_seed42.pth
93
+ TEAM_CKPT = re.compile(r"^(best_auroc|best_balanced_acc|swa_).*_seed\d+.*\.pth$")
94
+
95
+ STEP = 1e-6 # keeps the logit margin away from 0, so argmax always equals the thresholded decision
96
+
97
+
98
+ def _norm(name):
99
+ return re.sub(r"[^a-z0-9]+", "_", str(name).lower()).strip("_")
100
+
101
+
102
+ def _key_exact(name):
103
+ n = _norm(name)
104
+ if n in THRESHOLDS:
105
+ return n
106
+ return ALIASES.get(n)
107
+
108
+
109
+ def _key_fuzzy(name):
110
+ """Exact or alias match first, then a known name at the start or end of `name` (longest match wins)."""
111
+ k = _key_exact(name)
112
+ if k:
113
+ return k
114
+ n = _norm(name)
115
+ known = sorted(list(THRESHOLDS) + list(ALIASES), key=len, reverse=True)
116
+ for cand in known:
117
+ if n.endswith("_" + cand) or n.startswith(cand + "_"):
118
+ return cand if cand in THRESHOLDS else ALIASES[cand]
119
+ return None
120
+
121
+
122
+ def resolve_threshold(target, ck_dir, override=None):
123
+ """Return (threshold, key, how). The threshold belongs to the trained head, so the checkpoint dir name
124
+ is checked first (exact or alias match), then the --target name."""
125
+ if override is not None:
126
+ return float(override), None, "--threshold"
127
+ parts = [p for p in os.path.normpath(os.path.abspath(ck_dir)).split(os.sep) if p]
128
+ for p in reversed(parts):
129
+ k = _key_exact(p)
130
+ if k:
131
+ how = f"checkpoint dir '{p}'" + (f" -> {k}" if _norm(p) != k else "")
132
+ tk = _key_fuzzy(target)
133
+ if tk and tk != k:
134
+ print(f"[warn] target '{target}' looks like '{tk}' but the checkpoints are '{k}'; using '{k}'")
135
+ return THRESHOLDS[k], k, how
136
+ k = _key_fuzzy(target)
137
+ if k:
138
+ return THRESHOLDS[k], k, f"target '{target}'" + (f" -> {k}" if _norm(target) != k else "")
139
+ return 0.5, None, "no threshold found for this target, using 0.5"
140
+
141
 
142
  class SpatialFeaturesDataset(Dataset):
143
  def __init__(self, embeds_dir, csv_path, split, target_column):
144
  df = pd.read_csv(csv_path)
145
  split_df = df[df["split"] == split].copy()
146
  self.paths, self.label_mapping = [], {}
147
+ self.n_missing = 0
148
  for _, row in split_df.iterrows():
149
  case_id = str(row["case_id"])
150
  base = case_id.split(".nii.gz")[0] if ".nii.gz" in case_id else case_id
 
153
  if os.path.exists(path):
154
  self.paths.append(path)
155
  self.label_mapping[base] = int(row[target_column])
156
+ else:
157
+ self.n_missing += 1
158
+ self.n_expected = len(split_df)
159
 
160
  def __len__(self):
161
  return len(self.paths)
 
180
  return out
181
 
182
 
183
+ def list_team_ckpts(ck_dir, target):
184
+ allp = sorted(f for f in os.listdir(ck_dir) if f.endswith(".pth"))
185
+ team = [f for f in allp if TEAM_CKPT.match(f)]
186
+ if not team:
187
+ if allp:
188
+ print(f"[warn] {target}: no file matches this team's checkpoint names; using all {len(allp)} .pth files")
189
+ return allp
190
+ other = [f for f in allp if f not in team]
191
+ if other:
192
+ print(f"[info] {target}: ignoring {len(other)} .pth file(s) that are not this team's: {other}")
193
+ return team
194
+
195
+
196
+ def parse_head_hparams(ckpt, num_heads, dropout, ffn_mult):
197
  """The state dict keys look like `heads.head_lr_1e_03.<...>`. We rebuild
198
  a head with the same architecture as training (defaults match starter)."""
199
  sd = ckpt["state_dict"]
200
+ stripped, head_names = {}, set()
 
201
  for k, v in sd.items():
202
  if k.startswith("heads."):
203
  parts = k.split(".", 2)
204
  if len(parts) >= 3:
205
+ head_names.add(parts[1])
206
  stripped[parts[2]] = v
207
+ if len(head_names) != 1:
208
+ raise RuntimeError(f"Expected exactly one head in the checkpoint, found {sorted(head_names)}")
209
 
210
  cls_w = stripped.get("classifier.weight")
211
  cq = stripped.get("class_query")
 
216
  assert q_times_d == query_num * embed_dim, (
217
  f"Mismatch: classifier in_features={q_times_d} vs query_num*embed_dim={query_num*embed_dim}"
218
  )
 
219
  num_layers = 1 + max(
220
  (int(k.split(".")[1]) for k in stripped.keys() if k.startswith("layers.")),
221
  default=-1,
222
  )
223
  if num_layers < 1:
224
+ num_layers = 2
225
  return stripped, dict(
226
  embed_dim=embed_dim, query_num=query_num, num_classes=num_classes,
227
+ num_layers=num_layers, num_heads=num_heads, dropout=dropout, ffn_mult=ffn_mult,
228
  )
229
 
230
 
231
+ def load_head(ckpt_path, device, num_heads, dropout, ffn_mult):
232
  ckpt = torch.load(ckpt_path, map_location="cpu")
233
+ stripped, hp = parse_head_hparams(ckpt, num_heads, dropout, ffn_mult)
234
  head = MultiLayersCrossAttentionPooling(**hp)
235
  head.load_state_dict(stripped, strict=True)
236
  head.to(device).eval()
 
250
  return torch.cat(all_probs), torch.cat(all_labels), all_filenames
251
 
252
 
253
+ def threshold_outputs(probs_avg, threshold):
254
+ """Return (preds, logits, probs) as float64 tensors; see the module docstring.
255
+ preds = p1 >= t, compared in float32 exactly as threshold_optimize_v2.py did when fitting t."""
256
+ if probs_avg.shape[1] != 2:
257
+ p = probs_avg.double()
258
+ return p.argmax(1), torch.log(p.clamp_min(1e-300)), p
259
+ thr = 0.5 if threshold is None else float(threshold)
260
+ t = float(np.float32(thr)) # the float32 value t was read from
261
+ p1 = probs_avg[:, 1].float().double()
262
+ preds = (p1 >= t).long()
263
+ lo, hi = 1e-300, 1.0 - 2.0 ** -53 # only exact 0 and exact 1 are moved
264
+ p = p1.clamp(lo, hi)
265
+ tc = min(max(t, lo), hi)
266
+ m = (torch.log(p) - torch.log1p(-p)) - (math.log(tc) - math.log1p(-tc))
267
+ m = torch.where(preds == 1, m.clamp_min(0.0) + STEP, m.clamp_max(0.0) - STEP)
268
+ logits = torch.stack([-m / 2, m / 2], dim=1)
269
+ probs = torch.stack([torch.sigmoid(-m), torch.sigmoid(m)], dim=1)
270
+ return preds, logits, probs
271
 
272
+
273
+ def write_per_sample_csv(probs_avg, labels, filenames, out_path, threshold=None):
274
+ """Columns as in the organizer's cvpr26_inference_EAO.py:
275
+ filename, label, prediction, logit_class_0..C-1, prob_class_0..C-1"""
276
  num_classes = probs_avg.shape[1]
277
+ preds, logits, probs = threshold_outputs(probs_avg, threshold)
278
+ cols = {"filename": list(filenames), "label": labels.numpy(), "prediction": preds.numpy()}
 
 
 
 
 
 
279
  for c in range(num_classes):
280
+ cols[f"logit_class_{c}"] = logits[:, c].numpy()
281
  for c in range(num_classes):
282
+ cols[f"prob_class_{c}"] = probs[:, c].numpy()
283
  df = pd.DataFrame(cols)
284
  os.makedirs(os.path.dirname(out_path), exist_ok=True)
285
  df.to_csv(out_path, index=False)
286
  return df
287
 
288
 
289
+ def balanced_accuracy(y, yhat):
290
+ y, yhat = np.asarray(y), np.asarray(yhat)
291
+ return float(np.mean([np.mean(yhat[y == c] == c) for c in np.unique(y)]))
292
+
293
+
294
+ def auroc(y, s):
295
+ """Binary AUROC with average ranks for ties (same value as sklearn.metrics.roc_auc_score)."""
296
+ y = np.asarray(y).astype(int)
297
+ n1, n0 = int((y == 1).sum()), int((y == 0).sum())
298
+ if n1 == 0 or n0 == 0:
299
+ return float("nan")
300
+ r = pd.Series(np.asarray(s, dtype=np.float64)).rank(method="average").to_numpy()
301
+ return float((r[y == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0))
302
+
303
+
304
  def main():
305
  ap = argparse.ArgumentParser()
306
  ap.add_argument("--embeds_root", required=True,
307
  help="Root with {target}/embeddings/ subdirs")
308
  ap.add_argument("--labels_root", required=True,
309
  help="Dir with {target}.csv label files")
310
+ ap.add_argument("--results_root", default=None,
311
+ help="Dir with {target}/ subdirs containing .pth ckpts (all-targets mode)")
312
+ ap.add_argument("--target", default=None,
313
+ help="Single target (organizer style). Use with --ckpt_dir.")
314
+ ap.add_argument("--ckpt_dir", default=None,
315
+ help="Checkpoint dir for --target (default: results_root/target)")
316
  ap.add_argument("--split", default="val", choices=["train", "val", "test"])
317
+ ap.add_argument("--threshold", type=float, default=None,
318
+ help="Override the built-in threshold (single-target mode only)")
319
  ap.add_argument("--out_zip", default=None,
320
+ help="Where to write prediction.zip (all-targets mode default: results_root/prediction.zip; "
321
+ "single-target mode writes it only when this is given)")
322
  ap.add_argument("--batch_size", type=int, default=64)
323
  ap.add_argument("--num_workers", type=int, default=2)
324
  ap.add_argument("--targets", nargs="*", default=None,
325
  help="Subset to predict (default: all subdirs with checkpoints)")
326
  ap.add_argument("--top_k_ckpts", type=int, default=0,
327
  help="If >0, only use top-K checkpoints per target by filename score")
328
+ # accepted for compatibility with cvpr26_inference_EAO.py; query_num / num_layers are read from the checkpoint
329
+ ap.add_argument("--query_num", type=int, default=None)
330
+ ap.add_argument("--num_layers", type=int, default=None)
331
+ ap.add_argument("--num_heads", type=int, default=4)
332
+ ap.add_argument("--dropout", type=float, default=0.0)
333
+ ap.add_argument("--ffn_mult", type=int, default=1)
334
  args = ap.parse_args()
335
 
336
+ if args.target is None and args.results_root is None:
337
+ ap.error("provide --results_root (all targets) or --target with --ckpt_dir")
338
+ if args.target is not None and args.ckpt_dir is None and args.results_root is None:
339
+ ap.error("--target needs --ckpt_dir (or --results_root)")
340
+ if args.threshold is not None and args.target is None:
341
+ ap.error("--threshold can only be used with --target")
342
+
343
  device = "cuda" if torch.cuda.is_available() else "cpu"
344
+ single = args.target is not None
345
+ if single:
346
+ targets = [args.target]
347
+ else:
348
+ targets = args.targets or discover_target_dirs(args.results_root)
349
  if not targets:
350
  raise SystemExit(f"No target subdirs with .pth found in {args.results_root}")
351
 
352
  aggregate_dfs = []
353
  for target in targets:
354
+ ck_dir = args.ckpt_dir if (single and args.ckpt_dir) else os.path.join(args.results_root, target)
355
+ if not os.path.isdir(ck_dir):
356
+ print(f"[skip] {target}: checkpoint dir {ck_dir} does not exist")
357
+ continue
358
+ ckpts = list_team_ckpts(ck_dir, target)
359
  if not ckpts:
360
  print(f"[skip] {target}: no checkpoints")
361
  continue
362
  if args.top_k_ckpts > 0:
 
363
  def score_of(fn):
364
  for tag in ("balanced_acc", "auroc"):
365
  if tag in fn:
 
380
  continue
381
 
382
  df = pd.read_csv(labels_csv)
383
+ if target in df.columns:
384
+ target_col = target
385
+ else:
386
  cand = [c for c in df.columns if c not in ("case_id", "split")]
387
+ same = [c for c in cand if _key_fuzzy(c) is not None and _key_fuzzy(c) == _key_fuzzy(target)]
388
+ if len(cand) == 1:
389
+ target_col = cand[0]
390
+ elif len(same) == 1:
391
+ target_col = same[0]
392
+ else:
393
  raise RuntimeError(f"Cannot infer target col for {target}: {df.columns.tolist()}")
 
 
 
394
  ds = SpatialFeaturesDataset(embeds_dir, labels_csv, args.split, target_col)
395
+ if ds.n_missing:
396
+ print(f"[warn] {target}: {ds.n_missing} of {ds.n_expected} '{args.split}' cases have no embedding file and are skipped")
397
  if len(ds) == 0:
398
  print(f"[skip] {target}: empty {args.split} split (no .h5 files matched)")
399
  continue
400
  loader = DataLoader(ds, batch_size=args.batch_size, shuffle=False,
401
+ num_workers=args.num_workers, pin_memory=torch.cuda.is_available())
402
 
 
403
  probs_sum = None
404
  labels_keep, filenames_keep = None, None
405
  for ck in ckpts:
406
+ head, hp = load_head(os.path.join(ck_dir, ck), device, args.num_heads, args.dropout, args.ffn_mult)
407
+ if args.query_num is not None and args.query_num != hp["query_num"]:
408
+ print(f"[warn] {target}: --query_num={args.query_num} but checkpoint has {hp['query_num']}; using checkpoint")
409
+ if args.num_layers is not None and args.num_layers != hp["num_layers"]:
410
+ print(f"[warn] {target}: --num_layers={args.num_layers} but checkpoint has {hp['num_layers']}; using checkpoint")
411
  probs, labels, filenames = predict_one_head(head, loader, device)
412
  if probs_sum is None:
413
  probs_sum = probs
 
415
  else:
416
  probs_sum = probs_sum + probs
417
  probs_avg = probs_sum / len(ckpts)
418
+ key = _key_fuzzy(target)
419
+ if (target in INVERTED or (key is not None and key in INVERTED)) and probs_avg.shape[1] == 2:
420
+ probs_avg = probs_avg.flip(1) # p1 -> 1 - p1, as in threshold_optimize_v2.py
421
 
422
+ thr, _, how = resolve_threshold(target, ck_dir, args.threshold if single else None)
423
+ if how.startswith("no threshold"):
424
+ print(f"[warn] {target}: {how}")
425
  out_csv = os.path.join(ck_dir, f"{args.split}_per_sample_predictions.csv")
426
  df_out = write_per_sample_csv(probs_avg, labels_keep, filenames_keep, out_csv, threshold=thr)
427
+
428
+ # self-checks: every column carries the same decision, and the AUROC is the raw ensemble AUROC
429
+ lg = df_out[[c for c in df_out.columns if c.startswith("logit_class_")]].to_numpy()
430
+ pr = df_out[[c for c in df_out.columns if c.startswith("prob_class_")]].to_numpy()
431
+ pred = df_out["prediction"].to_numpy()
432
+ if not (np.array_equal(lg.argmax(1), pred) and np.array_equal(pr.argmax(1), pred)):
433
+ raise RuntimeError(f"{target}: prediction, argmax(logits) and argmax(probs) disagree")
434
+ y = df_out["label"].to_numpy()
435
+ bal = balanced_accuracy(y, pred)
436
+ acc = float(np.mean(pred == y))
437
+ auc = auroc(y, df_out["prob_class_1"]) if pr.shape[1] == 2 else float("nan")
438
+ if pr.shape[1] == 2:
439
+ auc_raw = auroc(y, probs_avg[:, 1].double().numpy())
440
+ if not (np.isnan(auc) and np.isnan(auc_raw)) and abs(auc - auc_raw) > 1e-12:
441
+ print(f"[warn] {target}: AUROC changed by the threshold transform ({auc_raw:.6f} -> {auc:.6f})")
442
+ pd.DataFrame([{"acc": acc, "auroc": auc, "balanced_acc": bal}]).round(4).to_csv(
443
+ os.path.join(ck_dir, f"{args.split}_metrics.csv"), index=False)
444
+ print(f"[{target}] ckpts={len(ckpts)} n={len(df_out)} bal_acc={bal:.4f} auroc={auc:.4f} "
445
+ f"thr={thr:.4f} ({how})")
446
  df_out["disease_name"] = target
 
 
 
 
 
 
 
 
 
 
 
447
  aggregate_dfs.append(df_out)
448
 
449
  if not aggregate_dfs:
450
  raise SystemExit("No predictions written.")
451
+ if single and args.out_zip is None:
452
+ return
453
  df_all = pd.concat(aggregate_dfs, ignore_index=True)
 
 
 
 
454
  out_zip = args.out_zip or os.path.join(args.results_root, "prediction.zip")
455
+ pred_csv = os.path.join(os.path.dirname(os.path.abspath(out_zip)), "predictions.csv")
456
+ df_all.to_csv(pred_csv, index=False)
457
  with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:
458
  zf.write(pred_csv, arcname="predictions.csv")
459
  print(f"\nWrote {pred_csv} ({len(df_all)} rows, {df_all['disease_name'].nunique()} diseases)")