#!/usr/bin/env python3 """ Dump learned frame representations for the loop detector's bake-off. This is the offline half of the experiment `RESEARCH-frontier-loop-points.md` §7 L1 calls for. The question it exists to answer is narrow and it is the only question that matters before a week is spent on shipping a feature encoder to a browser: Does any learned representation make two frames of *different* music look different? The detector's own diagnosis (`RESEARCH-loops-to-the-beat.md` §11, measured on ten real tracks) is that chroma does not: every track's 98th-percentile lag score came back between 0.955 and 0.998, which is the threshold's comparative half saying "everything here repeats", on tracks that do not. Every constant downstream of that — the floor, the tail quantile, the trim gate — is inert on real material until something upstream of it can separate a frame from its neighbour. So this script does not score loops. It converts audio into matrices, in as many representations as the machine has libraries for, and leaves the scoring to `bakeoff.ts`, which runs the *app's own search* over each matrix and prints the tail per representation. If no representation lifts the tail off 0.99, representation is not the lever, and the whole L1 branch closes. Out per track, in `--out`: .audio.f32 the decoded mono mix, float32 at --sr: what the TS side reads as samples ..f32 one row per analysed frame, row-major float32, NOT normalised (TS does that) ..json {model, width, frames, hopSec, firstSec, sr, layer, pool} No audio format handling here beyond whatever `torchaudio`/`soundfile` will decode, which is the convenient half of the design: the browser's decoder is the app's problem and this script's problem is only that a file must become a matrix at a stated frame rate. LICENSE, before anything is downloaded. `muq` and `musicfm` checkpoints are research weights under CC-BY-NC-4.0 — non-commercial. This app is MIT. Nothing in this script's output may become an app artifact without a licence decision (see `scripts/neural-beat/` for what shipping a model actually takes: MIT weights, exported to ONNX, hashed, and parity-tested against the authors' own torch code). Running this on your own library for calibration is a different matter from shipping the weights, and the distinction is the reason the two directories are separate. """ from __future__ import annotations import argparse import json import sys import time from pathlib import Path SR = 44100 # what the app decodes at; the analysis grid is derived from this, not the other way round def load_audio(path: Path, sr: int): """Mono float32 at `sr`, however the installed audio library prefers to be asked.""" try: import soundfile as sf # type: ignore data, rate = sf.read(str(path), dtype="float32", always_2d=True) if data.shape[1] > 1: data = data.mean(axis=1) else: data = data[:, 0] if rate != sr: # Resampling here rather than in the harness keeps the frame times honest: a matrix whose # frame rate was derived against a different duration than the samples it is pooled against # would silently slide every beat onto the wrong row. import scipy.signal as sps # type: ignore data = sps.resample_poly(data, sr, rate).astype("float32") return data except ImportError: pass import torchaudio # type: ignore wav, rate = torchaudio.load(str(path)) wav = wav.mean(dim=0) if rate != sr: wav = torchaudio.functional.resample(wav, rate, sr) return wav.numpy().astype("float32") def write_matrix(out: Path, stem: str, model: str, frames, width: int, hop: float, first: float, meta_extra=None): """Row-major float32 plus the metadata that makes the rows mean something.""" bin_path = out / f"{stem}.{model}.f32" meta_path = out / f"{stem}.{model}.json" arr = frames.astype("float32") if arr.ndim == 1: arr = arr.reshape(-1, width) bin_path.write_bytes(arr.tobytes()) meta = { "model": model, "width": int(arr.shape[1]), "frames": int(arr.shape[0]), "hopSec": float(hop), "firstSec": float(first), "sr": SR, } if meta_extra: meta.update(meta_extra) meta_path.write_text(json.dumps(meta, indent=2) + "\n") return arr.shape def frames_for(duration: float, n: int): """ Frame times inferred from the output length. The honest way would be to carry each backbone's stride and receptive field through from its paper, and every one of those numbers is reported in the literature; the way that cannot drift out of step with a library's own padding behaviour is to say `n` frames covered `duration`, so the hop is `duration / n` and row 0 sits at the middle of the first hop. For pooling frames onto beats that is the only two numbers that enter, and a frame centre a few milliseconds off changes no verdict about whether a tail collapsed. """ hop = duration / max(1, n) return hop, hop / 2 def dump_muq(models_dir: str, layer: int | None, wave, duration: float, out: Path, stem: str): import torch # type: ignore from muq import MuQ # type: ignore model = MuQ.from_pretrained("OpenMuQ/MuQ-large-msd-iter") model.eval() with torch.no_grad(): outp = model(torch.from_numpy(wave).unsqueeze(0).float(), output_hidden_states=True) # The MuQ paper's own finding (ICASSP 2025) is that its *early*, contrastive-predictive-coding # layers carry the acoustic detail — beat and bar tracking came from the second-to-last CNN layer, # not the fine-tuned top. `--layer -2` is the default for that reason, and it is a knob rather than # a constant because the paper's optimum was for a different task. hs = outp.hidden_states which = len(hs) - 2 if layer is None else layer emb = hs[which][0].cpu().numpy() if emb.ndim == 3: emb = emb[0] hop, first = frames_for(duration, emb.shape[0]) return write_matrix(out, stem, f"muq-l{which}", emb, emb.shape[-1], hop, first, {"layer": which, "pool": "none"}) def dump_mert(models_dir: str, layer: int | None, wave, duration: float, out: Path, stem: str): import torch # type: ignore from transformers import MertModel, MertFeatureExtractor # type: ignore name = "m-a-p/MERT-v1-95M" feat = MertFeatureExtractor.from_pretrained(name, trust_remote_code=True) model = MertModel.from_pretrained(name, trust_remote_code=True).eval() inputs = feat(wave, sampling_rate=SR, return_tensors="pt") with torch.no_grad(): hidden = model(**inputs, output_hidden_states=True).hidden_states which = len(hidden) - 2 if layer is None else layer emb = hidden[which][0].cpu().numpy() hop, first = frames_for(duration, emb.shape[0]) return write_matrix(out, stem, f"mert-l{which}", emb, emb.shape[-1], hop, first, {"layer": which, "pool": "none"}) def dump_musicfm(models_dir: str, layer: int | None, wave, duration: float, out: Path, stem: str): from musicfm import MusicFM, load_musicfm_audio # type: ignore import torch # type: ignore ckpt = Path(models_dir) / "musicfm_finetuned_msd_f13k.pt" if not ckpt.exists(): raise FileNotFoundError( f"{ckpt} not found: MusicFM ships weights as a release download rather than a Hub repo " "(mum651/MusicFM). Fetch it once, or drop --models musicfm." ) model = MusicFM.from_pretrained(str(ckpt), config={"use_scriptmelody": True}) wav = load_musicfm_audio(wave, in_sr=SR) # type: ignore[arg-type] with torch.no_grad(): _, feats = model.extract_features(wav.unsqueeze(0)) emb = feats.cpu().numpy() if hasattr(feats, "cpu") else feats if emb.ndim == 3: emb = emb[0] hop, first = frames_for(duration, emb.shape[0]) return write_matrix(out, stem, "musicfm", emb, emb.shape[-1], hop, first, {"pool": "none"}) DUMPERS = {"muq": dump_muq, "mert": dump_mert, "musicfm": dump_musicfm} def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[1] if __doc__ else "") ap.add_argument("--audio", nargs="+", required=True, help="audio files (whatever soundfile/torchaudio decode)") ap.add_argument("--out", required=True, help="directory for the dumps") ap.add_argument("--models", default="muq", help="comma list of: " + ",".join(DUMPERS)) ap.add_argument("--layer", type=int, default=None, help="hidden layer index, negative counts from the top") ap.add_argument("--models-dir", default="/tmp/ssl-bakeoff/models") ap.add_argument("--sr", type=int, default=SR) ap.add_argument("--dry-run", action="store_true", help="print what would run, import nothing") args = ap.parse_args() wanted = [m.strip() for m in args.models.split(",") if m.strip()] for m in wanted: if m not in DUMPERS: print(f"unknown model {m!r}; have {', '.join(DUMPERS)}", file=sys.stderr) return 2 out = Path(args.out) out.mkdir(parents=True, exist_ok=True) if args.dry_run: for a in args.audio: for m in wanted: print(f"would dump {a} → {out / (Path(a).stem + '.' + m + '.f32')}") return 0 print( "NOTE: MuQ and MusicFM checkpoints are CC-BY-NC-4.0 research weights. Fine for measuring;\n" "not shippable in an MIT app without a licence decision. See scripts/neural-beat/ for what\n" "shipping a model takes (MIT weights, ONNX export, hashes, parity tests).", file=sys.stderr, ) failures = [] for path in args.audio: p = Path(path) if not p.exists(): print(f"missing {p}", file=sys.stderr) failures.append(str(p)) continue wave = load_audio(p, args.sr) duration = len(wave) / args.sr (out / f"{p.stem}.audio.f32").write_bytes(wave.astype("float32").tobytes()) (out / f"{p.stem}.audio.json").write_text( json.dumps({"sr": args.sr, "samples": int(len(wave)), "seconds": duration}, indent=2) + "\n" ) print(f"{p.name}: {duration:.1f}s") for m in wanted: t0 = time.time() try: rows, cols = DUMPERS[m](args.models_dir, args.layer, wave, duration, out, p.stem) print(f" {m:8s} {rows:6d} rows × {cols:4d} ({time.time() - t0:.1f}s)") except Exception as exc: # one missing library must not lose the other arms print(f" {m:8s} FAILED: {type(exc).__name__}: {exc}", file=sys.stderr) failures.append(f"{p.stem}/{m}") if failures: print(f"\n{len(failures)} arm(s) did not produce a matrix: {', '.join(failures[:8])}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())