"""大规模基准:合成曲库在 300 / 600 / 1000 首规模下的召回率与检索延迟。 关注两件事: 1. **粗召回率**是否随曲库增大而下降(倒排索引能否把答案保留在候选集里); 2. **延迟**的扩展性——两级检索的耗时是否近似随 ``候选数 × DTW 规模`` 增长, 而不是随曲库线性增长。 合成曲库与合成查询同源,因此准确率只作**相对参考**;真实基线请以 ``data/midi`` 的 27 首真实旋律为准(见 docs/评测报告.md)。 """ from __future__ import annotations import json import shutil import statistics import tempfile import time from dataclasses import dataclass, field from pathlib import Path import numpy as np from .config import DEFAULT, Config from .evaluate import make_query_specs, perturb_melody, synth_query_audio from .library import Library from .melody import Melody from .search import SearchEngine from .store import Store __all__ = ["generate_melody", "run_scale_benchmark"] _SCALES: dict[str, list[int]] = { "major": [0, 2, 4, 5, 7, 9, 11], "minor": [0, 2, 3, 5, 7, 8, 10], "pentatonic": [0, 2, 4, 7, 9], } _RHYTHMS: tuple[tuple[float, ...], ...] = ( (1.0, 1.0, 1.0, 1.0), (1.5, 0.5, 1.0, 1.0), (0.5, 0.5, 1.0, 2.0), (2.0, 1.0, 1.0), (1.0, 0.5, 0.5, 2.0), (0.75, 0.25, 1.0, 2.0), ) def generate_melody( rng: np.random.Generator, song_id: str, *, n_notes: int = 32, root: int = 60, scale: str = "major", bpm: float = 100.0, ) -> Melody: """生成一条有动机重复与变化的结构化旋律。""" steps = _SCALES[scale] motif_len = int(rng.integers(3, 7)) motif = [int(rng.integers(0, len(steps))) for _ in range(motif_len)] degrees: list[int] = [] while len(degrees) < n_notes: transposition = int(rng.integers(-2, 3)) for degree in motif: if len(degrees) >= n_notes: break value = degree + transposition if rng.random() < 0.15: # 局部变化 value += int(rng.integers(-1, 2)) degrees.append(value) midis: list[float] = [] for degree in degrees: octave, index = divmod(degree, len(steps)) midi = root + 12 * octave + steps[index] while midi < 45: midi += 12 while midi > 84: midi -= 12 midis.append(float(midi)) beat = 60.0 / bpm pattern = _RHYTHMS[int(rng.integers(0, len(_RHYTHMS)))] starts: list[float] = [] durs: list[float] = [] cursor = 0.0 for i in range(len(midis)): beats = pattern[i % len(pattern)] starts.append(cursor) durs.append(beats * beat) cursor += beats * beat return Melody(np.array(midis), np.array(starts), np.array(durs), song_id, song_id) @dataclass class ScaleResult: n_songs: int n_queries: int n_grams: int build_seconds: float index_seconds: float candidate_recall: float top1: float top5: float mrr: float mean_candidates: float p50_ms: float p95_ms: float mean_ms: float def to_dict(self) -> dict: return { "n_songs": self.n_songs, "n_queries": self.n_queries, "n_grams": self.n_grams, "build_seconds": round(self.build_seconds, 2), "index_seconds": round(self.index_seconds, 3), "candidate_recall": round(self.candidate_recall, 4), "top1": round(self.top1, 4), "top5": round(self.top5, 4), "mrr": round(self.mrr, 4), "mean_candidates": round(self.mean_candidates, 1), "p50_ms": round(self.p50_ms, 2), "p95_ms": round(self.p95_ms, 2), "mean_ms": round(self.mean_ms, 2), } @dataclass class BenchReport: sizes: list[int] results: list[ScaleResult] = field(default_factory=list) difficulty: str = "normal" seed: int = 20260908 config: dict = field(default_factory=dict) def to_dict(self) -> dict: return { "sizes": self.sizes, "difficulty": self.difficulty, "seed": self.seed, "config": self.config, "results": [r.to_dict() for r in self.results], } def save(self, path: str | Path) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(self.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8") def markdown_table(self) -> str: head = ( "| 曲库规模 | n-gram 数 | 候选召回率 | Top-1 | Top-5 | MRR | " "平均候选数 | 延迟 p50 | 延迟 p95 | 索引构建 |\n" "|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|\n" ) rows = [ f"| {r.n_songs} | {r.n_grams} | {r.candidate_recall*100:.1f}% | " f"{r.top1*100:.1f}% | {r.top5*100:.1f}% | {r.mrr:.3f} | " f"{r.mean_candidates:.0f} | {r.p50_ms:.0f} ms | {r.p95_ms:.0f} ms | " f"{r.index_seconds*1000:.0f} ms |" for r in self.results ] return head + "\n".join(rows) def run_scale_benchmark( sizes: tuple[int, ...] = (300, 600, 1000), *, n_queries_per_size: int = 60, difficulty: str = "normal", seed: int = 20260908, cfg: Config = DEFAULT, verbose: bool = True, ) -> BenchReport: """在多个曲库规模上跑基准测试。""" report = BenchReport(sizes=list(sizes), difficulty=difficulty, seed=seed, config=cfg.to_dict()) rng = np.random.default_rng(seed) for size in sizes: work_dir = Path(tempfile.mkdtemp(prefix=f"qbh_bench_{size}_")) try: started = time.perf_counter() store = Store(work_dir / "bench.db") library = Library( store, cfg, midi_dir=work_dir / "midi", audio_dir=work_dir / "audio" ) scales = ("major", "minor", "pentatonic") for i in range(size): melody = generate_melody( rng, f"s{i:05d}", n_notes=int(rng.integers(20, 48)), root=int(rng.integers(55, 68)), scale=scales[int(rng.integers(0, len(scales)))], bpm=float(rng.uniform(70, 150)), ) library.add_melody(melody, song_id=melody.song_id, title=melody.title, source="synthetic", render_audio=False) build_seconds = time.perf_counter() - started started = time.perf_counter() engine = SearchEngine(library, cfg) index_seconds = time.perf_counter() - started melodies = library.melodies() specs = make_query_specs( melodies, n_per_song=1, difficulty=difficulty, seed=seed + size )[:n_queries_per_size] ranks: list[int] = [] latencies: list[float] = [] candidate_hits = 0 n_candidates: list[int] = [] for spec in specs: source = next(m for m in melodies if m.song_id == spec.song_id) truth = perturb_melody(source, spec, cfg) audio = synth_query_audio(truth, spec, cfg) result, _ = engine.search_audio(audio, cfg.sample_rate, top_k=10, cfg=cfg) cand_ids = {sid for sid, _ in engine.coarse_candidates(result.query)} candidate_hits += int(spec.song_id in cand_ids) n_candidates.append(result.n_candidates) latencies.append(result.elapsed_ms) rank = next( (i + 1 for i, h in enumerate(result.hits) if h.song_id == spec.song_id), 0 ) ranks.append(rank) n = max(len(specs), 1) lat = np.asarray(latencies, dtype=np.float64) result = ScaleResult( n_songs=size, n_queries=len(specs), n_grams=engine.index.n_grams(), build_seconds=build_seconds, index_seconds=index_seconds, candidate_recall=candidate_hits / n, top1=sum(1 for r in ranks if r == 1) / n, top5=sum(1 for r in ranks if 0 < r <= 5) / n, mrr=sum((1.0 / r) for r in ranks if r > 0) / n, mean_candidates=float(statistics.fmean(n_candidates)) if n_candidates else 0.0, p50_ms=float(np.percentile(lat, 50)) if lat.size else 0.0, p95_ms=float(np.percentile(lat, 95)) if lat.size else 0.0, mean_ms=float(lat.mean()) if lat.size else 0.0, ) report.results.append(result) if verbose: print( f" 曲库 {size:>4} 首 · n-gram {result.n_grams:>6} · " f"召回率 {result.candidate_recall*100:5.1f}% · Top-1 {result.top1*100:5.1f}% · " f"候选 {result.mean_candidates:5.1f} · 延迟 p50 {result.p50_ms:6.1f}ms " f"p95 {result.p95_ms:6.1f}ms" ) store.close() finally: shutil.rmtree(work_dir, ignore_errors=True) return report