File size: 10,227 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
---
language:
- en
license: mit
tags:
- medical-imaging
- chest-xray
- pediatric-pneumonia
- state-space-models
- mamba
- knowledge-distillation
- reproducible-research
datasets:
- paultimothymooney/chest-xray-pneumonia
pipeline_tag: image-classification
---

# BioHCL-SSSM: Biologically-Gated Hybrid Convolutional Linear Selective State-Space Model (Audited Clean Release)

**BioHCL-SSSM** (`unknownBrain/BioHCL-SSSM`) is a consolidated, leak-free, fully reproducible codebase and checkpoint archive for pediatric chest X-ray pneumonia classification (**Kermany et al., *Cell* 2018; `paultimothymooney/chest-xray-pneumonia`, `N = 5,856` JPEGs only**). Every architectural module, checkpoint, CSV log, bootstrap confidence interval, McNemar significance test, and scientific disclosure in this repository has been independently audited across multi-stage verification gates.

For full methodology, calibration analysis, patient-grouping forensics, legacy artifact corrections, and complete tables, see [TECHNICAL_REPORT.md](TECHNICAL_REPORT.md).

---

## Key Verified Results

### 1. Held-Out Official Kermany Test Set (`N = 624`, Fixed Threshold `t = 0.50`, Strict FP32)

| Model | Params (Trainable) | GMACs | Test Acc [95% CI] | Precision | Recall | Specificity | F1 | ROC-AUC | Brier | ECE (10-bin) |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| **Student BioHCL-SSSM (`256-d`, KD)** | **8,340,554** | **3.429** | **87.50%** [84.78, 90.06] | **83.62%** | 99.49% | 67.52% | **0.9087** | 0.9391 | 0.1218 | 0.1229 |
| Baseline ResNet-50 | 23,512,130 | 4.132 | 84.29%* [81.41, 87.18] | 80.17% | 99.49% | 58.97% | 0.8879 | **0.9605** | 0.1481 | 0.1465 |
| Ablation: Single-CNN Branch | 1,249,822 | 1.132 | 83.81% [80.93, 86.70] | 84.99% | 90.00% | **73.50%** | 0.8742 | 0.9116 | **0.1179** | **0.0467** |
| Ablation: No Bio-Prior | 8,340,554 | 3.429 | 82.37% [79.33, 85.42] | 78.11% | 99.74% | 53.42% | 0.8761 | 0.9506 | 0.1701 | 0.1681 |
| Ablation: No Positional Encoding | 8,340,554 | 3.417 | 81.09% [77.88, 84.13] | 76.88% | 99.74% | 50.00% | 0.8683 | 0.9701 | 0.1875 | 0.1879 |

*\*`Baseline_ResNet50` scores `84.29%` (`526/624`) in strict FP32 and `84.46%` (`527/624`) under `torch.amp.autocast('cuda')` due to 1 borderline image (`p=0.5036` FP32). Paired McNemar exact test (`Student` vs `ResNet-50` FP32): `Ξ”Acc = +3.21% [+1.44%, +4.97%]`, `27` vs `7` discordant pairs, **`p = 0.000821`**.*

### 2. Clean Patient-Grouped 5-Fold Cross-Validation (`N = 5,232`, `2,861` Patient/MD5 Groups, Direct `256-d` `L=2`)

Using **Union-Find patient + exact MD5 grouping BEFORE `StratifiedGroupKFold`** (`0` patient overlap, `0` MD5 overlap per fold; official `test/` untouched):
- **Mean Β± SD across 5 folds:** Accuracy **`99.35% Β± 0.26%`**, Macro-F1 **`0.9915 Β± 0.0032`**, F1 **`0.9956 Β± 0.0017`**, Specificity **`99.11% Β± 0.61%`**, Recall **`99.43% Β± 0.21%`**, ROC-AUC **`0.9994 Β± 0.0004`**, Brier **`0.0064 Β± 0.0025`**, ECE **`0.0065 Β± 0.0027`**.
- **Pooled Out-Of-Fold (`N = 5,232`):** Accuracy **`99.35%` [99.12%, 99.56%]**, `TN = 1,337`, `FP = 12`, `FN = 22`, `TP = 3,861`, ROC-AUC `0.9991`, Brier `0.0064`, ECE `0.0061`.

> **Central Generalization Gap Finding:** BioHCL-SSSM achieves **99.35% Β± 0.26%** internal patient-grouped CV accuracy (`N=5,232`), demonstrating strong within-cohort generalization, while external transfer to the official held-out Kermany test set (`N=624`) yields **87.50%** (KD Student) and **80.61%–85.90%** across single-fold `Ξ»_phys=0.0` direct runs (`78.69%–85.90%` across all `11` variants including regularized sweeps) β€” reflecting documented distribution shift (`train+val` 74.1% vs `test` 62.5% Pneumonia, acquisition/spectrum differences). We never conflate internal CV with external generalization.

### 3. Unified Controlled `256-d` Fold-0 Ablation Highlights (`--epochs 30 --patience 8`, 11 Variants)

All `11` variants converged without single-class collapse (`WeightedRandomSampler` never stacked with weighted losses):
- **SSSM vs. Tuned 8-Head MHSA:** `SSSM_L2_Ref` (`8.34M` params: `82.69%` Test Acc `[79.65, 85.58]`, `0.9588` AUC) vs. `MHSA_L2_8Heads` (`8.56M` params: `83.01%` Test Acc `[79.97, 85.90]`, `0.9482` AUC) perform within sampling noise on Fold 0 β€” no superiority claimed over MHSA without multi-fold testing.
- **Depth & Skip Connections (Single-Fold):** `Depth_SSSM_L4` reached **`85.26%`** (`0.9708` AUC) and `Ablation_NoSkip_L2` reached **`84.62%`** (`0.9759` AUC), outperforming `SSSM_L2_Ref` (`82.69%`) on Fold 0 β€” reported transparently as single-fold observations requiring multi-fold validation.
- **Class-Imbalance Strategy:** `Loss_WeightedCE_Uniform` (uniform shuffle + inverse class weights, no sampler) achieved the highest Fold-0 test accuracy at **`85.90%`** (`0.8981` F1, `63.25%` Specificity, `0.9384` AUC).
- **Batch Feature-Consistency Regularizer (`Ξ»_phys`):** Sweeping `Ξ»_phys ∈ {0.0, 0.01, 0.05, 0.20}` kept high internal Val accuracy (`98.8%–99.1%`) while degrading external Test ROC-AUC sharply from **`0.9588` (`Ξ»=0.0`) β†’ `0.8514` (`Ξ»=0.01`) β†’ `0.7233` (`Ξ»=0.05`)** and `0.8867` (`Ξ»=0.20`), empirically validating why `Ξ»_phys = 0.0` is used in all clean configurations.

---

## Visualizations

| Figure | Description |
|---|---|
| [Confusion Matrices](figures/fig1_priority1_confusion_matrices.png) | Side-by-side held-out test confusion matrices (`N = 624`, fixed `t = 0.50`) for all 5 verified Aug-12 models. |
| [ROC & Calibration](figures/fig2_roc_and_calibration.png) | Ranking ROC-AUC vs. top-label reliability calibration explaining why Student KD wins at `t = 0.50`. |
| [Patient-Grouped CV](figures/fig3_priority3_patient_cv.png) | Per-fold accuracy/F1/AUC across all 5 patient-grouped folds + pooled `N = 5,232` OOF confusion matrix. |
| [Clean 256-d Ablations](figures/fig4_priority4_ablations.png) | Complete 11-variant Fold-0 test accuracy & 95% CI comparison at fixed `t = 0.50`. |

---

## Repository Structure

```text
BioHCL-SSSM/
β”œβ”€β”€ README.md                              # Overview, verified metrics, quick-start
β”œβ”€β”€ TECHNICAL_REPORT.md                    # Full audit report, Old-vs-New comparison & disclosures D1–D7
β”œβ”€β”€ requirements.txt                       # Clean Python dependencies
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ models/biohcl_sssm.py              # Single canonical BioHCLSSSM (`256-d`, `L=2` default) + MHSA/ResNet50
β”‚   β”œβ”€β”€ data/dataset.py                    # Union-Find patient + MD5 grouping + StratifiedGroupKFold
β”‚   β”œβ”€β”€ losses/losses.py                   # FP32 CE, Weighted CE, Focal (Ξ³=2), & documented consistency term
β”‚   β”œβ”€β”€ training/trainer.py                # Shared AdamW + warmup-cosine loop, collapse guard & FP32 eval
β”‚   └── utils/metrics.py                   # Acc/Prec/Rec/Spec/F1/AUC/PR-AUC/Brier/ECE, 10k bootstrap, McNemar
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ smoke_check.py                     # Architecture, forward/backward, zero-leakage & zero-secret check
β”‚   β”œβ”€β”€ evaluate_single_checkpoint.py      # Standalone FP32 checkpoint evaluator CLI
β”‚   β”œβ”€β”€ run_phase0_eval.py                 # Reproduce Priority 1 official test evaluation + McNemar tests
β”‚   β”œβ”€β”€ run_phase1_groupkfold.py           # Reproduce Priority 3 5-fold patient-grouped CV
β”‚   β”œβ”€β”€ run_phase1_ablations.py            # Reproduce Priority 4 11-variant 256-d ablation suite
β”‚   └── generate_figures.py                # Regenerate all 4 300-DPI figures from CSV/NPZ outputs
β”œβ”€β”€ results/                               # Audited CSVs, JSON summaries, McNemar results & NPZ probabilities
β”œβ”€β”€ figures/                               # 300-DPI PNG figures
└── checkpoints/                           # 21 clean verified `.pt` state_dicts + checkpoints/README.md
```

---

## Quick Start & Reproducibility

```bash
pip install -r requirements.txt

# 1. Verify package integrity, zero secrets, zero thop buffers, and patient/MD5 CV isolation
python scripts/smoke_check.py

# 2. Evaluate the verified Aug-12 Student BioHCL-SSSM checkpoint on official Kermany test (N=624)
python scripts/evaluate_single_checkpoint.py \
  --checkpoint checkpoints/aug12_verified/biohcl_sssm_student_256d.pt \
  --data-dir /path/to/chest_xray

# 3. Reproduce full Priority 1 table + exact McNemar test + Brier/ECE
python scripts/run_phase0_eval.py --data-dir /path/to/chest_xray

# 4. Reproduce 5-fold patient-grouped CV (official test/ untouched)
python scripts/run_phase1_groupkfold.py --data-dir /path/to/chest_xray

# 5. Reproduce the unified 11-variant 256-d ablation suite on Fold 0
python scripts/run_phase1_ablations.py --data-dir /path/to/chest_xray --epochs 30 --patience 8
```

---

## Mandatory Scientific Scope & Limitations

- **Single-Dataset Provenance:** All experiments in this repository were executed strictly on the **Kermany Pediatric Chest X-Ray cohort** (`ages 1–5`, Guangzhou Women and Children's Medical Center). Results do not establish generalization to adult populations or other modalities (no Brain MRI, RSNA, or NIH runs were executed).
- **Kermany Dataset Artifacts:** Official `test/PNEUMONIA/` restarts `person` numbering independently of `train/`; patient tokens are disambiguated by split prefix (`{split}_person_{id}`). One exact-byte duplicate pair exists inside official `test/NORMAL` (`NORMAL2-IM-0095-0001.jpeg == NORMAL2-IM-0096-0001.jpeg`) and is retained unmodified inside `N = 624` for benchmark comparability.
- **Architecture & Regularizer Transparency:** `ResidualConnector` projection/norm layers (`132,608` params inside the `8,340,554` trainable total) exist inside `state_dict` for checkpoint compatibility while `BioHCLSSSM.forward()` reads `skip_step` directly. The auxiliary `features.roll(1)` L2 penalty is accurately documented as a **Batch Feature-Consistency Regularizer** (disabled at `Ξ»_phys = 0.0`), not a biophysical PDE loss.
- **Clinical Sensitivity vs. Specificity:** At fixed `t = 0.50`, all models prioritize Pneumonia Sensitivity (`β‰₯ 90%` / `99.49%`) with moderate external Specificity (`44%–73.5%`). Clinical deployment would require threshold calibration on a dedicated held-out validation calibration subset.