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