"""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()