diff --git a/legacy/final/README.md b/legacy/final/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6c8c749024ed670cb3b0aeb7ccc8490a511e8148 --- /dev/null +++ b/legacy/final/README.md @@ -0,0 +1,174 @@ +# CD-MSC — Best Ensemble (techniques, losses, and how to run) + +BioDCASE 2026 Task 5 — Cross-Domain Mosquito Species Classification. Optimize **BA_unseen** = mean over the 9 +species of per-species recall on each species' **held-out unseen recording domain** (true leave-one-domain-out). + +This folder is the self-contained final model: every model/loss/feature definition, all member checkpoints, +the gate manifest, and a one-command inference script that reproduces test BA_unseen. + +--- + +## 1. The problem the techniques are designed around + +- 9 species; 5 recording **domains** D1–D5 (devices). **D5 is ~98% of training** (clean studio); D1–D4 are + small and shifted. Each species is **tested on a domain it was never trained on** (LODO). +- The domain shift is a **spectral-envelope EQ tilt**: it re-colors the overall spectrum but **preserves the + harmonic comb / wingbeat fundamental f0**. No information is destroyed — it is a *style* shift. +- Failure mode without DG: the model latches onto the device "style" as a shortcut → collapses on unseen + domains (especially the studio→D1 transfer, where the envelope inverts). + +Two structural walls cap any model near ~0.40–0.45 (oracle): (a) the **movers** gambiae/arabiensis/quinque are +100% D5-trained but tested on D1 (no in-domain anchor); (b) **dirus** has 0 D5 clips; (c) validation is 99.4% +D5, so you cannot model-select for the unseen regime. + +--- + +## 2. Representations (frozen embeddings — no encoder is fine-tuned) + +| member | embedding | dim | why | +|---|---|---|---| +| `base_perch` | **Perch v2** (Google bird-vocalization model, frozen) | 1536 | strongest general bioacoustic encoder here | +| `arm_harmonic` | **physics harmonic feature** (`harmonic_features.py`) | 102 | device-INVARIANT by construction (comb/f0) | +| `arm_birdmae` | **BirdMAE** (frozen) | 1024 | independent FM; agrees with harmonic on Aedes | +| `arm_bgwhiten` | **background-whitened spectrum** (`bgwhiten_features.py`) | 257 | device channel estimated from the clip's background frames and subtracted; 3rd independent device-invariant voter | + +The harmonic feature = liftered cepstrum (drops the low-quefrency EQ envelope, keeps the pitch band) + f0/ +harmonic ratios on the whitened spectrum. Perch's fine-tuning is impossible (it ships as a jax2tf SavedModel +with gradients disabled), so all members are **frozen embedding + trainable probe**. + +--- + +## 3. Probe architectures (`model.py`) + +- **RP** (Perch, BirdMAE): input LayerNorm → Linear(d→256) → 2× Pre-LN residual block (LN→Linear(4×,GELU)→ + Dropout→Linear→+residual) → LayerNorm → species head (9) + auxiliary domain head (5). +- **HarmNet** (harmonic): LN → Linear(102→128) → GELU → Dropout → Linear(128→64) → LN → species + domain heads. + +--- + +## 4. Training techniques & losses (`losses.py`) + +Per-member objective (every member, same recipe): + +``` +L = CE(species) + + 0.01 * CE(domain) # auxiliary domain head (plain aux, not adversarial) + + 0.50 * genus_aux # hierarchical Aedes/Culex/Anopheles consistency + + 0.50 * supcon(T=0.10) # supervised contrastive on the L2-normalized embedding + + 1.00 * coral # Deep CORAL — align per-domain covariances + + 0.25 * mmd # multi-kernel Gaussian MMD — align per-domain distributions <-- THE lever +``` + +- **MMD (0.25)** is the single most important knob: aligning the per-domain embedding distributions lifted + BA_unseen ~0.25 → ~0.33. The weight 0.25 is the measured optimum (a sweep peak); 0.0→0.245, 0.1→0.31, + 0.25→0.33, 0.5→0.30, 0.75→0.28. +- **CORAL** complements MMD (second-order alignment). +- **genus_aux** keeps cross-genus structure correct (so Aedes/Culex aren't mislabeled Anopheles). +- **SupCon** (L2-normalized; an earlier L1 bug made it inert) — small positive. +- Domain head at 0.01 is a *plain* classifier (DANN/gradient-reversal was tried, ~neutral). + +### Augmentations (in `model.py`, active only in `.train()`) +- **Embedding Gaussian noise** σ=0.05 (RP) / 0.03 (HarmNet). +- **Feature channel-dropout** p=0.1 (RP). +- *Tested and dropped (within noise / negative):* class-mixup (slightly hurts), domain-mixup (≈neutral), + DicL contrastive (hurts), forward EQ-augmentation (neutral), MixStyle, genus-gated MoE (hurts). + +### Optimization / selection +- AdamW, lr 3e-4, cosine schedule + 5% warmup, weight decay 1e-4, batch 512. +- Base: **30 epochs**; arms: 20 epochs. **Uniform** sampling. +- Checkpoint selection on **seen-val species balanced accuracy** (never the test set). +- Per member: ensemble over seeds by **softmax averaging** (base 8 seeds, each arm 3 seeds). + +--- + +## 5. The ensemble + the UNANIMOUS-3 AGREEMENT GATE (the headline technique) + +Each member is a seed-ensemble. The final prediction: + +``` +pred = base_perch_ensemble +EXCEPT on clips where harmonic.argmax == birdmae.argmax == bgwhiten.argmax == c AND min(all 3 confs) > tau: + there, override with mean(harmonic, birdmae, bgwhiten) +``` + +- **Why it works:** the studio→D1 EQ shift inverts Perch's envelope (Perch lands *below chance* on D5→D1), + while the device-invariant reps survive. Both harmonic and BirdMAE independently nail **aegypti** (Aedes, + distinct wingbeat: harmonic 0.90, BirdMAE 0.93 vs Perch 0.43), so the agreement captures aegypti (0.43→~0.81). +- **The 3rd voter is a precision VETO (this is what raised the score).** A *two*-voter gate (harmonic+birdmae) + over-fires: it overrides true **mover** clips (arabiensis/quinque) toward aegypti — the metric-aware cost. + Adding the **background-whitened** spectrum as a *third independent device-invariant voter*, and requiring + **unanimous** agreement, makes the gate fire only when it is really safe. It keeps aegypti high **and stops + sacrificing the movers**: arabiensis 0.148→0.192, quinque 0.140→0.196. The bgwhiten voter need not predict + the movers itself — it simply *vetoes the bad overrides*. Net **+0.02 over the 2-voter gate**, and the gain + is on the LARGE-n unseen partitions (arabiensis 1820, quinque 672 clips), LOSO-stable across seeds. +- `tau` is the only knob, selected on seen-val → deployable, no test-set tuning. +- **Honest caveat:** it still cannot *separate* the *An. gambiae* complex (gambiae/arabiensis share wingbeat + f0); gambiae stays floored. The win is recovering the movers the 2-voter gate was throwing away. + +The exact numbers (base, 2-voter, unanimous-3 BA_unseen, tau, per-species) are in `ensemble.json` and printed +by `infer.py`. The previous 2-voter package is preserved in `checkpoints_backup_2voter/`. + +--- + +## 6. Files + +``` +final/ + README.md <- this file + model.py <- RP, HarmNet, ResidualBlock + losses.py <- CE/genus/SupCon/MMD/CORAL + total_loss (the recipe) + harmonic_features.py <- raw audio -> 102-d device-invariant harmonic feature + bgwhiten_features.py <- raw audio -> 257-d background-whitened spectrum (3rd voter) + infer.py <- load checkpoints + cached embeddings -> unanimous-3 gated BA_unseen + ensemble_model.py <- GatedEnsemble: one object loads bundle.pt and applies the 3-voter gate + bundle_ensemble.py <- packs all 19 checkpoints + gate tau into bundle.pt + ensemble.json <- member list, gate tau, results + checkpoints/ + base_perch_s{1234,42,2023,7,99,123,256,777}.pt (8) + arm_harmonic_s{1234,42,2023}.pt (3) + arm_birdmae_s{1234,42,2023}.pt (3) + arm_bgwhiten_s{1234,42,2023,7,99}.pt (5) + checkpoints_backup_2voter/ <- the previous 2-voter package (revertable) +``` + +Each `.pt` holds: `model_state_dict`, standardization `mean`/`std`, `modality`, `arch`, `feature_dim`, +`seed`, `val_ba`, `test_ba_unseen`. + +## 7. Run + +```bash +# reproduces test BA_unseen from the per-member checkpoints + cached embeddings +python final/infer.py +``` + +### Single-file ensemble checkpoint (all 14 members + gate in one object) +```bash +python final/bundle_ensemble.py # packs checkpoints/ -> final/bundle.pt (~85 MB, 19 members) +``` +```python +from ensemble_model import GatedEnsemble +ens = GatedEnsemble("final/bundle.pt") # one object = whole ensemble + gate +probs = ens.predict_proba(perch_emb, harmonic_feat, birdmae_emb, bgwhiten_feat) # (N,9) gated probabilities +labels = probs.argmax(1) # species 0..8 +# ens.member_probs(...) returns the 4 pre-gate group probabilities if you want to inspect the gate. +``` +`bundle.pt` holds every member's weights + standardization stats + the gate tau, so it is the single +"checkpoint with the ensemble." It reproduces gated BA_unseen = 0.3616. + +For new raw audio: produce Perch (1536-d) and BirdMAE (1024-d) embeddings with those frozen models, the 102-d +harmonic feature via `harmonic_features.harmonic_feature_from_path(wav)`, and the 257-d background-whitened +spectrum via `bgwhiten_features.bgwhiten_feature_from_path(wav)`, then feed each to its member checkpoints and +apply the unanimous-3 gate (see `infer.py`). + +--- + +## 8. Results & honesty + +- Best deployable: **unanimous-3 gated ensemble = 0.3616** (base 0.3178; 2-voter 0.3411; +0.020 from the + background-whitened 3rd voter). LOSO-stable; gains on the large-n movers (arabiensis 0.148→0.192, quinque + 0.140→0.196) plus aegypti (0.81). +- Two levers found beyond the MMD/CORAL recipe: (1) the agreement gate, (2) the **background-whitened 3rd + voter** that turns the gate unanimous and stops it sacrificing the movers. sl-BEATs, HumBug (mosquito CNN), + CLAP/BioLingual were all tested and did NOT help; CQT helped the kill-test but not the gated metric. +- The remaining floor is **data/biology-bound**: nothing separates gambiae/arabiensis (acoustically identical + congeners) without an in-domain anchor the splits don't provide. gambiae stays ~0.05. diff --git a/legacy/final/__pycache__/bgwhiten_features.cpython-312.pyc b/legacy/final/__pycache__/bgwhiten_features.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b05153dd38b0ef74999b890281ee450948edcf86 Binary files /dev/null and b/legacy/final/__pycache__/bgwhiten_features.cpython-312.pyc differ diff --git a/legacy/final/__pycache__/ensemble_model.cpython-312.pyc b/legacy/final/__pycache__/ensemble_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..437364846413cc997570fbf8fa2a57a87f19a7ff Binary files /dev/null and b/legacy/final/__pycache__/ensemble_model.cpython-312.pyc differ diff --git a/legacy/final/__pycache__/harmonic_features.cpython-312.pyc b/legacy/final/__pycache__/harmonic_features.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c596e68a1717c3c735f3f791e0e4a2d6a76dfbb Binary files /dev/null and b/legacy/final/__pycache__/harmonic_features.cpython-312.pyc differ diff --git a/legacy/final/__pycache__/model.cpython-312.pyc b/legacy/final/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b127233ce8cea14b9ddb91b1ae8c12f6399946ce Binary files /dev/null and b/legacy/final/__pycache__/model.cpython-312.pyc differ diff --git a/legacy/final/__pycache__/predict_eval.cpython-312.pyc b/legacy/final/__pycache__/predict_eval.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72c80514493d0d42bb9d8324cfb0fb983e24bb46 Binary files /dev/null and b/legacy/final/__pycache__/predict_eval.cpython-312.pyc differ diff --git a/legacy/final/__pycache__/predict_eval_baseline.cpython-312.pyc b/legacy/final/__pycache__/predict_eval_baseline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6909065fcdb833b0efe41d76a3e60942ebe9dd01 Binary files /dev/null and b/legacy/final/__pycache__/predict_eval_baseline.cpython-312.pyc differ diff --git a/legacy/final/bgwhiten_features.py b/legacy/final/bgwhiten_features.py new file mode 100644 index 0000000000000000000000000000000000000000..1e7489483271ffc15f6b2103ffa2e72d35aafebb --- /dev/null +++ b/legacy/final/bgwhiten_features.py @@ -0,0 +1,42 @@ +"""Background-whitened spectrum feature (257-d) — the 3rd gate voter's input. + +Idea: a recording's DEVICE channel (EQ tilt + noise floor) is revealed by its non-mosquito BACKGROUND frames. +Estimate that channel from the low-energy frames and SUBTRACT it from the mean mosquito-frame log-spectrum -> +a device-invariant 'clean' spectrum. This is the strongest device-invariant species signal we measured on the +catastrophic studio->field (D5->D1) transfer (cross-domain 0.530 vs Perch 0.140), and as a 3rd unanimous-gate +voter it vetoes bad overrides and recovers the movers. + + from bgwhiten_features import bgwhiten_feature, bgwhiten_feature_from_path + w = bgwhiten_feature(y) # y: mono waveform; -> (257,) float32 + w = bgwhiten_feature_from_path("x.wav") # load + extract +""" +import numpy as np +import librosa, soundfile as sf + +SR = 16000; DUR = 1.0; NS = int(SR * DUR); N_FFT = 512; HOP = 128 +BG_Q = 0.30 # background = lowest 30% energy frames (device channel estimate) +FG_Q = 0.50 # foreground = top 50% energy frames (mosquito present) +BGW_DIM = N_FFT // 2 + 1 # 257 + + +def load_wav(path): + y, sr = sf.read(path) + if y.ndim > 1: y = y.mean(1) + y = y.astype(np.float32) + if sr != SR: y = librosa.resample(y, orig_sr=sr, target_sr=SR) + y = y[:NS] if len(y) >= NS else np.pad(y, (0, NS - len(y))) + m = np.abs(y).max(); return y / m if m > 0 else y + + +def bgwhiten_feature(y): + """Mono waveform (any length; trimmed/padded to 1 s) -> 257-d background-whitened log-spectrum.""" + if len(y) < N_FFT: y = np.pad(y, (0, N_FFT - len(y))) + S = np.abs(librosa.stft(y, n_fft=N_FFT, hop_length=HOP)) + 1e-8 + logS = np.log(S); e = S.sum(0); T = S.shape[1] + bg = np.argsort(e)[:max(3, int(BG_Q * T))] # quietest frames = device channel + fg = np.argsort(e)[::-1][:max(3, int(FG_Q * T))] # loudest frames = mosquito + return (logS[:, fg].mean(1) - logS[:, bg].mean(1)).astype(np.float32) + + +def bgwhiten_feature_from_path(path): + return bgwhiten_feature(load_wav(path)) diff --git a/legacy/final/bundle.pt b/legacy/final/bundle.pt new file mode 100644 index 0000000000000000000000000000000000000000..dcb3482861128a4005ccbb94a82f4925b595d073 --- /dev/null +++ b/legacy/final/bundle.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02f9e6d23f20eb4e43a777aa6acf9a17e1209d0452fe51bf9d44c56ec005cbf1 +size 85342253 diff --git a/legacy/final/bundle_ensemble.py b/legacy/final/bundle_ensemble.py new file mode 100644 index 0000000000000000000000000000000000000000..f68b8e37cd7bf17cac86cbe6468e9112d133cf29 --- /dev/null +++ b/legacy/final/bundle_ensemble.py @@ -0,0 +1,26 @@ +"""Pack the 14 per-member checkpoints + gate config into ONE file: final/bundle.pt. +Load it with: GatedEnsemble("final/bundle.pt"). Run: python final/bundle_ensemble.py +""" +import os, sys, glob, json +import torch +HERE = os.path.dirname(os.path.abspath(__file__)); CKPT = os.path.join(HERE, "checkpoints") +man = json.load(open(os.path.join(HERE, "ensemble.json"))) + +bundle = {"tau": man["gate"]["tau"], "members": {}, + "meta": {"pipeline": man["pipeline"], "description": man["description"], + "results": man["results"], "feature_dims": man["feature_dims"]}} +n = 0 +for group in ("base_perch", "arm_harmonic", "arm_birdmae", "arm_bgwhiten"): + bundle["members"][group] = [] + for cp in sorted(glob.glob(os.path.join(CKPT, f"{group}_s*.pt"))): + st = torch.load(cp, map_location="cpu", weights_only=False) + bundle["members"][group].append({ + "state": st["model_state_dict"], "mean": st["mean"], "std": st["std"], + "standardize": st["standardize"], "arch": st["arch"], "feature_dim": st["feature_dim"], + "seed": st["seed"]}) + n += 1 +out = os.path.join(HERE, "bundle.pt") +torch.save(bundle, out) +mb = os.path.getsize(out) / 1e6 +print(f"bundled {n} member checkpoints + gate(tau={bundle['tau']}) -> {out} ({mb:.1f} MB)") +print("groups:", {g: len(v) for g, v in bundle["members"].items()}) diff --git a/legacy/final/checkpoints/arm_bgwhiten_s1234.pt b/legacy/final/checkpoints/arm_bgwhiten_s1234.pt new file mode 100644 index 0000000000000000000000000000000000000000..31485846fa53457a2dc9b1ed985ac19a4f71caef --- /dev/null +++ b/legacy/final/checkpoints/arm_bgwhiten_s1234.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ef53039e3e4b73780ea26cdcd1f1c396885df707c45c05f83d187a73380545c +size 4502101 diff --git a/legacy/final/checkpoints/arm_bgwhiten_s2023.pt b/legacy/final/checkpoints/arm_bgwhiten_s2023.pt new file mode 100644 index 0000000000000000000000000000000000000000..9d2c184ea1bfa6d4e89949bf25b3317135ce808f --- /dev/null +++ b/legacy/final/checkpoints/arm_bgwhiten_s2023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1e88991ab12b71159ea222bcfe0cf824b8c226fd53471f461c2df8cb2feac14 +size 4502101 diff --git a/legacy/final/checkpoints/arm_bgwhiten_s42.pt b/legacy/final/checkpoints/arm_bgwhiten_s42.pt new file mode 100644 index 0000000000000000000000000000000000000000..b5f683fe55ebff55ba00f69efcc38acf43aa85f1 --- /dev/null +++ b/legacy/final/checkpoints/arm_bgwhiten_s42.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c9dde138a978758e481511c5ef817bd53da87b81ff5e02f490ab5cd1ac59d53 +size 4502045 diff --git a/legacy/final/checkpoints/arm_bgwhiten_s7.pt b/legacy/final/checkpoints/arm_bgwhiten_s7.pt new file mode 100644 index 0000000000000000000000000000000000000000..8698aa035d95b587378e2f2c3110545c7dedcc06 --- /dev/null +++ b/legacy/final/checkpoints/arm_bgwhiten_s7.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e799f1073610ca7de3f118b357912efb742c50930dc87b1456215fe54a992114 +size 4502017 diff --git a/legacy/final/checkpoints/arm_bgwhiten_s99.pt b/legacy/final/checkpoints/arm_bgwhiten_s99.pt new file mode 100644 index 0000000000000000000000000000000000000000..2a0565c8ffac77268f6b2f2894fc6fde5f281767 --- /dev/null +++ b/legacy/final/checkpoints/arm_bgwhiten_s99.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47e7b8a57616a9dc4988a4e6e7256ac117b4c39e14c54dc798cab8da50dcde89 +size 4502045 diff --git a/legacy/final/checkpoints/arm_birdmae_s1234.pt b/legacy/final/checkpoints/arm_birdmae_s1234.pt new file mode 100644 index 0000000000000000000000000000000000000000..bcd9530f597bc047816f226b94aabe737241f798 --- /dev/null +++ b/legacy/final/checkpoints/arm_birdmae_s1234.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96068fbe76aae1f47fcf0a631f9d2317e9b1f31441f4a6ebfb50affe251ff712 +size 5302713 diff --git a/legacy/final/checkpoints/arm_birdmae_s2023.pt b/legacy/final/checkpoints/arm_birdmae_s2023.pt new file mode 100644 index 0000000000000000000000000000000000000000..c8526b6e0c405b579874063da2e9c0ec47a2d031 --- /dev/null +++ b/legacy/final/checkpoints/arm_birdmae_s2023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c305e2bb41333897e8be6b43fa8430982d6b9f1ff327ebdcd34814656451830 +size 5302713 diff --git a/legacy/final/checkpoints/arm_birdmae_s42.pt b/legacy/final/checkpoints/arm_birdmae_s42.pt new file mode 100644 index 0000000000000000000000000000000000000000..74edacbc9e433956fc6fd266af9be673ad5aac69 --- /dev/null +++ b/legacy/final/checkpoints/arm_birdmae_s42.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d72e97e52b31554cb1db42d7028af5187fbc644cbf40a934747b7f8dd4037f0a +size 5302657 diff --git a/legacy/final/checkpoints/arm_harmonic_s1234.pt b/legacy/final/checkpoints/arm_harmonic_s1234.pt new file mode 100644 index 0000000000000000000000000000000000000000..d5c5dbc90460497e0a80e579b2f0bbd7bfa72224 --- /dev/null +++ b/legacy/final/checkpoints/arm_harmonic_s1234.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28614528dbbe6eefbe8b6e64c6f0e0e73bda280797ce54d885d9e334e152e5ed +size 96901 diff --git a/legacy/final/checkpoints/arm_harmonic_s2023.pt b/legacy/final/checkpoints/arm_harmonic_s2023.pt new file mode 100644 index 0000000000000000000000000000000000000000..d53fb757b273019facfd4ba95e8dd9401dde0a7c --- /dev/null +++ b/legacy/final/checkpoints/arm_harmonic_s2023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:960ed67d5bc0fc96d49ad373020387fcd3ce248f9b2f827695f5b86cbdb5b021 +size 96901 diff --git a/legacy/final/checkpoints/arm_harmonic_s42.pt b/legacy/final/checkpoints/arm_harmonic_s42.pt new file mode 100644 index 0000000000000000000000000000000000000000..33a5ca05784a89a80ce7af1c4b13ba2a29ce2d09 --- /dev/null +++ b/legacy/final/checkpoints/arm_harmonic_s42.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6e3e7c73e06808149ce226c8dd558b6f44c16b2672ad09d6cfec45ad7a22b7e +size 96801 diff --git a/legacy/final/checkpoints/base_perch_s123.pt b/legacy/final/checkpoints/base_perch_s123.pt new file mode 100644 index 0000000000000000000000000000000000000000..1ab5012007779abcd4a2cfe3bfce32bbc6af5747 --- /dev/null +++ b/legacy/final/checkpoints/base_perch_s123.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2447bb132bac1e6f8e4a08791b9093ae07146521edf56fba6adf80c4327770b +size 5832833 diff --git a/legacy/final/checkpoints/base_perch_s1234.pt b/legacy/final/checkpoints/base_perch_s1234.pt new file mode 100644 index 0000000000000000000000000000000000000000..aab2710c89146f125b5c833666210e4825b798fd --- /dev/null +++ b/legacy/final/checkpoints/base_perch_s1234.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2e753aba405627f5b3413f926d096a208735699d6d3cfe4d7780ddacf6db7c1 +size 5832861 diff --git a/legacy/final/checkpoints/base_perch_s2023.pt b/legacy/final/checkpoints/base_perch_s2023.pt new file mode 100644 index 0000000000000000000000000000000000000000..1db2778fd12061099a77f05859bd8225b451e5a3 --- /dev/null +++ b/legacy/final/checkpoints/base_perch_s2023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:166ca097b8a1dc83e8ca38dfea054d968a96a460bbbd688eeb8ec14e529a58aa +size 5832861 diff --git a/legacy/final/checkpoints/base_perch_s256.pt b/legacy/final/checkpoints/base_perch_s256.pt new file mode 100644 index 0000000000000000000000000000000000000000..fd3659298db1b4f992edb25843ce50856e2201b0 --- /dev/null +++ b/legacy/final/checkpoints/base_perch_s256.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45d1a064959c8c2d5710b19066c6262d417f06361f43a49203860dbf44993409 +size 5832833 diff --git a/legacy/final/checkpoints/base_perch_s42.pt b/legacy/final/checkpoints/base_perch_s42.pt new file mode 100644 index 0000000000000000000000000000000000000000..6ef00b382eb26211ce6762327741d0d4a0cf705d --- /dev/null +++ b/legacy/final/checkpoints/base_perch_s42.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5256eb6cf121f5ce843cc476d87dec8bae50a7dcab17982fd51f0716e47db36c +size 5832805 diff --git a/legacy/final/checkpoints/base_perch_s7.pt b/legacy/final/checkpoints/base_perch_s7.pt new file mode 100644 index 0000000000000000000000000000000000000000..363ea0b0efb2154e974cad9d79e7db28ec774c42 --- /dev/null +++ b/legacy/final/checkpoints/base_perch_s7.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d09ec9bb2fbdb62e13789574611f1aa34bceee461e993f42884da408f78ed50 +size 5832777 diff --git a/legacy/final/checkpoints/base_perch_s777.pt b/legacy/final/checkpoints/base_perch_s777.pt new file mode 100644 index 0000000000000000000000000000000000000000..29edd395360148f9e2b8f58d670eee24fa6e1070 --- /dev/null +++ b/legacy/final/checkpoints/base_perch_s777.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:543ad5fdf750ad863355cbada7e83f2973c7abea58ee2db27021d2c88a4d1d51 +size 5832833 diff --git a/legacy/final/checkpoints/base_perch_s99.pt b/legacy/final/checkpoints/base_perch_s99.pt new file mode 100644 index 0000000000000000000000000000000000000000..6a2c3d4a679ca0838f1554bc6fc80d2248a7cc18 --- /dev/null +++ b/legacy/final/checkpoints/base_perch_s99.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62f361355f32327de0d1341807701e798a17df6da43e77a54f35ccf5236fa262 +size 5832805 diff --git a/legacy/final/checkpoints_backup_2voter/arm_birdmae_s1234.pt b/legacy/final/checkpoints_backup_2voter/arm_birdmae_s1234.pt new file mode 100644 index 0000000000000000000000000000000000000000..bcd9530f597bc047816f226b94aabe737241f798 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/arm_birdmae_s1234.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96068fbe76aae1f47fcf0a631f9d2317e9b1f31441f4a6ebfb50affe251ff712 +size 5302713 diff --git a/legacy/final/checkpoints_backup_2voter/arm_birdmae_s2023.pt b/legacy/final/checkpoints_backup_2voter/arm_birdmae_s2023.pt new file mode 100644 index 0000000000000000000000000000000000000000..c8526b6e0c405b579874063da2e9c0ec47a2d031 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/arm_birdmae_s2023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c305e2bb41333897e8be6b43fa8430982d6b9f1ff327ebdcd34814656451830 +size 5302713 diff --git a/legacy/final/checkpoints_backup_2voter/arm_birdmae_s42.pt b/legacy/final/checkpoints_backup_2voter/arm_birdmae_s42.pt new file mode 100644 index 0000000000000000000000000000000000000000..74edacbc9e433956fc6fd266af9be673ad5aac69 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/arm_birdmae_s42.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d72e97e52b31554cb1db42d7028af5187fbc644cbf40a934747b7f8dd4037f0a +size 5302657 diff --git a/legacy/final/checkpoints_backup_2voter/arm_harmonic_s1234.pt b/legacy/final/checkpoints_backup_2voter/arm_harmonic_s1234.pt new file mode 100644 index 0000000000000000000000000000000000000000..d5c5dbc90460497e0a80e579b2f0bbd7bfa72224 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/arm_harmonic_s1234.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28614528dbbe6eefbe8b6e64c6f0e0e73bda280797ce54d885d9e334e152e5ed +size 96901 diff --git a/legacy/final/checkpoints_backup_2voter/arm_harmonic_s2023.pt b/legacy/final/checkpoints_backup_2voter/arm_harmonic_s2023.pt new file mode 100644 index 0000000000000000000000000000000000000000..d53fb757b273019facfd4ba95e8dd9401dde0a7c --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/arm_harmonic_s2023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:960ed67d5bc0fc96d49ad373020387fcd3ce248f9b2f827695f5b86cbdb5b021 +size 96901 diff --git a/legacy/final/checkpoints_backup_2voter/arm_harmonic_s42.pt b/legacy/final/checkpoints_backup_2voter/arm_harmonic_s42.pt new file mode 100644 index 0000000000000000000000000000000000000000..33a5ca05784a89a80ce7af1c4b13ba2a29ce2d09 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/arm_harmonic_s42.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6e3e7c73e06808149ce226c8dd558b6f44c16b2672ad09d6cfec45ad7a22b7e +size 96801 diff --git a/legacy/final/checkpoints_backup_2voter/base_perch_s123.pt b/legacy/final/checkpoints_backup_2voter/base_perch_s123.pt new file mode 100644 index 0000000000000000000000000000000000000000..1ab5012007779abcd4a2cfe3bfce32bbc6af5747 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/base_perch_s123.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2447bb132bac1e6f8e4a08791b9093ae07146521edf56fba6adf80c4327770b +size 5832833 diff --git a/legacy/final/checkpoints_backup_2voter/base_perch_s1234.pt b/legacy/final/checkpoints_backup_2voter/base_perch_s1234.pt new file mode 100644 index 0000000000000000000000000000000000000000..aab2710c89146f125b5c833666210e4825b798fd --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/base_perch_s1234.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2e753aba405627f5b3413f926d096a208735699d6d3cfe4d7780ddacf6db7c1 +size 5832861 diff --git a/legacy/final/checkpoints_backup_2voter/base_perch_s2023.pt b/legacy/final/checkpoints_backup_2voter/base_perch_s2023.pt new file mode 100644 index 0000000000000000000000000000000000000000..1db2778fd12061099a77f05859bd8225b451e5a3 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/base_perch_s2023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:166ca097b8a1dc83e8ca38dfea054d968a96a460bbbd688eeb8ec14e529a58aa +size 5832861 diff --git a/legacy/final/checkpoints_backup_2voter/base_perch_s256.pt b/legacy/final/checkpoints_backup_2voter/base_perch_s256.pt new file mode 100644 index 0000000000000000000000000000000000000000..fd3659298db1b4f992edb25843ce50856e2201b0 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/base_perch_s256.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45d1a064959c8c2d5710b19066c6262d417f06361f43a49203860dbf44993409 +size 5832833 diff --git a/legacy/final/checkpoints_backup_2voter/base_perch_s42.pt b/legacy/final/checkpoints_backup_2voter/base_perch_s42.pt new file mode 100644 index 0000000000000000000000000000000000000000..6ef00b382eb26211ce6762327741d0d4a0cf705d --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/base_perch_s42.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5256eb6cf121f5ce843cc476d87dec8bae50a7dcab17982fd51f0716e47db36c +size 5832805 diff --git a/legacy/final/checkpoints_backup_2voter/base_perch_s7.pt b/legacy/final/checkpoints_backup_2voter/base_perch_s7.pt new file mode 100644 index 0000000000000000000000000000000000000000..363ea0b0efb2154e974cad9d79e7db28ec774c42 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/base_perch_s7.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d09ec9bb2fbdb62e13789574611f1aa34bceee461e993f42884da408f78ed50 +size 5832777 diff --git a/legacy/final/checkpoints_backup_2voter/base_perch_s777.pt b/legacy/final/checkpoints_backup_2voter/base_perch_s777.pt new file mode 100644 index 0000000000000000000000000000000000000000..29edd395360148f9e2b8f58d670eee24fa6e1070 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/base_perch_s777.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:543ad5fdf750ad863355cbada7e83f2973c7abea58ee2db27021d2c88a4d1d51 +size 5832833 diff --git a/legacy/final/checkpoints_backup_2voter/base_perch_s99.pt b/legacy/final/checkpoints_backup_2voter/base_perch_s99.pt new file mode 100644 index 0000000000000000000000000000000000000000..6a2c3d4a679ca0838f1554bc6fc80d2248a7cc18 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/base_perch_s99.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62f361355f32327de0d1341807701e798a17df6da43e77a54f35ccf5236fa262 +size 5832805 diff --git a/legacy/final/checkpoints_backup_2voter/bundle.pt b/legacy/final/checkpoints_backup_2voter/bundle.pt new file mode 100644 index 0000000000000000000000000000000000000000..582db9a1f8f378e56c03b48f77ca52b22933432d --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/bundle.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e100d18ddd5d41f1062ca096b7f3feb7a673712f0b23751282b7a913bed4ce1 +size 62838583 diff --git a/legacy/final/checkpoints_backup_2voter/ensemble.json b/legacy/final/checkpoints_backup_2voter/ensemble.json new file mode 100644 index 0000000000000000000000000000000000000000..b654b429c54209eed2fe700c198bc2655bf6a8c1 --- /dev/null +++ b/legacy/final/checkpoints_backup_2voter/ensemble.json @@ -0,0 +1,74 @@ +{ + "pipeline": "agreement_gate_ensemble", + "description": "8-seed Perch base + harmonic arm + BirdMAE arm -> agreement gate", + "members": { + "base_perch": { + "checkpoints": [ + "base_perch_s1234.pt", + "base_perch_s42.pt", + "base_perch_s2023.pt", + "base_perch_s7.pt", + "base_perch_s99.pt", + "base_perch_s123.pt", + "base_perch_s256.pt", + "base_perch_s777.pt" + ], + "modality": "perch", + "arch": "rp", + "standardize": false, + "combine": "softmax-mean", + "selection": "synthval" + }, + "arm_harmonic": { + "checkpoints": [ + "arm_harmonic_s1234.pt", + "arm_harmonic_s42.pt", + "arm_harmonic_s2023.pt" + ], + "modality": "harmonic", + "arch": "harm", + "standardize": true, + "combine": "softmax-mean" + }, + "arm_birdmae": { + "checkpoints": [ + "arm_birdmae_s1234.pt", + "arm_birdmae_s42.pt", + "arm_birdmae_s2023.pt" + ], + "modality": "birdmae", + "arch": "rp", + "standardize": true, + "combine": "softmax-mean" + } + }, + "gate": { + "type": "agreement", + "rule": "override base where harm.argmax==birdmae.argmax and min(conf)>tau", + "tau": 0.4, + "override": "0.5*(harm+birdmae)" + }, + "results": { + "base_BA_unseen": 0.3178, + "gated_BA_unseen": 0.3411, + "gate_delta": 0.0233, + "per_species": { + "aegypti": 0.7969, + "albopictus": 0.3675, + "quinquefasciatus": 0.1399, + "gambiae": 0.0452, + "arabiensis": 0.1478, + "dirus": 0.0, + "pipiens": 0.8824, + "minimus": 0.6364, + "stephensi": 0.0541 + }, + "selector": "synth-shift val (analysis/test_selection.py); seen-val variant in checkpoints_backup_seenval/" + }, + "git_commit": "9b54ec6", + "feature_dims": { + "perch": 1536, + "harmonic": 102, + "birdmae": 1024 + } +} \ No newline at end of file diff --git a/legacy/final/checkpoints_backup_seenval/base_perch_s123.pt b/legacy/final/checkpoints_backup_seenval/base_perch_s123.pt new file mode 100644 index 0000000000000000000000000000000000000000..c829aee2f93f408c7a0ca080ec684fd0045de0cb --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/base_perch_s123.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d6f729c7caa045b2904a768cd45a9d1442e8f0dfac2b6983a52f3a32bcd5faf +size 5832833 diff --git a/legacy/final/checkpoints_backup_seenval/base_perch_s1234.pt b/legacy/final/checkpoints_backup_seenval/base_perch_s1234.pt new file mode 100644 index 0000000000000000000000000000000000000000..860a182887f0bab2571900923ee6682d08cff72d --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/base_perch_s1234.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aca1b63836f175527bc1203c734ef2b53c1a6ccc970308f06f5da6f5a48d3ce5 +size 5832861 diff --git a/legacy/final/checkpoints_backup_seenval/base_perch_s2023.pt b/legacy/final/checkpoints_backup_seenval/base_perch_s2023.pt new file mode 100644 index 0000000000000000000000000000000000000000..f30578eae01257a4486c2fe4c9d07ed3490c94bb --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/base_perch_s2023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fea9f727845497c3fa2ef73fb748e47a13954afc97b8e8d1258b02af2a04868 +size 5832861 diff --git a/legacy/final/checkpoints_backup_seenval/base_perch_s256.pt b/legacy/final/checkpoints_backup_seenval/base_perch_s256.pt new file mode 100644 index 0000000000000000000000000000000000000000..2e18b7baf9697da8d2ec176438bfc57d8299233e --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/base_perch_s256.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99b047654a78cf7e4d11c2bba156c3093358c15d8fddc311dc693b5ee383d615 +size 5832833 diff --git a/legacy/final/checkpoints_backup_seenval/base_perch_s42.pt b/legacy/final/checkpoints_backup_seenval/base_perch_s42.pt new file mode 100644 index 0000000000000000000000000000000000000000..c5c75a67b99b67bb6fd78ef7358cf2a751b3e2d3 --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/base_perch_s42.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b576050da34227ffda8f8f0e36f4c99a8df6417b066aef69c96f7df7393050ab +size 5832805 diff --git a/legacy/final/checkpoints_backup_seenval/base_perch_s7.pt b/legacy/final/checkpoints_backup_seenval/base_perch_s7.pt new file mode 100644 index 0000000000000000000000000000000000000000..eb038fb40c892ca893c97f23acac76885d4be237 --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/base_perch_s7.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4080ba2f3982fa07dcc48aafd7bc32c4c966d11031f3308ed2bbca5a084c2994 +size 5832777 diff --git a/legacy/final/checkpoints_backup_seenval/base_perch_s777.pt b/legacy/final/checkpoints_backup_seenval/base_perch_s777.pt new file mode 100644 index 0000000000000000000000000000000000000000..46540624269d5ad6c8f541edede8c7c0079a548c --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/base_perch_s777.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6cbca4937e8363bb8f4e1d7c5b670f58e75ca7e8eddeab4d742eb24139ae6d5 +size 5832833 diff --git a/legacy/final/checkpoints_backup_seenval/base_perch_s99.pt b/legacy/final/checkpoints_backup_seenval/base_perch_s99.pt new file mode 100644 index 0000000000000000000000000000000000000000..54217d24cebdf4c487d7281a0750ea973134942a --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/base_perch_s99.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:350094c6023f9f159724317ded736503f3482888dc9c3661e823fe1755f6cdac +size 5832805 diff --git a/legacy/final/checkpoints_backup_seenval/bundle.pt b/legacy/final/checkpoints_backup_seenval/bundle.pt new file mode 100644 index 0000000000000000000000000000000000000000..b588648467211bd7d6e3de7db3af6bf4d6ff5f38 --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/bundle.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59b82e3bc8d7d47dabbeacd4bae77b9110eb9706e10b0d5aac1493158c3e5827 +size 62838455 diff --git a/legacy/final/checkpoints_backup_seenval/ensemble.json b/legacy/final/checkpoints_backup_seenval/ensemble.json new file mode 100644 index 0000000000000000000000000000000000000000..bc8a262a0b8d4cd86941c576a22a9fed70cd199f --- /dev/null +++ b/legacy/final/checkpoints_backup_seenval/ensemble.json @@ -0,0 +1,72 @@ +{ + "pipeline": "agreement_gate_ensemble", + "description": "8-seed Perch base + harmonic arm + BirdMAE arm -> agreement gate", + "members": { + "base_perch": { + "checkpoints": [ + "base_perch_s1234.pt", + "base_perch_s42.pt", + "base_perch_s2023.pt", + "base_perch_s7.pt", + "base_perch_s99.pt", + "base_perch_s123.pt", + "base_perch_s256.pt", + "base_perch_s777.pt" + ], + "modality": "perch", + "arch": "rp", + "standardize": false, + "combine": "softmax-mean" + }, + "arm_harmonic": { + "checkpoints": [ + "arm_harmonic_s1234.pt", + "arm_harmonic_s42.pt", + "arm_harmonic_s2023.pt" + ], + "modality": "harmonic", + "arch": "harm", + "standardize": true, + "combine": "softmax-mean" + }, + "arm_birdmae": { + "checkpoints": [ + "arm_birdmae_s1234.pt", + "arm_birdmae_s42.pt", + "arm_birdmae_s2023.pt" + ], + "modality": "birdmae", + "arch": "rp", + "standardize": true, + "combine": "softmax-mean" + } + }, + "gate": { + "type": "agreement", + "rule": "override base where harm.argmax==birdmae.argmax and min(conf)>tau", + "tau": 0.4, + "override": "0.5*(harm+birdmae)" + }, + "results": { + "base_BA_unseen": 0.3128336430842054, + "gated_BA_unseen": 0.33764640138355856, + "gate_delta": 0.024812758299353144, + "per_species": { + "aegypti": 0.7917, + "albopictus": 0.3652, + "quinquefasciatus": 0.1324, + "gambiae": 0.0367, + "arabiensis": 0.1401, + "dirus": 0.0, + "pipiens": 0.8824, + "minimus": 0.6364, + "stephensi": 0.0541 + } + }, + "git_commit": "9b54ec6", + "feature_dims": { + "perch": 1536, + "harmonic": 102, + "birdmae": 1024 + } +} \ No newline at end of file diff --git a/legacy/final/ensemble.json b/legacy/final/ensemble.json new file mode 100644 index 0000000000000000000000000000000000000000..ad5057db845c6b42cdf8ed9ebe4528fd3bd52a8b --- /dev/null +++ b/legacy/final/ensemble.json @@ -0,0 +1,95 @@ +{ + "pipeline": "agreement_gate_ensemble", + "description": "8-seed Perch base + harmonic arm + BirdMAE arm -> agreement gate", + "members": { + "base_perch": { + "checkpoints": [ + "base_perch_s1234.pt", + "base_perch_s42.pt", + "base_perch_s2023.pt", + "base_perch_s7.pt", + "base_perch_s99.pt", + "base_perch_s123.pt", + "base_perch_s256.pt", + "base_perch_s777.pt" + ], + "modality": "perch", + "arch": "rp", + "standardize": false, + "combine": "softmax-mean", + "selection": "synthval" + }, + "arm_harmonic": { + "checkpoints": [ + "arm_harmonic_s1234.pt", + "arm_harmonic_s42.pt", + "arm_harmonic_s2023.pt" + ], + "modality": "harmonic", + "arch": "harm", + "standardize": true, + "combine": "softmax-mean" + }, + "arm_birdmae": { + "checkpoints": [ + "arm_birdmae_s1234.pt", + "arm_birdmae_s42.pt", + "arm_birdmae_s2023.pt" + ], + "modality": "birdmae", + "arch": "rp", + "standardize": true, + "combine": "softmax-mean" + }, + "arm_bgwhiten": { + "checkpoints": [ + "arm_bgwhiten_s1234.pt", + "arm_bgwhiten_s42.pt", + "arm_bgwhiten_s2023.pt", + "arm_bgwhiten_s7.pt", + "arm_bgwhiten_s99.pt" + ], + "modality": "bgwhiten", + "arch": "rp", + "standardize": true, + "combine": "softmax-mean", + "feature": "background-whitened 257-d spectrum (analysis/extract_bgwhiten_full.py)" + } + }, + "gate": { + "type": "agreement_unanimous_3", + "rule": "override base where harmonic.argmax==birdmae.argmax==bgwhiten.argmax and min(conf)>tau", + "tau": 0.3, + "override": "mean(harm,birdmae,bgwhiten)", + "voters": [ + "arm_harmonic", + "arm_birdmae", + "arm_bgwhiten" + ] + }, + "results": { + "base_BA_unseen": 0.3178, + "two_voter_BA_unseen": 0.3411, + "gated_BA_unseen": 0.3616, + "gate_delta_vs_2voter": 0.0204, + "per_species": { + "aegypti": 0.8125, + "albopictus": 0.3795, + "quinquefasciatus": 0.1964, + "gambiae": 0.0465, + "arabiensis": 0.1923, + "dirus": 0.0, + "pipiens": 0.8824, + "minimus": 0.6364, + "stephensi": 0.1081 + }, + "note": "bgwhiten 3rd voter acts as a precision VETO; gains on large-n movers arabiensis/quinque; LOSO-stable; 2-voter backup in checkpoints_backup_2voter/" + }, + "git_commit": "9b54ec6", + "feature_dims": { + "perch": 1536, + "harmonic": 102, + "birdmae": 1024, + "bgwhiten": 257 + } +} \ No newline at end of file diff --git a/legacy/final/ensemble_model.py b/legacy/final/ensemble_model.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ce04581925cdf5fe15b2a5142a89c8731a425c --- /dev/null +++ b/legacy/final/ensemble_model.py @@ -0,0 +1,68 @@ +"""Single-object wrapper for the whole gated ensemble. Load ONE file (bundle.pt) and call .predict_proba(). + + from ensemble_model import GatedEnsemble + ens = GatedEnsemble("final/bundle.pt") + probs = ens.predict_proba(perch_emb, harmonic_feat, birdmae_emb, bgwhiten_feat) # (N,9) gated probabilities + labels = probs.argmax(1) # 0..8 species index + +Inputs are the four representations for the SAME N clips: + perch_emb (N,1536) Perch v2 mean-pooled embedding + harmonic_feat (N,102) from final/harmonic_features.harmonic_feature(...) + birdmae_emb (N,1024) BirdMAE embedding + bgwhiten_feat (N,257) from final/bgwhiten_features.bgwhiten_feature(...) (background-whitened spectrum) +The wrapper holds every member model + its standardization stats + the gate tau, so there is nothing else to +wire up. bundle.pt is produced by final/bundle_ensemble.py from the 19 per-member checkpoints. The gate is +UNANIMOUS-3: override base only where harmonic, birdmae AND bgwhiten all agree confidently (bgwhiten vetoes +bad overrides -> keeps the movers). +""" +import os, sys +import numpy as np, torch, torch.nn.functional as F +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from model import build + +# group -> which input argument feeds it +_GROUP_INPUT = {"base_perch": "perch", "arm_harmonic": "harmonic", "arm_birdmae": "birdmae", "arm_bgwhiten": "bgwhiten"} + + +class GatedEnsemble: + def __init__(self, bundle, device=None): + if isinstance(bundle, str): + bundle = torch.load(bundle, map_location="cpu", weights_only=False) + self.device = device or ("cuda" if torch.cuda.is_available() else "cpu") + self.tau = bundle["tau"] + self.meta = bundle.get("meta", {}) + self.models = {} # group -> list of (model, mean, std, standardize) + for group, members in bundle["members"].items(): + self.models[group] = [] + for ck in members: + m = build(ck["arch"], ck["feature_dim"]).to(self.device) + m.load_state_dict(ck["state"]); m.eval() + self.models[group].append((m, ck["mean"], ck["std"], ck["standardize"])) + + @torch.no_grad() + def _group_probs(self, group, X): + """Average softmax over all seed models in a group.""" + X = np.asarray(X, dtype=np.float32) + probs = [] + for m, mean, std, std_flag in self.models[group]: + x = (X - mean) / std if std_flag else X + probs.append(F.softmax(m(torch.tensor(x, dtype=torch.float32, device=self.device))[0], 1).cpu().numpy()) + return np.mean(probs, 0) + + def member_probs(self, perch_emb, harmonic_feat, birdmae_emb, bgwhiten_feat): + """Return the group ensemble probability arrays (before the gate).""" + ins = {"perch": perch_emb, "harmonic": harmonic_feat, "birdmae": birdmae_emb, "bgwhiten": bgwhiten_feat} + return {g: self._group_probs(g, ins[_GROUP_INPUT[g]]) for g in self.models} + + def predict_proba(self, perch_emb, harmonic_feat, birdmae_emb, bgwhiten_feat): + """Full gated ensemble probabilities (N,9). UNANIMOUS-3 gate: override base only where the three + device-invariant voters (harmonic, birdmae, bgwhiten) all agree, min-confidence > tau.""" + p = self.member_probs(perch_emb, harmonic_feat, birdmae_emb, bgwhiten_feat) + pb = p["base_perch"]; voters = [p["arm_harmonic"], p["arm_birdmae"], p["arm_bgwhiten"]] + A = np.stack([v.argmax(1) for v in voters], 1); M = np.stack([v.max(1) for v in voters], 1) + fire = (A[:, 0] == A[:, 1]) & (A[:, 1] == A[:, 2]) & (M.min(1) > self.tau) + out = pb.copy(); out[fire] = np.mean([v[fire] for v in voters], 0) + return out + + def predict(self, perch_emb, harmonic_feat, birdmae_emb, bgwhiten_feat): + return self.predict_proba(perch_emb, harmonic_feat, birdmae_emb, bgwhiten_feat).argmax(1) diff --git a/legacy/final/harmonic_features.py b/legacy/final/harmonic_features.py new file mode 100644 index 0000000000000000000000000000000000000000..06c5c224e7e4bfdd556498b68cbfc745d5cb0800 --- /dev/null +++ b/legacy/final/harmonic_features.py @@ -0,0 +1,62 @@ +"""Device-INVARIANT physics harmonic feature (102-d) used by the harmonic ensemble member. +Rationale: the recording-device shift is a smooth spectral-ENVELOPE EQ tilt; it corrupts the envelope (which +every foundation model encodes) but PRESERVES the harmonic comb / wingbeat fundamental f0. This feature throws +away the envelope (low-quefrency cepstrum) and keeps the comb, so it transfers across devices where Perch +collapses (kill-test D5->D1: harmonic 0.55 vs Perch 0.14). + +Feature = concat(liftered_cepstrum[93], f0harm[9]): + liftered_cepstrum: real cepstrum of the mean log-magnitude spectrum, keeping only the pitch quefrency band + [SR/1200 .. SR/150] -> the EQ envelope (low quefrency) is dropped (device-invariant). + f0harm: [f0_median/600, f0_std/200, voiced_fraction, 6 normalized harmonic amplitudes on the whitened spectrum] +""" +import os, warnings +warnings.filterwarnings("ignore") +import numpy as np +import librosa +import soundfile as sf + +SR = 16000; DUR = 1.0; NS = int(SR * DUR); N_FFT = 512; HOP = 128 +Q_LO = int(SR / 1200); Q_HI = int(SR / 150) # pitch quefrency band -> ~13..106 (93 coeffs) +HARM_DIM = (Q_HI - Q_LO) + 9 # 93 + 9 = 102 + + +def load_wav(path): + y, sr = sf.read(path) + if y.ndim > 1: y = y.mean(1) + y = y.astype(np.float32) + if sr != SR: y = librosa.resample(y, orig_sr=sr, target_sr=SR) + y = y[:NS] if len(y) >= NS else np.pad(y, (0, NS - len(y))) + m = np.abs(y).max() + return y / m if m > 0 else y + + +def harmonic_feature(y): + """Raw mono waveform -> 102-d device-invariant harmonic vector.""" + S = np.abs(librosa.stft(y, n_fft=N_FFT, hop_length=HOP)) + 1e-8 + meanlog = np.log(S).mean(1) + cep = np.fft.irfft(meanlog, n=N_FFT) + liftered = cep[Q_LO:Q_HI].copy() # pitch/comb only (EQ envelope removed) + try: + f0 = librosa.yin(y, fmin=150, fmax=1200, sr=SR, frame_length=N_FFT) + f0 = f0[np.isfinite(f0)] + except Exception: + f0 = np.array([]) + if len(f0): + f0med, f0std, voiced = float(np.median(f0)), float(np.std(f0)), len(f0) / max(1, len(y) // HOP) + else: + f0med = f0std = voiced = 0.0 + env = np.fft.rfft(np.concatenate([cep[:Q_LO], np.zeros(N_FFT - Q_LO)]))[:len(meanlog)].real + white = meanlog - env + freqs = np.fft.rfftfreq(N_FFT, 1 / SR) + hr = [] + if f0med > 0: + for k in range(1, 7): + fk = k * f0med + if fk < freqs[-1]: hr.append(white[np.argmin(np.abs(freqs - fk))]) + hr = np.array(hr + [0.0] * (6 - len(hr))) + f0harm = np.array([f0med / 600.0, f0std / 200.0, voiced] + list(hr / (np.abs(hr).max() + 1e-6)), np.float32) + return np.concatenate([liftered.astype(np.float32), f0harm]).astype(np.float32) + + +def harmonic_feature_from_path(path): + return harmonic_feature(load_wav(path)) diff --git a/legacy/final/infer.py b/legacy/final/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..7543884741d828cbdf0143448b9b7f88abbc8d28 --- /dev/null +++ b/legacy/final/infer.py @@ -0,0 +1,93 @@ +"""Run the CD-MSC best ensemble end-to-end from saved checkpoints and reproduce test BA_unseen. + +Pipeline: + 1. For each member group (base_perch / arm_harmonic / arm_birdmae / arm_bgwhiten): load every seed checkpoint, + standardize the member's input with the checkpoint's saved (mean,std), forward, softmax, average over seeds. + 2. UNANIMOUS-3 AGREEMENT GATE: start from the base-Perch ensemble; on clips where the harmonic, BirdMAE AND + background-whitened ensembles ALL agree on the same class with min-confidence > tau, override the base with + the mean of the three. The 3rd (background-whitened) voter acts as a precision VETO: it stops the gate from + over-firing and sacrificing the movers, lifting arabiensis/quinque while keeping aegypti. + 3. Report BA_unseen (mean per-species recall on each species' held-out unseen domain) + per-species. + +Embeddings are read from the project cache (data/perch/*.npz + the BirdMAE parquet). To score NEW raw audio you +would first produce Perch (1536-d) and BirdMAE (1024-d) embeddings with those frozen models, the 102-d harmonic +feature via final/harmonic_features.py, and the 257-d background-whitened spectrum via final/bgwhiten_features.py. +Run: python final/infer.py +""" +import os, sys, json, glob +import numpy as np, torch, torch.nn.functional as F +HERE = os.path.dirname(os.path.abspath(__file__)); ROOT = os.path.dirname(HERE) +sys.path.insert(0, HERE); sys.path.insert(0, ROOT) +from model import build +from framework.metadata import SPECIES_NAMES, DOMAIN_NAMES +DEV = "cuda" if torch.cuda.is_available() else "cpu" +P = os.path.join(ROOT, "data/perch"); CKPT = os.path.join(HERE, "checkpoints") + +def ba(p, y, n=9): + r = [(p[y == c] == c).mean() for c in range(n) if (y == c).any()] + return float(np.mean(r)) if r else 0.0 +def per_species(p, y): + return {SPECIES_NAMES[c].split()[1]: round(float((p[y == c] == c).mean()), 4) for c in range(9) if (y == c).any()} + +# ---- test labels + unseen mask ---- +d = np.load(f"{P}/test.npz", allow_pickle=True) +perch_te = d["emb"].astype(np.float32); yte = d["species"].astype(int); dte = d["domain"].astype(int) +fte = np.array([str(f) for f in d["file_id"]]) +sm = json.load(open(f"{ROOT}/data/metadata/split_summary.json")) +ud = {SPECIES_NAMES.index(k): DOMAIN_NAMES.index(v) for k, v in sm["unseen_domain_by_species"].items()} +teu = np.array([dte[i] == ud.get(int(yte[i]), -1) for i in range(len(yte))]); yy = yte[teu] + +def load_member_test(modality): + if modality == "perch": + return perch_te + if modality == "harmonic": + h = np.load(f"{P}/harmonic_test.npz", allow_pickle=True); idx = {str(f): i for i, f in enumerate(h["file_id"])} + return h["harm"].astype(np.float32)[np.array([idx[f] for f in fte])] + if modality == "bgwhiten": + h = np.load(f"{P}/bgwhiten_test.npz", allow_pickle=True); idx = {str(f): i for i, f in enumerate(h["file_id"])} + return h["bgw"].astype(np.float32)[np.array([idx[f] for f in fte])] + if modality == "birdmae": + import pyarrow.parquet as pq + t = pq.read_table("/home/alaska/Projects/Cross-Domain-Mosquito-Species-Classification-Tensorflow/reports/fm_embeddings/birdmae.parquet") + fid = np.array(t.column("file_id").to_pylist()); DIM = len(t.column("embedding")[0].as_py()) + emb = t.column("embedding").combine_chunks().values.to_numpy().reshape(-1, DIM).astype(np.float32); idx = {f: i for i, f in enumerate(fid)} + return np.array([emb[idx[f]] if f in idx else np.zeros(DIM, np.float32) for f in fte]) + raise ValueError(modality) + +def ensemble_probs(group_prefix): + """Average softmax over all seed checkpoints of a member group on the test set.""" + cks = sorted(glob.glob(os.path.join(CKPT, f"{group_prefix}_s*.pt"))) + assert cks, f"no checkpoints for {group_prefix} in {CKPT}" + probs = [] + for cp in cks: + st = torch.load(cp, map_location=DEV, weights_only=False) + X = load_member_test(st["modality"]) + if st.get("standardize", False): + X = (X - st["mean"]) / st["std"] + mo = build(st["arch"], st["feature_dim"]).to(DEV); mo.load_state_dict(st["model_state_dict"]); mo.eval() + with torch.no_grad(): + probs.append(F.softmax(mo(torch.tensor(X, dtype=torch.float32).to(DEV))[0], 1).cpu().numpy()) + return np.mean(probs, 0), len(cks) + +def main(): + man = json.load(open(os.path.join(HERE, "ensemble.json"))) + tau = man["gate"]["tau"] + base, nb = ensemble_probs("base_perch") + harm, nh = ensemble_probs("arm_harmonic") + bird, nm = ensemble_probs("arm_birdmae") + bgw, nw = ensemble_probs("arm_bgwhiten") + print(f"members: base_perch x{nb}, arm_harmonic x{nh}, arm_birdmae x{nm}, arm_bgwhiten x{nw}; gate={man['gate']['type']} tau={tau}") + base_ba = ba(base[teu].argmax(1), yy) + # unanimous-3 agreement gate: all three voters agree on the same class, min-confidence > tau + voters = [harm, bird, bgw] + A = np.stack([v.argmax(1) for v in voters], 1); M = np.stack([v.max(1) for v in voters], 1) + fire = (A[:, 0] == A[:, 1]) & (A[:, 1] == A[:, 2]) & (M.min(1) > tau) + gated = base.copy(); gated[fire] = np.mean([v[fire] for v in voters], 0) + gba = ba(gated[teu].argmax(1), yy) + print(f"\nbase Perch ensemble BA_unseen = {base_ba:.4f}") + print(f"+ unanimous-3 gate BA_unseen = {gba:.4f} (+{gba-base_ba:.4f}, fired on {int(fire[teu].sum())}/{int(teu.sum())} unseen clips)") + print(f"per-species: {per_species(gated[teu].argmax(1), yy)}") + return gba + +if __name__ == "__main__": + main() diff --git a/legacy/final/losses.py b/legacy/final/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..fc37bddc77b79a3f6a7109a09aabccaf66b0ccd0 --- /dev/null +++ b/legacy/final/losses.py @@ -0,0 +1,103 @@ +"""Loss functions for the CD-MSC best ensemble. The training objective per member is: + + L = CE(species) # primary species cross-entropy + + 0.01 * CE(domain) # auxiliary domain classifier (plain aux head, NOT adversarial) + + 0.50 * genus_aux(species, y) # hierarchical genus consistency (Aedes/Culex/Anopheles) + + 0.50 * supcon(e, y; T=0.10) # supervised contrastive on the L2-normalized embedding + + 1.00 * coral(e, domain) # Deep CORAL: align 2nd-order (covariance) stats across domains + + 0.25 * mmd(e, domain) # multi-kernel MMD: align distributions across domains <-- the key lever + +`e` is the post-LayerNorm embedding from the probe. MMD weight 0.25 is the measured optimum of this port +(the sibling's 1.0 was a different kernel-scale operating point). SupCon uses L2 normalization (p=2) — an +earlier L1 bug made it inert. Domains are the 5 recording devices D1..D5; the DG losses (MMD/CORAL) pull the +per-domain embedding distributions together so the classifier can't lean on the device "style" shortcut. +""" +import torch, torch.nn.functional as F + +# species (0-indexed) -> genus index: Aedes={aegypti,albopictus}, Culex={quinque,pipiens}, Anopheles={the rest} +SPECIES_TO_GENUS = torch.tensor([0, 0, 1, 2, 2, 2, 1, 2, 2]) +# multi-kernel Gaussian bandwidths (median-heuristic ladder), in standardized embedding space +MMD_SIGMAS = [0.79, 1.58, 3.15, 6.30, 12.60] + + +def genus_aux(species_logits, y, G=None): + """Marginalize species softmax into genus probabilities and apply NLL against the true genus. + Encourages the cross-genus structure to stay correct even when within-genus species are confused.""" + G = SPECIES_TO_GENUS.to(species_logits.device) if G is None else G + NG = int(G.max()) + 1 + p = F.softmax(species_logits, 1) + gp = species_logits.new_zeros(p.size(0), NG).index_add_(1, G, p) + return F.nll_loss(gp.clamp_min(1e-8).log(), G[y]) + + +def _supcon(h, pos_mask, T): + z = F.normalize(h, p=2, dim=1) # L2 normalize (critical) + B = z.size(0) + eye = torch.eye(B, device=z.device, dtype=torch.bool) + sim = (z @ z.T) / T + sim = sim.masked_fill(eye, -float("inf")) + pos = pos_mask & ~eye + lp = torch.log_softmax(sim, 1) + lp = torch.where(pos, lp, torch.zeros_like(lp)) + pc = pos.sum(1).float() + has = pc > 0 + return -(torch.where(has, lp.sum(1) / pc.clamp_min(1), torch.zeros_like(pc)).sum() / has.sum().clamp_min(1)) + + +def supcon(h, y, T=0.10): + """Supervised contrastive: pull same-species embeddings together (positives = same label).""" + return _supcon(h, (y[:, None] == y[None, :]), T) + + +def dicl(h, d, T=0.07): + """Domain-invariant contrastive (different-domain positives). Tested, did NOT help — kept for reference.""" + return _supcon(h, (d[:, None] != d[None, :]), T) + + +def _gaussian_multi(a, b): + d2 = ((a * a).sum(1, keepdim=True) - 2 * a @ b.T + (b * b).sum(1)[None, :]).clamp_min(0) + return sum(torch.exp(-d2 / (2 * s * s)) for s in MMD_SIGMAS) + + +def mmd(h, domain): + """Multi-kernel Gaussian MMD averaged over all unordered domain pairs present in the batch. + This is THE lever: aligning the per-domain embedding distributions raised BA_unseen ~0.25 -> ~0.33.""" + t = h.new_tensor(0.0); n = 0 + for i in range(5): + mi = domain == i + if mi.sum() < 2: continue + for j in range(i + 1, 5): + mj = domain == j + if mj.sum() < 2: continue + a, b = h[mi], h[mj]; na, nb = a.size(0), b.size(0) + kaa = _gaussian_multi(a, a); kbb = _gaussian_multi(b, b); kab = _gaussian_multi(a, b) + t = t + (kaa.sum() - kaa.trace()) / (na * (na - 1)) + (kbb.sum() - kbb.trace()) / (nb * (nb - 1)) - 2 * kab.mean() + n += 1 + return t / max(n, 1) + + +def coral(h, domain): + """Deep CORAL: squared Frobenius distance between per-domain feature covariances, /(4 D^2).""" + t = h.new_tensor(0.0); n = 0; D = h.size(1); cov = {} + for i in range(5): + m = domain == i + if m.sum() >= 2: + c = h[m] - h[m].mean(0, keepdim=True) + cov[i] = (c.T @ c) / (m.sum() - 1) + ks = list(cov) + for a in range(len(ks)): + for b in range(a + 1, len(ks)): + t = t + ((cov[ks[a]] - cov[ks[b]]) ** 2).sum() / (4 * D * D); n += 1 + return t / max(n, 1) + + +def total_loss(species_logits, domain_logits, emb, y, domain, + w_domain=0.01, w_genus=0.5, w_supcon=0.5, w_coral=1.0, w_mmd=0.25): + """The exact training objective used for every ensemble member.""" + loss = F.cross_entropy(species_logits, y) + loss = loss + w_domain * F.cross_entropy(domain_logits, domain) + loss = loss + w_genus * genus_aux(species_logits, y) + loss = loss + w_supcon * supcon(emb, y, 0.10) + loss = loss + w_coral * coral(emb, domain) + loss = loss + w_mmd * mmd(emb, domain) + return loss diff --git a/legacy/final/model.py b/legacy/final/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c556bf31424276dea621ffe73010f4b97f790b03 --- /dev/null +++ b/legacy/final/model.py @@ -0,0 +1,77 @@ +"""Model definitions for the CD-MSC best ensemble (frozen-embedding probes). +Two architectures, both consuming a frozen foundation-model / physics embedding and emitting 9 species logits: + - RP : rich Pre-LN residual probe, used for the Perch (1536-d) and BirdMAE (1024-d) members. + - HarmNet : small MLP, used for the 102-d physics harmonic feature member. +Both also carry an auxiliary 5-way domain head (`dm`) used only during training (domain-aux / for MMD/CORAL on +the embedding); it is unused at inference. The architecture must match the training script exactly so saved +checkpoints load cleanly. +""" +import torch, torch.nn as nn, torch.nn.functional as F + + +class ResidualBlock(nn.Module): + """Pre-LayerNorm residual MLP block: x + Dropout(W2 GELU(W1 LN(x))).""" + def __init__(self, d, p=0.2): + super().__init__() + self.ln = nn.LayerNorm(d, eps=1e-6) + self.f1 = nn.Linear(d, d * 4) + self.f2 = nn.Linear(d * 4, d) + self.d1 = nn.Dropout(p) + self.d2 = nn.Dropout(p) + + def forward(self, x): + return x + self.d2(self.f2(self.d1(F.gelu(self.f1(self.ln(x)))))) + + +class RP(nn.Module): + """Rich probe for high-dim FM embeddings (Perch / BirdMAE). + input LayerNorm -> Linear(d->256) -> 2x ResidualBlock -> LayerNorm -> {species head, domain head}. + Training-time augmentation (active only in .train()): additive Gaussian embedding noise (sigma=0.05) and + feature channel-dropout (p=0.1). `e` is the L2-normalizable embedding used by SupCon/MMD/CORAL. + """ + def __init__(self, d, pd=256, p=0.2, noise=0.05, chdrop=0.1): + super().__init__() + self.iln = nn.LayerNorm(d, eps=1e-6) + self.pr = nn.Linear(d, pd) + self.b = nn.ModuleList([ResidualBlock(pd, p), ResidualBlock(pd, p)]) + self.po = nn.LayerNorm(pd, eps=1e-6) + self.sp = nn.Linear(pd, 9) # species logits + self.dm = nn.Linear(pd, 5) # auxiliary domain logits (training only) + self.noise = noise + self.chdrop = chdrop + + def forward(self, x): + if self.training: + x = x + torch.randn_like(x) * self.noise + x = x * (torch.rand(x.shape[1], device=x.device) > self.chdrop).float()[None, :] + h = self.pr(self.iln(x)) + for bl in self.b: + h = bl(h) + e = self.po(h) + return self.sp(e), self.dm(e), e + + +class HarmNet(nn.Module): + """Dedicated MLP for the 102-d physics harmonic feature (device-invariant comb / f0). + LN -> Linear(d->128) -> GELU -> Dropout(0.2) -> Linear(128->64) -> LN -> {species head, domain head}. + Training-time additive noise sigma=0.03. + """ + def __init__(self, d): + super().__init__() + self.net = nn.Sequential( + nn.LayerNorm(d, eps=1e-6), nn.Linear(d, 128), nn.GELU(), + nn.Dropout(0.2), nn.Linear(128, 64), nn.LayerNorm(64, eps=1e-6), + ) + self.sp = nn.Linear(64, 9) + self.dm = nn.Linear(64, 5) + + def forward(self, x): + if self.training: + x = x + torch.randn_like(x) * 0.03 + e = self.net(x) + return self.sp(e), self.dm(e), e + + +def build(arch, d): + """Factory: arch in {'rp','harm'} -> model for a d-dim input embedding.""" + return HarmNet(d) if arch == "harm" else RP(d) diff --git a/legacy/final/predict_eval.py b/legacy/final/predict_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..36bccbe8b9360bcbb755d0c9df56feb9bd229ffa --- /dev/null +++ b/legacy/final/predict_eval.py @@ -0,0 +1,176 @@ +"""Score the released BioDCASE-2026 Task 5 evaluation clips with the deployed unanimous-3 +agreement-gate ensemble and write the official submission .txt. + +Pipeline (mirrors final/infer.py, but on the eval set instead of cached test): + 1. Perch (1536-d) and BirdMAE (1024-d) embeddings are read from parquets produced by the + sibling repo's scripts/extract_fm_embeddings.py (frozen FMs, cannot run in this repo). + 2. Harmonic (102-d) and background-whitened (257-d) features are computed here, directly + from each eval wav, with the SAME helpers the deployed members were trained on. + 3. GatedEnsemble(bundle.pt).predict_proba(perch, harmonic, birdmae, bgwhiten) -> (N,9). + 4. argmax -> class index 0..8 -> OFFICIAL 1-based predicted_species_id via framework.metadata. + 5. write file_id,predicted_species_id rows (file_id without .wav). + +Run with the sibling TF venv python (has torch + librosa + soundfile + pyarrow): + .../Cross-Domain-Mosquito-Species-Classification-Tensorflow/.venv/bin/python final/predict_eval.py +Add --self-test to first confirm the bundle reproduces dev BA_unseen ~= 0.3616 on cached test. +""" +import os, sys, glob, argparse, json +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +sys.path.insert(0, HERE) # final/ : ensemble_model, harmonic_features, bgwhiten_features, model +sys.path.insert(0, ROOT) # repo root : framework/ + +from framework.metadata import SPECIES_NAMES, SPECIES_ID_TO_NAME, DOMAIN_NAMES # noqa: E402 +import harmonic_features as HF # noqa: E402 +import bgwhiten_features as BG # noqa: E402 + +# class index 0..8 -> official 1-based species id, DERIVED from metadata (not a literal +1) +_NAME_TO_SPECIES_ID = {name: int(sid) for sid, name in SPECIES_ID_TO_NAME.items()} +IDX_TO_SPECIES_ID = [_NAME_TO_SPECIES_ID[SPECIES_NAMES[i]] for i in range(len(SPECIES_NAMES))] + +EVAL_PARQUET_DIR = "/home/alaska/Projects/Cross-Domain-Mosquito-Species-Classification-Tensorflow/reports/fm_embeddings/eval" +DEV_BIRDMAE_PARQUET = "/home/alaska/Projects/Cross-Domain-Mosquito-Species-Classification-Tensorflow/reports/fm_embeddings/birdmae.parquet" + + +def read_ids(path): + with open(path) as fh: + return [ln.strip() for ln in fh if ln.strip()] + + +def load_parquet_emb(path, ids, dim): + """Return (len(ids), dim) array aligned to `ids` by file_id; missing -> zeros (counted).""" + import pyarrow.parquet as pq + t = pq.read_table(path) + fid = np.array(t.column("file_id").to_pylist()) + emb = t.column("embedding").combine_chunks().values.to_numpy().reshape(-1, dim).astype(np.float32) + idx = {f: i for i, f in enumerate(fid)} + out = np.zeros((len(ids), dim), np.float32) + missing = 0 + for j, f in enumerate(ids): + i = idx.get(f) + if i is None: + missing += 1 + else: + out[j] = emb[i] + return out, missing + + +def _feat_one(args): + """Worker: load one wav once, return (harmonic102, bgwhiten257, ok).""" + audio_root, fid = args + try: + y = HF.load_wav(os.path.join(audio_root, f"{fid}.wav")) + return HF.harmonic_feature(y), BG.bgwhiten_feature(y), True + except Exception: + return np.zeros(HF.HARM_DIM, np.float32), np.zeros(BG.BGW_DIM, np.float32), False + + +def compute_handcrafted(ids, audio_root, workers): + """Harmonic (N,102) + bgwhiten (N,257) for ids, in order. Returns (harm, bgw, n_failed).""" + harm = np.zeros((len(ids), HF.HARM_DIM), np.float32) + bgw = np.zeros((len(ids), BG.BGW_DIM), np.float32) + failed = 0 + work = [(audio_root, f) for f in ids] + if workers and workers > 1: + from concurrent.futures import ProcessPoolExecutor + with ProcessPoolExecutor(max_workers=workers) as ex: + for j, (h, b, ok) in enumerate(ex.map(_feat_one, work, chunksize=32)): + harm[j], bgw[j] = h, b + if not ok: + failed += 1 + if (j + 1) % 2000 == 0: + print(f" handcrafted features {j+1}/{len(ids)}", flush=True) + else: + for j, w in enumerate(work): + h, b, ok = _feat_one(w) + harm[j], bgw[j] = h, b + if not ok: + failed += 1 + if (j + 1) % 2000 == 0: + print(f" handcrafted features {j+1}/{len(ids)}", flush=True) + return harm, bgw, failed + + +def self_test(): + """Confirm GatedEnsemble(bundle) reproduces the deployed dev BA_unseen (~0.3616) on cached test.""" + from ensemble_model import GatedEnsemble + P = os.path.join(ROOT, "data/perch") + d = np.load(f"{P}/test.npz", allow_pickle=True) + perch = d["emb"].astype(np.float32) + yte = d["species"].astype(int); dte = d["domain"].astype(int) + fte = np.array([str(f) for f in d["file_id"]]) + + def by_fid(npz, key): + h = np.load(npz, allow_pickle=True) + idx = {str(f): i for i, f in enumerate(h["file_id"])} + return h[key].astype(np.float32)[np.array([idx[f] for f in fte])] + + harm = by_fid(f"{P}/harmonic_test.npz", "harm") + bgw = by_fid(f"{P}/bgwhiten_test.npz", "bgw") + bird, miss = load_parquet_emb(DEV_BIRDMAE_PARQUET, list(fte), 1024) + sm = json.load(open(f"{ROOT}/data/metadata/split_summary.json")) + ud = {SPECIES_NAMES.index(k): DOMAIN_NAMES.index(v) for k, v in sm["unseen_domain_by_species"].items()} + unseen = np.array([dte[i] == ud.get(int(yte[i]), -1) for i in range(len(yte))]) + + ens = GatedEnsemble(os.path.join(HERE, "bundle.pt")) + probs = ens.predict_proba(perch, harm, bird, bgw) + pred = probs.argmax(1) + yy = yte[unseen]; pp = pred[unseen] + rec = [(pp[yy == c] == c).mean() for c in range(9) if (yy == c).any()] + ba = float(np.mean(rec)) + print(f"[self-test] birdmae missing={miss} gated BA_unseen={ba:.4f} (expect ~0.3616)") + assert abs(ba - 0.3616) < 0.01, f"bundle gate mismatch: {ba:.4f} != 0.3616" + print("[self-test] OK\n") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--audio-root", default=os.path.join(ROOT, "eval")) + ap.add_argument("--ids", default=os.path.join(ROOT, "data/metadata_eval/Test_ids.txt")) + ap.add_argument("--parquet-dir", default=EVAL_PARQUET_DIR) + ap.add_argument("--bundle", default=os.path.join(HERE, "bundle.pt")) + ap.add_argument("--out", default=os.path.join(ROOT, "final_submission/architecture_1/predictions.txt")) + ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1)) + ap.add_argument("--self-test", action="store_true") + args = ap.parse_args() + + if args.self_test: + self_test() + + ids = read_ids(args.ids) + print(f"eval clips: {len(ids)}") + + print("loading Perch + BirdMAE eval embeddings ...") + perch, miss_p = load_parquet_emb(os.path.join(args.parquet_dir, "perch.parquet"), ids, 1536) + bird, miss_b = load_parquet_emb(os.path.join(args.parquet_dir, "birdmae.parquet"), ids, 1024) + print(f" perch missing={miss_p} birdmae missing={miss_b}") + + print(f"computing harmonic + bgwhiten features ({args.workers} workers) ...") + harm, bgw, failed = compute_handcrafted(ids, args.audio_root, args.workers) + print(f" handcrafted done; unreadable clips (zero-filled)={failed}") + + print("running gated ensemble ...") + from ensemble_model import GatedEnsemble + ens = GatedEnsemble(args.bundle) + probs = ens.predict_proba(perch, harm, bird, bgw) + idx = probs.argmax(1) + species_id = np.array([IDX_TO_SPECIES_ID[i] for i in idx], dtype=int) + + os.makedirs(os.path.dirname(args.out), exist_ok=True) + with open(args.out, "w") as fh: + fh.write("file_id,predicted_species_id\n") + for fid, sid in zip(ids, species_id): + fh.write(f"{fid},{sid}\n") + + # report + counts = {int(s): int((species_id == s).sum()) for s in range(1, 10)} + print(f"\nwrote {len(ids)} rows -> {args.out}") + print("predicted_species_id histogram (1-based):") + for s in range(1, 10): + print(f" {s:>2} {SPECIES_ID_TO_NAME[str(s)]:<26} {counts[s]:>6} ({100*counts[s]/len(ids):.1f}%)") + + +if __name__ == "__main__": + main() diff --git a/legacy/final/predict_eval_baseline.py b/legacy/final/predict_eval_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..3412185b34d4bd5fb47ee46fb03a571619fd5fc4 --- /dev/null +++ b/legacy/final/predict_eval_baseline.py @@ -0,0 +1,175 @@ +"""architecture_4 = the MTRCNN baseline with the CONTRASTIVE loss (seed 42), last-epoch +checkpoint (model_final.pth, dev BA_unseen 0.3104). Completely different system from the +frozen-embedding gate: a trained CNN on 8 kHz log-mel. + +Inference reuses the framework building blocks (config -> build_model -> on-the-fly log-mel -> +batched forward -> argmax), like evaluate.py. Two wrinkles handled here: + * the checkpoint embeds a now-renamed `schema.loss.ContrastiveLossParams`, so weights are + extracted with a permissive unpickler (we only need the tensors); + * the model is rebuilt fresh from resolved_config.json (current schema) and the state_dict + loaded into it (strict match: missing=[], unexpected=[]). + +Eval audio is already 8 kHz (== config sample_rate) so no resampling; normalize_features=false +so no training-stats file is needed. Run with the sibling TF venv python: + .../.venv/bin/python final/predict_eval_baseline.py [--self-test] [--checkpoint model_final.pth] +""" +import os, sys, json, types, pickle, io, argparse +import numpy as np, torch +from torch.nn.utils.rnn import pad_sequence + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +sys.path.insert(0, HERE) +sys.path.insert(0, ROOT) + +from framework.acoustic_feature import LogMelSpectrogram, load_waveform # noqa: E402 +from framework.utilization import build_model, choose_device # noqa: E402 +from framework.metadata import SPECIES_NAMES, SPECIES_ID_TO_NAME # noqa: E402 +from schema.trial import TrialConfig # noqa: E402 +from predict_eval import read_ids, IDX_TO_SPECIES_ID # noqa: E402 + +EXP_DIR = os.path.join(ROOT, "experiment-contrastive-patient_seed_42_d741c13") +DEV_RAW = os.path.join(ROOT, "data/raw_audio") + + +# --- load weights past the stale pickled config class --- +class _Any: + def __init__(self, *a, **k): pass + def __setstate__(self, s): + if isinstance(s, dict): self.__dict__.update(s) + def __reduce__(self): return (_Any, ()) + + +def _permissive_load(path, device): + class _U(pickle.Unpickler): + def find_class(self, module, name): + try: return super().find_class(module, name) + except Exception: return _Any + fake = types.ModuleType("permissive_pickle") + fake.Unpickler = _U + fake.load = lambda f, **k: _U(f).load() + fake.loads = lambda b, **k: _U(io.BytesIO(b)).load() + fake.Pickler = pickle.Pickler; fake.dump = pickle.dump; fake.dumps = pickle.dumps + return torch.load(path, map_location=device, weights_only=False, pickle_module=fake) + + +def load_model_and_extractor(checkpoint, device): + cfg = json.load(open(os.path.join(EXP_DIR, "resolved_config.json"))) + config = TrialConfig(**cfg) + model = build_model(config, device) + ck = _permissive_load(os.path.join(EXP_DIR, "model", checkpoint), device) + miss, unexp = model.load_state_dict(ck["model_state_dict"], strict=False) + assert not miss and not unexp, f"state_dict mismatch missing={miss} unexpected={unexp}" + model.eval() + fe = config.feature_extraction + extractor = LogMelSpectrogram(sample_rate=fe.sample_rate, n_fft=fe.n_fft, hop_length=fe.hop_length, + win_length=fe.win_length, n_mels=fe.n_mels, fmin=fe.f_min, fmax=fe.f_max).to(device) + extractor.eval() + return model, extractor, config + + +@torch.no_grad() +def _feature(path, extractor, fe, device, max_samples=None): + """log-mel (T, n_mels); pads short clips to n_fft (parity with the cached extraction, + acoustic_feature.extract_split_features) and centre-crops pathologically long clips.""" + wav = load_waveform(path, fe.sample_rate, fe.normalize_waveform) + if wav.shape[0] < fe.n_fft: + wav = np.pad(wav, (0, fe.n_fft - wav.shape[0])) + if max_samples and wav.shape[0] > max_samples: + off = (wav.shape[0] - max_samples) // 2 + wav = wav[off:off + max_samples] + t = torch.tensor(wav, dtype=torch.float32, device=device).unsqueeze(0) + return extractor(t)[0].cpu().numpy().astype(np.float32) + + +@torch.no_grad() +def infer_paths(model, extractor, config, device, paths, batch=64, bucket=False, + max_samples=None, progress_every=4000): + """Per-clip species logits. The MTRCNN is padding-sensitive on variable-length clips, so + `bucket=True` length-sorts before batching -> equal-length clips share a batch with ZERO + padding (the faithful per-clip result; this is what every uniform-length eval clip gets and + what the baseline's get_loader produces for them). `bucket=False` keeps natural order to + reproduce the saved dev predictions made at eval_batch_size=8.""" + fe = config.feature_extraction + feats = [] + for i, p in enumerate(paths): + feats.append(torch.from_numpy(_feature(p, extractor, fe, device, max_samples)).float()) + if progress_every and i and i % progress_every == 0: + print(f" extracted {i}/{len(paths)}", flush=True) + order = sorted(range(len(feats)), key=lambda i: feats[i].shape[0]) if bucket else list(range(len(feats))) + logits = [None] * len(feats) + for s in range(0, len(order), batch): + idxs = order[s:s + batch] + bf = [feats[i] for i in idxs] + lengths = torch.tensor([f.shape[0] for f in bf], dtype=torch.long, device=device) + padded = pad_sequence(bf, batch_first=True, padding_value=0).to(device) + lg = model(padded, lengths).species_logits.cpu().numpy() + for k, i in enumerate(idxs): + logits[i] = lg[k] + return np.stack(logits, 0) + + +def self_test(model, extractor, config, device): + """Validate the pipeline on the dev TEST unseen clips two ways: + (1) official methodology (eval_batch_size=8, natural order) must reproduce the saved + predictions -> proves config/weights/features/forward are correct; + (2) padding-free length-bucketed inference (what the uniform eval set gets) -> reported + for transparency (differs slightly because dev clips are variable-length).""" + rows = [json.loads(l) for l in open(os.path.join(EXP_DIR, "final_model_eval/test_predictions.jsonl"))] + unseen = [r for r in rows if r.get("evaluation_partition") == "unseen"] + paths = [os.path.join(DEV_RAW, f"{r['file_id']}.wav") for r in unseen] + saved = np.array([r["predicted_species_index"] for r in unseen]) + ytrue = np.array([r["true_species_index"] for r in unseen]) + + def ba(p): + return float(np.mean([(p[ytrue == c] == c).mean() for c in range(9) if (ytrue == c).any()])) + + pred8 = infer_paths(model, extractor, config, device, paths, batch=8, bucket=False).argmax(1) + match = float((pred8 == saved).mean()) + print(f"[self-test] official (batch=8) exact-match vs saved={match:.4f} BA_unseen={ba(pred8):.4f} (saved 0.3104)") + assert match >= 0.98, f"pipeline does not reproduce official predictions ({match:.4f})" + + predpf = infer_paths(model, extractor, config, device, paths, batch=64, bucket=True).argmax(1) + agree = float((predpf == pred8).mean()) + print(f"[self-test] padding-free per-clip BA_unseen={ba(predpf):.4f} (agrees with official on {agree:.4f})") + print("[self-test] OK\n") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--checkpoint", default="model_final.pth") + ap.add_argument("--audio-root", default=os.path.join(ROOT, "eval")) + ap.add_argument("--ids", default=os.path.join(ROOT, "data/metadata_eval/Test_ids.txt")) + ap.add_argument("--out", default=os.path.join(ROOT, "final_submission/architecture_4/predictions.txt")) + ap.add_argument("--self-test", action="store_true") + args = ap.parse_args() + device = choose_device("auto") + + model, extractor, config = load_model_and_extractor(args.checkpoint, device) + print(f"loaded {type(model).__name__} from {args.checkpoint} on {device}") + + if args.self_test: + self_test(model, extractor, config, device) + + fe = config.feature_extraction + ids = read_ids(args.ids) + paths = [os.path.join(args.audio_root, f"{i}.wav") for i in ids] + print(f"eval clips: {len(ids)}; running MTRCNN-contrastive inference (length-bucketed, padding-free) ...") + logits = infer_paths(model, extractor, config, device, paths, batch=64, bucket=True, + max_samples=fe.sample_rate * 60) + idx = logits.argmax(1) + sid = np.array([IDX_TO_SPECIES_ID[i] for i in idx], dtype=int) + + os.makedirs(os.path.dirname(args.out), exist_ok=True) + with open(args.out, "w") as fh: + fh.write("file_id,predicted_species_id\n") + for f, s in zip(ids, sid): + fh.write(f"{f},{s}\n") + print(f"\nwrote {len(ids)} rows -> {args.out}") + for s in range(1, 10): + c = int((sid == s).sum()) + print(f" {s:>2} {SPECIES_ID_TO_NAME[str(s)]:<26} {c:>6} ({100*c/len(ids):.1f}%)") + + +if __name__ == "__main__": + main() diff --git a/legacy/final/predict_eval_extra.py b/legacy/final/predict_eval_extra.py new file mode 100644 index 0000000000000000000000000000000000000000..0df86499a8a10933afd9aae0cd7657e19cac0140 --- /dev/null +++ b/legacy/final/predict_eval_extra.py @@ -0,0 +1,221 @@ +"""Emit the two ADDITIONAL submissions on the eval set, reusing one feature pass: + architecture_2 = FG gate : unanimous-3 with the harmonic voter swapped for the + FOREGROUND-harmonic feature (dev BA_unseen 0.365, tau=0.0). + architecture_3 = 2-voter gate: override base where harmonic & birdmae agree (dev 0.3411, tau=0.4). + +Both reuse the deployed bundle's base/harmonic/birdmae/bgwhiten members; FG adds the saved +5-seed fg-harmonic arm (data/perch/harmonicfg_arm.pt). Run with the sibling TF venv python: + .../.venv/bin/python final/predict_eval_extra.py [--self-test] +""" +import os, sys, json, argparse +import numpy as np +import torch, torch.nn as nn, torch.nn.functional as F +import librosa + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +sys.path.insert(0, HERE) +sys.path.insert(0, ROOT) + +from framework.metadata import SPECIES_NAMES, SPECIES_ID_TO_NAME, DOMAIN_NAMES # noqa: E402 +import harmonic_features as HF # noqa: E402 (load_wav, harmonic_feature, HARM_DIM) +import bgwhiten_features as BG # noqa: E402 (bgwhiten_feature, BGW_DIM) +from predict_eval import read_ids, load_parquet_emb, IDX_TO_SPECIES_ID, EVAL_PARQUET_DIR, DEV_BIRDMAE_PARQUET # noqa: E402 + +FG_ARM_PT = os.path.join(ROOT, "data/perch/harmonicfg_arm.pt") +# val-selected gate taus that reproduce the published dev BA_unseen numbers +TAU_GATE3, TAU_FG, TAU_2VOTER = 0.3, 0.0, 0.4 + + +# --- foreground-harmonic feature: deployed harmonic feature but on the loudest-50% frames --- +def fg_harmonic_feature(y): + Q_LO, Q_HI, N_FFT, HOP, SR = HF.Q_LO, HF.Q_HI, HF.N_FFT, HF.HOP, HF.SR + S = np.abs(librosa.stft(y, n_fft=N_FFT, hop_length=HOP)) + 1e-8 + logS = np.log(S); e = S.sum(0); T = S.shape[1] + fg = np.argsort(e)[::-1][:max(3, int(0.50 * T))] + meanlog = logS[:, fg].mean(1) # FOREGROUND mean spectrum (vs whole-clip) + cep = np.fft.irfft(meanlog, n=N_FFT) + liftered = cep[Q_LO:Q_HI].copy() + try: + f0 = librosa.yin(y, fmin=150, fmax=1200, sr=SR, frame_length=N_FFT); f0 = f0[np.isfinite(f0)] + except Exception: + f0 = np.array([]) + if len(f0): + f0med, f0std, voiced = float(np.median(f0)), float(np.std(f0)), len(f0) / max(1, len(y) // HOP) + else: + f0med = f0std = voiced = 0.0 + env = np.fft.rfft(np.concatenate([cep[:Q_LO], np.zeros(N_FFT - Q_LO)]))[:len(meanlog)].real + white = meanlog - env + freqs = np.fft.rfftfreq(N_FFT, 1 / SR); hr = [] + if f0med > 0: + for k in range(1, 7): + fk = k * f0med + if fk < freqs[-1]: hr.append(white[np.argmin(np.abs(freqs - fk))]) + hr = np.array(hr + [0.0] * (6 - len(hr))) + f0harm = np.array([f0med / 600.0, f0std / 200.0, voiced] + list(hr / (np.abs(hr).max() + 1e-6)), np.float32) + return np.concatenate([liftered.astype(np.float32), f0harm]).astype(np.float32) + + +# --- HarmNet identical to analysis/add_harmonicfg.py (so the saved state_dicts load) --- +class HarmNet(nn.Module): + def __init__(s, d): + super().__init__() + s.net = nn.Sequential(nn.LayerNorm(d, eps=1e-6), nn.Linear(d, 128), nn.GELU(), + nn.Dropout(0.2), nn.Linear(128, 64), nn.LayerNorm(64, eps=1e-6)) + s.sp = nn.Linear(64, 9); s.dm = nn.Linear(64, 5) + + def forward(s, x): + e = s.net(x); return s.sp(e), s.dm(e), e + + +def _feat_one(args): + audio_root, fid = args + try: + y = HF.load_wav(os.path.join(audio_root, f"{fid}.wav")) + return HF.harmonic_feature(y), BG.bgwhiten_feature(y), fg_harmonic_feature(y), True + except Exception: + return (np.zeros(HF.HARM_DIM, np.float32), np.zeros(BG.BGW_DIM, np.float32), + np.zeros(HF.HARM_DIM, np.float32), False) + + +def compute_features(ids, audio_root, workers): + harm = np.zeros((len(ids), HF.HARM_DIM), np.float32) + bgw = np.zeros((len(ids), BG.BGW_DIM), np.float32) + fg = np.zeros((len(ids), HF.HARM_DIM), np.float32) + failed = 0 + work = [(audio_root, f) for f in ids] + from concurrent.futures import ProcessPoolExecutor + with ProcessPoolExecutor(max_workers=workers) as ex: + for j, (h, b, g, ok) in enumerate(ex.map(_feat_one, work, chunksize=32)): + harm[j], bgw[j], fg[j] = h, b, g + if not ok: failed += 1 + if (j + 1) % 2000 == 0: print(f" features {j+1}/{len(ids)}", flush=True) + return harm, bgw, fg, failed + + +def fg_arm_probs(fg_feat, device): + """Mean softmax over the 5 saved fg-harmonic HarmNet seeds.""" + arm = torch.load(FG_ARM_PT, map_location=device, weights_only=False) + mean, std = arm["means_stds"][0] + X = torch.tensor((fg_feat - mean) / std, dtype=torch.float32, device=device) + probs = [] + for entry in arm["states"]: + state = entry[1] # (seed, state_dict, vba, fba) + mo = HarmNet(arm["feature_dim"]).to(device); mo.load_state_dict(state); mo.eval() + with torch.no_grad(): + probs.append(F.softmax(mo(X)[0], 1).cpu().numpy()) + return np.mean(probs, 0) + + +def unaniN(base, voters, tau): + A = np.stack([v.argmax(1) for v in voters], 1) + M = np.stack([v.max(1) for v in voters], 1) + fire = np.all(A == A[:, :1], 1) & (M.min(1) > tau) + out = base.copy(); out[fire] = np.mean([v[fire] for v in voters], 0) + return out, int(fire.sum()) + + +def _ba_unseen(pred, y, unseen): + yy = y[unseen]; pp = pred[unseen] + r = [(pp[yy == c] == c).mean() for c in range(9) if (yy == c).any()] + return float(np.mean(r)) + + +def write_submission(ids, probs, out_path, title): + idx = probs.argmax(1) + sid = np.array([IDX_TO_SPECIES_ID[i] for i in idx], dtype=int) + os.makedirs(os.path.dirname(out_path), exist_ok=True) + with open(out_path, "w") as fh: + fh.write("file_id,predicted_species_id\n") + for f, s in zip(ids, sid): + fh.write(f"{f},{s}\n") + print(f"\n{title}: wrote {len(ids)} rows -> {out_path}") + for s in range(1, 10): + c = int((sid == s).sum()) + print(f" {s:>2} {SPECIES_ID_TO_NAME[str(s)]:<26} {c:>6} ({100*c/len(ids):.1f}%)") + + +def self_test(device): + from ensemble_model import GatedEnsemble + P = os.path.join(ROOT, "data/perch") + d = np.load(f"{P}/test.npz", allow_pickle=True) + perch = d["emb"].astype(np.float32); yte = d["species"].astype(int); dte = d["domain"].astype(int) + fte = np.array([str(f) for f in d["file_id"]]) + + def by_fid(npz, key): + h = np.load(npz, allow_pickle=True); ix = {str(f): i for i, f in enumerate(h["file_id"])} + return h[key].astype(np.float32)[np.array([ix[f] for f in fte])] + + harm = by_fid(f"{P}/harmonic_test.npz", "harm") + bgw = by_fid(f"{P}/bgwhiten_test.npz", "bgw") + bird, _ = load_parquet_emb(DEV_BIRDMAE_PARQUET, list(fte), 1024) + sm = json.load(open(f"{ROOT}/data/metadata/split_summary.json")) + ud = {SPECIES_NAMES.index(k): DOMAIN_NAMES.index(v) for k, v in sm["unseen_domain_by_species"].items()} + unseen = np.array([dte[i] == ud.get(int(yte[i]), -1) for i in range(len(yte))]) + + ens = GatedEnsemble(os.path.join(HERE, "bundle.pt"), device=device) + mp = ens.member_probs(perch, harm, bird, bgw) + base, harmp, birdp, bgwp = mp["base_perch"], mp["arm_harmonic"], mp["arm_birdmae"], mp["arm_bgwhiten"] + + # fg dev-test probs: recompute from the arm on harmonicfg_test.npz, and check vs the saved `ft` + fg_feat = by_fid(f"{P}/harmonicfg_test.npz", "harm") + fgp = fg_arm_probs(fg_feat, device) + saved_ft = torch.load(FG_ARM_PT, map_location="cpu", weights_only=False)["ft"] + drift = float(np.abs(fgp - saved_ft).max()) + print(f"[self-test] fg-arm reproduce vs saved ft: max|delta|={drift:.4g}") + assert drift < 1e-4, "fg-arm inference does not reproduce saved probs" + + g3, _ = unaniN(base, [harmp, birdp, bgwp], TAU_GATE3) + fg, _ = unaniN(base, [fgp, birdp, bgwp], TAU_FG) + tv, _ = unaniN(base, [harmp, birdp], TAU_2VOTER) + for name, pred, exp in [("gate3", g3, 0.3616), ("FG", fg, 0.365), ("2voter", tv, 0.3411)]: + ba = _ba_unseen(pred.argmax(1), yte, unseen) + print(f"[self-test] {name:7s} dev BA_unseen={ba:.4f} (expect {exp})") + assert abs(ba - exp) < 0.001, f"{name} mismatch {ba} != {exp}" + print("[self-test] OK\n") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--audio-root", default=os.path.join(ROOT, "eval")) + ap.add_argument("--ids", default=os.path.join(ROOT, "data/metadata_eval/Test_ids.txt")) + ap.add_argument("--parquet-dir", default=EVAL_PARQUET_DIR) + ap.add_argument("--bundle", default=os.path.join(HERE, "bundle.pt")) + ap.add_argument("--sub-dir", default=os.path.join(ROOT, "final_submission")) + ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1)) + ap.add_argument("--self-test", action="store_true") + args = ap.parse_args() + device = "cuda" if torch.cuda.is_available() else "cpu" + + if args.self_test: + self_test(device) + + ids = read_ids(args.ids) + print(f"eval clips: {len(ids)}") + print("loading Perch + BirdMAE eval embeddings ...") + perch, mp_ = load_parquet_emb(os.path.join(args.parquet_dir, "perch.parquet"), ids, 1536) + bird, mb_ = load_parquet_emb(os.path.join(args.parquet_dir, "birdmae.parquet"), ids, 1024) + print(f" perch missing={mp_} birdmae missing={mb_}") + print(f"computing harmonic + bgwhiten + fg-harmonic ({args.workers} workers) ...") + harm, bgw, fgf, failed = compute_features(ids, args.audio_root, args.workers) + print(f" features done; unreadable clips (zero-filled)={failed}") + + print("running member probes ...") + from ensemble_model import GatedEnsemble + ens = GatedEnsemble(args.bundle, device=device) + mp = ens.member_probs(perch, harm, bird, bgw) + base, harmp, birdp, bgwp = mp["base_perch"], mp["arm_harmonic"], mp["arm_birdmae"], mp["arm_bgwhiten"] + fgp = fg_arm_probs(fgf, device) + + fg_pred, n_fg = unaniN(base, [fgp, birdp, bgwp], TAU_FG) + tv_pred, n_tv = unaniN(base, [harmp, birdp], TAU_2VOTER) + print(f"FG gate fired on {n_fg}/{len(ids)} clips; 2-voter gate fired on {n_tv}/{len(ids)}") + + write_submission(ids, fg_pred, os.path.join(args.sub_dir, "architecture_2/predictions.txt"), + "architecture_2 (FG gate, dev 0.365)") + write_submission(ids, tv_pred, os.path.join(args.sub_dir, "architecture_3/predictions.txt"), + "architecture_3 (2-voter gate, dev 0.3411)") + + +if __name__ == "__main__": + main()