#!/usr/bin/env python3 """Priority 1: Re-evaluate all 5 verified Aug-12 checkpoints at fixed t=0.50 on Kermany test (N=624).""" from __future__ import annotations import argparse import hashlib import json import sys from pathlib import Path import numpy as np import pandas as pd import thop import torch import torch.nn.functional as F from torch.utils.data import DataLoader REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO_ROOT)) from src.data.dataset import ChestXrayDataset, get_transforms, load_kermany_dataframes # noqa: E402 from src.models.biohcl_sssm import BioHCLSSSM, build_baseline_resnet50, strip_thop_keys # noqa: E402 from src.utils.metrics import ( # noqa: E402 bootstrap_confidence_intervals, compute_classification_metrics, exact_mcnemar_test, ) DEFAULT_PROBE_ROOT = Path( r"C:\Users\udayb\.gemini\antigravity-cli\brain\7bd11986-ba6d-433b-813b-73ac445cbd8d\scratch_hf_biohcl_all\weights_probe" ) def sha256_file(path: Path) -> str: h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(65536), b""): h.update(chunk) return h.hexdigest() @torch.no_grad() def predict_loader(model: torch.nn.Module, loader: DataLoader, device: torch.device, is_biohcl: bool) -> tuple[np.ndarray, np.ndarray]: model.eval() probs_all, labels_all = [], [] for imgs, labels in loader: imgs = imgs.to(device, non_blocking=True) out = model(imgs) logits = out[0] if is_biohcl else out probs = F.softmax(logits.float(), dim=1)[:, 1] probs_all.append(probs.cpu().numpy()) labels_all.append(labels.numpy()) return np.concatenate(labels_all), np.concatenate(probs_all) def measure_complexity(model_builder) -> tuple[int, int, float]: """Measure exact parameter count and MACs (`thop.profile`) on a throwaway CPU copy.""" m = model_builder().cpu().eval() params = sum(p.numel() for p in m.parameters()) dummy = torch.randn(1, 3, 224, 224) macs, _ = thop.profile(m, inputs=(dummy,), verbose=False) del m return int(params), int(macs), float(macs / 1e9) def main(): parser = argparse.ArgumentParser() parser.add_argument("--data-dir", type=str, default=None) parser.add_argument("--probe-dir", type=str, default=str(DEFAULT_PROBE_ROOT)) parser.add_argument("--batch-size", type=int, default=32) args = parser.parse_args() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") df_trainval, df_test, meta = load_kermany_dataframes(args.data_dir) print(f"Dataset loaded: {meta}") _, eval_transform = get_transforms() test_loader = DataLoader( ChestXrayDataset(df_test, transform=eval_transform), batch_size=args.batch_size, shuffle=False, num_workers=0, pin_memory=device.type == "cuda", ) probe = Path(args.probe_dir) ckpt_dest = REPO_ROOT / "checkpoints" / "aug12_verified" ckpt_dest.mkdir(parents=True, exist_ok=True) res_dir = REPO_ROOT / "results" res_dir.mkdir(parents=True, exist_ok=True) specs = [ { "name": "Student_BioHCL_SSSM", "role": "core_Aug12", "src": probe / "chest-xray-pneumonia-sssm" / "best_student.pt", "dest_name": "biohcl_sssm_student_256d.pt", "is_biohcl": True, "builder": lambda: BioHCLSSSM( num_classes=2, embed_dim=256, chain_mode="dual", num_sssm_blocks=2, use_bio_prior=True, use_positional=True, pretrained_backbone=False, ), }, { "name": "Baseline_ResNet50", "role": "core_Aug12", "src": probe / "chest-xray-pneumonia-sssm" / "best_baseline.pt", "dest_name": "baseline_resnet50.pt", "is_biohcl": False, "builder": lambda: build_baseline_resnet50(num_classes=2, pretrained=False), }, { "name": "Ablation_SingleCNN", "role": "ablation_Aug12", "src": probe / "chest-xray-pneumonia-sssm-ablation-single_cnn" / "best_student_single_cnn.pt", "dest_name": "ablation_single_cnn_256d.pt", "is_biohcl": True, "builder": lambda: BioHCLSSSM( num_classes=2, embed_dim=256, chain_mode="single_cnn", num_sssm_blocks=2, use_bio_prior=True, use_positional=True, pretrained_backbone=False, ), }, { "name": "Ablation_NoBioPrior", "role": "ablation_Aug12", "src": probe / "chest-xray-pneumonia-sssm-ablation-bioprior" / "best_student_bioprior.pt", "dest_name": "ablation_no_bioprior_256d.pt", "is_biohcl": True, "builder": lambda: BioHCLSSSM( num_classes=2, embed_dim=256, chain_mode="dual", num_sssm_blocks=2, use_bio_prior=False, use_positional=True, pretrained_backbone=False, ), }, { "name": "Ablation_NoPositional", "role": "ablation_Aug12", "src": probe / "chest-xray-pneumonia-sssm-ablation-no_positional" / "best_student_no_positional.pt", "dest_name": "ablation_no_positional_256d.pt", "is_biohcl": True, "builder": lambda: BioHCLSSSM( num_classes=2, embed_dim=256, chain_mode="dual", num_sssm_blocks=2, use_bio_prior=True, use_positional=False, pretrained_backbone=False, ), }, ] rows = [] probs_store = {} labels_ref = None for sp in specs: src_path = Path(sp["src"]) raw_sd = torch.load(src_path, map_location="cpu", weights_only=True) clean_sd = strip_thop_keys(raw_sd) dropped_thop = len(raw_sd) - len(clean_sd) # Save verified clean state_dict into repo dest_path = ckpt_dest / sp["dest_name"] torch.save(clean_sd, dest_path) model = sp["builder"]().to(device) model.load_state_dict(clean_sd, strict=True) labels, probs = predict_loader(model, test_loader, device, sp["is_biohcl"]) if labels_ref is None: labels_ref = labels else: assert np.array_equal(labels_ref, labels) m = compute_classification_metrics(labels, probs, threshold=0.50) cis = bootstrap_confidence_intervals(labels, probs, threshold=0.50, n_boot=10000, seed=42) del model if torch.cuda.is_available(): torch.cuda.empty_cache() params, macs, gmacs = measure_complexity(sp["builder"]) size_mb = dest_path.stat().st_size / (1024 ** 2) row = { "model": sp["name"], "role": sp["role"], "checkpoint": dest_path.name, "sha256_prefix": sha256_file(dest_path)[:16], "strict_loaded": True, "dropped_thop_keys": dropped_thop, "params": params, "size_mb": round(size_mb, 2), "gmacs": round(gmacs, 4), "accuracy_pct": round(m["accuracy"] * 100.0, 2), "acc_ci95_low": round(cis["accuracy_ci95"][0] * 100.0, 2), "acc_ci95_high": round(cis["accuracy_ci95"][1] * 100.0, 2), "precision_pct": round(m["precision"] * 100.0, 2), "recall_pct": round(m["recall"] * 100.0, 2), "specificity_pct": round(m["specificity"] * 100.0, 2), "f1": round(m["f1"], 4), "f1_ci95_low": round(cis["f1_ci95"][0], 4), "f1_ci95_high": round(cis["f1_ci95"][1], 4), "macro_f1": round(m["macro_f1"], 4), "roc_auc": round(m["roc_auc"], 4), "auc_ci95_low": round(cis["roc_auc_ci95"][0], 4), "auc_ci95_high": round(cis["roc_auc_ci95"][1], 4), "pr_auc": round(m["pr_auc"], 4), "brier_score": round(m["brier_score"], 4), "ece": round(m["ece"], 4), "tp": m["tp"], "fp": m["fp"], "tn": m["tn"], "fn": m["fn"], } rows.append(row) probs_store[sp["name"]] = probs print( f"[Priority1] {sp['name']:24s} | Acc={row['accuracy_pct']:5.2f}% [{row['acc_ci95_low']:.2f},{row['acc_ci95_high']:.2f}] " f"| F1={row['f1']:.4f} | Spec={row['specificity_pct']:5.2f}% | Rec={row['recall_pct']:5.2f}% " f"| AUC={row['roc_auc']:.4f} | Brier={row['brier_score']:.4f} | ECE={row['ece']:.4f} " f"| Params={params:,} | GMACs={gmacs:.3f} | CM(TN={m['tn']},FP={m['fp']},FN={m['fn']},TP={m['tp']})" ) df_out = pd.DataFrame(rows) df_out.to_csv(res_dir / "priority1_test_evaluation.csv", index=False) # Exact McNemar comparisons vs Student_BioHCL_SSSM preds_student = (probs_store["Student_BioHCL_SSSM"] >= 0.50).astype(np.int64) mcnemar_results = {} for other in ["Baseline_ResNet50", "Ablation_SingleCNN", "Ablation_NoBioPrior", "Ablation_NoPositional"]: preds_other = (probs_store[other] >= 0.50).astype(np.int64) res_mc = exact_mcnemar_test(labels_ref, preds_student, preds_other, n_boot=10000, seed=42) mcnemar_results[f"Student_vs_{other}"] = res_mc print( f"[McNemar] Student vs {other:22s}: diff={res_mc['acc_diff_a_minus_b']*100:+.2f}% " f"[{res_mc['acc_diff_ci95_low']*100:+.2f}%, {res_mc['acc_diff_ci95_high']*100:+.2f}%] | " f"A_only={res_mc['a_only_correct']}, B_only={res_mc['b_only_correct']} | exact_p={res_mc['mcnemar_exact_p']:.6f}" ) (res_dir / "priority1_mcnemar.json").write_text(json.dumps(mcnemar_results, indent=2), encoding="utf-8") np.savez( res_dir / "priority1_predictions.npz", labels=labels_ref, **{f"probs_{k}": v for k, v in probs_store.items()}, ) print("Saved Priority 1 outputs to", res_dir) if __name__ == "__main__": main()