File size: 10,967 Bytes
bb5e4ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env python3
"""Priority 4: Clean Unified 256-d Ablation Suite on Fold 0 Patient-Grouped Split.

Enforces Opus Gate 0 binding protocol:
- Deterministic patient-grouped Fold 0 train/val split (`0` group overlap, `0` MD5 overlap).
- Never combines WeightedRandomSampler with weighted CE/Focal losses.
- Saves clean weights without `thop` buffer pollution; measures GMACs/params post-save on throwaway copy.
- Single evaluation on official N=624 `test/` at fixed t=0.50 (NO threshold tuning on test!).
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

import numpy as np
import pandas as pd
import thop
import torch
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 (  # noqa: E402
    ChestXrayDataset,
    get_transforms,
    iter_patient_grouped_folds,
    load_kermany_dataframes,
)
from src.models.biohcl_sssm import BioHCLSSSM, strip_thop_keys  # noqa: E402
from src.training.trainer import TrainConfig, fit_and_select_best, predict_probs  # noqa: E402
from src.utils.metrics import bootstrap_confidence_intervals, compute_classification_metrics  # noqa: E402


def build_variant_specs():
    return [
        # 1. Canonical 256-d L=2 Reference (WeightedRandomSampler + Unweighted CE)
        {"name": "SSSM_L2_Ref", "block_type": "sssm", "L": 2, "use_skip": True, "sampler": True, "loss": "ce", "lambda_phys": 0.0},
        # 2. Fair Tuned MHSA Baseline (8 heads x 32d = 256, L=2, DenseNet backbone)
        {"name": "MHSA_L2_8Heads", "block_type": "mhsa", "L": 2, "use_skip": True, "sampler": True, "loss": "ce", "lambda_phys": 0.0},
        # 3-5. Depth Sweep L in [1, 3, 4]
        {"name": "Depth_SSSM_L1", "block_type": "sssm", "L": 1, "use_skip": True, "sampler": True, "loss": "ce", "lambda_phys": 0.0},
        {"name": "Depth_SSSM_L3", "block_type": "sssm", "L": 3, "use_skip": True, "sampler": True, "loss": "ce", "lambda_phys": 0.0},
        {"name": "Depth_SSSM_L4", "block_type": "sssm", "L": 4, "use_skip": True, "sampler": True, "loss": "ce", "lambda_phys": 0.0},
        # 6. Residual / Skip Removal
        {"name": "Ablation_NoSkip_L2", "block_type": "sssm", "L": 2, "use_skip": False, "sampler": True, "loss": "ce", "lambda_phys": 0.0},
        # 7-8. Loss Family Comparison (Uniform Random Shuffle ONLY - NO WeightedRandomSampler!)
        {"name": "Loss_WeightedCE_Uniform", "block_type": "sssm", "L": 2, "use_skip": True, "sampler": False, "loss": "weighted_ce", "lambda_phys": 0.0},
        {"name": "Loss_FocalGamma2_Uniform", "block_type": "sssm", "L": 2, "use_skip": True, "sampler": False, "loss": "focal", "lambda_phys": 0.0},
        # 9-11. Batch Feature-Consistency Regularizer Sweep
        {"name": "Consistency_Lambda_0.01", "block_type": "sssm", "L": 2, "use_skip": True, "sampler": True, "loss": "ce", "lambda_phys": 0.01},
        {"name": "Consistency_Lambda_0.05", "block_type": "sssm", "L": 2, "use_skip": True, "sampler": True, "loss": "ce", "lambda_phys": 0.05},
        {"name": "Consistency_Lambda_0.20", "block_type": "sssm", "L": 2, "use_skip": True, "sampler": True, "loss": "ce", "lambda_phys": 0.20},
    ]


def measure_clean_complexity(spec: dict) -> tuple[int, float]:
    m = BioHCLSSSM(
        num_classes=2,
        embed_dim=256,
        chain_mode="dual",
        backbone_type="densenet",
        num_sssm_blocks=spec["L"],
        use_bio_prior=True,
        use_positional=True,
        use_skip=spec["use_skip"],
        block_type=spec["block_type"],
        pretrained_backbone=False,
    ).cpu().eval()
    params = sum(p.numel() for p in m.parameters())
    macs, _ = thop.profile(m, inputs=(torch.randn(1, 3, 224, 224),), verbose=False)
    del m
    return int(params), float(macs / 1e9)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-dir", type=str, default=None)
    parser.add_argument("--epochs", type=int, default=50)
    parser.add_argument("--patience", type=int, default=10)
    parser.add_argument("--batch-size", type=int, default=16)
    parser.add_argument("--num-workers", type=int, default=4)
    parser.add_argument("--seed", type=int, default=42)
    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)
    _, df_tr, df_va = next(iter_patient_grouped_folds(df_trainval, n_splits=5, shuffle=True, random_state=args.seed))
    print(f"[Priority4 Ablations] Split Fold0: Train={len(df_tr)} ({df_tr['group_id'].nunique()} grps) | Val={len(df_va)} ({df_va['group_id'].nunique()} grps) | Test={len(df_test)}")

    _, eval_tf = get_transforms()
    test_loader = DataLoader(
        ChestXrayDataset(df_test, transform=eval_tf),
        batch_size=32,
        shuffle=False,
        num_workers=args.num_workers,
        pin_memory=device.type == "cuda",
    )

    ckpt_dir = REPO_ROOT / "checkpoints" / "ablations_256d"
    res_dir = REPO_ROOT / "results"
    ckpt_dir.mkdir(parents=True, exist_ok=True)
    res_dir.mkdir(parents=True, exist_ok=True)

    rows = []
    histories = {}
    probs_test_store = {}
    labels_ref = None

    for spec in build_variant_specs():
        vname = spec["name"]
        print(f"\n>>> Starting Variant: {vname} | spec={spec}", flush=True)
        model = BioHCLSSSM(
            num_classes=2,
            embed_dim=256,
            chain_mode="dual",
            backbone_type="densenet",
            num_sssm_blocks=spec["L"],
            use_bio_prior=True,
            use_positional=True,
            use_skip=spec["use_skip"],
            block_type=spec["block_type"],
            pretrained_backbone=True,
        ).to(device)

        cfg = TrainConfig(
            epochs=args.epochs,
            warmup_epochs=5,
            patience=args.patience,
            batch_size=args.batch_size,
            lr=1e-4,
            warmup_start_lr=1e-6,
            weight_decay=1e-2,
            grad_clip=1.0,
            loss_type=spec["loss"],
            use_weighted_sampler=spec["sampler"],
            lambda_phys=spec["lambda_phys"],
            focal_gamma=2.0,
            num_workers=args.num_workers,
            seed=args.seed,
        )

        ckpt_path = ckpt_dir / f"{vname}.pt"
        train_out = fit_and_select_best(
            model=model,
            df_train=df_tr,
            df_val=df_va,
            cfg=cfg,
            device=device,
            save_path=ckpt_path,
            run_name=vname,
        )
        histories[vname] = train_out["history"]

        # Load clean saved weights strictly from disk and perform SINGLE t=0.50 test evaluation
        del model
        if torch.cuda.is_available():
            torch.cuda.empty_cache()

        saved_sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)
        assert not any(k.endswith(("total_ops", "total_params")) for k in saved_sd), f"thop key leak in {ckpt_path}"

        eval_model = BioHCLSSSM(
            num_classes=2,
            embed_dim=256,
            chain_mode="dual",
            backbone_type="densenet",
            num_sssm_blocks=spec["L"],
            use_bio_prior=True,
            use_positional=True,
            use_skip=spec["use_skip"],
            block_type=spec["block_type"],
            pretrained_backbone=False,
        ).to(device)
        eval_model.load_state_dict(strip_thop_keys(saved_sd), strict=True)
        test_labels, test_probs, _ = predict_probs(eval_model, test_loader, device)
        if labels_ref is None:
            labels_ref = test_labels
        else:
            assert np.array_equal(labels_ref, test_labels)

        tm = compute_classification_metrics(test_labels, test_probs, threshold=0.50)
        tci = bootstrap_confidence_intervals(test_labels, test_probs, threshold=0.50, n_boot=10000, seed=args.seed)
        vm = train_out["best_val_metrics"]

        del eval_model
        if torch.cuda.is_available():
            torch.cuda.empty_cache()

        params, gmacs = measure_clean_complexity(spec)
        row = {
            "variant": vname,
            "block_type": spec["block_type"],
            "layers": spec["L"],
            "use_skip": spec["use_skip"],
            "weighted_sampler": spec["sampler"],
            "loss_type": spec["loss"],
            "lambda_phys": spec["lambda_phys"],
            "status": train_out["status"],
            "collapse_reason": train_out["collapse_reason"],
            "best_epoch": train_out["best_epoch"],
            "epochs_ran": train_out["epochs_ran"],
            "elapsed_sec": train_out["elapsed_sec"],
            "params": params,
            "gmacs": round(gmacs, 4),
            "val_acc_pct": round(vm["accuracy"] * 100.0, 2),
            "val_macro_f1": round(vm["macro_f1"], 4),
            "val_auc": round(vm["roc_auc"], 4),
            "test_acc_pct": round(tm["accuracy"] * 100.0, 2),
            "test_acc_ci95_low": round(tci["accuracy_ci95"][0] * 100.0, 2),
            "test_acc_ci95_high": round(tci["accuracy_ci95"][1] * 100.0, 2),
            "test_precision_pct": round(tm["precision"] * 100.0, 2),
            "test_recall_pct": round(tm["recall"] * 100.0, 2),
            "test_specificity_pct": round(tm["specificity"] * 100.0, 2),
            "test_f1": round(tm["f1"], 4),
            "test_macro_f1": round(tm["macro_f1"], 4),
            "test_auc": round(tm["roc_auc"], 4),
            "test_pr_auc": round(tm["pr_auc"], 4),
            "test_brier": round(tm["brier_score"], 4),
            "test_ece": round(tm["ece"], 4),
            "test_unique_preds": tm["unique_preds"],
            "tp": tm["tp"],
            "fp": tm["fp"],
            "tn": tm["tn"],
            "fn": tm["fn"],
        }
        rows.append(row)
        probs_test_store[vname] = test_probs
        # Save incrementally so partial progress is never lost
        pd.DataFrame(rows).to_csv(res_dir / "priority4_clean_ablations.csv", index=False)
        print(
            f"[Priority4] {vname:24s} | status={row['status']:10s} | Val_mF1={row['val_macro_f1']:.4f} "
            f"| Test_Acc={row['test_acc_pct']:5.2f}% [{row['test_acc_ci95_low']:.2f},{row['test_acc_ci95_high']:.2f}] "
            f"| Test_F1={row['test_f1']:.4f} | Spec={row['test_specificity_pct']:5.2f}% | Rec={row['test_recall_pct']:5.2f}% "
            f"| AUC={row['test_auc']:.4f} | CM(TN={row['tn']},FP={row['fp']},FN={row['fn']},TP={row['tp']})",
            flush=True,
        )

    (res_dir / "priority4_ablation_history.json").write_text(json.dumps(histories, indent=2), encoding="utf-8")
    np.savez(
        res_dir / "priority4_ablation_test_probs.npz",
        labels=labels_ref,
        **{f"probs_{k}": v for k, v in probs_test_store.items()},
    )
    print("\nSaved complete Priority 4 ablations to", res_dir / "priority4_clean_ablations.csv")


if __name__ == "__main__":
    main()