From 6a6e619184e2531ffdba1b376820a891a38f88b2 Mon Sep 17 00:00:00 2001 From: "jiyun.park" Date: Wed, 11 Nov 2026 12:49:13 +0100 Subject: [PATCH 1/3] Use musical-beat evaluation and publish CI results as releases --- .github/install_matchmaker.py | 62 +++++ .github/workflows/evaluate-amt.yml | 119 +++++++++ .github/workflows/evaluate-diagnostics.yml | 118 +++++++++ .github/workflows/evaluate-offline.yml | 137 ++++++++++ .github/workflows/evaluate-references.yml | 193 +++++++++++--- .github/workflows/evaluate.yml | 175 ++++--------- .github/workflows/pages.yml | 58 ++++- .github/workflows/tests.yml | 2 +- .github/workflows/validate-submission.yml | 7 +- .gitignore | 23 +- README.md | 24 +- data/builtin_methods.yaml | 9 + data/data_sources.yaml | 9 + docs/ci-evaluation.md | 154 ++++++++++++ docs/diagnostics.md | 82 ++++++ docs/eval-protocol.md | 46 +++- docs/index.html | 38 +-- docs/maintaining.md | 96 ++++--- docs/submitting.md | 47 ++-- matchmaker_eval/build_site.py | 5 +- matchmaker_eval/diagnostics.py | 277 +++++++++++++++++++++ matchmaker_eval/eval.py | 66 ++--- matchmaker_eval/export_details.py | 23 +- matchmaker_eval/fetch_data.py | 9 + matchmaker_eval/folds.py | 1 + matchmaker_eval/leaderboard.py | 24 +- matchmaker_eval/merge_references.py | 38 ++- matchmaker_eval/merge_shards.py | 3 + matchmaker_eval/provenance.py | 66 +++-- matchmaker_eval/release_results.py | 256 +++++++++++++++++++ matchmaker_eval/retract.py | 7 +- matchmaker_eval/run_amt.py | 71 ++++++ matchmaker_eval/run_offline.py | 132 ++++++++++ matchmaker_eval/run_submission.py | 59 ++++- matchmaker_eval/test_symbolic.py | 14 +- matchmaker_eval/verify_tracking.py | 123 ++++++++- tests/test_data_paths.py | 29 +++ tests/test_evaluation_key.py | 53 ++++ tests/test_merge_shards.py | 127 ++++++++++ tests/test_musical_beats.py | 62 +++++ tests/test_workflows.py | 145 ++++++++--- 41 files changed, 2564 insertions(+), 425 deletions(-) create mode 100644 .github/install_matchmaker.py create mode 100644 .github/workflows/evaluate-amt.yml create mode 100644 .github/workflows/evaluate-diagnostics.yml create mode 100644 .github/workflows/evaluate-offline.yml create mode 100644 docs/ci-evaluation.md create mode 100644 docs/diagnostics.md create mode 100644 matchmaker_eval/diagnostics.py create mode 100644 matchmaker_eval/release_results.py create mode 100644 matchmaker_eval/run_amt.py create mode 100644 matchmaker_eval/run_offline.py create mode 100644 tests/test_musical_beats.py diff --git a/.github/install_matchmaker.py b/.github/install_matchmaker.py new file mode 100644 index 0000000..265f014 --- /dev/null +++ b/.github/install_matchmaker.py @@ -0,0 +1,62 @@ +"""Install the same immutable Matchmaker sources in every CI job. + +Pending changes are applied only in a temporary checkout, without creating +commits or changing upstream branches. Remove a patch once it is in BASE. +""" + +import hashlib +import json +import subprocess +import sys +import tempfile +from pathlib import Path + + +REPOSITORY = "https://github.com/pymatchmaker/matchmaker.git" +BASE = "25960ea95aadf1b98d1bc753c8be133e0bc859ff" # develop, including #79, #80 and #81 +PATCHES = ( + # Retain the existing bounded repeat enumeration used by diagnostics. + ("678366b034edc7cb10e3cf71bb1755b1a679e6c1", + "0e673e2bfebd86c1e814ed9f5270b926c053a0ae"), +) + + +def main(): + with tempfile.TemporaryDirectory(prefix="benchmark-matchmaker-") as folder: + source = Path(folder) + + def git(*args, **kwargs): + return subprocess.run( + ["git", "-C", str(source), *args], check=True, **kwargs + ) + + git("init", "--quiet") + git("config", "core.autocrlf", "false") + git("remote", "add", "origin", REPOSITORY) + refs = sorted({BASE, *(ref for pair in PATCHES for ref in pair)}) + git("fetch", "--quiet", "--depth=1", "origin", *refs) + git("checkout", "--quiet", "--detach", BASE) + patches = [] + for base, head in PATCHES: + patch = git("diff", "--binary", base, head, capture_output=True).stdout + git("apply", "--check", "-", input=patch) + git("apply", "-", input=patch) + patches.append({ + "base": base, "head": head, + "sha256": hashlib.sha256(patch).hexdigest(), + }) + provenance = { + "matchmaker_base_commit": BASE, + "matchmaker_patches": patches, + } + manifest = source / "matchmaker" / "assets" / "benchmark-source.json" + manifest.write_text(json.dumps(provenance, indent=2) + "\n") + print(json.dumps(provenance, indent=2), flush=True) + subprocess.run( + [sys.executable, "-m", "pip", "install", *sys.argv[1:], str(source)], + check=True, + ) + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/evaluate-amt.yml b/.github/workflows/evaluate-amt.yml new file mode 100644 index 0000000..3f0b624 --- /dev/null +++ b/.github/workflows/evaluate-amt.yml @@ -0,0 +1,119 @@ +name: Evaluate frozen AMT outputs +on: + workflow_call: + inputs: + shards: + type: string + default: '4' +permissions: + contents: read +jobs: + plan: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.plan.outputs.matrix }} + shards: ${{ steps.plan.outputs.shards }} + steps: + - id: plan + env: + SHARDS: ${{ inputs.shards }} + run: | + python - <<'PY' >> "$GITHUB_OUTPUT" + import json,os + n=int(os.environ['SHARDS']) + if not 1 <= n <= 32:raise SystemExit('Use 1–32 shards') + print('matrix='+json.dumps({'method':['arzt','pthmm','SLT_OLTW'],'shard':list(range(n))})) + print('shards='+str(n)) + PY + evaluate: + needs: plan + runs-on: ubuntu-latest + timeout-minutes: 180 + strategy: + fail-fast: false + max-parallel: 8 + matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} + env: + MATCHMAKER_DATA_DIR: ${{ github.workspace }}/benchmark-data + MATCHMAKER_DATA_BRANCH: 03b51262b9bce7993203044fa45c9be9dadebd34 + OMP_NUM_THREADS: '1' + OPENBLAS_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + NUMBA_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: pip + - run: | + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 ffmpeg + python .github/install_matchmaker.py + pip install pyyaml pydantic-settings + - name: Run symbolic follower on frozen transcription + run: | + python matchmaker_eval/run_amt.py --method '${{ matrix.method }}' \ + --shard '${{ matrix.shard }}' --num-shards '${{ needs.plan.outputs.shards }}' --output results/amt + - name: Record provenance + if: always() + run: | + mkdir -p results/amt + pip freeze > results/amt/environment.txt + python - <<'PY' + import json,os + from pathlib import Path + Path('results/amt/CI.json').write_text(json.dumps({k:os.environ.get(k) for k in ['GITHUB_RUN_ID','GITHUB_RUN_ATTEMPT','GITHUB_SHA','MATCHMAKER_DATA_BRANCH']},indent=2)) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: amt-${{ matrix.method }}-${{ matrix.shard }} + path: results/amt + retention-days: 30 + merge: + needs: [plan,evaluate] + if: always() && needs.plan.result == 'success' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: | + python .github/install_matchmaker.py + pip install pyyaml pydantic-settings + - uses: actions/download-artifact@v4 + with: + pattern: amt-* + path: results/shards + - name: Merge and verify complete test set + env: + SHARDS: ${{ needs.plan.outputs.shards }} + run: | + python - <<'PY' + import sys,os,json,shutil + from pathlib import Path + sys.path.insert(0,'matchmaker_eval') + from merge_shards import merge + out=Path('results/amt-reference');out.mkdir(parents=True,exist_ok=True) + errors=[] + for method in ['arzt','pthmm','SLT_OLTW']: + stage=Path('results/staging')/method;stage.mkdir(parents=True,exist_ok=True) + try: + for i in range(int(os.environ['SHARDS'])):shutil.copytree(Path('results/shards')/f'amt-{method}-{i}',stage/str(i)) + r=merge(stage,out/method) + if r['partial'] or r['n_failed'] or r['n_pieces']!=146:raise ValueError('Incomplete AMT reference') + except Exception as e:errors.append(method+': '+str(e)) + shutil.copytree('results/shards',out/'raw-shards') + from matchmaker_eval.fetch_data import frozen_source + (out/'amt-data-pin.json').write_text(json.dumps(frozen_source('amt'),indent=2)) + (out/'verification.json').write_text(json.dumps({'complete':not errors,'errors':errors},indent=2)) + if errors:raise SystemExit(errors) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: benchmark-results-amt-reference + path: results/amt-reference + retention-days: 90 diff --git a/.github/workflows/evaluate-diagnostics.yml b/.github/workflows/evaluate-diagnostics.yml new file mode 100644 index 0000000..ebce202 --- /dev/null +++ b/.github/workflows/evaluate-diagnostics.yml @@ -0,0 +1,118 @@ +name: Evaluate diagnostic suites +on: + workflow_call: + inputs: + shards: + type: string + default: '4' + only: + type: string + default: '' + input_type: + type: string + default: both +permissions: + contents: read +env: + ONLY: ${{ inputs.only }} + INPUT_TYPE: ${{ inputs.input_type }} +jobs: + plan: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.plan.outputs.matrix }} + shards: ${{ steps.plan.outputs.shards }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - id: plan + env: + SHARDS: ${{ inputs.shards }} + run: | + python - <<'PY' >> "$GITHUB_OUTPUT" + import json, os + from matchmaker_eval.diagnostics import select_configs + n = int(os.environ['SHARDS']) + if not 1 <= n <= 8: raise SystemExit('Use 1–8 shards for diagnostics') + configs = select_configs(os.environ['ONLY'], os.environ['INPUT_TYPE']) + print('matrix='+json.dumps([{'config': c, 'shard': s} for c in configs for s in range(n)])) + print('shards='+str(n)) + PY + evaluate: + needs: plan + runs-on: ubuntu-latest + timeout-minutes: 350 + strategy: + fail-fast: false + max-parallel: 12 + matrix: + job: ${{ fromJSON(needs.plan.outputs.matrix) }} + env: + OMP_NUM_THREADS: '1' + OPENBLAS_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + NUMEXPR_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: pip + - name: Install environment + run: | + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 ffmpeg + python .github/install_matchmaker.py + pip install pyyaml pydantic-settings + - name: Run frozen diagnostic cases + run: | + python matchmaker_eval/diagnostics.py run \ + --config '${{ matrix.job.config }}' --shard '${{ matrix.job.shard }}' \ + --shards '${{ needs.plan.outputs.shards }}' --output results/diagnostics + - uses: actions/upload-artifact@v4 + if: always() + with: + name: diagnosis-${{ matrix.job.config }}-${{ matrix.job.shard }} + path: results/diagnostics + if-no-files-found: error + retention-days: 30 + merge: + needs: [plan, evaluate] + if: always() && needs.plan.result == 'success' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: pip install numpy pyyaml + - uses: actions/download-artifact@v4 + with: + pattern: diagnosis-* + path: results/shards + - name: Fetch and verify frozen manifest + run: | + python - <<'PY' + import json + from pathlib import Path + from matchmaker_eval.diagnostics import download, sha + from matchmaker_eval.fetch_data import frozen_source + p = frozen_source('diagnostics') + dest = Path('results/data_manifest.json') + download(f'https://raw.githubusercontent.com/{p["repository"]}/{p["commit"]}/diagnostics/manifest.json', dest) + assert sha(dest) == p['manifest_sha256'] + PY + - name: Verify completeness and aggregate + run: | + python matchmaker_eval/diagnostics.py merge --source results/shards \ + --output results/diagnosis --manifest results/data_manifest.json \ + --shards '${{ needs.plan.outputs.shards }}' --only "$ONLY" --input-type "$INPUT_TYPE" + - uses: actions/upload-artifact@v4 + if: always() + with: + name: benchmark-results-diagnosis + path: results/diagnosis + if-no-files-found: error + retention-days: 90 diff --git a/.github/workflows/evaluate-offline.yml b/.github/workflows/evaluate-offline.yml new file mode 100644 index 0000000..082c1da --- /dev/null +++ b/.github/workflows/evaluate-offline.yml @@ -0,0 +1,137 @@ +name: Evaluate offline reference +on: + workflow_call: + inputs: + shards: + type: string + default: '8' +permissions: + contents: read +jobs: + plan: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.plan.outputs.matrix }} + shards: ${{ steps.plan.outputs.shards }} + steps: + - id: plan + env: + SHARDS: ${{ inputs.shards }} + run: | + python - <<'PY' >> "$GITHUB_OUTPUT" + import json,os + n=int(os.environ['SHARDS']) + if not 1 <= n <= 32: raise SystemExit('Use 1–32 shards') + jobs=[{'fold':fold,'shard':s} for fold in ['eval','beyond_piano'] for s in range(n)] + print('matrix='+json.dumps(jobs));print('shards='+str(n)) + PY + evaluate: + needs: plan + runs-on: ubuntu-latest + timeout-minutes: 350 + strategy: + fail-fast: false + max-parallel: 12 + matrix: + job: ${{ fromJSON(needs.plan.outputs.matrix) }} + env: + MATCHMAKER_DATA_DIR: ${{ github.workspace }}/benchmark-data + MATCHMAKER_DATA_BRANCH: 03b51262b9bce7993203044fa45c9be9dadebd34 + OMP_NUM_THREADS: '1' + OPENBLAS_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + NUMEXPR_NUM_THREADS: '1' + NUMBA_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: pip + - name: Install fixed environment + run: | + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 ffmpeg + python .github/install_matchmaker.py + pip install pyyaml pydantic-settings + - name: Install archived offline numerical environment + run: | + # The original server uses these numerical packages with synctoolbox + # 1.3.2, despite its obsolete pandas/numba upper bounds. Its used DTW + # and audio functions are smoke-tested below before the full shard. + pip install 'numpy==1.26.4' 'scipy==1.14.1' 'pandas==2.2.3' 'librosa==0.10.2' 'numba==0.64.0' ipython pretty_midi music21 + pip install --no-deps 'synctoolbox==1.3.2' 'libfmp==1.3.0' + python matchmaker_eval/run_offline.py --fold example --no-fetch --output results/offline-preflight + python - <<'PY' + import json + r=json.load(open('results/offline-preflight/metrics.json')) + assert r['n_failed']==0 and r['n_pieces']==1 + PY + - name: Run offline reference + run: | + python matchmaker_eval/run_offline.py --fold '${{ matrix.job.fold }}' \ + --shard '${{ matrix.job.shard }}' --num-shards '${{ needs.plan.outputs.shards }}' \ + --piece-timeout 2400 --output results/offline + - name: Record runner and package provenance + if: always() + run: | + mkdir -p results/offline + pip freeze > results/offline/environment.txt + python - <<'PY' + import json,os + from pathlib import Path + Path('results/offline/CI.json').write_text(json.dumps({k:os.environ.get(k) for k in ['GITHUB_RUN_ID','GITHUB_RUN_ATTEMPT','GITHUB_SHA','MATCHMAKER_DATA_BRANCH']},indent=2)) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: offline-${{ matrix.job.fold }}-${{ matrix.job.shard }} + path: results/offline + retention-days: 30 + merge: + needs: [plan,evaluate] + if: always() && needs.plan.result == 'success' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: | + python .github/install_matchmaker.py + pip install pyyaml pydantic-settings + - uses: actions/download-artifact@v4 + with: + pattern: offline-* + path: results/shards + - name: Merge and verify completeness + env: + SHARDS: ${{ needs.plan.outputs.shards }} + run: | + python - <<'PY' + import sys,os,json,shutil + from pathlib import Path + sys.path.insert(0,'matchmaker_eval') + from merge_shards import merge + errors=[] + output=Path('results/offline-reference');output.mkdir(parents=True,exist_ok=True) + for fold in ['eval','beyond_piano']: + key='offline-'+fold + stage=Path('results/staging')/key;stage.mkdir(parents=True,exist_ok=True) + try: + for i in range(int(os.environ['SHARDS'])): + src=Path('results/shards')/f'{key}-{i}' + shutil.copytree(src,stage/str(i)) + r=merge(stage,output/key) + if r['partial'] or r['n_failed']:raise ValueError('Incomplete cases') + except Exception as e:errors.append(key+': '+str(e)) + shutil.copytree('results/shards',output/'raw-shards') + (output/'verification.json').write_text(json.dumps({'complete':not errors,'errors':errors},indent=2)) + if errors:raise SystemExit(errors) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: benchmark-results-offline + path: results/offline-reference + retention-days: 90 diff --git a/.github/workflows/evaluate-references.yml b/.github/workflows/evaluate-references.yml index 10e1e4f..7160be7 100644 --- a/.github/workflows/evaluate-references.yml +++ b/.github/workflows/evaluate-references.yml @@ -17,7 +17,7 @@ # Actions -> Evaluate references -> Run workflow # input_type: both shards: 8 # -# 15 described entries x 8 shards is 120 jobs. They queue against the account's +# 17 described entries x 8 shards is 136 jobs. They queue against the account's # concurrency limit rather than all starting at once, so expect this to take a # while; that is the price of every row being measured the same way. name: Evaluate references @@ -36,7 +36,7 @@ on: required: false default: "" fold: - description: "Fold to evaluate on" + description: "Fold: eval, beyond_piano, diagnostics, offline, or amt_reference" required: false default: eval shards: @@ -45,26 +45,132 @@ on: default: "8" permissions: - contents: write + contents: read concurrency: - # Shares evaluate.yml's group: both commit results/, and two at once would - # race on the leaderboard. - group: evaluate + # Avoid overlapping evaluations of the same branch and fold. + group: evaluate-${{ github.ref }}-${{ github.event.inputs.fold || 'eval' }} cancel-in-progress: false env: FOLD: ${{ github.event.inputs.fold || 'eval' }} jobs: + ophmm_playthrough: + name: ophmm comparison / evaluate (${{ matrix.condition }}, ${{ matrix.shard }}) + if: github.event.inputs.fold == 'ophmm_playthrough' + runs-on: ubuntu-latest + timeout-minutes: 180 + strategy: + fail-fast: false + max-parallel: 8 + matrix: + condition: ['on', 'off'] + shard: [0, 1, 2, 3] + env: + OMP_NUM_THREADS: '1' + OPENBLAS_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + NUMEXPR_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install pinned environment + run: | + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 + python .github/install_matchmaker.py + pip install pyyaml pydantic-settings + - name: Evaluate frozen piano fold + run: | + python matchmaker_eval/run_submission.py --method outerhmm --input-type midi --fold eval \ + --global-transition '${{ matrix.condition }}' \ + --shard '${{ matrix.shard }}' --num-shards 4 --output results/run + pip freeze > results/run/environment.txt + - uses: actions/upload-artifact@v4 + if: always() + with: + name: ophmm-${{ matrix.condition }}-${{ matrix.shard }} + path: results/run + retention-days: 90 + merge_ophmm_playthrough: + name: ophmm comparison / merge + needs: ophmm_playthrough + if: always() && needs.ophmm_playthrough.result != 'skipped' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: | + python .github/install_matchmaker.py + pip install pyyaml pydantic-settings + - uses: actions/download-artifact@v4 + with: + pattern: ophmm-* + path: results/shards + - name: Merge both conditions and check coverage + run: | + python - <<'PY' + import json,shutil + from pathlib import Path + from matchmaker_eval.merge_shards import merge + out=Path('results/comparison') + for condition in ('on','off'): + staging=Path('results/staging')/condition + for shard in range(4): + src=Path('results/shards')/f'ophmm-{condition}-{shard}' + meta=json.loads((src/'metrics.json').read_text()) + assert meta['metadata']['global_transition']==condition + if condition=='off': assert all(x['global_transition_nonzero']==0 for x in meta['pieces']) + shutil.copytree(src,staging/str(shard)) + result=merge(staging,out/condition) + assert not result['partial'] and result['n_failed']==0 and result['n_pieces']==146 + shutil.copytree('results/shards',out/'raw-shards') + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: ophmm-playthrough-comparison + path: results/comparison + retention-days: 90 + + amt_reference: + name: amt replay + if: github.event.inputs.fold == 'amt_reference' + uses: ./.github/workflows/evaluate-amt.yml + with: + shards: ${{ github.event.inputs.shards || '4' }} + + offline: + if: github.event.inputs.fold == 'offline' + uses: ./.github/workflows/evaluate-offline.yml + with: + shards: ${{ github.event.inputs.shards || '8' }} + + diagnostics: + if: github.event.inputs.fold == 'diagnostics' + uses: ./.github/workflows/evaluate-diagnostics.yml + with: + shards: ${{ github.event.inputs.shards || '4' }} + only: ${{ github.event.inputs.only || '' }} + input_type: ${{ github.event.inputs.input_type || 'both' }} + plan: + name: main / plan + if: github.event.inputs.fold != 'diagnostics' && github.event.inputs.fold != 'offline' && github.event.inputs.fold != 'amt_reference' && github.event.inputs.fold != 'ophmm_playthrough' runs-on: ubuntu-latest outputs: jobs: ${{ steps.plan.outputs.jobs }} count: ${{ steps.plan.outputs.count }} + entries: ${{ steps.plan.outputs.entries }} data_repo: ${{ steps.source.outputs.data_repo }} data_branch: ${{ steps.source.outputs.branch }} num_shards: ${{ steps.plan.outputs.num_shards }} + results_root: ${{ steps.plan.outputs.results_root }} steps: - uses: actions/checkout@v4 @@ -78,6 +184,7 @@ jobs: pip install --quiet pyyaml python - <<'PY' >> "$GITHUB_OUTPUT" import json, os, yaml + from matchmaker_eval.folds import load_fold described = yaml.safe_load( open("data/builtin_methods.yaml").read() ) or {} @@ -85,6 +192,14 @@ jobs: types = ("midi", "audio") if wanted == "both" else (wanted,) only = [m for m in os.environ["ONLY"].split() if m] n = int(os.environ["SHARDS"]) + if not 1 <= n <= 32: + raise SystemExit("shards must be between 1 and 32") + fold = os.environ["FOLD"] + pieces = load_fold(fold) + available = {t for t in ("midi", "audio") if any(p.has_performance(t) for p in pieces)} + if wanted != "both" and wanted not in available: + raise SystemExit(f"Fold {fold!r} has no {wanted} performances") + types = tuple(t for t in types if t in available) jobs = [ {"method": method, "input_type": t, "shard": s} @@ -95,7 +210,11 @@ jobs: ] print(f"jobs={json.dumps(jobs)}") print(f"count={len(jobs)}") + entries = sorted({j["method"] + "-" + j["input_type"] for j in jobs}) + print(f"entries={json.dumps(entries)}") print(f"num_shards={n}") + output = f"results/ci/{fold}" + print(f"results_root={output}") PY env: INPUT_TYPE: ${{ github.event.inputs.input_type || 'both' }} @@ -115,6 +234,7 @@ jobs: echo "${{ steps.plan.outputs.count }} shard job(s) to run" evaluate: + name: main / evaluate (${{ matrix.job.method }}, ${{ matrix.job.input_type }}, ${{ matrix.job.shard }}) needs: plan if: needs.plan.outputs.count != '0' runs-on: ${{ vars.BENCHMARK_RUNNER || 'ubuntu-latest' }} @@ -141,11 +261,8 @@ jobs: - name: Install the benchmark environment run: | python -m pip install --upgrade pip - # Pinned to the matchmaker 0.4.0 release (tag v0.4.0, main after #73): - # its sources are part of the evaluation key, so every row of a run - # must be scored by the same matchmaker. Move every workflow together - # when the pin changes, and re-run the entries: their keys will change. - pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" + # The shared installer fixes the library sources for every job. + python .github/install_matchmaker.py pip install pyyaml pydantic-settings - name: Check out the benchmark data @@ -221,21 +338,15 @@ jobs: retention-days: 14 merge: + name: main / merge needs: [plan, evaluate] - if: always() && needs.plan.outputs.count != '0' + if: always() && needs.plan.result == 'success' && needs.plan.outputs.count != '0' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - name: Catch up with anything committed while this run was queued or evaluating - # actions/checkout pins to the commit that existed when this run was - # dispatched, not now. The `evaluate` concurrency group serializes the - # actual pushes, but a run can still sit queued -- or just take a long - # time evaluating -- behind another one that lands a commit in the - # meantime. leaderboard.py rewrites the whole file rather than - # appending, so building on a stale base produces a real content - # conflict at push time instead of a clean fast-forward. - run: git pull + - name: Keep preview files outside the code checkout + run: echo "MATCHMAKER_RESULTS_DIR=$RUNNER_TEMP/benchmark-preview" >> "$GITHUB_ENV" - uses: actions/setup-python@v5 with: @@ -243,7 +354,7 @@ jobs: - name: Install what the merge needs run: | - pip install --quiet "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" + python .github/install_matchmaker.py pip install --quiet pyyaml pydantic-settings - uses: actions/download-artifact@v4 @@ -255,34 +366,40 @@ jobs: # One run produces shards for many entries; this regroups them by entry # and merges each separately. An entry missing shards stays partial and # off the leaderboard. - run: python matchmaker_eval/merge_references.py results/refshards + env: + EXPECTED_ENTRIES: ${{ needs.plan.outputs.entries }} + run: python matchmaker_eval/merge_references.py results/refshards --fold "$FOLD" --output "${{ needs.plan.outputs.results_root }}" --expected-entries-json "$EXPECTED_ENTRIES" + + - name: Upload the complete merged results + if: always() + uses: actions/upload-artifact@v4 + with: + name: benchmark-results-${{ env.FOLD }} + path: ${{ needs.plan.outputs.results_root }} + if-no-files-found: error + retention-days: 30 + + - name: Stage the piano results for the leaderboard + if: env.FOLD == 'eval' + run: | + mkdir -p "$MATCHMAKER_RESULTS_DIR/submissions" + cp -a "${{ needs.plan.outputs.results_root }}/." "$MATCHMAKER_RESULTS_DIR/submissions/" - name: Export the per-piece detail + if: env.FOLD == 'eval' run: python matchmaker_eval/export_details.py - name: Rebuild the leaderboard + if: env.FOLD == 'eval' run: python matchmaker_eval/leaderboard.py - name: Assemble the site for review + if: env.FOLD == 'eval' run: python matchmaker_eval/build_site.py _site - uses: actions/upload-artifact@v4 + if: env.FOLD == 'eval' with: name: leaderboard-site path: _site retention-days: 14 - - - name: Commit the results - run: | - git config user.name "matchmaker-benchmark[bot]" - git config user.email "actions@github.com" - git add results/ - if git diff --cached --quiet; then - echo "Leaderboard unchanged." - exit 0 - fi - git commit -m "benchmark: evaluate references on the ${{ env.FOLD }} fold - - Run ${{ github.run_id }}, ${{ needs.plan.outputs.count }} shard jobs." - git pull --rebase --autostash - git push diff --git a/.github/workflows/evaluate.yml b/.github/workflows/evaluate.yml index 974c7f0..30fd2a8 100644 --- a/.github/workflows/evaluate.yml +++ b/.github/workflows/evaluate.yml @@ -7,35 +7,14 @@ # data/data_sources.yaml; the plan job reads it there so the address is written # down once (`fetch_data.py --source`). # -# This is the only workflow that writes to the repository, and it runs only on -# `submissions` — on code a maintainer has already reviewed and merged there. -# -# Two branches, on purpose: -# -# submissions a contributor's pull request lands here first. validate- -# submission.yml smoke-tests it on one piece before merge; that -# merge is what this workflow watches for. It diffs -# `submissions/` against its own previous commit, evaluates -# every submission that is new or has changed since — skipping -# ones that are unchanged and already evaluated — and commits -# the result here. Nothing is published from this branch. -# main merging `submissions` into it just carries the already- -# computed results over; nothing is re-evaluated. That merge -# is what publishes (see pages.yml), so it is also the moment -# to read `results/leaderboard.json` on `submissions` first and -# decide whether this batch is ready to go live. -# -# So review has to happen before merging a submission's pull request into -# `submissions` (see docs/maintaining.md#reviewing-a-submission): that merge -# is what starts this workflow, which is the first time the submitted code -# actually runs against the real datasets. To withdraw a result after the -# fact, see matchmaker_eval/retract.py. +# A maintainer explicitly selects a reviewed submission or built-in method. +# Results are uploaded as artifacts and never committed to the code branch. +# After the code is on main, evaluate that main commit and select the +# completed run in Publish leaderboard to preserve and publish a release. # # Sharding is what makes this fit: a job on a GitHub runner is capped at 6 # hours, and audio evaluation over 146 pieces does not fit in one. Shards are -# round-robin, so the merged numbers are identical to an unsharded run. A push -# that brings several new or changed submissions fans out over all of them at -# once — one (submission x shard) matrix, mirroring evaluate-references.yml. +# round-robin, so the merged numbers are identical to an unsharded run. # # It also works unchanged on a self-hosted runner that already holds the data: # set the repository variable MATCHMAKER_DATA_DIR to that copy and the checkout @@ -43,18 +22,10 @@ name: Evaluate submissions on: - push: - # `submissions` only, deliberately — see the branch note above. Evaluating - # on `main` too would re-run everything a merge to `main` brings with it; - # `main` only ever receives already-computed results. `branches:` cannot - # take a variable, so the branch is named here. - branches: [submissions] - paths: - - "submissions/**" workflow_dispatch: inputs: submission: - description: "Submission directory (empty = whatever this push changed)" + description: "Submission directory (leave empty only when specifying method)" required: false default: "" method: @@ -77,11 +48,11 @@ on: default: "8" permissions: - contents: write + contents: read concurrency: - # One evaluation at a time: two would race on results/leaderboard.json. - group: evaluate + # Share the references workflow's lock for the same branch and fold. + group: evaluate-${{ github.ref }}-${{ github.event.inputs.fold || 'eval' }} cancel-in-progress: false env: @@ -97,10 +68,9 @@ jobs: num_shards: ${{ steps.plan.outputs.num_shards }} data_repo: ${{ steps.source.outputs.data_repo }} data_branch: ${{ steps.source.outputs.branch }} + results_root: ${{ steps.plan.outputs.results_root }} steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 - uses: actions/setup-python@v5 with: @@ -108,17 +78,11 @@ jobs: - name: Decide what to evaluate id: plan - # A manual `method` dispatch is a single reference row. A manual - # `submission` dispatch is that one directory, changed or not -- - # useful for a forced rerun after a pipeline fix. Otherwise (a push to - # `submissions`, i.e. a submission's pull request just got merged) - # every submissions// directory touched since the previous - # commit on `submissions` is new or changed, and anything not in that - # diff is already evaluated and skipped. + # Full evaluations are explicit, so a merge cannot start a duplicate run. run: | pip install --quiet pyyaml python - <<'PY' >> "$GITHUB_OUTPUT" - import json, os, subprocess + import json, os import yaml @@ -126,19 +90,10 @@ jobs: method = os.environ.get("METHOD") or "" submission = os.environ.get("SUBMISSION") or "" - def changed_submissions(before, after): - if not before or before == "0" * 40: - return [] - diff = subprocess.run( - ["git", "diff", "--name-only", before, after], - capture_output=True, text=True, check=True, - ).stdout - found = set() - for line in diff.splitlines(): - parts = line.split("/") - if len(parts) >= 3 and parts[0] == "submissions" and not parts[1].startswith("_"): - found.add(f"submissions/{parts[1]}") - return sorted(found) + if not 1 <= n <= 32: + raise SystemExit("shards must be between 1 and 32") + if bool(method) == bool(submission): + raise SystemExit("Specify one submission directory or method, not both") entries = [] jobs = [] @@ -156,40 +111,27 @@ jobs: for s in range(n) ] else: - if submission: - dirs = [submission] - elif os.environ["EVENT_NAME"] == "push": - dirs = changed_submissions(os.environ.get("BEFORE"), os.environ.get("AFTER")) - else: - dirs = [] - for d in dirs: - metadata_path = f"{d}/metadata.yaml" - if not os.path.exists(metadata_path): - # A directory can show up as "changed" because a pull - # request deleted it -- nothing to evaluate there. - print(f"{d} no longer exists, skipping") - continue - input_type = yaml.safe_load(open(metadata_path))["input_type"] - entry = d.split("/")[-1] - entries.append(entry) - jobs += [ - {"target": d, "entry": entry, "input_type": input_type, "shard": s} - for s in range(n) - ] + input_type = yaml.safe_load(open(f"{submission}/metadata.yaml"))["input_type"] + entry = submission.rstrip("/").split("/")[-1] + entries.append(entry) + jobs += [ + {"target": submission, "entry": entry, "input_type": input_type, "shard": s} + for s in range(n) + ] print(f"jobs={json.dumps(jobs)}") print(f"count={len(jobs)}") print(f"entries={' '.join(entries) or 'none'}") print(f"num_shards={n}") + fold = os.environ["FOLD"] + output = f"results/ci/{fold}" + print(f"results_root={output}") PY env: METHOD: ${{ github.event.inputs.method }} SUBMISSION: ${{ github.event.inputs.submission }} INPUT_TYPE: ${{ github.event.inputs.input_type || 'midi' }} SHARDS: ${{ github.event.inputs.shards || '8' }} - EVENT_NAME: ${{ github.event_name }} - BEFORE: ${{ github.event.before }} - AFTER: ${{ github.sha }} - name: Locate this fold's data id: source @@ -229,11 +171,8 @@ jobs: - name: Install the benchmark environment run: | python -m pip install --upgrade pip - # Pinned to the matchmaker 0.4.0 release (tag v0.4.0, main after #73): - # its sources are part of the evaluation key, so every row of a run - # must be scored by the same matchmaker. Move every workflow together - # when the pin changes, and re-run the entries: their keys will change. - pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" + # The shared installer fixes the library sources for every job. + python .github/install_matchmaker.py pip install pyyaml pydantic-settings if [ -d "${{ matrix.job.target }}" ] && [ -s "${{ matrix.job.target }}/requirements.txt" ]; then pip install -r "${{ matrix.job.target }}/requirements.txt" @@ -333,21 +272,13 @@ jobs: merge: needs: [plan, evaluate] - if: always() && needs.plan.outputs.count != '0' + if: always() && needs.plan.result == 'success' && needs.plan.outputs.count != '0' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - name: Catch up with anything committed while this run was queued or evaluating - # actions/checkout pins to the commit that existed when this run was - # dispatched, not now. The `evaluate` concurrency group serializes the - # actual pushes, but a run can still sit queued -- or just take a long - # time evaluating -- behind another one that lands a commit in the - # meantime (evaluate-references.yml shares this group). leaderboard.py - # rewrites the whole file rather than appending, so building on a - # stale base produces a real content conflict at push time instead of - # a clean fast-forward. - run: git pull + - name: Keep preview files outside the code checkout + run: echo "MATCHMAKER_RESULTS_DIR=$RUNNER_TEMP/benchmark-preview" >> "$GITHUB_ENV" - uses: actions/setup-python@v5 with: @@ -357,7 +288,7 @@ jobs: # Merging only recomputes the pooled summary from the shards' alignment # paths, so it needs numpy and the eval helpers, not matchmaker itself. run: | - pip install --quiet "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" + python .github/install_matchmaker.py pip install --quiet pyyaml pydantic-settings - uses: actions/download-artifact@v4 @@ -370,41 +301,41 @@ jobs: # this regroups them by entry (see refshard-- above) and # merges each separately. An entry missing shards stays partial and # off the leaderboard rather than being merged into a bad record. - run: python matchmaker_eval/merge_references.py results/refshards + run: python matchmaker_eval/merge_references.py results/refshards --fold "$FOLD" --output "${{ needs.plan.outputs.results_root }}" + + - name: Upload the complete merged results + if: always() + uses: actions/upload-artifact@v4 + with: + name: benchmark-results-${{ env.FOLD }} + path: ${{ needs.plan.outputs.results_root }} + if-no-files-found: error + retention-days: 30 + + - name: Stage the piano results for the leaderboard + if: env.FOLD == 'eval' + run: | + mkdir -p "$MATCHMAKER_RESULTS_DIR/submissions" + cp -a "${{ needs.plan.outputs.results_root }}/." "$MATCHMAKER_RESULTS_DIR/submissions/" - name: Export the per-piece detail + if: env.FOLD == 'eval' # Dataset breakdowns, per-piece rows and the decimated alignment paths # the leaderboard page plots. Written per entry and loaded on demand. run: python matchmaker_eval/export_details.py - name: Rebuild the leaderboard + if: env.FOLD == 'eval' run: python matchmaker_eval/leaderboard.py - name: Assemble the site for review - # `submissions` does not publish (see pages.yml), so the only way to - # see what this run did to the leaderboard would otherwise be to read - # JSON. This uploads the real page as an artifact: download it, - # `python -m http.server` inside it, and you are looking at what - # merging `submissions` into `main` would publish. + if: env.FOLD == 'eval' + # Preview only this run; it does not alter the public leaderboard. run: python matchmaker_eval/build_site.py _site - uses: actions/upload-artifact@v4 + if: env.FOLD == 'eval' with: name: leaderboard-site path: _site retention-days: 14 - - - name: Commit the results - run: | - git config user.name "matchmaker-benchmark[bot]" - git config user.email "actions@github.com" - git add results/ - if git diff --cached --quiet; then - echo "Leaderboard unchanged." - exit 0 - fi - git commit -m "benchmark: evaluate ${{ needs.plan.outputs.entries }} on the ${{ env.FOLD }} fold - - Run ${{ github.run_id }}, ${{ needs.plan.outputs.num_shards }} shards each." - git pull --rebase --autostash - git push diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index c547bbb..c8863b2 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -1,48 +1,86 @@ # Publish the leaderboard to GitHub Pages. # -# The site is docs/ plus a copy of results/leaderboard.json, so the page is a -# static read of exactly the file the evaluation workflow committed. +# Selected completed runs are preserved in a release before deployment. +# Documentation-only rebuilds reuse the last published result snapshot. name: Publish leaderboard on: push: - # `main` only, deliberately. The `submissions` branch evaluates and commits - # results without publishing them, so a run can be checked or withdrawn - # before it reaches the site. See the note in evaluate.yml. branches: [main] paths: - - "results/leaderboard.json" - "docs/**" + - "matchmaker_eval/build_site.py" + - "matchmaker_eval/release_results.py" - ".github/workflows/pages.yml" workflow_dispatch: + inputs: + source_runs: + description: "Completed CI run IDs, separated by spaces; later runs replace entries (empty = republish)" + required: false + default: "" + release_tag: + description: "New benchmark-* tag when releasing; otherwise existing tag or empty for latest" + required: false + default: "" permissions: - contents: read + contents: write + actions: read pages: write id-token: write concurrency: group: pages - cancel-in-progress: true + cancel-in-progress: false jobs: build: + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest + outputs: + ready: ${{ steps.results.outputs.ready }} + env: + GH_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Keep published results outside the code checkout + run: echo "MATCHMAKER_RESULTS_DIR=$RUNNER_TEMP/benchmark-published-results" >> "$GITHUB_ENV" + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install result export dependencies + if: inputs.source_runs != '' + run: | + python .github/install_matchmaker.py + pip install pyyaml pydantic-settings + + - name: Preserve selected runs or fetch published results + id: results + env: + SOURCE_RUNS: ${{ inputs.source_runs }} + RELEASE_TAG: ${{ inputs.release_tag }} + run: | + python matchmaker_eval/release_results.py --source-runs "$SOURCE_RUNS" --tag "$RELEASE_TAG" - name: Assemble the site - # Same script the staging preview uses, so what a maintainer looked at - # on the `submissions` branch is assembled exactly like what goes live. + if: steps.results.outputs.ready == 'true' run: python matchmaker_eval/build_site.py _site - uses: actions/configure-pages@v5 + if: steps.results.outputs.ready == 'true' - uses: actions/upload-pages-artifact@v3 + if: steps.results.outputs.ready == 'true' with: path: _site deploy: needs: build + if: needs.build.outputs.ready == 'true' runs-on: ubuntu-latest environment: name: github-pages diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a7d4857..7e220db 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -41,7 +41,7 @@ jobs: # matchmaker_eval/test_audio.py, which tests/test_audio_runner.py loads. run: | python -m pip install --upgrade pip - pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" + python .github/install_matchmaker.py pip install pyyaml pydantic-settings tabulate wandb pytest - name: Run the tests diff --git a/.github/workflows/validate-submission.yml b/.github/workflows/validate-submission.yml index 968972f..25c37ea 100644 --- a/.github/workflows/validate-submission.yml +++ b/.github/workflows/validate-submission.yml @@ -54,11 +54,8 @@ jobs: # matchmaker_eval/utils.py, and nothing else. run: | python -m pip install --upgrade pip - # Pinned to the matchmaker 0.4.0 release (tag v0.4.0, main after #73): - # its sources are part of the evaluation key, so every row of a run - # must be scored by the same matchmaker. Move every workflow together - # when the pin changes, and re-run the entries: their keys will change. - pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" + # The shared installer fixes the library sources for every job. + python .github/install_matchmaker.py pip install pyyaml pydantic-settings - name: Find the submissions touched by this pull request diff --git a/.gitignore b/.gitignore index 2d5e45c..b5e764e 100644 --- a/.gitignore +++ b/.gitignore @@ -182,26 +182,9 @@ reports/ *exports/ scripts/ -# The top-level results/ directory is the published benchmark record, so it is -# tracked. `*results/` above would otherwise swallow it, and git cannot -# re-include a file whose parent directory is excluded — hence the explicit -# un-ignore of the directory before its contents are filtered. -!/results/ -/results/* -!/results/leaderboard.json -!/results/leaderboard.csv -# Per-dataset boards (linked from the page) and every evaluation key's table: -# pages.yml builds the site from what is committed here. -!/results/leaderboard-*.json -!/results/leaderboard-*.csv -!/results/archive/ -!/results/submissions/ -!/results/details/ -# Per-submission runs: keep the metrics record, drop the reproducible bulk -# (alignment paths and plots, ~8 MB per submission per fold). Those are -# published as workflow artifacts instead. -/results/submissions/*/* -!/results/submissions/*/metrics.json +# New generated results belong in CI artifacts and release assets. +# Previously tracked snapshots remain unchanged; CI never commits results. +/results/ # Assembled leaderboard site (matchmaker_eval/build_site.py) _site/ diff --git a/README.md b/README.md index 243bc90..16bf2c0 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,12 @@ data** — the evaluation runs on GitHub's runners, which fetch what they need. | **Library** | [matchmaker](https://github.com/pymatchmaker/matchmaker) | | **Metrics** | beat error, ms error, tracking rate, real-time factor | +Final result bundles are available under [Releases](https://github.com/pymatchmaker/matchmaker_benchmark/releases). +Maintainers squash-merge code into main, preserve selected completed CI runs in +a release and publish its snapshot. Reviewed pre-merge results can be reused +when the evaluation logic and data are unchanged. Generated results +are not committed by CI. See [running and publishing results](docs/ci-evaluation.md). + ## Submit a score follower ```bash @@ -83,13 +89,15 @@ code; after merge it is evaluated and appears on the leaderboard. │ │ │ fetches its own data, │ │ │ runs 146 pieces in │ │ │ parallel shards, - │ │ │ commits the leaderboard + │ │ │ uploads results for release │ │ │ │ └──────────────── leaderboard on GitHub Pages ◄─────────────────────┘ ``` Review is the trust boundary: CI executes submitted code, it does not sandbox -it. Everything after merge is automatic. +it. Full evaluation and publication are explicitly started by a maintainer. +Evaluation may run on a reviewed branch; publication runs from `main` after +merge. A merge alone does not start a full evaluation. ## Folds @@ -202,9 +210,13 @@ contract. from the first annotated performance onset through the first window that reaches the final onset. A window's statistic is the median absolute beat error, and a piece fails when any evaluated window exceeds the modality - threshold — 1.0 beat for audio, 0.5 for MIDI. + threshold — 1.0 musical beat for audio, 0.1 for MIDI. A musical beat groups + three denominator-note units in compound meter (6/8, 9/8, 12/8, 6/4, etc.) + and one elsewhere. The reference score's time signature is looked up at + each annotated onset, including changes within a piece and a window. - **Precision metric**: beat error (performance → score), pooled over the - pieces that method actually tracked. + pieces that method actually tracked. These error summaries and tolerance + accuracies retain denominator-note beat units. - **Secondary precision metric**: ms error (score → performance), same pooling. - **Aggregation**: precision metrics are event-pooled across tracked pieces. - **Ranking**: tracking rate first, then median beat error. @@ -259,8 +271,8 @@ docs/ — contributor and maintainer documentation, and the GitHub Pages leaderboard .github/workflows/ validate-submission.yml — pull-request checks (no secrets, read-only token) - evaluate.yml — post-merge evaluation in parallel shards - pages.yml — publishes the leaderboard + evaluate.yml — explicitly dispatched evaluation in parallel shards + pages.yml — preserves selected CI runs in a release and publishes its snapshot ``` ## Acknowledgments diff --git a/data/builtin_methods.yaml b/data/builtin_methods.yaml index 8003cca..178328d 100644 --- a/data/builtin_methods.yaml +++ b/data/builtin_methods.yaml @@ -15,6 +15,15 @@ # leaderboard links each reference's citation to that entry. midi: + dannenberg: + name: Dynamic programming (Bloch and Dannenberg) + authors: ["Bloch and Dannenberg (1985)"] + bib: Bloch1985Real + description: > + Dynamic grouping of individual MIDI notes against score chords, using + a dynamic-programming rating for matched, missing and extra notes. + Reports a match when its rating exceeds the previous maximum. + pthmm: name: Pitch HMM authors: ["Cancino-Chacón et al. (2023)"] diff --git a/data/data_sources.yaml b/data/data_sources.yaml index c765367..cca5fda 100644 --- a/data/data_sources.yaml +++ b/data/data_sources.yaml @@ -35,6 +35,15 @@ branches: # test-only beyond-piano corpora, held with the eval data beyond_piano: eval +# Auxiliary experiments use immutable manifests from the same data repository. +frozen_sources: + diagnostics: + commit: 2840905846c62074555d7be566757ac6fce2d179 + manifest_sha256: 742ca3ab6beab0ce379f20e6f293c07a4a227f2312150a09cf9541e58786ad32 + amt: + commit: 74298e15338a7b0431e96443e965025705736f61 + manifest_sha256: d35985e237869a19455bc4e37d07d92a6776232879d22f8b520b66b258ad3b90 + # Where a fold's / sits inside that repository. Change this if # the repository nests the datasets under a subdirectory, e.g. "data/{dataset}/{path}". layout: "{dataset}/{path}" diff --git a/docs/ci-evaluation.md b/docs/ci-evaluation.md new file mode 100644 index 0000000..d76d5c4 --- /dev/null +++ b/docs/ci-evaluation.md @@ -0,0 +1,154 @@ +# Running the full benchmark on GitHub Actions + +Open **Actions → Evaluate references → Run workflow** and select the code +branch to evaluate. Every shard and the merge use the same Matchmaker sources +from `.github/install_matchmaker.py`, including the 3 kHz SPARC implementation. +The first release under musical-beat TR must include +the complete piano evaluation; run the beyond-piano fold as well for the paper. +Full evaluations run only when explicitly dispatched. PR checks still validate +the code and bundled example without starting the full benchmark. + +The installer pins `develop` at `25960ea`, which includes merged PRs #79, #80 +and #81, including the Dannenberg initial-window correction. It retains the +existing bounded Multi-Fold enumeration (`678366b..0e673e2`) needed by diagnostics, +applied in a temporary CI checkout. No upstream branch or PR is changed. +Every result records the full base commit and patch commits and hashes in +`environment.matchmaker_base_commit` and `environment.matchmaker_patches`. +The full installed-source hash remains part of each run's provenance. +Once the remaining patch is merged upstream, update the installer's base and +remove it. Reviewed branch evaluations can be reused for publication as +described below. + +| Run | input_type | fold | only | shards | +| --- | --- | --- | --- | --- | +| All piano references | both | eval | leave empty | 8 | +| All beyond-piano references | audio | beyond_piano | leave empty | 8 | +| MIDI OPHMM global-transition comparison | midi | ophmm_playthrough | ignored | fixed at 4 | +| Manuscript diagnostics | both | diagnostics | leave empty | 4 | +| Dannenberg perturbations only | midi | diagnostics | dannenberg | 4 | +| Offline reference, both folds | audio | offline | ignored | 8 | +| Frozen AMT reference | midi | amt_reference | ignored | 4 | + +The piano fold contains 146 performances with audio and MIDI. The beyond-piano +fold contains 343 audio inputs: ChoraleBricks (191), KRAISLER (60), SWD (48), and +URMP (44). It has no performance MIDI files. Selecting `both` on that fold runs +only its available audio inputs; explicitly selecting MIDI fails during planning. + +Both folds read the `eval` branch of `pymatchmaker/matchmaker-benchmark-data`, +as configured in `data/data_sources.yaml`. Each shard checks all required score, +performance, and ground-truth files before running. + +## Downloading results + +Once the merge finishes, download **benchmark-results-eval** or +**benchmark-results-beyond_piano** from the run's Artifacts section. This single +artifact contains every merged method directory, including `metrics.json`, +full `wp_.tsv` and `gt_.tsv` paths, and the score meter maps +`meter_.json`. Individual `refshard-*` artifacts remain available for +diagnosing a missing or failed shard. + +CI first merges into a fresh `results/ci//` directory, so the combined +artifact contains only the current run. Piano entries also produce a +`leaderboard-site` preview of this run. Evaluation never commits result files +or updates the public website. Beyond-piano results stay in their own artifact. +A missing method or incomplete merge fails rather than reporting a complete evaluation. +For local merges without `--output`, auxiliary folds use `results/runs//`. + +## Preserving and publishing final results + +1. Squash-merge the code PR into `main` without generated result changes. +2. Select successful **Evaluate references** runs for each required fold. Reuse + reviewed pre-merge runs when their evaluation logic and data match the merged + code. If a method changed, select its corrected rerun after the original run. + Run missing evaluations on `main` only when needed. +3. Check the merged results and the preview. Then open **Publish leaderboard → + Run workflow** on `main`. Set `source_runs` to the completed run IDs separated + by spaces, in replacement order, and `release_tag` to a new version such as + `benchmark-v1`. Later listed runs replace earlier entries for the same method. +4. The workflow preserves the results in that release, targets the publishing + `main` commit, and deploys the website. It does not run any follower again. + +The release contains the original `benchmark-results-*` artifact ZIPs, including +non-piano and auxiliary results when their run IDs are selected, a +`benchmark-snapshot.zip` for the website, and `SHA256SUMS`. The snapshot includes +`release.json` with source run IDs, evaluated commits, branches, attempts, artifact +hashes, the selected run for each leaderboard entry and the previous release. +Python, library, data and evaluation metadata remain in the original +result files. Raw paths stay in the run ZIPs; the website uses decimated paths. + +Only successful, completed runs from this repository can be combined. Each +piano result must identify the commit of its source run. Publishing requires +`main`, but source runs may come from different commits or reviewed PR branches; +their original commit metadata is preserved, including after a squash merge. +The original ZIPs are all retained, including entries superseded in the snapshot. +Previously published methods are retained from the last release; methods under +older evaluation conditions remain outside the current ranking. The first +release must include the piano leaderboard. Later releases can also archive +non-piano or diagnostic results while retaining that leaderboard. + +Result versions are never overwritten. Uploads are prepared as a draft and +published only after all assets have been uploaded. If an upload fails, inspect +the draft before retrying; the workflow refuses to overwrite an existing version. +Actions artifacts expire, so preserve final runs before that happens. + +To redeploy an existing release, leave `source_runs` empty and optionally select +its `release_tag`. With no tag, the latest published `benchmark-*` snapshot is +used. Documentation-only updates reuse that snapshot. Before the first release, +the existing website stays unchanged. No result PR, additional branch or +additional repository is required. The old tracked `results/` files are retained +unchanged for this migration; new publication reads release assets instead. + +## Adding or updating one method + +After the first complete release, add the new method's description to +`data/builtin_methods.yaml` and update the pinned Matchmaker sources in +`.github/install_matchmaker.py`. Merge that code change, then run **Evaluate references** +on `main` with `only=dannenberg`, `input_type=midi` and `fold=eval`, for example. +For an audio method, run its beyond-piano fold too when needed. + +Publish only those new run IDs in a new release. The website snapshot retains +the other methods and replaces the evaluated entries; the previous release +keeps their previous results. This needs no additional selection UI or result +PR. A follower-only change preserves comparison with earlier methods. A data, +fold, ground-truth or scoring change requires results under the new conditions +before they can be ranked together. See [evaluation keys](eval-protocol.md#the-evaluation-key). + +## Evaluation settings + +TR uses onset-anchored 30 s windows and tolerances of 1.0 musical beat for audio +and 0.1 for MIDI. The compound-meter factor is applied at each ground-truth onset, +including meter changes within a window. Position-error summaries remain in +denominator-note beats. See [the evaluation protocol](eval-protocol.md). + +For a saved performance, the same TR calculation and plot can be reproduced with: + +```sh +python matchmaker_eval/verify_tracking.py \ + --wp path/to/wp_1.tsv --gt path/to/gt_1.tsv \ + --meter path/to/meter_1.json --threshold 0.1 --save tracking_1.png +``` + +Use `--threshold 1.0` for audio. The meter map comes from the follower's actual +unfolded score, so it preserves the score-position system used by the saved paths. + + +## MIDI OPHMM play-through comparison + +The `ophmm_playthrough` selection evaluates the same 146-piece piano fold with +score-wide transitions enabled and disabled. It calls the common benchmark +runner and saves both conditions in `ophmm-playthrough-comparison`. It does +not replace the default reference or publish either condition to the leaderboard. + +```sh +python matchmaker_eval/run_submission.py --method outerhmm --input-type midi --fold eval \ + --global-transition off --output results/ophmm-off +``` + +Use `on` for the paired comparison. Disabling the option zeros the skip-from +probabilities before alignment; local transitions and pitch observations are +unchanged. The setting is saved in merged metadata and per-piece +records. The merge requires 146 completed performances per condition and checks +that the disabled transition probabilities remained zero. + +The [diagnostic suites](diagnostics.md) retain their explicit repeat/skip +settings. Selecting a play-through setting does not change those experiments. diff --git a/docs/diagnostics.md b/docs/diagnostics.md new file mode 100644 index 0000000..5008f8a --- /dev/null +++ b/docs/diagnostics.md @@ -0,0 +1,82 @@ +# Running the manuscript diagnostics + +In Actions, choose **Evaluate references**, set `fold` to `diagnostics`, and +use four shards. Select the branch containing this workflow. No leaderboard +files are changed by this run. `benchmark-results-diagnosis` contains all raw +paths, ground truth, per-case metrics, logs, input hashes and a merged summary. +The merge fails if any case or shard of a selected configuration is missing, +duplicated or failed. Leave `only` empty and `input_type=both` for all suites; +set `only=dannenberg` and `input_type=midi` for its 34 perturbation conditions only. + +For non-piano evaluation use the same workflow with `fold=beyond_piano`, +`input_type=audio`. Its artifact is `benchmark-results-beyond_piano`. + +Diagnostic inputs are pinned under `frozen_sources.diagnostics` in +`data/data_sources.yaml`. The runner verifies +the manifest hash and each selected input, including losslessly encoded audio. +The source data release documents the original generator scripts and licenses. +No regeneration with an unrecorded soundfont occurs in CI. + +The diagnostic configurations are in `matchmaker_eval/diagnostics.py`: + +- Perturbations: four audio and seven MIDI followers on 41/34 conditions. +- Repeat examples: Arzt, Multi-Fold Arzt and OPHMM on two K.282 excerpts. +- Folded Batik: Dixon, Arzt, SKF, OPHMM and Multi-Fold Arzt on 24 test movements. +- Global skip: symbolic OPHMM on two K.279 conditions, changing only its + skip-from distribution to disable the global transition. + +Audio OPHMM uses `s_j=1e-100` for the synthetic diagnostic suites, where jumps +are part of the experiment. The folded-Batik OPHMM configuration uses `s_j=1e-5`, as in the original +folded-score diagnostic protocol. The play-through baseline registry uses zero. +Nominal tempo is provided only for the two K.282 illustrative cases (60 BPM). +The synthetic perturbations and recorded folded cases receive the normal +score-based tempo initialization, not the performance's estimated tempo. + +All suites use the same `run_evaluation`, causal onset sampling, 3 kHz SPARC +implementation, and musical-beat tracking criterion as the main benchmark. +Accuracy remains in score denominator-note beats. The input manifest specifies +whether the score is unfolded. Repeat ground truth retains backward jumps. +The perturbation summary averages per-condition MeanAE over tracked cases; +raw per-case paths also support pooled accuracy and common-tracked analyses. +Timing measured on these runners is retained separately from previously +reported RTF. A new runner measurement must not silently replace an earlier +measurement or be selected because it is smaller. + +Local reproduction: + +```sh +python matchmaker_eval/diagnostics.py run \ + --config perturbations-audio-arzt --shard 0 --shards 4 --output results/diagnostics/arzt-0 +``` + +Use the library revision installed by the workflow. Artifacts record both +library and benchmark commits and the GitHub run ID. A raw-path re-score from +an old local experiment is not equivalent to a CI execution of a follower. + +## Offline reference + +Set `fold=offline` (eight shards) to run the offline reference on the piano +and beyond-piano folds. `benchmark-results-offline` includes the merged +results and original shards. The offline pipeline is migrated from the saved +server script, using its verified synctoolbox 1.3.2 environment, 50 Hz features, +22,050 Hz onset filterbank and DTW weights [1.5, 1.5, 2.0]. It is not an online +follower. These results are archived, never inserted into the online leaderboard. + +The archived offline numerical environment uses NumPy 1.26.4, SciPy 1.14.1, +pandas 2.2.3, librosa 0.10.2, numba 0.64.0 and libfmp 1.3.0, verified on the +original server. Synctoolbox 1.3.2's old dependency upper bounds do not describe +that working environment. CI installs the two pure-Python toolbox packages +without their obsolete dependency pins, then runs the example alignment as a +preflight. The exact installed package list is saved in each artifact. This +compatibility setup is confined to offline reference jobs. + +## Frozen AMT outputs + +Set `fold=amt_reference` (four shards) for the 146 piano transcriptions with +OLTWArzt, PTHMM and SLT_OLTW. The source MIDI is public and pinned by +`data/data_sources.yaml` under `frozen_sources.amt`. CI executes the symbolic +followers, not the private AMT model. +It uses the original audio ground truth and the audio TR tolerance. The saved +MIDI timestamps are unchanged. New runner timings measure the follower only +and must not replace end-to-end AMT RTF in the manuscript. +The artifact is `benchmark-results-amt-reference`. diff --git a/docs/eval-protocol.md b/docs/eval-protocol.md index a757bb5..4576dcd 100644 --- a/docs/eval-protocol.md +++ b/docs/eval-protocol.md @@ -163,8 +163,25 @@ the threshold, and the piece counts as **lost** if any evaluated window fails. | Input | Threshold | | --- | --- | -| audio | 1.0 beat | -| MIDI | 0.5 beat | +| audio | 1.0 musical beat | +| MIDI | 0.1 musical beat | + +A musical beat contains three denominator-note units in compound time +signatures (numerators 6, 9, 12, and larger multiples of three), and one in +other meters. Simple triple meters such as 3/4 and 3/8 are not grouped. +At every reference onset, the absolute position error is divided by the factor +for the time signature at that reference score position **before** computing +the window median. This uses the follower's actual unfolded score, retaining +meter changes within a performance, even inside a single evaluation window. +The factor follows the reference position, not a potentially incorrect estimate. + +Thus the native-coordinate tolerance in a compound passage is 3.0 +denominator-note beats for audio and 0.3 for MIDI. The output paths, ground +truth, MeanAE, MedAE, standard deviations, and tolerance accuracies retain +denominator-note units; only TR uses musical beats. Each run saves a +`meter_.json` alongside its full paths so the criterion can be reproduced. +Scores without a time signature use the parser's 4/4 default, recorded as +`assumed_time_signature` in that file. Accuracy metrics are reported over tracked pieces only. A piece that crashes or times out counts as lost. @@ -230,28 +247,37 @@ one is a matter of data hosting and policy, not code. It is not in place today. Two rows are only comparable when everything that decides their numbers, apart from the follower itself, was the same. Every run records those -conditions and hashes them into one **evaluation key**, e.g. `ek1-3f9c0a1b2d4e`: +conditions and hashes them into one **evaluation key**, e.g. `ek2-3f9c0a1b2d4e`: | Component | What it pins | | --- | --- | | `fold_sha256` | The fold CSV: which pieces, their paths, `estimated_bpm` | | `data_sha256` | The bytes of every file a piece was scored with: the score, the performance that was streamed, the ground truth | | `scoring_sha256` | The benchmark's scoring code: `eval.py`, `utils.py`, `verify_tracking.py`, and the thresholds and per-piece scoring in `run_submission.py` | -| `matchmaker_sha256` | The installed matchmaker sources: ground-truth resolution, beat errors, tracking windows, SPARC, and the reference followers | +| `matchmaker_scoring_sha256` | Matchmaker's `matchmaker.py` and `utils/eval.py`: shared score loading, ground-truth resolution, beat errors, tracking windows and SPARC | | `partitura` | The version that parses every score and match file | They are content hashes, not commit ids, on purpose: a results commit or a README edit changes a commit but not a number, while any change to what is -read or how it is scored changes the key. The `ek1` prefix names the scheme; if +read or how it is scored changes the key. The `ek2` prefix names the scheme; if the set of components ever changes, so does the prefix. +The full library hash, `matchmaker_sha256`, and the installed commit and +environment are retained as provenance. All shards of one method's run must +still share that full hash. It is excluded from the ek2 comparison key, so a +new follower or a change confined to a follower does not invalidate other +methods' results. Maintainers must rerun methods affected by a shared follower +implementation change. Changes to the shared score loading or scoring modules +do change the comparison key. Legacy ek1 records keep their original keys; +they are not silently promoted to ek2. + MIDI and audio runs stream different performance files, so their keys always differ in `data_sha256`: each input type has its own current key. The current conditions are set by the most recent run. Its code components (`fold_sha256`, -`scoring_sha256`, `matchmaker_sha256`, `partitura`) apply to every input type, +`scoring_sha256`, `matchmaker_scoring_sha256`, `partitura`) apply to every input type, and each input type's key is that of its most recent run under them. The leaderboard ranks a row only when it has the current key of its input type, so -every ranked row was scored by the same code, and rows of one input type also +every ranked row was scored by the same evaluation code, and rows of one input type also on the same data. A row with another key — from before a scoring fix, a data correction or a fold change — is listed below the table as scored under earlier conditions, with the components that differ, and rejoins the ranking @@ -267,10 +293,10 @@ first and last published, and its components. A key's archive is updated while i and frozen once a newer key takes over. So cite a number together with the key of its input type, e.g. *"tracking rate 0.84 (benchmark -evaluation key `ek1-3f9c0a1b2d4e`)"*. Anyone can then find the exact table it +evaluation key `ek2-3f9c0a1b2d4e`)"*. Anyone can then find the exact table it came from, and see whether a later leaderboard was scored under the same -conditions or not. The per-piece records of a key are in the repository's -history at the `benchmark_commit` its rows record. +conditions or not. Release assets preserve the per-piece records and identify +the `benchmark_commit` that produced them. ## Reproducing a leaderboard row diff --git a/docs/index.html b/docs/index.html index 28262ef..919c90e 100644 --- a/docs/index.html +++ b/docs/index.html @@ -600,8 +600,11 @@

Tracked

The performance is walked in 30-second windows, one starting at every annotated onset. A piece counts as tracked unless the median beat error - in any window exceeds the tolerance — 0.5 beats for MIDI, 1.0 for - audio. A follower that loses the performer produces meaningless errors, + in any window exceeds the tolerance — 0.1 musical beat for MIDI, 1.0 for + audio. In compound meter, three denominator-note units form one musical + beat. The reference meter is applied at each onset, including changes + within a piece. Position-error summaries retain denominator-note units. + A follower that loses the performer produces meaningless errors, so accuracy is only reported over the pieces it held onto.

@@ -644,7 +647,7 @@

Per-piece and per-dataset results

Evaluation key

Every ranked row was scored under the same conditions: the same fold, - scoring code, matchmaker sources and score parser, and, within an input + scoring code, shared score loading and score parser, and, within an input type, the same data files. MIDI and audio stream different files, so each has its own key above, a hash of all of these. Cite the key of the row's input type with any number you take from here; @@ -669,7 +672,8 @@

Submitting

Write one Python file and open a pull request. How to submit · Evaluation protocol · - Download CSV + Download CSV · + Download full results

@@ -869,21 +873,23 @@

Submitting

const { W, H } = plotSize(width, 6.4, 120, 190); const PAD = { l: 52, r: 14, t: 14, b: 30 }; const xs = all.map((p) => p[0]); - const top = Math.max(0.5, ...all.map((p) => p[1])); + // Full-path export retains every meter transition. Historical details use + // the earlier denominator-note thresholds until evaluated under the new rule. + const nativeThreshold = detail.input_type === "audio" ? 1.0 : 0.5; + const tolerance = piece.tr_tolerance || (piece.tracking_criterion ? [] : + [[Math.min(...xs), nativeThreshold], [Math.max(...xs), nativeThreshold]]); + const top = Math.max(0.5, ...all.map((p) => p[1]), ...tolerance.map((p) => p[1])); const { sx, sy, grid, labels } = svgAxes( W, H, PAD, [Math.min(...xs), Math.max(...xs)], [0, top], - detail.axes.x, "|beat error|", (v) => v.toFixed(v < 1 ? 2 : v < 10 ? 1 : 0) + detail.axes.x, "|error| (denominator-note beats)", (v) => v.toFixed(v < 1 ? 2 : v < 10 ? 1 : 0) ); - // The tracking verdict is decided against this line: 0.5 beats for MIDI, - // 1.0 for audio, as a median over each 30-second segment. - const threshold = detail.input_type === "audio" ? 1.0 : 0.5; - const rule = threshold <= top - ? ` - tracking threshold ${threshold}` - : ""; + const tolerancePath = tolerance.map(([t, v], i) => i + ? `H${sx(t).toFixed(1)}V${sy(v).toFixed(1)}` + : `M${sx(t).toFixed(1)},${sy(v).toFixed(1)}`).join(" "); + const rule = tolerance.length ? ` + TR tolerance before window median` : ""; // Without `err` the series is rebuilt from the decimated paths: close, but // a hold followed by a jump can still show as a spike the metrics never saw. const approximate = [piece, other].some((p) => p && !(p.err && p.err.length)); diff --git a/docs/maintaining.md b/docs/maintaining.md index 0164e35..db3873b 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -6,11 +6,9 @@ decisions baked into this setup. ## Reviewing a submission CI has already checked structure, metadata and that the follower runs on one -piece. **Review is the trust boundary**: merging a submission's pull request -into `submissions` is what triggers `evaluate.yml`, which executes the -submitted code on a machine that holds the datasets, immediately and with no -further review in between. Nothing sandboxes it. Read the code before you -merge, not after. +piece. **Review is the trust boundary**: `evaluate.yml` executes the submitted +code on a machine that holds the datasets. Read the code before merging it or +dispatching a full evaluation. A merge does not start that evaluation automatically. `validate_submission.py` prints `review` lines for things worth a second look — network access, subprocesses, `.match` file access, reaching for @@ -32,20 +30,21 @@ What to check by hand: interesting research but will take a long time on 146 pieces. The per-piece budget is 15 minutes. -When in doubt, ask in the pull request. Merging into `submissions` is what -starts the evaluation — see "Staging a run before it is published" below. +When in doubt, ask in the pull request. See "Staging a run before it is published" +below for the evaluation and publication steps. ## Running the evaluation -After merge, `.github/workflows/evaluate.yml` runs the eval fold on GitHub's own -runners and commits the leaderboard. Nobody has to hold the data locally. +After merge, dispatch **Evaluate submissions** on `main` with the submission +directory. It runs on GitHub's runners and uploads merged results and a preview. +Nobody has to hold the data locally. ``` plan ──► evaluate (8 parallel shards) ──► merge │ │ │ │ each shard: combines the shards, which submission, check out the data repo, rebuilds the leaderboard, -which input type, verify its slice is present, commits results/ +which input type, verify its slice is present, uploads artifacts how many shards, run it, upload results where the data is ``` @@ -300,41 +299,24 @@ differ on their own. ### Staging a run before it is published -`submissions` is where evaluation happens; `main` is where it is published. - -| branch | runs the full evaluation | publishes to the site | -| --- | --- | --- | -| `submissions` | yes | **no** | -| `main` | no — just receives the result | yes | - -The order is: - -1. review the code, then merge the submission's pull request into - `submissions`. It is restricted to that one `submissions//` - directory (see `validate-submission.yml`), and CI has only smoke-tested it - on the committed example before this point. -2. That merge is what `evaluate.yml` watches for. It diffs `submissions/` - against its own previous commit and evaluates every directory that is new - or has changed since — including any other submission that was already - waiting there — skipping ones that are unchanged and already evaluated. - This is the first time the submitted code actually runs against the real - datasets, which is why review has to happen at step 1: nothing re-reviews - a submission between merging it and this run. -3. It rebuilds the leaderboard and commits `results/` to `submissions`. - Nothing is published yet — read `results/leaderboard.json` there (or the - `leaderboard-site` artifact for the real page) and rerun or withdraw - anything that looks wrong. -4. When you are satisfied, merge `submissions` into `main`. This is a plain - merge of the already-computed `results/` — it does not re-run anything — - and the resulting commit is what `pages.yml` publishes. - -`pages.yml` is deliberately `main`-only and only triggers on a change to -`results/leaderboard.json`, so nothing reaches the site until step 4 — a bad -run is a branch to fix rather than a page to correct. - -To re-run something already evaluated — after a pipeline bug fix, say — the -diff-based skip in step 2 only applies to the automatic trigger. Dispatch -`evaluate.yml` manually with that submission's name to force it. +Evaluation and publication are separate. Evaluation workflows upload merged +artifacts and a preview without committing results or publishing the website. +Full evaluations require an explicit dispatch; merging a submission cannot +start a duplicate run. Publication runs from `main` after the code has been +squash-merged. Reviewed branch runs can be reused when the merged evaluation +logic and data match; their original code commits remain recorded. + +Inspect the required evaluations, then dispatch **Publish leaderboard** on +`main` with the selected `source_runs` and a new `benchmark-*` release tag. +Later listed runs replace earlier entries for the same method, so put a +corrected method's rerun after the full evaluation. The workflow attaches all +original merged artifacts and the website snapshot to the publishing commit's +release before deploying. +See [the release procedure](ci-evaluation.md#preserving-and-publishing-final-results) +for inputs, downloads and redeployment. No result changes need merging into main. + +A manually dispatched evaluation runs only the requested methods or submission; +publication reuses those outputs and never executes a follower. ### Withdrawing or replacing a published result @@ -342,11 +324,13 @@ A leaderboard row is not a database record. It is derived from `results/submissions//metrics.json` every time `leaderboard.py` runs, so results can always be corrected. -**To replace one** — a rerun after a bug fix — just evaluate again. -`run_submission.py` overwrites the same directory and the next rebuild picks up -the new numbers. Nothing needs deleting. +**To replace one**, evaluate the corrected code on main and select that run in +a new result release. Its completed entries replace those entries in the new +snapshot; the previous release and its raw outputs remain available. -**To withdraw one**, use `retract.py` rather than deleting by hand: it also +**To withdraw one**, first download the released snapshot to a working directory +and set `MATCHMAKER_RESULTS_DIR` to that directory. Use `retract.py` rather than +deleting by hand: it also removes the per-piece detail file, which the site fetches by name and which would otherwise stay readable after the row disappeared. @@ -366,6 +350,9 @@ a result that was on the leaderboard and is not any more is itself a fact about the leaderboard, so it is published rather than quietly erased. The run is moved to `results/retracted//`, so `--reason` is required and `--undo` puts it back. `--purge` deletes instead of archiving, and cannot be undone. +These commands edit the local snapshot only. A withdrawal needs a new corrected +release snapshot and checksums; changing a file in the code checkout does not +change the website. Preserve the original release. `export_details.py` also removes any detail file whose run has gone, so a hand-deleted result cannot leave one behind either. @@ -475,9 +462,10 @@ somewhere else. ## Publishing -`.github/workflows/pages.yml` builds the site from `docs/` plus a copy of -`results/leaderboard*.json`, the CSVs and `results/details/`, and deploys it to -GitHub Pages. It runs whenever the leaderboard changes. +`.github/workflows/pages.yml` combines `docs/` with the selected release snapshot +and deploys it to GitHub Pages. A documentation update reuses the last published +snapshot. `MATCHMAKER_RESULTS_DIR` points the existing export and site-building +scripts at a temporary directory outside the code checkout. ### What the site can show @@ -529,6 +517,6 @@ about 1 MB, or 300 KB over the wire once Pages gzips it. `PATH_POINTS` in A Hugging Face Space is a reasonable second surface — sorting and filtering are easier there than in a static page, and it reaches a different audience. It needs nothing new from this repository: a Space can read -`results/leaderboard.json` straight from the raw GitHub URL, so it stays a -consumer of the same file and cannot drift from it. Add a push step here only if +`leaderboard.json` from the published Pages site, so it stays a consumer of +the same file. Add a push step here only if a Space needs to be told to refresh. diff --git a/docs/submitting.md b/docs/submitting.md index 7a59f33..368fa1e 100644 --- a/docs/submitting.md +++ b/docs/submitting.md @@ -1,11 +1,10 @@ # Submitting a score follower The benchmark takes submissions as pull requests **against the `submissions` -branch**, not `main`. You add one directory, CI checks it, and once a -maintainer reads the code and merges your pull request, that merge itself -evaluates it — along with any other new or changed submission already waiting -on `submissions`. A maintainer publishes the result to the live site by -merging `submissions` into `main` whenever they judge the batch ready. +branch**, not `main`. You add one directory and CI checks it on the bundled +example. A maintainer reviews and squash-merges the code into `main`, explicitly +runs the full evaluation, and selects the completed run for a result release. +Merging alone does not start a full evaluation. ``` you GitHub maintainer GitHub Actions @@ -14,18 +13,17 @@ merging `submissions` into `main` whenever they judge the batch ready. ├────────────────►│ structure + contract │ │ │ ├──► smoke test on the ──────┤ │ │ │ committed example │ reads the code │ - │ │ (no data needed) │ and merges into │ - │ │ │ `submissions` │ + │ │ (no data needed) │ and squash-merges │ + │ │ │ into main │ │ │ ├───────────────────►│ │ │ │ fetches its own data, - │ │ │ evaluates every new or - │ │ │ changed submission in + │ │ │ explicitly evaluates + │ │ │ the selected entry in │ │ │ parallel shards, - │ │ │ commits the result - │ │ │ to `submissions` + │ │ │ uploads results + │ │ │ and a preview │ │ │ │ - │ │ ...whenever ready, the maintainer merges - │ │ `submissions` into `main` to publish... + │ │ ...maintainer checks and releases the results... │ │ │ │ └──────────────── leaderboard on GitHub Pages ◄─────────────────────┘ ``` @@ -179,10 +177,9 @@ GitHub will hold the workflow until a maintainer approves the run. ## 6. After merge -Merging your pull request into `submissions` is what evaluates it — along -with any other submission already on `submissions` that is new or has -changed since the last time this ran, skipping anything unchanged. It runs on -the eval fold, in parallel shards, and commits the result to `submissions`. +A maintainer dispatches **Evaluate submissions** on the merged `main` commit, +specifying your submission directory. It runs on the eval fold in parallel +shards and uploads the result as an artifact. It splits the 146 pieces across parallel jobs, each of which fetches only its own share of the data, so the whole thing finishes in well under an hour even @@ -190,20 +187,20 @@ though a single job could not. The merged result is identical to an unsharded run. The full per-piece output (alignment paths, per-piece metrics) is attached to -the workflow run as an artifact for 30 days; the summary record stays in -`results/submissions/your-name/metrics.json` on `submissions`. +the workflow run as an artifact for 30 days. Evaluation does not commit files +to either code branch. -This does not publish yet. A maintainer reads the result there and decides -when to merge `submissions` into `main`, which is what actually updates the -live leaderboard at +A maintainer checks the result. Selected final runs are then preserved as downloadable +[release assets](https://github.com/pymatchmaker/matchmaker_benchmark/releases). +The release snapshot supplies the live leaderboard at [pymatchmaker.github.io/matchmaker_benchmark](https://pymatchmaker.github.io/matchmaker_benchmark/). ## Updating a submission Open a new pull request against the same directory, still based on -`submissions`. Merging it evaluates your submission again and replaces its -row on `submissions`; the live leaderboard picks up the change the next time -`submissions` merges into `main`. If the change is substantial enough that it +`submissions`. After review and merge, a maintainer evaluates the updated entry +on `main`. A new result release publishes that evaluation; +previous releases remain available. If the change is substantial enough that it is really a different method, submit it under a new name so both can be compared. diff --git a/matchmaker_eval/build_site.py b/matchmaker_eval/build_site.py index 68d15ef..41c34ed 100644 --- a/matchmaker_eval/build_site.py +++ b/matchmaker_eval/build_site.py @@ -25,10 +25,9 @@ import argparse import shutil -from matchmaker_eval.folds import REPO_ROOT +from matchmaker_eval.folds import REPO_ROOT, RESULTS_DIR DOCS_DIR = REPO_ROOT / "docs" -RESULTS_DIR = REPO_ROOT / "results" class SiteError(Exception): @@ -45,7 +44,7 @@ def build(destination: Path) -> dict: shutil.copytree(DOCS_DIR, destination) summary = {"boards": [], "details": 0, "archives": 0, "missing": []} - for name in ("leaderboard.json", "leaderboard.csv"): + for name in ("leaderboard.json", "leaderboard.csv", "release.json"): source = RESULTS_DIR / name if source.exists(): shutil.copy2(source, destination / name) diff --git a/matchmaker_eval/diagnostics.py b/matchmaker_eval/diagnostics.py new file mode 100644 index 0000000..1ec4611 --- /dev/null +++ b/matchmaker_eval/diagnostics.py @@ -0,0 +1,277 @@ +"""Frozen diagnostic suites, executed and scored with the benchmark evaluator. + +The data manifest records every input hash. No paths from a developer's machine +are used at evaluation time. Jobs fail on missing inputs or incomplete results. +""" +from pathlib import Path +import argparse +import hashlib +import json +import os +import sys +import time +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +for p in (ROOT, ROOT / 'matchmaker_eval'): + sys.path.insert(0, str(p)) + +CONFIGS = { + **{f'perturbations-{mode}-{m}': dict(suite='perturbations', input_type=mode, method=m) + for mode, methods in [('audio', ['dixon', 'arzt', 'outerhmm', 'skf']), + ('midi', ['pthmm', 'hmm', 'outerhmm', 'dixon', 'arzt', 'SLT_OLTW', 'dannenberg'])] + for m in methods}, + **{f'repeat_examples-audio-{m}': dict(suite='repeat_examples', input_type='audio', method=m) + for m in ['arzt', 'arzt_multi_fold', 'outerhmm']}, + **{f'folded_batik-audio-{m}': dict(suite='folded_batik', input_type='audio', method=m, + kwargs={'s_j': 1e-5} if m == 'outerhmm' else {}) + for m in ['dixon', 'arzt', 'skf', 'outerhmm', 'arzt_multi_fold']}, + **{f'global_skip-midi-{state}': dict(suite='global_skip', input_type='midi', method='outerhmm', disable_global_skip=state == 'off') + for state in ['on', 'off']}, +} + + +def select_configs(only='', input_type='both'): + methods = set(only.split()) + selected = {name: config for name, config in CONFIGS.items() + if (input_type == 'both' or config['input_type'] == input_type) + and (not methods or config['method'] in methods)} + missing = methods - {config['method'] for config in selected.values()} + if not selected or missing: + raise ValueError(f'No diagnostic configuration for {input_type}: {sorted(missing or methods)}') + return selected + + +def json_value(value): + """Retain model-class identity when serializing effective settings.""" + if isinstance(value, type): + return f'{value.__module__}.{value.__qualname__}' + return float(value) + + +def sha(path): + h = hashlib.sha256() + with Path(path).open('rb') as f: + for chunk in iter(lambda: f.read(1 << 20), b''): + h.update(chunk) + return h.hexdigest() + + +def download(url, path): + path.parent.mkdir(parents=True, exist_ok=True) + for attempt in range(4): + try: + with urllib.request.urlopen(url, timeout=120) as response, path.open('wb') as out: + import shutil + shutil.copyfileobj(response, out) + return + except Exception: + if attempt == 3: + raise + time.sleep(2 ** attempt) + + +def materialize(rel, manifest, root, base_url): + """Fetch a frozen file, reassembling large lossless audio when necessary.""" + meta = manifest['files'][rel] + dest = root / rel + if dest.exists() and sha(dest) == meta['sha256']: + return dest + dest.parent.mkdir(parents=True, exist_ok=True) + if meta.get('parts'): + import shutil + with dest.open('wb') as out: + for part in meta['parts']: + local = root / part['path'] + if not local.exists() or sha(local) != part['sha256']: + download(base_url + part['path'], local) + if sha(local) != part['sha256']: + raise ValueError(f'Corrupt data chunk: {part["path"]}') + with local.open('rb') as f: + shutil.copyfileobj(f, out) + else: + download(base_url + rel, dest) + if sha(dest) != meta['sha256']: + raise ValueError(f'Input hash mismatch: {rel}') + return dest + + +def select_cases(manifest, config, shard=0, shards=1): + if not 1 <= shards <= 32 or not 0 <= shard < shards: + raise ValueError('Invalid shard selection') + cases = [c for c in manifest['cases'] if c['suite'] == config['suite'] and c['input_type'] == config['input_type']] + ids = [c['id'] for c in cases] + if not ids or len(ids) != len(set(ids)): + raise ValueError('Empty or duplicated diagnostic cases') + return [(i, c) for i, c in enumerate(cases) if i % shards == shard] + + +def run_case(case, config, paths, out): + import numpy as np + from matchmaker import Matchmaker + from matchmaker.matchmaker import DEFAULT_KWARGS + from matchmaker.utils.eval import resolve_gt + from matchmaker_eval.eval import run_evaluation + from matchmaker_eval.run_submission import check_follower, piece_time_budget + from matchmaker_eval.utils import TOLERANCES_IN_BEATS + from matchmaker_eval.verify_tracking import TRACKING_THRESHOLDS, score_meter_map, musical_beat_factors + from matchmaker_eval.verify_tracking import check_tracking + + mode, method = config['input_type'], config['method'] + kwargs = dict(DEFAULT_KWARGS[mode][method]) + # The diagnosis tests jumps; the play-through audio registry disables them. + if mode == 'audio' and method == 'outerhmm': + kwargs['s_j'] = 1e-100 + kwargs.update(config.get('kwargs', {})) + out.mkdir(parents=True, exist_ok=True) + with piece_time_budget(2400): + mm = Matchmaker(score_file=str(paths['xml_score']), performance_file=str(paths[f'{mode}_performance']), + method=method, input_type=mode, wait=False, + unfold_score=case['unfold_score'], tempo=case['tempo'], kwargs=kwargs) + check_follower(mm.score_follower) + if config.get('disable_global_skip'): + # S is the skip-from distribution used at every OPHMM update. + # Zero it without changing pitch observations or local transitions. + mm.score_follower.S[:] = 0. + for _ in mm.run(verbose=False): + pass + t, b = resolve_gt(paths['match'], mm.score_part.note_array(), + performance=str(paths[f'{mode}_performance']) if mode == 'midi' else None) + gt = np.column_stack((t, b)) + metrics = run_evaluation(mm, gt=gt, tolerances=TOLERANCES_IN_BEATS, domain='score', + debug=True, save_dir=out, run_name='0', make_plot=False, plot_dist_matrix=False) + wp = mm.score_follower.alignment_path.T + meter = score_meter_map(mm.score_part) + tracking = check_tracking(wp, gt, threshold=TRACKING_THRESHOLDS[mode], segment_duration=30., + beat_factors=musical_beat_factors(gt[:, 1], meter)) + (out/'meter_0.json').write_text(json.dumps(meter, indent=2)+'\n') + # Save directly too: the full path and all annotation points are required. + for name, array in [('wp_0', wp), ('gt_0', gt)]: + np.savetxt(out/(name+'.tsv'), array, delimiter='\t', fmt='%.12g', header='perf_sec\tscore_beat', comments='') + wp = wp[np.argsort(wp[:, 0], kind='stable')] + ix = np.searchsorted(wp[:, 0], gt[:, 0], side='right')-1 + valid = ix >= 0 + error = np.full(len(gt), np.nan) + error[valid] = np.abs(gt[valid, 1]-wp[ix[valid], 1]) + intervals = {} + if 'repeat_metadata' in case: + m = case['repeat_metadata'] + masks = {'before': gt[:, 0] < m['replay_start_sec'], + 'replay': (gt[:, 0] >= m['replay_start_sec']) & (gt[:, 0] < m['replay_end_sec']), + 'after': gt[:, 0] >= m['replay_end_sec']} + for name, mask in masks.items(): + intervals[name] = dict(onsets=int(mask.sum()), within_1_beat=float(np.mean(error[mask] <= 1)), + median_beat_error=float(np.nanmedian(error[mask]))) + return dict(case_id=case['id'], category=case['category'], method=method, input_type=mode, + unfold_score=case['unfold_score'], tempo=case['tempo'], kwargs=kwargs, + disable_global_skip=config.get('disable_global_skip', False), + tracked=bool(tracking['tracked']), max_deviation=float(tracking['max_deviation']), + tracking_criterion={k: tracking[k] for k in ('error_unit', 'threshold', 'window_duration')}, + mean_b=float(np.nanmean(error)), n_events=int(valid.sum()), n_annotated_onsets=len(gt), + metrics=metrics, intervals=intervals) + + +def run(args): + import contextlib + import traceback + from matchmaker_eval.run_submission import environment_info + from matchmaker_eval.fetch_data import frozen_source + pin = frozen_source('diagnostics') + base = f'https://raw.githubusercontent.com/{pin["repository"]}/{pin["commit"]}/diagnostics/' + args.cache.mkdir(parents=True, exist_ok=True) + mp = args.cache/'manifest.json' + if not mp.exists() or sha(mp) != pin['manifest_sha256']: + download(base+'manifest.json', mp) + if sha(mp) != pin['manifest_sha256']: + raise ValueError('Diagnostic manifest hash mismatch') + manifest = json.loads(mp.read_text()) + config = CONFIGS[args.config] + selected = select_cases(manifest, config, args.shard, args.shards) + args.output.mkdir(parents=True, exist_ok=True) + result = dict(config=args.config, definition=config, shard=args.shard, shards=args.shards, + data=pin, environment=environment_info(), github_run_id=os.environ.get('GITHUB_RUN_ID'), + github_run_attempt=os.environ.get('GITHUB_RUN_ATTEMPT'), expected=[c['id'] for _, c in selected], pieces=[], failures=[]) + for i, case in selected: + dest = args.output/f'{i:03d}' + dest.mkdir(exist_ok=True) + try: + keys = ['xml_score', 'match', config['input_type']+'_performance'] + paths = {k: materialize(case['paths'][k], manifest, args.cache, base) for k in keys} + with (dest/'run.log').open('w') as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): + record = run_case(case, config, paths, dest) + record['input_hashes'] = {k: manifest['files'][case['paths'][k]]['sha256'] for k in keys} + record['directory'] = dest.name + (dest/'result.json').write_text(json.dumps(record, indent=2, default=json_value)+'\n') + result['pieces'].append(record) + print(args.config, case['id'], record['tracked'], record['mean_b'], flush=True) + except Exception: + error = traceback.format_exc() + (dest/'error.txt').write_text(error) + result['failures'].append(dict(case_id=case['id'], error=error)) + print(error, flush=True) + (args.output/'metrics.json').write_text(json.dumps(result, indent=2, default=json_value)+'\n') + # Empty shards are valid when a suite contains fewer cases than shards. + (args.output/'metrics.json').write_text(json.dumps(result, indent=2, default=json_value)+'\n') + if result['failures']: + raise SystemExit(f'{len(result["failures"])} diagnostic cases failed') + + +def merge(args): + import shutil + from collections import defaultdict + import numpy as np + manifest = json.loads(args.manifest.read_text()) + records = [json.loads(p.read_text()) for p in args.source.glob('*/metrics.json')] + summary = {}; errors = [] + args.output.mkdir(parents=True, exist_ok=True) + for name, config in select_configs(args.only, args.input_type).items(): + rs = [r for r in records if r['config'] == name] + expected = {c['id'] for _, c in select_cases(manifest, config)} + found = [p['case_id'] for r in rs for p in r['pieces']] + if len(rs) != args.shards or {r['shard'] for r in rs} != set(range(args.shards)) or set(found) != expected or len(found) != len(expected) or any(r['failures'] for r in rs): + errors.append(name) + cells = defaultdict(list) + for r in rs: + for p in r['pieces']: + cells[p['category']].append(p) + summary[name] = {category: dict(total=len(ps), tracked=sum(p['tracked'] for p in ps), + mean_b_tracked=float(np.mean([p['mean_b'] for p in ps if p['tracked']])) if any(p['tracked'] for p in ps) else None, + mean_b_all=float(np.mean([p['mean_b'] for p in ps]))) for category, ps in cells.items()} + provenance = {(r['data']['commit'], r['environment']['benchmark_commit'], + json.dumps({k: v for k, v in r['environment'].items() + if k.startswith('matchmaker')}, sort_keys=True), + r['github_run_id']) for r in records} + if len(provenance) != 1: + errors.append('inconsistent provenance') + for src in args.source.iterdir(): + if src.is_dir(): + shutil.copytree(src, args.output/'raw'/src.name, dirs_exist_ok=True) + shutil.copyfile(args.manifest, args.output/'data_manifest.json') + (args.output/'summary.json').write_text(json.dumps(dict(complete=not errors, incomplete=errors, configurations=summary, + aggregation='For perturbations: arithmetic mean of per-condition MeanAE over tracked conditions; single cases also retain all-case error.', + provenance=[list(p) for p in provenance]), indent=2)+'\n') + if errors: + raise SystemExit('Incomplete diagnostic results: '+', '.join(errors)) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + sub = p.add_subparsers(dest='command', required=True) + r = sub.add_parser('run') + r.add_argument('--config', choices=CONFIGS, required=True) + r.add_argument('--shard', type=int, default=0) + r.add_argument('--shards', type=int, default=1) + r.add_argument('--output', type=Path, required=True) + r.add_argument('--cache', type=Path, default=Path('diagnostic-data')) + m = sub.add_parser('merge') + m.add_argument('--source', type=Path, required=True) + m.add_argument('--output', type=Path, required=True) + m.add_argument('--manifest', type=Path, required=True) + m.add_argument('--shards', type=int, required=True) + m.add_argument('--only', default='', help='Space-separated method names; empty selects all') + m.add_argument('--input-type', choices=['both', 'midi', 'audio'], default='both') + args = p.parse_args() + (run if args.command == 'run' else merge)(args) + +if __name__ == '__main__': + main() diff --git a/matchmaker_eval/eval.py b/matchmaker_eval/eval.py index 9d6a65f..0c99dbf 100644 --- a/matchmaker_eval/eval.py +++ b/matchmaker_eval/eval.py @@ -34,7 +34,9 @@ AudioEvalConfig, save_debug_results, ) -from matchmaker_eval.verify_tracking import check_tracking, plot_tracking +from matchmaker_eval.verify_tracking import ( + TRACKING_THRESHOLDS, check_tracking, plot_tracking, musical_beat_factors, score_meter_map, +) # --------------------------------------------------------------------------- # Evaluation against ground truth (post-processing of a completed Matchmaker run) @@ -300,33 +302,41 @@ def run_score_following( run_name=run_name, level=granularity, ) - # Tracking verification - try: - wp_for_check = wp.T - if gt_pairs is not None: - gt_for_check = gt_pairs - else: - score_annots_for_gt = mm.build_score_annotations( - level=granularity, return_type="beats" - ) - min_len = min(len(score_annots_for_gt), len(perf_annotations)) - gt_for_check = np.column_stack( - [perf_annotations[:min_len], score_annots_for_gt[:min_len]] - ) - tracking = check_tracking(wp_for_check, gt_for_check) - results["tracked"] = tracking["tracked"] - results["max_deviation"] = tracking["max_deviation"] - results["n_failed_segments"] = tracking["n_failed"] - - if save_plots and save_dir is not None and run_name: - plot_tracking( - wp_for_check, - gt_for_check, - title=f"{config.method} #{run_name}", - save_path=Path(save_dir) / f"tracking_{run_name}.png", - ) - except Exception: - pass + # Tracking verification: a scoring error must not silently drop the verdict. + wp_for_check = wp.T + if gt_pairs is not None: + gt_for_check = gt_pairs + else: + score_annots_for_gt = mm.build_score_annotations( + level=granularity, return_type="beats" + ) + min_len = min(len(score_annots_for_gt), len(perf_annotations)) + gt_for_check = np.column_stack( + [perf_annotations[:min_len], score_annots_for_gt[:min_len]] + ) + meter = score_meter_map(mm.score_part) + factors = musical_beat_factors(gt_for_check[:, 1], meter) + threshold = TRACKING_THRESHOLDS[mm.input_type] + tracking = check_tracking(wp_for_check, gt_for_check, threshold=threshold, + beat_factors=factors) + results["tracked"] = tracking["tracked"] + results["max_deviation"] = tracking["max_deviation"] + results["n_failed_segments"] = tracking["n_failed"] + results["tracking_criterion"] = { + key: tracking[key] for key in ("error_unit", "threshold", "window_duration") + } + if save_dir is not None and run_name: + (Path(save_dir) / f"meter_{run_name}.json").write_text(json.dumps(meter, indent=2) + "\n") + + if save_plots and save_dir is not None and run_name: + plot_tracking( + wp_for_check, + gt_for_check, + title=f"{config.method} #{run_name}", + save_path=Path(save_dir) / f"tracking_{run_name}.png", + threshold=threshold, + beat_factors=factors, + ) if save_dir is not None and run_name and not dry_run: with open(Path(save_dir) / f"{run_name}.json", "w") as f: diff --git a/matchmaker_eval/export_details.py b/matchmaker_eval/export_details.py index d24a959..c1f9a57 100644 --- a/matchmaker_eval/export_details.py +++ b/matchmaker_eval/export_details.py @@ -38,11 +38,11 @@ import numpy as np from matchmaker.utils.eval import transfer_positions -from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT +from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR from matchmaker_eval.leaderboard import ACCURACY_COLUMNS, without_nan -SUBMISSION_RESULTS = REPO_ROOT / "results" / "submissions" -DETAILS_DIR = REPO_ROOT / "results" / "details" +SUBMISSION_RESULTS = RESULTS_DIR / "submissions" +DETAILS_DIR = RESULTS_DIR / "details" #: Points kept per polyline. A leaderboard plot is a few hundred pixels wide; #: beyond roughly this many points the extra coordinates are invisible. @@ -63,6 +63,7 @@ #: ``data_sha256`` names the bytes a piece was scored with (see provenance.py): #: provenance, not a measurement. It is published beside the identity fields. PIECE_IDENTITY = ( + "tracking_criterion", "index", "piece_id", "dataset", @@ -182,6 +183,8 @@ def export(run_dir: Path, include_paths: bool = True) -> dict: } for key in ordered_metrics(piece): row[key] = piece[key] + if "tracking_criterion" in piece: + row["tracking_criterion"] = piece["tracking_criterion"] if piece.get("error"): row["error"] = piece["error"] @@ -192,6 +195,16 @@ def export(run_dir: Path, include_paths: bool = True) -> dict: row["wp"] = decimate(wp) row["gt"] = decimate(gt) row["err"] = decimate_peaks(error_series(wp, gt)) + meter_path = run_dir / f"meter_{index}.json" + if meter_path.exists() and len(gt) and piece.get("tracking_criterion"): + from matchmaker_eval.verify_tracking import musical_beat_factors + meter = json.loads(meter_path.read_text()) + factors = musical_beat_factors(gt[:, 1], meter) + changes = np.flatnonzero(np.r_[True, factors[1:] != factors[:-1]]) + keep = np.unique(np.r_[changes, len(gt) - 1]) + threshold = piece["tracking_criterion"]["threshold"] + row["tr_tolerance"] = np.column_stack([gt[keep, 0], threshold * factors[keep]]).tolist() + row["meter"] = meter detail_pieces.append(row) return { @@ -226,7 +239,7 @@ def export(run_dir: Path, include_paths: bool = True) -> dict: #: Per-piece fields built from the run's wp_/gt_ files rather than its metrics. -PATH_FIELDS = ("wp", "gt", "err") +PATH_FIELDS = ("wp", "gt", "err", "tr_tolerance", "meter") def has_path_files(run_dir: Path) -> bool: @@ -340,7 +353,7 @@ def main(): # evaluation it follows had already succeeded. print(f"No complete {args.fold}-fold runs to export.") return 0 - print(f"\nwrote {written} file(s) to {DETAILS_DIR.relative_to(REPO_ROOT)}") + print(f"\nwrote {written} file(s) to {DETAILS_DIR}") return 0 diff --git a/matchmaker_eval/fetch_data.py b/matchmaker_eval/fetch_data.py index e9fce0b..dcd7e68 100644 --- a/matchmaker_eval/fetch_data.py +++ b/matchmaker_eval/fetch_data.py @@ -113,12 +113,21 @@ def load_config() -> dict: value = os.environ.get(variable) if value: config[key] = value + if key == "branch": + # An explicit revision override applies to every selected fold. + config["branches"] = {} # An override of the address implies fetching is wanted, even if the # committed config still has it switched off. config["enabled"] = True return config +def frozen_source(name: str) -> dict: + config = load_config() + return {"repository": f"{config['owner']}/{config['repo']}", + **config["frozen_sources"][name]} + + #: Prefixes GitHub uses for access tokens. If one of these turns up where an #: environment variable *name* belongs, someone has pasted the secret itself. TOKEN_PREFIXES = ("github_pat_", "ghp_", "gho_", "ghs_", "ghu_", "ghr_") diff --git a/matchmaker_eval/folds.py b/matchmaker_eval/folds.py index 1e307b4..9730712 100644 --- a/matchmaker_eval/folds.py +++ b/matchmaker_eval/folds.py @@ -41,6 +41,7 @@ REPO_ROOT = Path(__file__).resolve().parent.parent FOLD_DIR = REPO_ROOT / "data" / "folds" +RESULTS_DIR = Path(os.environ.get("MATCHMAKER_RESULTS_DIR", REPO_ROOT / "results")) #: Root under which the (undistributed) datasets are expected. DATA_ROOT = Path(os.environ.get("MATCHMAKER_DATA_DIR", "~/data")).expanduser() diff --git a/matchmaker_eval/leaderboard.py b/matchmaker_eval/leaderboard.py index 4201a2b..f9ffdd3 100644 --- a/matchmaker_eval/leaderboard.py +++ b/matchmaker_eval/leaderboard.py @@ -46,12 +46,11 @@ from matchmaker.utils.eval import TOLERANCES_IN_BEATS -from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT -from matchmaker_eval.provenance import SHARED_COMPONENTS +from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR +from matchmaker_eval.provenance import comparison_components from matchmaker_eval.retract import read_retractions from matchmaker_eval.submission import read_descriptions -RESULTS_DIR = REPO_ROOT / "results" SUBMISSION_RESULTS = RESULTS_DIR / "submissions" LEADERBOARD_JSON = RESULTS_DIR / "leaderboard.json" LEADERBOARD_CSV = RESULTS_DIR / "leaderboard.csv" @@ -294,7 +293,7 @@ def split_by_conditions(rows: list) -> tuple: is the one that reflects them. MIDI and audio stream different files, so their keys always differ in ``data_sha256``: each input type has its own current key, the newest among its rows that share the newest run's code - components (fold, scoring, matchmaker, partitura). Every ranked row, + components (fold, scoring, shared score loading, partitura). Every ranked row, whichever its input type, therefore shares those. A row with any other key — or none, from before keys existed — was scored @@ -312,8 +311,11 @@ def evaluated(row): return row.get("evaluated") or "" def code(row): - theirs = row.get("evaluation") or {} - return {name: theirs.get(name) for name in SHARED_COMPONENTS} + return { + name: value + for name, value in comparison_components(row.get("evaluation") or {}).items() + if name != "data_sha256" + } newest_code = code(max(rows, key=evaluated)) conditions = {} @@ -326,7 +328,7 @@ def code(row): latest = max(same_code, key=evaluated) conditions[input_type] = { "key": latest.get("evaluation_key"), - "components": latest.get("evaluation") or {}, + "components": comparison_components(latest.get("evaluation") or {}), } current, earlier = [], [] @@ -336,11 +338,11 @@ def code(row): current.append(row) continue earlier.append(row) - theirs = row.get("evaluation") or {} + theirs = comparison_components(row.get("evaluation") or {}) # Without a current key of its own input type, only the code components # can be compared: another input type's data hash says nothing here. - ours = reference["components"] if reference else newest_code - names = set(ours) | set(theirs) if reference else SHARED_COMPONENTS + ours = comparison_components(reference["components"]) if reference else newest_code + names = set(ours) | set(theirs) if reference else set(newest_code) | set(code(row)) row["evaluation_changed"] = sorted( name for name in names if ours.get(name) != theirs.get(name) ) if row.get("evaluation_key") else [] @@ -587,7 +589,7 @@ def main(): written = write(leaderboard) print(render_table(leaderboard)) - print(f"\nwrote {', '.join(written)} to {RESULTS_DIR.relative_to(REPO_ROOT)}") + print(f"\nwrote {', '.join(written)} to {RESULTS_DIR}") return 0 diff --git a/matchmaker_eval/merge_references.py b/matchmaker_eval/merge_references.py index b006d31..2481f2f 100644 --- a/matchmaker_eval/merge_references.py +++ b/matchmaker_eval/merge_references.py @@ -24,6 +24,7 @@ sys.path.insert(0, str(_path)) import argparse +import json import re import shutil from collections import defaultdict @@ -89,6 +90,30 @@ def merge_all(download_dir: Path, output_root: Path, staging: Path) -> dict: return report +def output_for_fold(fold: str) -> Path: + """Keep auxiliary folds from replacing the published piano records.""" + return DEFAULT_OUTPUT if fold == "eval" else REPO_ROOT / "results" / "runs" / fold + + +def check_fold(download_dir: Path, expected: str) -> None: + """Validate the entire batch before any existing result is overwritten.""" + for entry, shards in group(download_dir).items(): + for shard in shards: + actual = json.loads((shard / "metrics.json").read_text()).get("fold") + if actual != expected: + raise MergeError(f"{entry}: expected fold {expected!r}, found {actual!r}") + + +def check_expected_entries(download_dir: Path, expected: list) -> None: + """An entirely missing method is a failed batch, not a smaller benchmark.""" + found = set(group(download_dir)) + if found != set(expected): + raise MergeError( + f"reference entries differ from plan: missing={sorted(set(expected)-found)}, " + f"unexpected={sorted(found-set(expected))}" + ) + + def main(): parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument( @@ -97,9 +122,11 @@ def main(): parser.add_argument( "--output", type=Path, - default=DEFAULT_OUTPUT, - help=f"where merged records go (default: {DEFAULT_OUTPUT})", + default=None, + help="where merged records go (default depends on --fold)", ) + parser.add_argument("--fold", default="eval", help="fold to merge; non-eval folds are isolated") + parser.add_argument("--expected-entries-json", help="JSON array of every entry planned by CI") parser.add_argument( "--staging", type=Path, @@ -110,7 +137,10 @@ def main(): staging = args.staging or (args.download_dir.parent / "refgrouped") try: - report = merge_all(args.download_dir, args.output, staging) + if args.expected_entries_json is not None: + check_expected_entries(args.download_dir, json.loads(args.expected_entries_json)) + check_fold(args.download_dir, args.fold) + report = merge_all(args.download_dir, args.output or output_for_fold(args.fold), staging) except MergeError as e: print(f"\n{e}", file=sys.stderr) return 1 @@ -131,7 +161,7 @@ def main(): f"{info['n_tracked']:>8} {status}" ) print(f"\n{len(report) - incomplete}/{len(report)} entry(ies) complete.") - return 0 + return 1 if incomplete else 0 if __name__ == "__main__": diff --git a/matchmaker_eval/merge_shards.py b/matchmaker_eval/merge_shards.py index 8f9cd5b..75e502b 100644 --- a/matchmaker_eval/merge_shards.py +++ b/matchmaker_eval/merge_shards.py @@ -101,6 +101,9 @@ def merge(root: Path, output: Path) -> dict: source = shard_dir / f"{prefix}_{index}.tsv" if source.exists(): shutil.copy2(source, output / source.name) + meter_path = shard_dir / f"meter_{index}.json" + if meter_path.exists(): + shutil.copy2(meter_path, output / meter_path.name) failures.extend(record.get("failures", [])) pieces.sort(key=lambda p: p["index"]) diff --git a/matchmaker_eval/provenance.py b/matchmaker_eval/provenance.py index 533d2bc..4f07115 100644 --- a/matchmaker_eval/provenance.py +++ b/matchmaker_eval/provenance.py @@ -10,21 +10,20 @@ scoring_sha256 the benchmark's own scoring code: the evaluation and tracking modules, and the parts of run_submission.py that decide ground truth and the tracked verdict - matchmaker_sha256 the installed matchmaker sources. They hold the ground - truth resolution, the beat errors, the tracking - windows and SPARC, and the reference followers + matchmaker_scoring_sha256 + Matchmaker's shared score loading and evaluation: + ground truth, beat errors, tracking windows and SPARC partitura how every score and match file is parsed -``evaluation_key()`` folds these into ``ek1-<12 hex>``. Same key, same -conditions; a different key means at least one of them changed. The ``ek1`` +``evaluation_key()`` folds these into ``ek2-<12 hex>``. Same key, same +conditions; a different key means at least one of them changed. The ``ek2`` prefix is the scheme: if what goes into the key ever changes, the prefix does too, so a key never silently changes meaning. -Content hashes, not commits, on purpose. A data-repository commit changes when -an unrelated corpus is added; a matchmaker commit changes when a follower -nobody evaluated is edited in a way that does not touch the sources (a README); -the benchmark commit changes with every results commit. The bytes that were -actually read are what decide the numbers, so they are what is hashed. +The full ``matchmaker_sha256`` is also recorded, and must agree across shards +of one method's run. It is provenance, not a comparison condition: adding a +follower must not exclude existing methods from the leaderboard. Legacy ek1 +records retain their original meaning and are never relabelled as ek2. """ import hashlib @@ -37,7 +36,7 @@ from matchmaker_eval.folds import REPO_ROOT #: Bumped whenever the set of components, or how one is computed, changes. -SCHEME = "ek1" +SCHEME = "ek2" #: Benchmark modules whose every line can move a score. Hashed whole. SCORING_MODULES = ( @@ -51,20 +50,40 @@ #: same source, and the .pyx they are built from is hashed instead. MATCHMAKER_SOURCE_SUFFIXES = (".py", ".pyx", ".pxd", ".yaml", ".yml", ".json") +# Shared score loading and evaluation live here. Method implementations, +# registration and defaults remain in the full-package provenance hash. +MATCHMAKER_SCORING_MODULES = ("matchmaker.py", "utils/eval.py") + #: The fields of the key, in the order they are documented. COMPONENTS = ( "scheme", "fold_sha256", "data_sha256", "scoring_sha256", - "matchmaker_sha256", + "matchmaker_scoring_sha256", "partitura", ) #: The components every shard of one run must share. data_sha256 is the one #: left out: a shard only hashes its own pieces, and merge_shards.py combines #: the per-piece hashes into the fold's. -SHARED_COMPONENTS = tuple(c for c in COMPONENTS if c != "data_sha256") +SHARED_COMPONENTS = tuple(c for c in COMPONENTS if c != "data_sha256") + ( + "matchmaker_sha256", +) + + +def comparison_components(components: dict) -> dict: + """Comparison conditions only, interpreted under the recorded scheme.""" + if components.get("scheme") == "ek1": + names = tuple( + "matchmaker_sha256" if c == "matchmaker_scoring_sha256" else c + for c in COMPONENTS + ) + elif components.get("scheme") == SCHEME: + names = COMPONENTS + else: + return {} + return {name: components.get(name) for name in names} def sha256_bytes(data: bytes) -> str: @@ -159,6 +178,17 @@ def matchmaker_sha256() -> str: return _digest_lines(lines) +def matchmaker_scoring_sha256() -> str: + """Hash shared score loading and evaluation independently of followers.""" + import matchmaker + + root = Path(matchmaker.__file__).resolve().parent + return _digest_lines( + f"{module}\t{file_sha256(root / module)}" + for module in MATCHMAKER_SCORING_MODULES + ) + + def package_version(name: str) -> str: try: return version(name) @@ -173,20 +203,22 @@ def code_components(fold_sha256: str, decisive: dict) -> dict: "fold_sha256": fold_sha256, "scoring_sha256": scoring_sha256(decisive), "matchmaker_sha256": matchmaker_sha256(), + "matchmaker_scoring_sha256": matchmaker_scoring_sha256(), "partitura": package_version("partitura"), } def evaluation_key(components: dict) -> Optional[str]: - """``ek1-<12 hex>`` for a complete set of components, else None.""" - if any(not components.get(name) for name in COMPONENTS): + """A scheme-qualified key for complete comparison conditions, else None.""" + conditions = comparison_components(components) + if not conditions or not all(conditions.values()): return None - canonical = json.dumps({name: components[name] for name in COMPONENTS}, sort_keys=True) + canonical = json.dumps(conditions, sort_keys=True) return f"{components['scheme']}-{sha256_bytes(canonical.encode())[:12]}" def evaluation_record(code: dict, pieces: list) -> dict: """The ``evaluation`` block a metrics.json carries: the key and what made it.""" components = {**code, "data_sha256": data_sha256(pieces)} - components = {name: components.get(name) for name in COMPONENTS} + components = {name: components.get(name) for name in (*SHARED_COMPONENTS, "data_sha256")} return {"key": evaluation_key(components), "components": components} diff --git a/matchmaker_eval/release_results.py b/matchmaker_eval/release_results.py new file mode 100644 index 0000000..b6a8fdb --- /dev/null +++ b/matchmaker_eval/release_results.py @@ -0,0 +1,256 @@ +"""Preserve completed CI runs in a release, or fetch a published snapshot. + +Called by pages.yml; requires the GitHub CLI and GH_TOKEN. Evaluation is never +run here. MATCHMAKER_RESULTS_DIR keeps downloaded/generated files out of the +source checkout. Raw merged artifacts are attached without modifying them. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import zipfile + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from matchmaker_eval.folds import REPO_ROOT, RESULTS_DIR + +SNAPSHOT = "benchmark-snapshot.zip" + + +def gh(*args): + return subprocess.check_output(["gh", *args], text=True).strip() + + +def api(path): + return json.loads(gh("api", path)) + + +def releases(repo): + pages = json.loads(gh("api", "--paginate", "--slurp", f"repos/{repo}/releases")) + return [release for page in pages for release in page] + + +def latest(records): + candidates = [r for r in records if r["tag_name"].startswith("benchmark-") + and not r["draft"] and not r["prerelease"] + and any(a["name"] == SNAPSHOT for a in r["assets"])] + return max(candidates, key=lambda r: r["published_at"], default=None) + + +def digest(path): + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def extract(archive, destination): + """Reject paths outside the destination before extracting any member.""" + destination = destination.resolve() + with zipfile.ZipFile(archive) as bundle: + for member in bundle.infolist(): + target = (destination / member.filename).resolve() + if not target.is_relative_to(destination) or member.filename.startswith("/"): + raise ValueError(f"Unsafe archive path: {member.filename}") + bundle.extractall(destination) + + +def fetch(repo, release, destination): + if release["draft"] or release["prerelease"]: + raise ValueError("Select a published benchmark release") + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + gh("release", "download", release["tag_name"], "--repo", repo, + "--pattern", SNAPSHOT, "--pattern", "SHA256SUMS", "--dir", str(work)) + hashes = dict(line.split(maxsplit=1)[::-1] + for line in (work / "SHA256SUMS").read_text().splitlines()) + if digest(work / SNAPSHOT) != hashes.get(SNAPSHOT): + raise ValueError("Published snapshot checksum does not match") + unpacked = work / "unpacked" + extract(work / SNAPSHOT, unpacked) + if not (unpacked / "leaderboard.json").is_file(): + raise ValueError("Published snapshot has no leaderboard") + if destination.exists(): + shutil.rmtree(destination) + shutil.copytree(unpacked, destination) + + +def validate_runs(runs, repo): + if not runs or any(r["status"] != "completed" or r["conclusion"] != "success" + or r["head_repository"]["full_name"] != repo for r in runs): + raise ValueError("Only successful, completed runs from this repository can be released") + + +def stage_piano(source, destination, commit): + """Later selected runs replace complete entries; other methods are retained.""" + metrics_paths = sorted(source.glob("*/metrics.json")) + if not metrics_paths: + raise ValueError("Piano artifact contains no merged entries") + for path in metrics_paths: + record = json.loads(path.read_text()) + entry = path.parent.name + if (record.get("submission") != entry or record.get("fold") != "eval" + or record.get("partial") is not False or record.get("n_failed") != 0 + or not record.get("fold_size") + or record.get("n_pieces") != record["fold_size"]): + raise ValueError(f"Incomplete or invalid piano entry: {entry}") + if record.get("environment", {}).get("benchmark_commit") != commit: + raise ValueError(f"Result does not identify its source run's commit: {entry}") + for path in metrics_paths: + target = destination / "submissions" / path.parent.name + if target.exists(): + shutil.rmtree(target) + shutil.copytree(path.parent, target) + return [path.parent.name for path in metrics_paths] + + +def snapshot(results, output): + """Store website data and metrics; full paths stay in the original run ZIPs.""" + with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as bundle: + for path in sorted(results.rglob("*")): + if not path.is_file(): + continue + relative = path.relative_to(results) + if relative.parts[0] == "submissions" and path.name != "metrics.json": + continue + bundle.write(path, str(relative)) + + +def publish(repo, tag, run_ids, records, destination): + if not re.fullmatch(r"benchmark-[A-Za-z0-9][A-Za-z0-9._-]*", tag): + raise ValueError("Use a new result tag such as benchmark-v1") + if any(r["tag_name"] == tag for r in records): + raise ValueError(f"Release {tag} already exists; published results are never overwritten") + if not run_ids or any(not re.fullmatch(r"[0-9]+", run) for run in run_ids): + raise ValueError("source_runs must contain numeric run IDs separated by spaces") + if len(set(run_ids)) != len(run_ids): + raise ValueError("Select each source run only once") + runs = [api(f"repos/{repo}/actions/runs/{run}") for run in run_ids] + validate_runs(runs, repo) + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, text=True).strip() + subprocess.run(["git", "merge-base", "--is-ancestor", commit, "origin/main"], + cwd=REPO_ROOT, check=True) + if any(ref["ref"] == f"refs/tags/{tag}" + for ref in api(f"repos/{repo}/git/matching-refs/tags/{tag}")): + raise ValueError(f"Tag {tag} already exists; choose a new result version") + + base = latest(records) + entry_sources = {} + if base: + fetch(repo, base, destination) + entry_sources = json.loads((destination / "release.json").read_text()).get("entry_sources", {}) + else: + destination.mkdir(parents=True, exist_ok=False) + # Retain existing public archive URLs during the first release migration. + old_archive = REPO_ROOT / "results" / "archive" + if old_archive.exists(): + shutil.copytree(old_archive, destination / "archive") + + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + assets = work / "assets" + assets.mkdir() + sources = [] + for run in runs: + pages = json.loads(gh("api", "--paginate", "--slurp", + f"repos/{repo}/actions/runs/{run['id']}/artifacts")) + artifacts = [a for page in pages for a in page["artifacts"] + if a["name"].startswith("benchmark-results-") + or a["name"] == "ophmm-playthrough-comparison"] + if not artifacts or any(a["expired"] for a in artifacts): + raise ValueError(f"Run {run['id']} has no available complete result artifact") + saved = [] + for artifact in artifacts: + name = artifact["name"] + if not re.fullmatch(r"[A-Za-z0-9_-]+", name): + raise ValueError(f"Unexpected artifact name: {name}") + output = assets / f"run-{run['id']}-{name}.zip" + with output.open("wb") as stream: + subprocess.run(["gh", "api", f"repos/{repo}/actions/artifacts/{artifact['id']}/zip"], + stdout=stream, check=True) + if name == "benchmark-results-eval": + unpacked = work / str(artifact["id"]) + extract(output, unpacked) + for entry in stage_piano(unpacked, destination, run["head_sha"]): + entry_sources[entry] = run["id"] + saved.append({"id": artifact["id"], "asset": output.name, + "sha256": digest(output)}) + sources.append({"id": run["id"], "url": run["html_url"], + "benchmark_commit": run["head_sha"], "branch": run["head_branch"], + "attempt": run["run_attempt"], "artifacts": saved}) + + if not list((destination / "submissions").glob("*/metrics.json")): + raise ValueError("The first release must include a complete piano evaluation") + env = {**os.environ, "MATCHMAKER_RESULTS_DIR": str(destination)} + for script in ("export_details.py", "leaderboard.py"): + subprocess.run([sys.executable, str(REPO_ROOT / "matchmaker_eval" / script)], + env=env, check=True) + board = json.loads((destination / "leaderboard.json").read_text()) + if not board["entries"] or board["skipped"]: + raise ValueError("The leaderboard is empty or contains invalid entries") + manifest = {"tag": tag, "publisher_commit": commit, "source_runs": sources, + "entry_sources": entry_sources, + "base_release": base["html_url"] if base else None, + "evaluation_keys": board["evaluation_keys"]} + (destination / "release.json").write_text(json.dumps(manifest, indent=2) + "\n") + subprocess.run([sys.executable, str(REPO_ROOT / "matchmaker_eval" / "build_site.py"), + str(work / "site")], env=env, check=True) + snapshot(destination, assets / SNAPSHOT) + checksums = assets / "SHA256SUMS" + checksums.write_text("".join(f"{digest(p)} {p.name}\n" for p in sorted(assets.iterdir()))) + if any(p.stat().st_size >= 2 * 1024**3 for p in assets.iterdir()): + raise ValueError("A result asset exceeds GitHub's 2 GiB limit") + notes = work / "release.md" + notes.write_text( + f"Benchmark results published from `{commit}`.\n\n" + + "\n".join(f"- [Run {s['id']}]({s['url']}), evaluated at `{s['benchmark_commit']}`" + for s in sources) + + "\n\nThe run ZIPs contain the original merged outputs, including full paths, " + "meter maps and environment metadata. `benchmark-snapshot.zip` contains " + "the leaderboard, per-piece views, metrics and `release.json`, which identifies " + "the selected run for each entry. Later listed runs replace earlier entries. " + "`SHA256SUMS` covers every attached ZIP.\n" + ) + # Upload everything as a draft; expose it only after every upload succeeds. + gh("release", "create", tag, *(str(p) for p in sorted(assets.iterdir())), + "--repo", repo, "--target", commit, "--title", tag, + "--notes-file", str(notes), "--draft", "--latest=false") + gh("release", "edit", tag, "--repo", repo, "--draft=false", "--latest=false") + return tag + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY")) + parser.add_argument("--tag", default="") + parser.add_argument("--source-runs", default="", help="space-separated completed CI run IDs") + args = parser.parse_args() + if not args.repo or not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repo): + parser.error("Set GITHUB_REPOSITORY or --repo owner/repository") + if RESULTS_DIR.resolve().is_relative_to(REPO_ROOT): + parser.error("Set MATCHMAKER_RESULTS_DIR to a directory outside the source checkout") + try: + records = releases(args.repo) + if args.source_runs: + tag = publish(args.repo, args.tag, args.source_runs.split(), records, RESULTS_DIR) + else: + release = next((r for r in records if r["tag_name"] == args.tag), None) if args.tag else latest(records) + if args.tag and release is None: + raise ValueError(f"Release {args.tag} was not found") + tag = release["tag_name"] if release else "" + if release: + fetch(args.repo, release, RESULTS_DIR) + if os.environ.get("GITHUB_OUTPUT"): + with open(os.environ["GITHUB_OUTPUT"], "a") as stream: + stream.write(f"ready={'true' if tag else 'false'}\ntag={tag}\n") + print(f"Results: {tag}" if tag else "No benchmark release yet; leave the existing website unchanged.") + except (ValueError, subprocess.CalledProcessError) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main() diff --git a/matchmaker_eval/retract.py b/matchmaker_eval/retract.py index e13586f..06f949d 100644 --- a/matchmaker_eval/retract.py +++ b/matchmaker_eval/retract.py @@ -42,9 +42,8 @@ import shutil from datetime import datetime, timezone -from matchmaker_eval.folds import REPO_ROOT +from matchmaker_eval.folds import REPO_ROOT, RESULTS_DIR -RESULTS_DIR = REPO_ROOT / "results" SUBMISSION_RESULTS = RESULTS_DIR / "submissions" DETAILS_DIR = RESULTS_DIR / "details" RETRACTED_PATH = RESULTS_DIR / "retracted.json" @@ -134,7 +133,7 @@ def retract(entry: str, reason: str, archive: bool = True) -> dict: if destination.exists(): shutil.rmtree(destination) shutil.move(str(run_dir), str(destination)) - record["archived"] = str(destination.relative_to(REPO_ROOT)) + record["archived"] = str(destination.relative_to(RESULTS_DIR)) else: shutil.rmtree(run_dir) @@ -163,7 +162,7 @@ def undo(entry: str) -> None: destination = SUBMISSION_RESULTS / entry if destination.exists(): raise RetractionError( - f"{destination.relative_to(REPO_ROOT)} already exists — " + f"{destination} already exists — " "remove or rename it before restoring." ) destination.parent.mkdir(parents=True, exist_ok=True) diff --git a/matchmaker_eval/run_amt.py b/matchmaker_eval/run_amt.py new file mode 100644 index 0000000..074607f --- /dev/null +++ b/matchmaker_eval/run_amt.py @@ -0,0 +1,71 @@ +"""Replay frozen online-AMT MIDI through symbolic followers, using audio GT. + +The transcription model is not executed. Runtime therefore covers the follower +only. MIDI event timestamps are preserved; there is no latency compensation. +""" +from pathlib import Path +import argparse +import hashlib +import json +import sys +ROOT=Path(__file__).resolve().parents[1] +for p in (ROOT,ROOT/'matchmaker_eval'): + sys.path.insert(0,str(p)) +import matchmaker_eval.run_submission as rs +from matchmaker_eval.diagnostics import download,sha +from matchmaker_eval.submission import DECLARATION_KEY +from matchmaker import Matchmaker + + +def load_outputs(cache): + from matchmaker_eval.fetch_data import frozen_source + pin=frozen_source('amt') + base=f'https://raw.githubusercontent.com/{pin["repository"]}/{pin["commit"]}/amt/' + cache.mkdir(parents=True,exist_ok=True) + p=cache/'manifest.json' + if not p.exists() or sha(p)!=pin['manifest_sha256']:download(base+'manifest.json',p) + if sha(p)!=pin['manifest_sha256']:raise ValueError('AMT manifest hash mismatch') + manifest=json.loads(p.read_text());cases=manifest['cases'] + if len(cases)!=146 or len({c['piece_id'] for c in cases})!=146:raise ValueError('Invalid AMT test census') + return pin,base,{c['piece_id']:c for c in cases} + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('--method',choices=['arzt','pthmm','SLT_OLTW'],default='arzt') + p.add_argument('--shard',type=int,default=0) + p.add_argument('--num-shards',type=int,default=1) + p.add_argument('--output',type=Path,required=True) + p.add_argument('--cache',type=Path,default=Path('amt-data')) + a=p.parse_args();pin,base,cases=load_outputs(a.cache) + original=rs.run_piece + def run_piece(method,piece,input_type,index,run_dir,save_plots,estimated_bpm=False): + case=cases[piece.piece_id];midi=a.cache/case['path'] + if not midi.exists() or sha(midi)!=case['sha256']:download(base+case['path'],midi) + if sha(midi)!=case['sha256']:raise ValueError('AMT MIDI hash mismatch') + def build(**kwargs): + kwargs.update(input_type='midi',performance_file=str(midi),method=a.method) + return Matchmaker(**kwargs) + previous=rs.Matchmaker;rs.Matchmaker=build + try: + # Keep input_type=audio here: use the original recording's GT and + # audio TR threshold, not transcribed-note times or MIDI tolerance. + result=original(method,piece,'audio',index,run_dir,save_plots,False) + finally:rs.Matchmaker=previous + result.update(amt_data_commit=pin['commit'],amt_output_sha256=case['sha256'], + amt_front_end_executed=False,timing_scope='symbolic follower only', + symbolic_method=a.method) + (run_dir/f'{index}.json').write_text(json.dumps(result,indent=2,default=float)+'\n') + return result + rs.run_piece=run_piece + rs.builtin_metadata=lambda method,input_type:dict(name='AMT + '+a.method,input_type='audio', + authors=['Matchmaker benchmark'],description='Frozen online AMT output replayed through a symbolic follower.', + **{rs.ESTIMATED_BPM_KEY:False,DECLARATION_KEY:True},kind='reference') + parts=rs.scoring_parts + rs.scoring_parts=lambda:{**parts(),'amt_inputs':pin,'amt_symbolic_method':a.method, + 'amt_runner_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest()} + result=rs.evaluate_submission(builtin=a.method,input_type='audio',fold='eval', + shard=a.shard,num_shards=a.num_shards,run_dir=a.output) + if result['n_failed']:raise SystemExit('Incomplete AMT replay') + +if __name__=='__main__':main() diff --git a/matchmaker_eval/run_offline.py b/matchmaker_eval/run_offline.py new file mode 100644 index 0000000..e2ac636 --- /dev/null +++ b/matchmaker_eval/run_offline.py @@ -0,0 +1,132 @@ +"""Reproduce the manuscript offline reference through the common benchmark. + +Non-causal chroma CENS + DLNCO / MrMsDTW, with the original fixed settings. +No online leaderboard publishing; the workflow archives complete reference results. +""" +import sys +import time +from pathlib import Path + +BENCH = Path(__file__).resolve().parents[1] +for p in (BENCH, BENCH / "matchmaker_eval"): + sys.path.insert(0, str(p)) + +import librosa # noqa: E402 +import numpy as np # noqa: E402 +from partitura.io.exportmidi import get_ppq # noqa: E402 +from synctoolbox.dtw.mrmsdtw import sync_via_mrmsdtw # noqa: E402 +from synctoolbox.feature.dlnco import pitch_onset_features_to_DLNCO # noqa: E402 +from synctoolbox.feature.pitch_onset import audio_to_pitch_onset_features # noqa: E402 + +import run_submission as rs # noqa: E402 +from matchmaker_eval.submission import DECLARATION_KEY # noqa: E402 +from matchmaker import Matchmaker # noqa: E402 +from matchmaker.utils.misc import generate_score_audio # noqa: E402 + +FEATURE_RATE = 50 +STEP_WEIGHTS = np.array([1.5, 1.5, 2.0]) +THRESHOLD_REC = 10 ** 6 +FEATURE_SR = 22050 + + +def safe_chroma_cens(y, sr, hop_length, chunk_sec=60.0, pad_sec=4.0): + total_len = len(y) + chunk_samples = int(chunk_sec * sr) + pad_samples = int(pad_sec * sr) + if total_len <= chunk_samples + pad_samples: + return librosa.feature.chroma_cens(y=y, sr=sr, hop_length=hop_length) + out = [] + start = 0 + while start < total_len: + end = min(start + chunk_samples, total_len) + left = max(0, start - pad_samples) + right = min(total_len, end + pad_samples) + c = librosa.feature.chroma_cens(y=y[left:right], sr=sr, hop_length=hop_length) + fc = left + np.arange(c.shape[1]) * hop_length + out.append(c[:, (fc >= start) & (fc < end)]) + start = end + return np.concatenate(out, axis=1) + +def features(audio, sr): + hop = sr // FEATURE_RATE + chroma = safe_chroma_cens(y=audio, sr=sr, hop_length=hop) + onset = audio_to_pitch_onset_features(f_audio=audio, Fs=sr) + dlnco = pitch_onset_features_to_DLNCO( + f_peaks=onset, feature_rate=FEATURE_RATE, + feature_sequence_length=chroma.shape[1], visualize=False) + return chroma, dlnco + + +def offline_path(mm, perf_path): + sr0 = mm.sample_rate + score_audio = generate_score_audio(mm.score_part, mm.tempo, sr0).astype(np.float64) + sr = FEATURE_SR + if sr != sr0: + score_audio = librosa.resample(score_audio, orig_sr=sr0, target_sr=sr) + perf_audio, _ = librosa.load(str(perf_path), sr=sr) + c1, o1 = features(score_audio, sr) + c2, o2 = features(perf_audio.astype(np.float64), sr) + wp = sync_via_mrmsdtw(f_chroma1=c1, f_onset1=o1, f_chroma2=c2, f_onset2=o2, + input_feature_rate=FEATURE_RATE, verbose=False, + step_weights=STEP_WEIGHTS, threshold_rec=THRESHOLD_REC) + hop = sr // FEATURE_RATE # the frame period is hop / sr exactly + score_sec = wp[0].astype(float) * hop / sr + perf_sec = wp[1].astype(float) * hop / sr + tick = get_ppq(mm.score_part) + beats = mm.score_part.beat_map(score_sec * tick * (mm.tempo / 60)) + order = np.argsort(perf_sec, kind="stable") + return perf_sec[order], np.asarray(beats, dtype=float)[order] + + + +def run_piece(method, piece, input_type, index, run_dir, save_plots, estimated_bpm=False): + import json + from matchmaker_eval.verify_tracking import score_meter_map, musical_beat_factors + mm = Matchmaker(score_file=str(piece.score_path), performance_file=str(piece.performance_path(input_type)), + input_type=input_type, method="arzt", wait=False, unfold_score=True) + t0 = time.perf_counter() + perf_sec, beats = offline_path(mm, piece.performance_path(input_type)) + mm.alignment_duration = time.perf_counter()-t0 + mm.score_follower._alignment_path = list(zip(perf_sec.tolist(), beats.tolist())) + mm._has_run = True + perf, score_beat = rs.resolve_gt(piece.match_path, mm.score_part.note_array(), performance=None) + gt = np.column_stack([perf, score_beat]) + metrics = rs.run_evaluation(mm, gt=gt, tolerances=rs.TOLERANCES_IN_BEATS, domain="score", + debug=True, save_dir=run_dir, run_name=str(index), + plot_dist_matrix=False, make_plot=False) + meter = score_meter_map(mm.score_part) + (run_dir/f"meter_{index}.json").write_text(json.dumps(meter,indent=2)+"\n") + tracking = rs.check_tracking(np.column_stack([perf_sec,beats]), gt, + segment_duration=rs.SEGMENT_DURATION, + threshold=rs.TRACKING_THRESHOLD[input_type], + beat_factors=musical_beat_factors(gt[:,1],meter)) + metrics.update(tracked=bool(tracking["tracked"]), max_deviation=float(tracking["max_deviation"]), + n_failed_segments=int(tracking["n_failed"]), + tracking_criterion={k:tracking[k] for k in ("error_unit","threshold","window_duration")}, + used_estimated_bpm=False, + offline=True, + offline_settings=dict(feature_rate=FEATURE_RATE, render_tempo="score", + feature_sample_rate=FEATURE_SR, step_weights=STEP_WEIGHTS.tolist(), threshold_rec=THRESHOLD_REC)) + (run_dir/f"{index}.json").write_text(json.dumps(metrics,indent=2,default=float)+"\n") + return metrics + + +def offline_metadata(method, input_type): + return {"name":"Offline (DLNCO + MrMsDTW)", "authors":["synctoolbox"], "input_type":input_type, + "description":"Non-causal MrMsDTW of performance and rendered score audio; chroma CENS + DLNCO.", + rs.ESTIMATED_BPM_KEY:False, "url":"https://github.com/meinardmueller/synctoolbox", + DECLARATION_KEY:True, "kind":"reference"} + + +def main(): + import hashlib + original_parts=rs.scoring_parts + rs.scoring_parts=lambda: {**original_parts(), "offline_source_sha256":hashlib.sha256(Path(__file__).read_bytes()).hexdigest()} + rs.run_piece=run_piece + rs.builtin_metadata=offline_metadata + if "--method" not in sys.argv: + sys.argv += ["--method","offline","--input-type","audio"] + return rs.main() + +if __name__ == "__main__": + sys.exit(main()) diff --git a/matchmaker_eval/run_submission.py b/matchmaker_eval/run_submission.py index 8c1e67b..b5fb313 100644 --- a/matchmaker_eval/run_submission.py +++ b/matchmaker_eval/run_submission.py @@ -47,7 +47,9 @@ from eval import run_evaluation from utils import TOLERANCES_IN_BEATS, dataset_summaries, pooled_summaries -from verify_tracking import check_tracking, plot_tracking +from matchmaker_eval.verify_tracking import ( + TRACKING_THRESHOLDS, check_tracking, plot_tracking, musical_beat_factors, score_meter_map, +) from matchmaker import Matchmaker from matchmaker.base import OnlineAlignment @@ -91,7 +93,7 @@ #: Tracking verdict thresholds, per input type. A piece counts as "tracked" #: unless some 30-second onset-wise window's median beat error exceeds the #: threshold. MIDI is held to a tighter bound than audio. -TRACKING_THRESHOLD = {"audio": 1.0, "midi": 0.5} +TRACKING_THRESHOLD = TRACKING_THRESHOLDS SEGMENT_DURATION = 30.0 DEFAULT_RESULTS_DIR = REPO_ROOT / "results" / "submissions" @@ -131,11 +133,12 @@ def sha256_of(path: Path) -> str: def _matchmaker_source() -> dict: - """The git ref and commit matchmaker was installed from, if it was. + """The git sources Matchmaker was installed from, if known. ``pip install git+...@`` leaves a direct_url.json beside the package - naming the ref asked for and the commit it resolved to. A release install - has none, and then there is nothing to add. + naming the ref asked for and the commit it resolved to. CI may instead + install a temporary checkout with pinned patches; its packaged manifest + identifies every source commit without claiming it is one upstream commit. """ try: import json @@ -144,7 +147,13 @@ def _matchmaker_source() -> dict: raw = distribution("pymatchmaker").read_text("direct_url.json") if not raw: return {} - vcs = (json.loads(raw).get("vcs_info") or {}) + direct_url = json.loads(raw) + if "dir_info" in direct_url: + from importlib.resources import files + + manifest = files("matchmaker").joinpath("assets/benchmark-source.json") + return json.loads(manifest.read_text()) if manifest.is_file() else {} + vcs = direct_url.get("vcs_info") or {} found = {} if vcs.get("commit_id"): found["matchmaker_commit"] = vcs["commit_id"] @@ -210,8 +219,19 @@ def check_follower(follower) -> None: ) +def set_global_transition(mm, setting): + """Override only MIDI OPHMM's global transition factor when requested.""" + if setting is None: + return + if setting not in ("on", "off") or mm.method != "outerhmm" or mm.input_type != "midi": + raise SubmissionError("--global-transition applies only to MIDI outerhmm") + if setting == "off": + mm.score_follower.S[:] = 0.0 + + def run_piece( - method, piece, input_type, index, run_dir, save_plots, estimated_bpm=False + method, piece, input_type, index, run_dir, save_plots, estimated_bpm=False, + global_transition=None, ): """Run and score one piece, returning the shared metric fields. @@ -242,6 +262,7 @@ def run_piece( tempo=tempo, ) check_follower(mm.score_follower) + set_global_transition(mm, global_transition) list(mm.run(verbose=False)) wp = mm.score_follower.alignment_path @@ -271,15 +292,22 @@ def run_piece( # alignment_path row 0 is already absolute performance seconds. wp_sec = np.stack([wp[0].astype(float), wp[1].astype(float)]).T threshold = TRACKING_THRESHOLD[input_type] + meter = score_meter_map(mm.score_part) + factors = musical_beat_factors(gt[:, 1], meter) + (run_dir / f"meter_{index}.json").write_text(json.dumps(meter, indent=2) + "\n") tracking = check_tracking( wp_sec, gt, segment_duration=SEGMENT_DURATION, threshold=threshold, + beat_factors=factors, ) metrics["tracked"] = bool(tracking["tracked"]) metrics["max_deviation"] = float(tracking["max_deviation"]) metrics["n_failed_segments"] = int(tracking["n_failed"]) + metrics["tracking_criterion"] = { + key: tracking[key] for key in ("error_unit", "threshold", "window_duration") + } if save_plots: plot_tracking( @@ -289,11 +317,15 @@ def run_piece( save_path=run_dir / f"tracking_{index}.png", segment_duration=SEGMENT_DURATION, threshold=threshold, + beat_factors=factors, ) # Whether this piece actually got a measured tempo. False both when the # entry never asked and when it asked and the fold had none — the run # summary separates the two, since only the second is worth reporting. + if global_transition is not None: + metrics["global_transition"] = global_transition + metrics["global_transition_nonzero"] = int(np.count_nonzero(mm.score_follower.S)) metrics["used_estimated_bpm"] = tempo is not None with open(run_dir / f"{index}.json", "w") as f: @@ -335,7 +367,7 @@ def fold_file_label(fold) -> str: #: the rerun would otherwise be scored on the previous run's path — and the #: progress count in run_references.py would read 146/146 from the first #: second. metrics.json stays until the run replaces it. -PIECE_OUTPUTS = ("wp_*.tsv", "gt_*.tsv", "tracking_*.png", "[0-9]*.json") +PIECE_OUTPUTS = ("wp_*.tsv", "gt_*.tsv", "meter_*.json", "tracking_*.png", "[0-9]*.json") def clear_piece_outputs(run_dir: Path) -> int: @@ -361,6 +393,7 @@ def evaluate_submission( builtin: Optional[str] = None, skip_missing: bool = False, fetch: bool = True, + global_transition: Optional[str] = None, ) -> dict: """Run a submission — or a built-in method — over a fold or one shard of it. @@ -386,6 +419,12 @@ def evaluate_submission( input_type = input_type or registered_input_type name = directory.name + if global_transition is not None: + if builtin != "outerhmm" or input_type != "midi" or global_transition not in ("on", "off"): + raise SubmissionError("--global-transition applies only to MIDI outerhmm") + name += "-global-" + global_transition + metadata = {**metadata, "global_transition": global_transition} + # Declared by the entry, not chosen here: a follower is given the tempo # only if it said it uses one, and the run is labelled accordingly. estimated_bpm = bool(metadata.get(ESTIMATED_BPM_KEY, False)) @@ -496,6 +535,7 @@ def evaluate_submission( run_dir, save_plots, estimated_bpm=estimated_bpm, + **({"global_transition": global_transition} if global_transition is not None else {}), ) except Exception as e: # One broken piece must not void a whole run: record it as an @@ -661,6 +701,8 @@ def main(): default=1, help="split the fold into this many shards (merge them with merge_shards.py)", ) + parser.add_argument("--global-transition", choices=("on", "off"), default=None, + help="MIDI OPHMM global transitions (default: unchanged)") args = parser.parse_args() try: @@ -677,6 +719,7 @@ def main(): fetch=not args.no_fetch, shard=args.shard, num_shards=args.num_shards, + global_transition=args.global_transition, ) except SubmissionError as e: print(f"\nSubmission error: {e}", file=sys.stderr) diff --git a/matchmaker_eval/test_symbolic.py b/matchmaker_eval/test_symbolic.py index 0620f2b..ca5e7ce 100644 --- a/matchmaker_eval/test_symbolic.py +++ b/matchmaker_eval/test_symbolic.py @@ -41,7 +41,9 @@ save_config, save_results_to_csv, ) -from matchmaker_eval.verify_tracking import check_tracking, plot_tracking +from matchmaker_eval.verify_tracking import ( + TRACKING_THRESHOLDS, check_tracking, plot_tracking, musical_beat_factors, score_meter_map, +) from tabulate import tabulate import wandb @@ -51,7 +53,7 @@ sys.setrecursionlimit(10000) -TRACKING_THRESHOLD = 0.5 # beats +TRACKING_THRESHOLD = TRACKING_THRESHOLDS["midi"] # musical beats WORKING_DIR = Path(__file__).parent.parent #: Resolved through MATCHMAKER_DATA_DIR rather than a hardcoded home @@ -168,11 +170,14 @@ def run_tests_and_eval_by_dataset( gt = np.column_stack([ps, sb]) wp_T = wp.T if wp.shape[0] == 2 else wp + meter = score_meter_map(mm.score_part) + factors = musical_beat_factors(gt[:, 1], meter) tracking = check_tracking( wp_T, gt, segment_duration=30, threshold=TRACKING_THRESHOLD, + beat_factors=factors, ) nested = run_evaluation( @@ -188,11 +193,15 @@ def run_tests_and_eval_by_dataset( nested["tracked"] = tracking["tracked"] nested["max_deviation"] = float(tracking["max_deviation"]) nested["n_failed_segments"] = int(tracking["n_failed"]) + nested["tracking_criterion"] = { + key: tracking[key] for key in ("error_unit", "threshold", "window_duration") + } piece_result = nested.copy() # Save WP/GT — column order: perf_sec, score_beat if run_dir is not None: + (run_dir / f"meter_{i}.json").write_text(json.dumps(meter, indent=2) + "\n") np.savetxt( run_dir / f"wp_{i}.tsv", wp_T, @@ -218,6 +227,7 @@ def run_tests_and_eval_by_dataset( title=f"{method} #{i}", save_path=run_dir / f"tracking_{i}.png", threshold=TRACKING_THRESHOLD, + beat_factors=factors, ) status = "TRACKED" if tracking["tracked"] else "FAILED" diff --git a/matchmaker_eval/verify_tracking.py b/matchmaker_eval/verify_tracking.py index 948f570..1ff7104 100644 --- a/matchmaker_eval/verify_tracking.py +++ b/matchmaker_eval/verify_tracking.py @@ -1,12 +1,15 @@ """ Check if a tracker followed the score throughout a piece. -Evaluates in the score domain, in beat unit. At every annotated onset it +Evaluates in the score domain. At every annotated onset it looks up the last score position emitted at or before that time, then computes the median absolute beat error in a forward window starting at each unique annotated performance onset. The window slides onset-wise until one first reaches the final annotation. A piece fails when any window median exceeds the -selected beat tolerance. +selected beat tolerance. Benchmark callers supply ``beat_factors`` from the +reference score: errors are divided by three in compound-meter passages and +by one elsewhere, before the window median is taken. Omitting the factors is +an explicit legacy denominator-note calculation. Input: wp.tsv Warping path (tab-separated) @@ -25,11 +28,85 @@ import matplotlib.pyplot as plt import numpy as np from matchmaker.utils.eval import ONSET_WINDOW_DURATION, onset_wise_windows +from partitura.score import TimeSignature BEAT_ERROR_THRESHOLD = 1.0 # threshold for window median beat error (beats) SEGMENT_DURATION = ONSET_WINDOW_DURATION # shared window duration (seconds) +TRACKING_THRESHOLDS = {"audio": 1.0, "midi": 0.1} +TRACKING_ERROR_UNIT = "musical_beat" +POSITION_ERROR_UNIT = "denominator_note" + + +def denominator_notes_per_beat(numerator: int) -> int: + """Three in compound meters (6, 9, 12, ...); one in other meters.""" + if numerator <= 0 or int(numerator) != numerator: + raise ValueError("time-signature numerator must be a positive integer") + return 3 if numerator >= 6 and numerator % 3 == 0 else 1 + + +def score_meter_map(part) -> dict: + """Serializable meter changes in the follower's score-beat coordinates. + + ``part`` must be the native, denominator-note score part passed to the + follower. Do not call ``use_musical_beat()`` on it: that would also change + its note array and the algorithm's behavior, rather than just evaluation. + A score without time signatures follows Partitura's 4/4 default, explicitly + recorded in the map instead of being mistaken for annotated meter. + """ + if getattr(part, "_use_musical_beat", False): + raise ValueError("TR expects score positions in denominator-note beats") + signatures = list(part.iter_all(TimeSignature)) + changes = [] + for ts in sorted(signatures, key=lambda ts: ts.start.t): + if ts.beat_type <= 0: + raise ValueError("time-signature denominator must be positive") + change = { + "start_score_beat": float(part.beat_map(ts.start.t)), + "numerator": int(ts.beats), + "denominator": int(ts.beat_type), + "denominator_notes_per_beat": denominator_notes_per_beat(ts.beats), + } + if changes and change["start_score_beat"] == changes[-1]["start_score_beat"]: + if change != changes[-1]: + raise ValueError("conflicting time signatures at one score position") + continue + changes.append(change) + if not changes: + changes = [{"start_score_beat": 0.0, "numerator": 4, "denominator": 4, + "denominator_notes_per_beat": 1}] + return { + "schema": 1, + "position_unit": POSITION_ERROR_UNIT, + "tracking_error_unit": TRACKING_ERROR_UNIT, + "assumed_time_signature": not bool(signatures), + "changes": changes, + } + + +def musical_beat_factors(score_positions, meter: dict) -> np.ndarray: + """The reference meter's factor at each position, right-inclusive at changes. + + Positions need not increase: the same lookup also applies when a performed + repeat returns to an earlier score position. Pickups before the first + explicit signature use that first signature. + """ + positions = np.asarray(score_positions, dtype=float) + if not np.all(np.isfinite(positions)): + raise ValueError("ground-truth score positions must be finite") + if meter.get("position_unit") != POSITION_ERROR_UNIT: + raise ValueError("meter map must use denominator-note score positions") + changes = meter["changes"] + starts = np.asarray([r["start_score_beat"] for r in changes], dtype=float) + factors = np.asarray([r["denominator_notes_per_beat"] for r in changes], dtype=float) + if (len(starts) == 0 or not np.all(np.isfinite(starts)) + or np.any(np.diff(starts) <= 0) or not np.all(np.isin(factors, [1., 3.]))): + raise ValueError("meter map must have ordered, finite changes and factors 1 or 3") + indices = np.maximum(np.searchsorted(starts, positions, side="right") - 1, 0) + return factors[indices] + + def _onset_wise_window_profile( times: np.ndarray, errors: np.ndarray, @@ -66,6 +143,8 @@ def check_tracking( gt: np.ndarray, segment_duration: float = SEGMENT_DURATION, threshold: float = BEAT_ERROR_THRESHOLD, + *, + beat_factors: np.ndarray = None, ) -> dict: """ Check tracking quality using an onset-wise sliding-window median. @@ -80,14 +159,29 @@ def check_tracking( gt : (M, 2) array — col 0: perf time (seconds), col 1: score position (beats) segment_duration : float — window duration W in seconds (default: 30) threshold : float — maximum median absolute beat error theta (default: 1.0) + beat_factors : (M,) array, optional + Denominator notes per musical beat at each GT score position. The + benchmark supplies this even for simple meter; without it, errors + remain in denominator-note units. Returns ------- dict with: windows, mean_onsets_per_window, worst_window, max_deviation, tracked, reason """ + if not np.isfinite(threshold) or threshold < 0: + raise ValueError("threshold must be finite and non-negative") + if beat_factors is not None: + beat_factors = np.asarray(beat_factors, dtype=float) + if (beat_factors.shape != (len(gt),) or not np.all(np.isfinite(beat_factors)) + or np.any(beat_factors <= 0)): + raise ValueError("beat_factors must contain one positive finite factor per GT onset") + unit = "musical_beat" if beat_factors is not None else "denominator_note" + criterion = {"error_unit": unit, "threshold": float(threshold), + "window_duration": float(segment_duration)} if wp.size == 0 or gt.size == 0: return { + **criterion, "windows": [], "n_windows": 0, "mean_onsets_per_window": 0.0, @@ -123,6 +217,8 @@ def check_tracking( errors_all = np.abs(predicted_score - gt_score) # beats errors_all[~valid] = np.inf # no causal estimate at an annotation + if beat_factors is not None: + errors_all = errors_all / beat_factors windows = _onset_wise_window_profile( gt_perf, errors_all, segment_duration, threshold @@ -148,6 +244,7 @@ def check_tracking( ) return { + **criterion, "windows": windows, "n_windows": len(windows), "mean_onsets_per_window": float( @@ -182,6 +279,8 @@ def plot_tracking( save_path: Path = None, segment_duration: float = SEGMENT_DURATION, threshold: float = BEAT_ERROR_THRESHOLD, + *, + beat_factors: np.ndarray = None, ): """Plot the alignment path and onset-wise window median-error profile.""" result = check_tracking( @@ -189,6 +288,7 @@ def plot_tracking( gt, segment_duration=segment_duration, threshold=threshold, + beat_factors=beat_factors, ) windows = result["windows"] worst_window = result["worst_window"] @@ -251,7 +351,7 @@ def plot_tracking( color="green" if tracked else "red", fontweight="bold", ) - ax1.set_ylabel("Score position") + ax1.set_ylabel("Score position (denominator-note beats)") ax1.set_xlabel("Performance time (s)") ax1.legend(loc="upper left") @@ -263,7 +363,8 @@ def plot_tracking( threshold, color="red", ls="--", lw=1.5, label=f"threshold={threshold:.1f}b" ) ax2.axhline(0, color="black", lw=0.5) - ax2.set_ylabel("Sliding median |beat error|") + beat_label = "musical beats" if beat_factors is not None else "denominator-note beats" + ax2.set_ylabel(f"Sliding median error ({beat_label})") yl = max(threshold * 2, max_dev * 1.3) if max_dev > 0 else threshold * 2 ax2.set_ylim(0, yl) ax2.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x:.1f}b")) @@ -332,6 +433,10 @@ def main(): ) parser.add_argument("--wp", type=Path, required=True, help="Warping path TSV") parser.add_argument("--gt", type=Path, required=True, help="Ground truth TSV") + parser.add_argument( + "--meter", type=Path, default=None, + help="Saved meter_.json from the benchmark; applies musical-beat TR", + ) parser.add_argument( "--save", type=Path, default=None, help="Save plot to file (default: show)" ) @@ -349,14 +454,19 @@ def main(): ) args = parser.parse_args() - wp = np.loadtxt(args.wp, delimiter="\t", skiprows=1) - gt = np.loadtxt(args.gt, delimiter="\t", skiprows=1) + wp = np.loadtxt(args.wp, delimiter="\t", skiprows=1, ndmin=2) + gt = np.loadtxt(args.gt, delimiter="\t", skiprows=1, ndmin=2) + factors = None + if args.meter is not None: + import json + factors = musical_beat_factors(gt[:, 1], json.loads(args.meter.read_text())) result = check_tracking( wp, gt, segment_duration=args.window_duration, threshold=args.threshold, + beat_factors=factors, ) title = _auto_title(args.wp) @@ -386,6 +496,7 @@ def main(): save_path=args.save, segment_duration=args.window_duration, threshold=args.threshold, + beat_factors=factors, ) diff --git a/tests/test_data_paths.py b/tests/test_data_paths.py index 548f8ae..d012354 100644 --- a/tests/test_data_paths.py +++ b/tests/test_data_paths.py @@ -89,6 +89,19 @@ def test_a_file_is_not_a_layout(self, data_root): assert not has_expected_layout(f) +def test_explicit_revision_overrides_every_fold_branch(tmp_path, monkeypatch): + from matchmaker_eval import fetch_data + + source = tmp_path / "sources.yaml" + source.write_text("branch: main\nbranches:\n eval: eval\n valid: valid\n") + monkeypatch.setattr(fetch_data, "CONFIG_PATH", source) + revision = "a" * 40 + monkeypatch.setenv("MATCHMAKER_DATA_BRANCH", revision) + config = fetch_data.load_config() + for fold in ("eval", "valid", "unlisted"): + assert fetch_data.branch_for(config, fold) == revision + + class TestMissingDataMessage: def test_it_says_how_to_fetch(self, data_root): from matchmaker_eval.folds import FoldError, load_fold, require_files @@ -164,3 +177,19 @@ def test_the_runners_point_submitters_at_the_fold_path(self): ) assert done.returncode == 0, done.stderr assert "--fold valid" in done.stdout + + +def test_diagnostic_chunked_input_verified(tmp_path): + import hashlib + from matchmaker_eval.diagnostics import materialize + chunks = [b'first', b'second'] + parts = [] + for i, data in enumerate(chunks): + p = tmp_path/f'p{i}'; p.write_bytes(data) + parts.append(dict(path=p.name, sha256=hashlib.sha256(data).hexdigest())) + m={'files':{'audio.flac':dict(parts=parts,sha256=hashlib.sha256(b''.join(chunks)).hexdigest())}} + out=materialize('audio.flac',m,tmp_path,'https://invalid/') + assert out.read_bytes() == b'firstsecond' + m['files']['audio.flac']['sha256']='wrong' + with pytest.raises(ValueError,match='hash mismatch'): + materialize('audio.flac',m,tmp_path,'https://invalid/') diff --git a/tests/test_evaluation_key.py b/tests/test_evaluation_key.py index 0156826..5e2a494 100644 --- a/tests/test_evaluation_key.py +++ b/tests/test_evaluation_key.py @@ -30,6 +30,12 @@ "partitura": "1.9.0", } +CURRENT_CODE = { + **CODE, + "scheme": P.SCHEME, + "matchmaker_scoring_sha256": "e" * 64, +} + class FakePiece: """The parts of folds.Piece the data hash reads.""" @@ -59,6 +65,14 @@ def records(n=3, prefix="h"): class TestTheKey: + def test_follower_source_changes_preserve_comparability_and_provenance(self): + old = P.evaluation_record(CURRENT_CODE, records()) + new = P.evaluation_record({**CURRENT_CODE, "matchmaker_sha256": "new"}, records()) + assert re.fullmatch(r"ek2-[0-9a-f]{12}", new["key"]) + assert old["key"] == new["key"] + assert old["components"]["matchmaker_sha256"] != new["components"]["matchmaker_sha256"] + assert old["key"] != P.evaluation_record(CODE, records())["key"] + def test_it_names_its_scheme_and_is_short(self): key = P.evaluation_record(CODE, records())["key"] assert re.fullmatch(r"ek1-[0-9a-f]{12}", key) @@ -101,6 +115,25 @@ def test_no_key_without_every_code_component(self): class TestTheComponents: + @pytest.mark.parametrize("module", ["matchmaker.py", "utils/eval.py"]) + def test_shared_score_loading_and_evaluation_change_conditions(self, tmp_path, monkeypatch, module): + import matchmaker + + monkeypatch.setattr(matchmaker, "__file__", str(tmp_path / "__init__.py")) + for name in P.MATCHMAKER_SCORING_MODULES: + path = tmp_path / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("original source") + before = P.matchmaker_scoring_sha256() + full_before = P.matchmaker_sha256() + (tmp_path / "new_follower.py").write_text("new follower") + assert P.matchmaker_sha256() != full_before + assert P.matchmaker_scoring_sha256() == before + (tmp_path / module).write_text("changed shared evaluation") + after = P.matchmaker_scoring_sha256() + assert after != before + assert P.evaluation_record({**CURRENT_CODE, "matchmaker_scoring_sha256": before}, records())["key"] != P.evaluation_record({**CURRENT_CODE, "matchmaker_scoring_sha256": after}, records())["key"] + def test_a_piece_hash_follows_its_bytes(self, tmp_path): piece = FakePiece(tmp_path / "asap") before = P.piece_data_sha256(piece, "midi") @@ -158,6 +191,13 @@ def write_shard(root: Path, index: int, piece: dict, code: dict) -> None: class TestMerging: + def test_shards_still_require_the_same_follower_sources(self, tmp_path): + piece = {"index": 0, "piece_id": "asap/a", "dataset": "asap", "tracked": False, "data_sha256": "h0"} + write_shard(tmp_path / "shards", 0, piece, CURRENT_CODE) + write_shard(tmp_path / "shards", 1, {**piece, "index": 1}, {**CURRENT_CODE, "matchmaker_sha256": "different"}) + with pytest.raises(MergeError, match="matchmaker_sha256"): + merge(tmp_path / "shards", tmp_path / "out") + def test_the_merged_key_is_the_whole_fold_key(self, tmp_path): pieces = [ {"index": 0, "piece_id": "asap/a", "dataset": "asap", "tracked": False, "data_sha256": "h0"}, @@ -227,6 +267,19 @@ def add(record): class TestTheLeaderboard: + def test_adding_a_method_preserves_both_modalities_under_the_same_protocol(self, results): + for name, kind, date, library in ( + ("existing-midi", "midi", "2026-10-01", "old"), + ("existing-audio", "audio", "2026-10-01", "old"), + ("new-midi", "midi", "2026-10-02", "new"), + ): + evaluation = P.evaluation_record({**CURRENT_CODE, "matchmaker_sha256": library}, records(prefix=kind)) + results(entry(name, evaluation["key"], date, evaluation["components"], input_type=kind)) + board = L.build() + assert {row["submission"] for row in board["entries"]} == {"existing-midi", "existing-audio", "new-midi"} + assert board["earlier_conditions"] == [] + assert all("matchmaker_sha256" not in value for value in board["evaluation_conditions"].values()) + def test_only_rows_with_the_newest_key_are_ranked(self, results): results(entry("old-ref", "ek1-aaaaaaaaaaaa", "2026-10-01T00:00:00+00:00", OLD)) results(entry("new-ref", "ek1-bbbbbbbbbbbb", "2026-10-28T00:00:00+00:00", NEW, 0.5)) diff --git a/tests/test_merge_shards.py b/tests/test_merge_shards.py index 7fe2d53..5e5ec2a 100644 --- a/tests/test_merge_shards.py +++ b/tests/test_merge_shards.py @@ -84,6 +84,22 @@ def test_a_short_merge_stays_partial(self, tmp_path): merged = merge(root, tmp_path / "out") assert merged["partial"] is True + def test_merge_retains_the_meter_and_criterion_needed_to_rescore(self, tmp_path): + criterion = {"error_unit": "musical_beat", "threshold": 0.1, "window_duration": 30.0} + meter = {"schema": 1, "position_unit": "denominator_note", "changes": [ + {"start_score_beat": 0.0, "numerator": 6, "denominator": 8, + "denominator_notes_per_beat": 3}, + {"start_score_beat": 6.0, "numerator": 4, "denominator": 4, + "denominator_notes_per_beat": 1}, + ]} + record = shard_record(0, fold_size=1) + record["pieces"][0]["tracking_criterion"] = criterion + root = write_shards(tmp_path / "shards", [record]) + (root / "shard-0" / "meter_0.json").write_text(json.dumps(meter)) + merged = merge(root, tmp_path / "out") + assert merged["pieces"][0]["tracking_criterion"] == criterion + assert json.loads((tmp_path / "out" / "meter_0.json").read_text()) == meter + class TestMergeRejectsMismatchedShards: @pytest.mark.parametrize("key,value", [ @@ -106,6 +122,39 @@ def test_a_duplicated_piece_index_is_rejected(self, tmp_path): merge(root, tmp_path / "out") +@pytest.mark.parametrize("missing_case", [False, True]) +def test_diagnostic_merge_requires_every_selected_case(tmp_path, monkeypatch, missing_case): + from argparse import Namespace + from matchmaker_eval import diagnostics + + config = dict(suite="perturbations", input_type="midi", method="chosen") + monkeypatch.setattr(diagnostics, "CONFIGS", { + "chosen-midi": config, "other-midi": {**config, "method": "other"}, + }) + cases = [{"id": name, "suite": "perturbations", "input_type": "midi"} + for name in ("a", "b")] + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({"cases": cases})) + shard = tmp_path / "shards" / "chosen-0" + shard.mkdir(parents=True) + record = dict(config="chosen-midi", shard=0, failures=[], + data={"commit": "data-revision"}, + environment={"benchmark_commit": "code-revision"}, github_run_id="1", + pieces=[dict(case_id=c["id"], category="example", tracked=True, mean_b=0.) + for c in cases[:1 if missing_case else 2]]) + (shard / "metrics.json").write_text(json.dumps(record)) + args = Namespace(source=tmp_path / "shards", output=tmp_path / "out", + manifest=manifest, shards=1, only="chosen", input_type="midi") + if missing_case: + with pytest.raises(SystemExit, match="Incomplete diagnostic results"): + diagnostics.merge(args) + else: + diagnostics.merge(args) + summary = json.loads((args.output / "summary.json").read_text()) + assert summary["complete"] is (not missing_case) + assert list(summary["configurations"]) == ["chosen-midi"] + + class TestMergeReferences: """One references run produces shards for many entries, flat in one dir.""" @@ -174,6 +223,33 @@ def test_unrelated_directories_are_ignored(self, tmp_path): (root / "some-other-artifact").mkdir() assert sorted(group(root)) == ["arzt-audio"] + def test_auxiliary_folds_do_not_default_to_the_piano_destination(self): + from merge_references import output_for_fold + + assert output_for_fold("beyond_piano") != output_for_fold("eval") + + @pytest.mark.parametrize("fold,expected", [ + ("beyond_piano", ["arzt-audio"]), + ("eval", ["arzt-audio", "pthmm-midi"]), + ]) + def test_wrong_fold_or_missing_method_cannot_overwrite_results( + self, tmp_path, monkeypatch, fold, expected, + ): + from merge_references import main + + root = self._flat_download(tmp_path, ["arzt-audio"]) + published = tmp_path / "published" / "arzt-audio" + published.mkdir(parents=True) + record = published / "metrics.json" + record.write_text('{"previous": true}') + monkeypatch.setattr(sys, "argv", [ + "merge_references.py", str(root), "--fold", fold, + "--expected-entries-json", json.dumps(expected), + "--output", str(published.parent), + ]) + assert main() == 1 + assert record.read_text() == '{"previous": true}' + class TestTheTempoLabelSurvivesMerging: """A sharded run must not lose the fact that it was given the tempo.""" @@ -210,3 +286,54 @@ def test_the_count_is_recomputed_from_the_pieces(self, tmp_path): root = write_shards(tmp_path / "shards", [one, two]) merged = merge(root, tmp_path / "merged") assert merged["n_estimated_bpm"] == 1 + + +def test_diagnostic_sharding_is_exhaustive_and_disjoint(): + from matchmaker_eval.diagnostics import select_cases + m = {'cases': [dict(id=str(i), suite='perturbations', input_type='audio') for i in range(41)]} + config = {'suite': 'perturbations', 'input_type': 'audio'} + shards = [select_cases(m, config, s, 4) for s in range(4)] + assert sorted(i for batch in shards for i, _ in batch) == list(range(41)) + + +def test_diagnostic_duplicate_cases_rejected(): + from matchmaker_eval.diagnostics import select_cases + c = dict(id='a', suite='perturbations', input_type='audio') + with pytest.raises(ValueError, match='duplicated'): + select_cases({'cases':[c,c]}, {'suite': 'perturbations', 'input_type': 'audio'}) + + +def test_diagnostic_merge_fails_incomplete_and_preserves_evidence(tmp_path): + from argparse import Namespace + from matchmaker_eval.diagnostics import CONFIGS, merge + source=tmp_path/'source';source.mkdir() + manifest=tmp_path/'manifest.json' + cases=[dict(id=k,suite=c['suite'],input_type=c['input_type']) for k,c in CONFIGS.items()] + # Unique IDs per suite/modality are enough; all output shards are absent. + manifest.write_text(json.dumps({'cases':cases})) + with pytest.raises(SystemExit,match='Incomplete'): + merge(Namespace(source=source,output=tmp_path/'out',manifest=manifest,shards=4, + only='',input_type='both')) + assert not json.loads((tmp_path/'out/summary.json').read_text())['complete'] + + +def test_diagnostic_merge_rejects_different_patched_sources(tmp_path, monkeypatch): + from argparse import Namespace + from matchmaker_eval import diagnostics as D + + config = {'suite': 'test', 'input_type': 'midi', 'method': 'test'} + monkeypatch.setattr(D, 'CONFIGS', {'test-midi': config}) + source = tmp_path / 'shards' + manifest = tmp_path / 'manifest.json' + manifest.write_text(json.dumps({'cases': [dict(id=str(i), **config) for i in range(2)]})) + for i in range(2): + folder = source / str(i) + folder.mkdir(parents=True) + record = dict(config='test-midi', shard=i, failures=[], data={'commit': 'data'}, + environment={'benchmark_commit': 'benchmark', 'matchmaker_base_commit': 'base', + 'matchmaker_patches': [{'head': str(i)}]}, github_run_id='run', + pieces=[dict(case_id=str(i), category='test', tracked=True, mean_b=0.)]) + (folder / 'metrics.json').write_text(json.dumps(record)) + with pytest.raises(SystemExit, match='inconsistent provenance'): + D.merge(Namespace(source=source, output=tmp_path / 'out', manifest=manifest, shards=2, + only='', input_type='both')) diff --git a/tests/test_musical_beats.py b/tests/test_musical_beats.py new file mode 100644 index 0000000..cc4fa2c --- /dev/null +++ b/tests/test_musical_beats.py @@ -0,0 +1,62 @@ +"""TR follows the ground-truth meter without changing position coordinates.""" +import numpy as np +import pytest +from partitura.score import Note, Part, TimeSignature + +from matchmaker_eval.verify_tracking import musical_beat_factors, score_meter_map +from matchmaker_eval.verify_tracking import check_tracking + + +def score(signatures=((0, 6, 8), (12, 4, 4))): + part = Part('P1', quarter_duration=4) + for start, numerator, denominator in signatures: + part.add(TimeSignature(numerator, denominator), start=start) + part.add(Note('C', 4, id='n0'), start=0, end=4) + part.add(Note('D', 4, id='n1'), start=12, end=16) + part.add(Note('E', 4, id='n2'), start=24, end=28) + return part + + +def test_meter_changes_and_returns_preserve_score_coordinates(): + part = score() + before = part.note_array().copy() + meter = score_meter_map(part) + # At the change and after a return, use the meter at that score position. + assert np.array_equal(musical_beat_factors([-1, 0, 5.99, 6, 10, 2], meter), [3,3,3,1,1,3]) + assert np.array_equal(part.note_array(), before) + + +@pytest.mark.parametrize('threshold,error', [(1.,2.0),(.1,.25)]) +@pytest.mark.parametrize('numerator,denominator,tracked', [ + (6,8,True), (9,8,True), (12,16,True), (3,4,False), (3,8,False), +]) +def test_tr_uses_compound_groups_but_not_simple_triple_meter( + threshold, error, numerator, denominator, tracked, +): + gt = np.array([[0.,0.],[1.,1.],[2.,2.]]) + wp = gt.copy();wp[:,1] += error + before = wp.copy() + meter = score_meter_map(score(((0,numerator,denominator),))) + result = check_tracking( + wp, gt, threshold=threshold, beat_factors=musical_beat_factors(gt[:,1], meter), + ) + assert result['tracked'] == tracked + assert np.array_equal(wp,before) + + +def test_change_inside_a_window_is_applied_before_taking_median(): + gt = np.array([[0.,5.0],[1.,5.5],[2.,6.0]]) + wp = gt.copy();wp[:,1] += [2.4,2.4,1.5] + # Two compound onsets are each 0.8 musical beat; the simple onset is 1.5. + meter = score_meter_map(score()) + result = check_tracking(wp,gt,threshold=1.,beat_factors=musical_beat_factors(gt[:,1],meter)) + assert result['tracked'] + assert result['worst_window']['deviation'] == pytest.approx(.8) + + +def test_factor_follows_ground_truth_not_incorrect_predicted_region(): + meter = score_meter_map(score()) + gt = np.array([[0.,6.1],[1.,6.2],[2.,6.3]]) + wp = gt.copy();wp[:,1] -= 2. + # Estimates lie back in compound meter, but ground truth is now in 4/4. + assert not check_tracking(wp,gt,threshold=1.,beat_factors=musical_beat_factors(gt[:,1],meter))['tracked'] diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 481e874..0d60d92 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -119,22 +119,17 @@ def test_the_run_step_pins_blas_threads(self): class TestMatchmakerPin: """All workflows must install the same matchmaker, or jobs disagree.""" - def _pins(self) -> dict: - import re - - found = {} + def test_every_workflow_uses_the_shared_installer(self): + installs = [] for path in sorted(WORKFLOWS.glob("*.yml")): - for match in re.finditer(r"matchmaker\.git@([\w./-]+)", path.read_text()): - found.setdefault(path.name, set()).add(match.group(1)) - return found - - def test_every_workflow_pins_the_same_ref(self): - refs = {ref for refs in self._pins().values() for ref in refs} - assert len(refs) == 1, ( - f"workflows install different matchmaker refs: {sorted(refs)}. " - "A partial revert leaves the merge job on a different version " - "from the shards." - ) + workflow = load_workflow(path) + for job in workflow.get("jobs", {}).values(): + commands = "\n".join(s.get("run", "") for s in job.get("steps", [])) + assert "matchmaker.git@" not in commands, path.name + if "run_submission.py" in commands or "merge_references.py" in commands: + assert "python .github/install_matchmaker.py" in commands, path.name + installs.append(path.name) + assert installs class TestSiteAssembly: @@ -186,11 +181,15 @@ class TestReferencesWorkflow: REFERENCES = WORKFLOWS / "evaluate-references.yml" - def test_it_shares_the_leaderboard_concurrency_group(self): - """Two workflows committing results/ at once would race.""" - mine = load_workflow(self.REFERENCES)["concurrency"]["group"] - theirs = load_workflow(EVALUATE)["concurrency"]["group"] - assert mine == theirs + def test_diagnostics_select_only_requested_methods_and_input(self): + from matchmaker_eval.diagnostics import select_configs + + selected = select_configs("dixon", "midi") + assert selected + assert all(c["method"] == "dixon" and c["input_type"] == "midi" + for c in selected.values()) + with pytest.raises(ValueError, match="unknown_method"): + select_configs("dixon unknown_method", "midi") def test_it_uses_the_same_data_route_as_evaluate(self): workflow = load_workflow(self.REFERENCES) @@ -271,9 +270,11 @@ def _branches(self, path): trigger = workflow.get(True) or workflow.get("on") return trigger["push"]["branches"] - def test_evaluation_runs_on_the_staging_branch(self): - assert "submissions" in self._branches(EVALUATE) - assert "main" not in self._branches(EVALUATE) + @pytest.mark.parametrize("path", [EVALUATE, WORKFLOWS / "evaluate-references.yml"]) + def test_full_evaluations_require_explicit_dispatch(self, path): + workflow = load_workflow(path) + trigger = workflow.get(True) or workflow.get("on") + assert set(trigger) == {"workflow_dispatch"} def test_the_site_publishes_only_from_main(self): """A staging run must be inspectable before anyone sees it.""" @@ -283,13 +284,6 @@ def test_the_site_publishes_only_from_main(self): "one: a result could reach the site before it was checked" ) - def test_a_results_only_commit_does_not_re_trigger_evaluation(self): - """Committing results/ must not start another evaluation.""" - workflow = load_workflow(EVALUATE) - trigger = workflow.get(True) or workflow.get("on") - paths = trigger["push"]["paths"] - assert not any(p.startswith("results") for p in paths) - class TestValidateWorkflow: def test_validation_needs_no_dataset(self): @@ -381,3 +375,94 @@ def read_text(self, name): "importlib.metadata.distribution", lambda name: NoDirectUrl() ) assert R._matchmaker_source() == {} + + def test_a_patched_install_records_all_sources_without_a_false_commit(self, tmp_path, monkeypatch): + from matchmaker_eval import run_submission as R + + provenance = {"matchmaker_base_commit": "base", "matchmaker_patches": [ + {"base": "parent", "head": "pr-head", "sha256": "patch-hash"}, + ]} + (tmp_path / "assets").mkdir() + import json + (tmp_path / "assets" / "benchmark-source.json").write_text(json.dumps(provenance)) + + class LocalInstall: + def read_text(self, name): + return '{"url": "file:///tmp/source", "dir_info": {}}' + + monkeypatch.setattr("importlib.metadata.distribution", lambda name: LocalInstall()) + monkeypatch.setattr("importlib.resources.files", lambda name: tmp_path) + assert R._matchmaker_source() == provenance + assert "matchmaker_commit" not in R._matchmaker_source() + + +class TestReleasedResults: + """A release must identify its evaluated code and preserve a usable snapshot.""" + + @pytest.mark.parametrize("change", [ + {"status": "in_progress"}, {"conclusion": "failure"}, + {"head_repository": {"full_name": "someone/fork"}}, + ]) + def test_only_successful_completed_repository_runs_can_be_released(self, change): + from matchmaker_eval.release_results import validate_runs + run = {"status": "completed", "conclusion": "success", "head_branch": "main", + "head_repository": {"full_name": "owner/benchmark"}, "head_sha": "abc"} + validate_runs([run, {**run, "head_branch": "feature", "head_sha": "def"}], "owner/benchmark") + with pytest.raises(ValueError, match="successful, completed runs"): + validate_runs([{**run, **change}], "owner/benchmark") + + def test_only_complete_results_with_matching_provenance_replace_an_entry(self, tmp_path): + import json + from matchmaker_eval.release_results import stage_piano + source = tmp_path / "source" / "method-midi" + source.mkdir(parents=True) + destination = tmp_path / "published" + existing = destination / "submissions" / source.name / "metrics.json" + existing.parent.mkdir(parents=True) + existing.write_text("previous result") + other = destination / "submissions" / "other-midi" / "metrics.json" + other.parent.mkdir() + other.write_text("other result") + record = {"submission": source.name, "fold": "eval", "partial": False, + "n_failed": 0, "n_pieces": 2, "fold_size": 2, + "environment": {"benchmark_commit": "abc"}} + metrics = source / "metrics.json" + metrics.write_text(json.dumps({**record, "partial": True})) + with pytest.raises(ValueError, match="Incomplete"): + stage_piano(source.parent, destination, "abc") + assert existing.read_text() == "previous result" + metrics.write_text(json.dumps(record)) + with pytest.raises(ValueError, match="source run's commit"): + stage_piano(source.parent, destination, "def") + assert existing.read_text() == "previous result" + assert stage_piano(source.parent, destination, "abc") == [source.name] + assert json.loads(existing.read_text()) == record + corrected = {**record, "n_tracked": 2, "environment": {"benchmark_commit": "def"}} + metrics.write_text(json.dumps(corrected)) + stage_piano(source.parent, destination, "def") + assert json.loads(existing.read_text()) == corrected + assert other.read_text() == "other result" + + def test_snapshot_round_trip_preserves_the_site_and_metrics(self, tmp_path, monkeypatch): + import json + import build_site + from matchmaker_eval.release_results import snapshot, extract + results = tmp_path / "results" + entry = results / "submissions" / "method-midi" + entry.mkdir(parents=True) + record = {"submission": "method-midi", "n_tracked": 2} + (entry / "metrics.json").write_text(json.dumps(record)) + (entry / "wp_0.tsv").write_text("0 0\n1 1\n") + (results / "leaderboard.json").write_text('{"entries": []}') + (results / "release.json").write_text('{"publisher_commit": "abc"}') + bundle = tmp_path / "snapshot.zip" + snapshot(results, bundle) + restored = tmp_path / "restored" + extract(bundle, restored) + assert json.loads((restored / "submissions/method-midi/metrics.json").read_text()) == record + monkeypatch.setattr(build_site, "RESULTS_DIR", restored) + site = tmp_path / "site" + build_site.build(site) + assert (site / "index.html").exists() + assert (site / "release.json").read_bytes() == (results / "release.json").read_bytes() + assert (site / "leaderboard.json").read_bytes() == (results / "leaderboard.json").read_bytes() From 65ec5a5d5b3d15228d3491d4780c94248d98c12e Mon Sep 17 00:00:00 2001 From: "jiyun.park" Date: Fri, 13 Nov 2026 14:20:17 +0100 Subject: [PATCH 2/3] trim the changes --- .github/install_matchmaker.py | 5 +- .github/workflows/evaluate-amt.yml | 11 +- .github/workflows/evaluate-diagnostics.yml | 11 +- .github/workflows/evaluate-offline.yml | 24 +- .github/workflows/evaluate-references.yml | 4 +- .github/workflows/evaluate.yml | 6 +- .gitignore | 3 +- README.md | 17 +- docs/ci-evaluation.md | 154 --------- docs/diagnostics.md | 82 ----- docs/eval-protocol.md | 31 +- docs/index.html | 8 +- docs/maintaining.md | 62 ++-- docs/submitting.md | 4 +- matchmaker_eval/build_site.py | 2 +- matchmaker_eval/diagnostics.py | 277 --------------- matchmaker_eval/download_data.py | 2 +- matchmaker_eval/estimate_perf_tempo.py | 2 +- matchmaker_eval/eval_symbolic.py | 2 +- .../{provenance.py => evaluation_key.py} | 87 ++--- matchmaker_eval/export_details.py | 6 +- matchmaker_eval/fetch_data.py | 6 +- matchmaker_eval/leaderboard.py | 25 +- matchmaker_eval/{folds.py => load_folds.py} | 0 matchmaker_eval/make_folds.py | 2 +- matchmaker_eval/merge_references.py | 2 +- matchmaker_eval/merge_shards.py | 4 +- matchmaker_eval/preprocess_urmp.py | 2 +- matchmaker_eval/preprocess_winterreise.py | 2 +- matchmaker_eval/release_results.py | 34 +- matchmaker_eval/retract.py | 2 +- matchmaker_eval/run_amt.py | 144 +++++--- matchmaker_eval/run_diagnostics.py | 319 ++++++++++++++++++ matchmaker_eval/run_references.py | 2 +- matchmaker_eval/run_submission.py | 8 +- matchmaker_eval/symbolic_alignment.py | 2 +- matchmaker_eval/test_audio.py | 2 +- matchmaker_eval/test_symbolic.py | 2 +- matchmaker_eval/validate_submission.py | 2 +- matchmaker_eval/verify_equivalence.py | 2 +- matchmaker_eval/verify_tracking.py | 4 +- tests/test_data_folder.py | 2 +- tests/test_data_paths.py | 57 +--- tests/test_estimated_bpm.py | 20 +- tests/test_evaluation_key.py | 57 +--- tests/test_merge_shards.py | 156 ++++----- tests/test_musical_beats.py | 82 ++--- tests/test_registry_integration.py | 2 +- tests/test_workflows.py | 150 ++++---- 49 files changed, 750 insertions(+), 1142 deletions(-) delete mode 100644 docs/ci-evaluation.md delete mode 100644 docs/diagnostics.md delete mode 100644 matchmaker_eval/diagnostics.py rename matchmaker_eval/{provenance.py => evaluation_key.py} (64%) rename matchmaker_eval/{folds.py => load_folds.py} (100%) create mode 100644 matchmaker_eval/run_diagnostics.py diff --git a/.github/install_matchmaker.py b/.github/install_matchmaker.py index 265f014..29753dd 100644 --- a/.github/install_matchmaker.py +++ b/.github/install_matchmaker.py @@ -13,9 +13,10 @@ REPOSITORY = "https://github.com/pymatchmaker/matchmaker.git" -BASE = "25960ea95aadf1b98d1bc753c8be133e0bc859ff" # develop, including #79, #80 and #81 +# develop with #79, #80 and #81: DPDannenberg, its initial-window fix, 3 kHz SPARC. +BASE = "25960ea95aadf1b98d1bc753c8be133e0bc859ff" PATCHES = ( - # Retain the existing bounded repeat enumeration used by diagnostics. + # Multi-Fold Arzt: retain the bounded repeat enumeration used by diagnostics. ("678366b034edc7cb10e3cf71bb1755b1a679e6c1", "0e673e2bfebd86c1e814ed9f5270b926c053a0ae"), ) diff --git a/.github/workflows/evaluate-amt.yml b/.github/workflows/evaluate-amt.yml index 3f0b624..07f3b5f 100644 --- a/.github/workflows/evaluate-amt.yml +++ b/.github/workflows/evaluate-amt.yml @@ -55,16 +55,9 @@ jobs: run: | python matchmaker_eval/run_amt.py --method '${{ matrix.method }}' \ --shard '${{ matrix.shard }}' --num-shards '${{ needs.plan.outputs.shards }}' --output results/amt - - name: Record provenance + - name: Record installed packages if: always() - run: | - mkdir -p results/amt - pip freeze > results/amt/environment.txt - python - <<'PY' - import json,os - from pathlib import Path - Path('results/amt/CI.json').write_text(json.dumps({k:os.environ.get(k) for k in ['GITHUB_RUN_ID','GITHUB_RUN_ATTEMPT','GITHUB_SHA','MATCHMAKER_DATA_BRANCH']},indent=2)) - PY + run: mkdir -p results/amt && pip freeze > results/amt/environment.txt - uses: actions/upload-artifact@v4 if: always() with: diff --git a/.github/workflows/evaluate-diagnostics.yml b/.github/workflows/evaluate-diagnostics.yml index ebce202..a1dbcd9 100644 --- a/.github/workflows/evaluate-diagnostics.yml +++ b/.github/workflows/evaluate-diagnostics.yml @@ -33,7 +33,7 @@ jobs: run: | python - <<'PY' >> "$GITHUB_OUTPUT" import json, os - from matchmaker_eval.diagnostics import select_configs + from matchmaker_eval.run_diagnostics import select_configs n = int(os.environ['SHARDS']) if not 1 <= n <= 8: raise SystemExit('Use 1–8 shards for diagnostics') configs = select_configs(os.environ['ONLY'], os.environ['INPUT_TYPE']) @@ -68,7 +68,7 @@ jobs: pip install pyyaml pydantic-settings - name: Run frozen diagnostic cases run: | - python matchmaker_eval/diagnostics.py run \ + python matchmaker_eval/run_diagnostics.py run \ --config '${{ matrix.job.config }}' --shard '${{ matrix.job.shard }}' \ --shards '${{ needs.plan.outputs.shards }}' --output results/diagnostics - uses: actions/upload-artifact@v4 @@ -97,16 +97,17 @@ jobs: python - <<'PY' import json from pathlib import Path - from matchmaker_eval.diagnostics import download, sha + from matchmaker_eval.evaluation_key import file_sha256 + from matchmaker_eval.run_diagnostics import download from matchmaker_eval.fetch_data import frozen_source p = frozen_source('diagnostics') dest = Path('results/data_manifest.json') download(f'https://raw.githubusercontent.com/{p["repository"]}/{p["commit"]}/diagnostics/manifest.json', dest) - assert sha(dest) == p['manifest_sha256'] + assert file_sha256(dest) == p['manifest_sha256'] PY - name: Verify completeness and aggregate run: | - python matchmaker_eval/diagnostics.py merge --source results/shards \ + python matchmaker_eval/run_diagnostics.py merge --source results/shards \ --output results/diagnosis --manifest results/data_manifest.json \ --shards '${{ needs.plan.outputs.shards }}' --only "$ONLY" --input-type "$INPUT_TYPE" - uses: actions/upload-artifact@v4 diff --git a/.github/workflows/evaluate-offline.yml b/.github/workflows/evaluate-offline.yml index 082c1da..fe26cbc 100644 --- a/.github/workflows/evaluate-offline.yml +++ b/.github/workflows/evaluate-offline.yml @@ -54,34 +54,20 @@ jobs: sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 ffmpeg python .github/install_matchmaker.py pip install pyyaml pydantic-settings - - name: Install archived offline numerical environment + - name: Install the offline numerical environment run: | - # The original server uses these numerical packages with synctoolbox - # 1.3.2, despite its obsolete pandas/numba upper bounds. Its used DTW - # and audio functions are smoke-tested below before the full shard. + # synctoolbox 1.3.2 declares pandas/numba upper bounds it does not + # need, so it is installed without its dependency pins. pip install 'numpy==1.26.4' 'scipy==1.14.1' 'pandas==2.2.3' 'librosa==0.10.2' 'numba==0.64.0' ipython pretty_midi music21 pip install --no-deps 'synctoolbox==1.3.2' 'libfmp==1.3.0' - python matchmaker_eval/run_offline.py --fold example --no-fetch --output results/offline-preflight - python - <<'PY' - import json - r=json.load(open('results/offline-preflight/metrics.json')) - assert r['n_failed']==0 and r['n_pieces']==1 - PY - name: Run offline reference run: | python matchmaker_eval/run_offline.py --fold '${{ matrix.job.fold }}' \ --shard '${{ matrix.job.shard }}' --num-shards '${{ needs.plan.outputs.shards }}' \ --piece-timeout 2400 --output results/offline - - name: Record runner and package provenance + - name: Record installed packages if: always() - run: | - mkdir -p results/offline - pip freeze > results/offline/environment.txt - python - <<'PY' - import json,os - from pathlib import Path - Path('results/offline/CI.json').write_text(json.dumps({k:os.environ.get(k) for k in ['GITHUB_RUN_ID','GITHUB_RUN_ATTEMPT','GITHUB_SHA','MATCHMAKER_DATA_BRANCH']},indent=2)) - PY + run: mkdir -p results/offline && pip freeze > results/offline/environment.txt - uses: actions/upload-artifact@v4 if: always() with: diff --git a/.github/workflows/evaluate-references.yml b/.github/workflows/evaluate-references.yml index 7160be7..8d54a37 100644 --- a/.github/workflows/evaluate-references.yml +++ b/.github/workflows/evaluate-references.yml @@ -17,7 +17,7 @@ # Actions -> Evaluate references -> Run workflow # input_type: both shards: 8 # -# 17 described entries x 8 shards is 136 jobs. They queue against the account's +# Every described entry runs as one job per shard. They queue against the account's # concurrency limit rather than all starting at once, so expect this to take a # while; that is the price of every row being measured the same way. name: Evaluate references @@ -184,7 +184,7 @@ jobs: pip install --quiet pyyaml python - <<'PY' >> "$GITHUB_OUTPUT" import json, os, yaml - from matchmaker_eval.folds import load_fold + from matchmaker_eval.load_folds import load_fold described = yaml.safe_load( open("data/builtin_methods.yaml").read() ) or {} diff --git a/.github/workflows/evaluate.yml b/.github/workflows/evaluate.yml index 30fd2a8..6417025 100644 --- a/.github/workflows/evaluate.yml +++ b/.github/workflows/evaluate.yml @@ -8,9 +8,8 @@ # down once (`fetch_data.py --source`). # # A maintainer explicitly selects a reviewed submission or built-in method. -# Results are uploaded as artifacts and never committed to the code branch. -# After the code is on main, evaluate that main commit and select the -# completed run in Publish leaderboard to preserve and publish a release. +# Results are uploaded as artifacts. To publish them, select the completed run +# in Publish leaderboard (see docs/maintaining.md). # # Sharding is what makes this fit: a job on a GitHub runner is capped at 6 # hours, and audio evaluation over 146 pieces does not fit in one. Shards are @@ -78,7 +77,6 @@ jobs: - name: Decide what to evaluate id: plan - # Full evaluations are explicit, so a merge cannot start a duplicate run. run: | pip install --quiet pyyaml python - <<'PY' >> "$GITHUB_OUTPUT" diff --git a/.gitignore b/.gitignore index b5e764e..4155576 100644 --- a/.gitignore +++ b/.gitignore @@ -182,8 +182,7 @@ reports/ *exports/ scripts/ -# New generated results belong in CI artifacts and release assets. -# Previously tracked snapshots remain unchanged; CI never commits results. +# Results are published as CI artifacts and release assets. /results/ # Assembled leaderboard site (matchmaker_eval/build_site.py) diff --git a/README.md b/README.md index 16bf2c0..36bb9e8 100644 --- a/README.md +++ b/README.md @@ -16,11 +16,8 @@ data** — the evaluation runs on GitHub's runners, which fetch what they need. | **Library** | [matchmaker](https://github.com/pymatchmaker/matchmaker) | | **Metrics** | beat error, ms error, tracking rate, real-time factor | -Final result bundles are available under [Releases](https://github.com/pymatchmaker/matchmaker_benchmark/releases). -Maintainers squash-merge code into main, preserve selected completed CI runs in -a release and publish its snapshot. Reviewed pre-merge results can be reused -when the evaluation logic and data are unchanged. Generated results -are not committed by CI. See [running and publishing results](docs/ci-evaluation.md). +Full results are published as [Releases](https://github.com/pymatchmaker/matchmaker_benchmark/releases). +See [publishing results](docs/maintaining.md#staging-a-run-before-it-is-published). ## Submit a score follower @@ -95,9 +92,8 @@ code; after merge it is evaluated and appears on the leaderboard. ``` Review is the trust boundary: CI executes submitted code, it does not sandbox -it. Full evaluation and publication are explicitly started by a maintainer. -Evaluation may run on a reviewed branch; publication runs from `main` after -merge. A merge alone does not start a full evaluation. +it. A maintainer starts full evaluation and publication explicitly; +publication runs from `main`. ## Folds @@ -215,8 +211,7 @@ contract. and one elsewhere. The reference score's time signature is looked up at each annotated onset, including changes within a piece and a window. - **Precision metric**: beat error (performance → score), pooled over the - pieces that method actually tracked. These error summaries and tolerance - accuracies retain denominator-note beat units. + pieces that method actually tracked, in denominator-note beats. - **Secondary precision metric**: ms error (score → performance), same pooling. - **Aggregation**: precision metrics are event-pooled across tracked pieces. - **Ranking**: tracking rate first, then median beat error. @@ -243,7 +238,7 @@ matchmaker_eval/ merge_references.py — regroup and merge a sharded multi-method run export_details.py — every pooled metric per dataset, per-piece detail and decimated alignment paths - folds.py, make_folds.py — fold definitions and their integrity checks + load_folds.py, make_folds.py — fold definitions and their integrity checks fetch_data.py — locate a fold's data (--source), check it is all present (--verify), or download just what it needs verify_equivalence.py — proves submissions are scored like built-in methods diff --git a/docs/ci-evaluation.md b/docs/ci-evaluation.md deleted file mode 100644 index d76d5c4..0000000 --- a/docs/ci-evaluation.md +++ /dev/null @@ -1,154 +0,0 @@ -# Running the full benchmark on GitHub Actions - -Open **Actions → Evaluate references → Run workflow** and select the code -branch to evaluate. Every shard and the merge use the same Matchmaker sources -from `.github/install_matchmaker.py`, including the 3 kHz SPARC implementation. -The first release under musical-beat TR must include -the complete piano evaluation; run the beyond-piano fold as well for the paper. -Full evaluations run only when explicitly dispatched. PR checks still validate -the code and bundled example without starting the full benchmark. - -The installer pins `develop` at `25960ea`, which includes merged PRs #79, #80 -and #81, including the Dannenberg initial-window correction. It retains the -existing bounded Multi-Fold enumeration (`678366b..0e673e2`) needed by diagnostics, -applied in a temporary CI checkout. No upstream branch or PR is changed. -Every result records the full base commit and patch commits and hashes in -`environment.matchmaker_base_commit` and `environment.matchmaker_patches`. -The full installed-source hash remains part of each run's provenance. -Once the remaining patch is merged upstream, update the installer's base and -remove it. Reviewed branch evaluations can be reused for publication as -described below. - -| Run | input_type | fold | only | shards | -| --- | --- | --- | --- | --- | -| All piano references | both | eval | leave empty | 8 | -| All beyond-piano references | audio | beyond_piano | leave empty | 8 | -| MIDI OPHMM global-transition comparison | midi | ophmm_playthrough | ignored | fixed at 4 | -| Manuscript diagnostics | both | diagnostics | leave empty | 4 | -| Dannenberg perturbations only | midi | diagnostics | dannenberg | 4 | -| Offline reference, both folds | audio | offline | ignored | 8 | -| Frozen AMT reference | midi | amt_reference | ignored | 4 | - -The piano fold contains 146 performances with audio and MIDI. The beyond-piano -fold contains 343 audio inputs: ChoraleBricks (191), KRAISLER (60), SWD (48), and -URMP (44). It has no performance MIDI files. Selecting `both` on that fold runs -only its available audio inputs; explicitly selecting MIDI fails during planning. - -Both folds read the `eval` branch of `pymatchmaker/matchmaker-benchmark-data`, -as configured in `data/data_sources.yaml`. Each shard checks all required score, -performance, and ground-truth files before running. - -## Downloading results - -Once the merge finishes, download **benchmark-results-eval** or -**benchmark-results-beyond_piano** from the run's Artifacts section. This single -artifact contains every merged method directory, including `metrics.json`, -full `wp_.tsv` and `gt_.tsv` paths, and the score meter maps -`meter_.json`. Individual `refshard-*` artifacts remain available for -diagnosing a missing or failed shard. - -CI first merges into a fresh `results/ci//` directory, so the combined -artifact contains only the current run. Piano entries also produce a -`leaderboard-site` preview of this run. Evaluation never commits result files -or updates the public website. Beyond-piano results stay in their own artifact. -A missing method or incomplete merge fails rather than reporting a complete evaluation. -For local merges without `--output`, auxiliary folds use `results/runs//`. - -## Preserving and publishing final results - -1. Squash-merge the code PR into `main` without generated result changes. -2. Select successful **Evaluate references** runs for each required fold. Reuse - reviewed pre-merge runs when their evaluation logic and data match the merged - code. If a method changed, select its corrected rerun after the original run. - Run missing evaluations on `main` only when needed. -3. Check the merged results and the preview. Then open **Publish leaderboard → - Run workflow** on `main`. Set `source_runs` to the completed run IDs separated - by spaces, in replacement order, and `release_tag` to a new version such as - `benchmark-v1`. Later listed runs replace earlier entries for the same method. -4. The workflow preserves the results in that release, targets the publishing - `main` commit, and deploys the website. It does not run any follower again. - -The release contains the original `benchmark-results-*` artifact ZIPs, including -non-piano and auxiliary results when their run IDs are selected, a -`benchmark-snapshot.zip` for the website, and `SHA256SUMS`. The snapshot includes -`release.json` with source run IDs, evaluated commits, branches, attempts, artifact -hashes, the selected run for each leaderboard entry and the previous release. -Python, library, data and evaluation metadata remain in the original -result files. Raw paths stay in the run ZIPs; the website uses decimated paths. - -Only successful, completed runs from this repository can be combined. Each -piano result must identify the commit of its source run. Publishing requires -`main`, but source runs may come from different commits or reviewed PR branches; -their original commit metadata is preserved, including after a squash merge. -The original ZIPs are all retained, including entries superseded in the snapshot. -Previously published methods are retained from the last release; methods under -older evaluation conditions remain outside the current ranking. The first -release must include the piano leaderboard. Later releases can also archive -non-piano or diagnostic results while retaining that leaderboard. - -Result versions are never overwritten. Uploads are prepared as a draft and -published only after all assets have been uploaded. If an upload fails, inspect -the draft before retrying; the workflow refuses to overwrite an existing version. -Actions artifacts expire, so preserve final runs before that happens. - -To redeploy an existing release, leave `source_runs` empty and optionally select -its `release_tag`. With no tag, the latest published `benchmark-*` snapshot is -used. Documentation-only updates reuse that snapshot. Before the first release, -the existing website stays unchanged. No result PR, additional branch or -additional repository is required. The old tracked `results/` files are retained -unchanged for this migration; new publication reads release assets instead. - -## Adding or updating one method - -After the first complete release, add the new method's description to -`data/builtin_methods.yaml` and update the pinned Matchmaker sources in -`.github/install_matchmaker.py`. Merge that code change, then run **Evaluate references** -on `main` with `only=dannenberg`, `input_type=midi` and `fold=eval`, for example. -For an audio method, run its beyond-piano fold too when needed. - -Publish only those new run IDs in a new release. The website snapshot retains -the other methods and replaces the evaluated entries; the previous release -keeps their previous results. This needs no additional selection UI or result -PR. A follower-only change preserves comparison with earlier methods. A data, -fold, ground-truth or scoring change requires results under the new conditions -before they can be ranked together. See [evaluation keys](eval-protocol.md#the-evaluation-key). - -## Evaluation settings - -TR uses onset-anchored 30 s windows and tolerances of 1.0 musical beat for audio -and 0.1 for MIDI. The compound-meter factor is applied at each ground-truth onset, -including meter changes within a window. Position-error summaries remain in -denominator-note beats. See [the evaluation protocol](eval-protocol.md). - -For a saved performance, the same TR calculation and plot can be reproduced with: - -```sh -python matchmaker_eval/verify_tracking.py \ - --wp path/to/wp_1.tsv --gt path/to/gt_1.tsv \ - --meter path/to/meter_1.json --threshold 0.1 --save tracking_1.png -``` - -Use `--threshold 1.0` for audio. The meter map comes from the follower's actual -unfolded score, so it preserves the score-position system used by the saved paths. - - -## MIDI OPHMM play-through comparison - -The `ophmm_playthrough` selection evaluates the same 146-piece piano fold with -score-wide transitions enabled and disabled. It calls the common benchmark -runner and saves both conditions in `ophmm-playthrough-comparison`. It does -not replace the default reference or publish either condition to the leaderboard. - -```sh -python matchmaker_eval/run_submission.py --method outerhmm --input-type midi --fold eval \ - --global-transition off --output results/ophmm-off -``` - -Use `on` for the paired comparison. Disabling the option zeros the skip-from -probabilities before alignment; local transitions and pitch observations are -unchanged. The setting is saved in merged metadata and per-piece -records. The merge requires 146 completed performances per condition and checks -that the disabled transition probabilities remained zero. - -The [diagnostic suites](diagnostics.md) retain their explicit repeat/skip -settings. Selecting a play-through setting does not change those experiments. diff --git a/docs/diagnostics.md b/docs/diagnostics.md deleted file mode 100644 index 5008f8a..0000000 --- a/docs/diagnostics.md +++ /dev/null @@ -1,82 +0,0 @@ -# Running the manuscript diagnostics - -In Actions, choose **Evaluate references**, set `fold` to `diagnostics`, and -use four shards. Select the branch containing this workflow. No leaderboard -files are changed by this run. `benchmark-results-diagnosis` contains all raw -paths, ground truth, per-case metrics, logs, input hashes and a merged summary. -The merge fails if any case or shard of a selected configuration is missing, -duplicated or failed. Leave `only` empty and `input_type=both` for all suites; -set `only=dannenberg` and `input_type=midi` for its 34 perturbation conditions only. - -For non-piano evaluation use the same workflow with `fold=beyond_piano`, -`input_type=audio`. Its artifact is `benchmark-results-beyond_piano`. - -Diagnostic inputs are pinned under `frozen_sources.diagnostics` in -`data/data_sources.yaml`. The runner verifies -the manifest hash and each selected input, including losslessly encoded audio. -The source data release documents the original generator scripts and licenses. -No regeneration with an unrecorded soundfont occurs in CI. - -The diagnostic configurations are in `matchmaker_eval/diagnostics.py`: - -- Perturbations: four audio and seven MIDI followers on 41/34 conditions. -- Repeat examples: Arzt, Multi-Fold Arzt and OPHMM on two K.282 excerpts. -- Folded Batik: Dixon, Arzt, SKF, OPHMM and Multi-Fold Arzt on 24 test movements. -- Global skip: symbolic OPHMM on two K.279 conditions, changing only its - skip-from distribution to disable the global transition. - -Audio OPHMM uses `s_j=1e-100` for the synthetic diagnostic suites, where jumps -are part of the experiment. The folded-Batik OPHMM configuration uses `s_j=1e-5`, as in the original -folded-score diagnostic protocol. The play-through baseline registry uses zero. -Nominal tempo is provided only for the two K.282 illustrative cases (60 BPM). -The synthetic perturbations and recorded folded cases receive the normal -score-based tempo initialization, not the performance's estimated tempo. - -All suites use the same `run_evaluation`, causal onset sampling, 3 kHz SPARC -implementation, and musical-beat tracking criterion as the main benchmark. -Accuracy remains in score denominator-note beats. The input manifest specifies -whether the score is unfolded. Repeat ground truth retains backward jumps. -The perturbation summary averages per-condition MeanAE over tracked cases; -raw per-case paths also support pooled accuracy and common-tracked analyses. -Timing measured on these runners is retained separately from previously -reported RTF. A new runner measurement must not silently replace an earlier -measurement or be selected because it is smaller. - -Local reproduction: - -```sh -python matchmaker_eval/diagnostics.py run \ - --config perturbations-audio-arzt --shard 0 --shards 4 --output results/diagnostics/arzt-0 -``` - -Use the library revision installed by the workflow. Artifacts record both -library and benchmark commits and the GitHub run ID. A raw-path re-score from -an old local experiment is not equivalent to a CI execution of a follower. - -## Offline reference - -Set `fold=offline` (eight shards) to run the offline reference on the piano -and beyond-piano folds. `benchmark-results-offline` includes the merged -results and original shards. The offline pipeline is migrated from the saved -server script, using its verified synctoolbox 1.3.2 environment, 50 Hz features, -22,050 Hz onset filterbank and DTW weights [1.5, 1.5, 2.0]. It is not an online -follower. These results are archived, never inserted into the online leaderboard. - -The archived offline numerical environment uses NumPy 1.26.4, SciPy 1.14.1, -pandas 2.2.3, librosa 0.10.2, numba 0.64.0 and libfmp 1.3.0, verified on the -original server. Synctoolbox 1.3.2's old dependency upper bounds do not describe -that working environment. CI installs the two pure-Python toolbox packages -without their obsolete dependency pins, then runs the example alignment as a -preflight. The exact installed package list is saved in each artifact. This -compatibility setup is confined to offline reference jobs. - -## Frozen AMT outputs - -Set `fold=amt_reference` (four shards) for the 146 piano transcriptions with -OLTWArzt, PTHMM and SLT_OLTW. The source MIDI is public and pinned by -`data/data_sources.yaml` under `frozen_sources.amt`. CI executes the symbolic -followers, not the private AMT model. -It uses the original audio ground truth and the audio TR tolerance. The saved -MIDI timestamps are unchanged. New runner timings measure the follower only -and must not replace end-to-end AMT RTF in the manuscript. -The artifact is `benchmark-results-amt-reference`. diff --git a/docs/eval-protocol.md b/docs/eval-protocol.md index 4576dcd..43b867f 100644 --- a/docs/eval-protocol.md +++ b/docs/eval-protocol.md @@ -171,13 +171,13 @@ signatures (numerators 6, 9, 12, and larger multiples of three), and one in other meters. Simple triple meters such as 3/4 and 3/8 are not grouped. At every reference onset, the absolute position error is divided by the factor for the time signature at that reference score position **before** computing -the window median. This uses the follower's actual unfolded score, retaining -meter changes within a performance, even inside a single evaluation window. +the window median. This uses the follower's actual unfolded score, so meter +changes within a performance apply, even inside a single evaluation window. The factor follows the reference position, not a potentially incorrect estimate. Thus the native-coordinate tolerance in a compound passage is 3.0 denominator-note beats for audio and 0.3 for MIDI. The output paths, ground -truth, MeanAE, MedAE, standard deviations, and tolerance accuracies retain +truth, MeanAE, MedAE, standard deviations, and tolerance accuracies use denominator-note units; only TR uses musical beats. Each run saves a `meter_.json` alongside its full paths so the criterion can be reproduced. Scores without a time signature use the parser's 4/4 default, recorded as @@ -247,37 +247,28 @@ one is a matter of data hosting and policy, not code. It is not in place today. Two rows are only comparable when everything that decides their numbers, apart from the follower itself, was the same. Every run records those -conditions and hashes them into one **evaluation key**, e.g. `ek2-3f9c0a1b2d4e`: +conditions and hashes them into one **evaluation key**, e.g. `ek1-3f9c0a1b2d4e`: | Component | What it pins | | --- | --- | | `fold_sha256` | The fold CSV: which pieces, their paths, `estimated_bpm` | | `data_sha256` | The bytes of every file a piece was scored with: the score, the performance that was streamed, the ground truth | | `scoring_sha256` | The benchmark's scoring code: `eval.py`, `utils.py`, `verify_tracking.py`, and the thresholds and per-piece scoring in `run_submission.py` | -| `matchmaker_scoring_sha256` | Matchmaker's `matchmaker.py` and `utils/eval.py`: shared score loading, ground-truth resolution, beat errors, tracking windows and SPARC | +| `matchmaker_sha256` | The installed matchmaker sources: ground-truth resolution, beat errors, tracking windows, SPARC, and the reference followers | | `partitura` | The version that parses every score and match file | They are content hashes, not commit ids, on purpose: a results commit or a README edit changes a commit but not a number, while any change to what is -read or how it is scored changes the key. The `ek2` prefix names the scheme; if +read or how it is scored changes the key. The `ek1` prefix names the scheme; if the set of components ever changes, so does the prefix. -The full library hash, `matchmaker_sha256`, and the installed commit and -environment are retained as provenance. All shards of one method's run must -still share that full hash. It is excluded from the ek2 comparison key, so a -new follower or a change confined to a follower does not invalidate other -methods' results. Maintainers must rerun methods affected by a shared follower -implementation change. Changes to the shared score loading or scoring modules -do change the comparison key. Legacy ek1 records keep their original keys; -they are not silently promoted to ek2. - MIDI and audio runs stream different performance files, so their keys always differ in `data_sha256`: each input type has its own current key. The current conditions are set by the most recent run. Its code components (`fold_sha256`, -`scoring_sha256`, `matchmaker_scoring_sha256`, `partitura`) apply to every input type, +`scoring_sha256`, `matchmaker_sha256`, `partitura`) apply to every input type, and each input type's key is that of its most recent run under them. The leaderboard ranks a row only when it has the current key of its input type, so -every ranked row was scored by the same evaluation code, and rows of one input type also +every ranked row was scored by the same code, and rows of one input type also on the same data. A row with another key — from before a scoring fix, a data correction or a fold change — is listed below the table as scored under earlier conditions, with the components that differ, and rejoins the ranking @@ -293,10 +284,10 @@ first and last published, and its components. A key's archive is updated while i and frozen once a newer key takes over. So cite a number together with the key of its input type, e.g. *"tracking rate 0.84 (benchmark -evaluation key `ek2-3f9c0a1b2d4e`)"*. Anyone can then find the exact table it +evaluation key `ek1-3f9c0a1b2d4e`)"*. Anyone can then find the exact table it came from, and see whether a later leaderboard was scored under the same -conditions or not. Release assets preserve the per-piece records and identify -the `benchmark_commit` that produced them. +conditions or not. The per-piece records of a key are in the repository's +history at the `benchmark_commit` its rows record. ## Reproducing a leaderboard row diff --git a/docs/index.html b/docs/index.html index 919c90e..b185538 100644 --- a/docs/index.html +++ b/docs/index.html @@ -603,7 +603,7 @@

Tracked

in any window exceeds the tolerance — 0.1 musical beat for MIDI, 1.0 for audio. In compound meter, three denominator-note units form one musical beat. The reference meter is applied at each onset, including changes - within a piece. Position-error summaries retain denominator-note units. + within a piece. Position-error summaries use denominator-note units. A follower that loses the performer produces meaningless errors, so accuracy is only reported over the pieces it held onto.

@@ -647,7 +647,7 @@

Per-piece and per-dataset results

Evaluation key

Every ranked row was scored under the same conditions: the same fold, - scoring code, shared score loading and score parser, and, within an input + scoring code, matchmaker sources and score parser, and, within an input type, the same data files. MIDI and audio stream different files, so each has its own key above, a hash of all of these. Cite the key of the row's input type with any number you take from here; @@ -873,8 +873,8 @@

Submitting

const { W, H } = plotSize(width, 6.4, 120, 190); const PAD = { l: 52, r: 14, t: 14, b: 30 }; const xs = all.map((p) => p[0]); - // Full-path export retains every meter transition. Historical details use - // the earlier denominator-note thresholds until evaluated under the new rule. + // tr_tolerance steps at every meter change. Details without a tracking + // criterion are drawn against a flat denominator-note threshold. const nativeThreshold = detail.input_type === "audio" ? 1.0 : 0.5; const tolerance = piece.tr_tolerance || (piece.tracking_criterion ? [] : [[Math.min(...xs), nativeThreshold], [Math.max(...xs), nativeThreshold]]); diff --git a/docs/maintaining.md b/docs/maintaining.md index db3873b..949a1ee 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -8,7 +8,7 @@ decisions baked into this setup. CI has already checked structure, metadata and that the follower runs on one piece. **Review is the trust boundary**: `evaluate.yml` executes the submitted code on a machine that holds the datasets. Read the code before merging it or -dispatching a full evaluation. A merge does not start that evaluation automatically. +dispatching a full evaluation. `validate_submission.py` prints `review` lines for things worth a second look — network access, subprocesses, `.match` file access, reaching for @@ -230,14 +230,30 @@ Actions -> Evaluate references -> Run workflow input_type: both only: (empty = all described) shards: 8 ``` +The `fold` input selects what to run. Only `eval` feeds the leaderboard; the +others are archived as artifacts. + +| fold | input_type | shards | what it runs | +| --- | --- | --- | --- | +| `eval` | both | 8 | the piano leaderboard | +| `beyond_piano` | audio | 8 | the non-piano corpora (audio only) | +| `diagnostics` | both | 4 | the manuscript diagnostic suites in `matchmaker_eval/run_diagnostics.py` | +| `offline` | audio | 8 | the offline reference in `matchmaker_eval/run_offline.py` | +| `amt_reference` | midi | 4 | symbolic followers on frozen AMT output, `matchmaker_eval/run_amt.py` | +| `ophmm_playthrough` | midi | 4 (fixed) | MIDI OPHMM with global transitions on and off | + +Each run uploads one `benchmark-results-` artifact with every merged +method directory: `metrics.json`, the full `wp_`/`gt_` paths and the +`meter_.json` maps. + It mirrors `evaluate.yml` exactly — same data checkout, same eight-way round-robin sharding, same merge, same leaderboard rebuild — and fans out over every method described in `data/builtin_methods.yaml`. Both workflows pin `OMP_NUM_THREADS=1` so a runner's core count cannot move the timing columns between one entry and the next. -11 described methods x 8 shards is 88 jobs, which queue against the account's -concurrency limit rather than all starting at once. To evaluate a single +Every described method runs as one job per shard; the jobs queue against the +account's concurrency limit rather than all starting at once. To evaluate a single reference instead, `Evaluate submissions` takes a `method` and `input_type`. Accuracy is unaffected by any of this — an alignment path is a deterministic @@ -299,21 +315,24 @@ differ on their own. ### Staging a run before it is published -Evaluation and publication are separate. Evaluation workflows upload merged -artifacts and a preview without committing results or publishing the website. -Full evaluations require an explicit dispatch; merging a submission cannot -start a duplicate run. Publication runs from `main` after the code has been -squash-merged. Reviewed branch runs can be reused when the merged evaluation -logic and data match; their original code commits remain recorded. +Evaluation and publication are separate. Evaluation workflows are dispatched +explicitly and upload merged artifacts and a preview. Publication runs from +`main` after the code has been squash-merged. Reviewed branch runs can be +reused when the merged evaluation logic and data match. Inspect the required evaluations, then dispatch **Publish leaderboard** on -`main` with the selected `source_runs` and a new `benchmark-*` release tag. -Later listed runs replace earlier entries for the same method, so put a -corrected method's rerun after the full evaluation. The workflow attaches all -original merged artifacts and the website snapshot to the publishing commit's -release before deploying. -See [the release procedure](ci-evaluation.md#preserving-and-publishing-final-results) -for inputs, downloads and redeployment. No result changes need merging into main. +`main`: + +- `source_runs`: the completed run IDs, separated by spaces. Later listed runs + replace earlier entries for the same method, so put a corrected method's + rerun after the full evaluation. Methods not listed are carried over from the + latest release. +- `release_tag`: a new `benchmark-*` tag. Leave `source_runs` empty to redeploy + that release, or both empty to redeploy the latest one. + +The workflow attaches the selected artifacts, a `benchmark-snapshot.zip` for +the site and `SHA256SUMS` to the release, then deploys. Actions artifacts +expire, so publish final runs before they do. A manually dispatched evaluation runs only the requested methods or submission; publication reuses those outputs and never executes a follower. @@ -350,9 +369,8 @@ a result that was on the leaderboard and is not any more is itself a fact about the leaderboard, so it is published rather than quietly erased. The run is moved to `results/retracted//`, so `--reason` is required and `--undo` puts it back. `--purge` deletes instead of archiving, and cannot be undone. -These commands edit the local snapshot only. A withdrawal needs a new corrected -release snapshot and checksums; changing a file in the code checkout does not -change the website. Preserve the original release. +These commands edit the local snapshot only; publish the corrected snapshot +as a new release. `export_details.py` also removes any detail file whose run has gone, so a hand-deleted result cannot leave one behind either. @@ -463,9 +481,9 @@ somewhere else. ## Publishing `.github/workflows/pages.yml` combines `docs/` with the selected release snapshot -and deploys it to GitHub Pages. A documentation update reuses the last published -snapshot. `MATCHMAKER_RESULTS_DIR` points the existing export and site-building -scripts at a temporary directory outside the code checkout. +and deploys it to GitHub Pages. A documentation update reuses the latest published +snapshot. `MATCHMAKER_RESULTS_DIR` points the export and site-building scripts +at a temporary directory outside the code checkout. ### What the site can show diff --git a/docs/submitting.md b/docs/submitting.md index 368fa1e..d9f00e9 100644 --- a/docs/submitting.md +++ b/docs/submitting.md @@ -4,7 +4,6 @@ The benchmark takes submissions as pull requests **against the `submissions` branch**, not `main`. You add one directory and CI checks it on the bundled example. A maintainer reviews and squash-merges the code into `main`, explicitly runs the full evaluation, and selects the completed run for a result release. -Merging alone does not start a full evaluation. ``` you GitHub maintainer GitHub Actions @@ -187,8 +186,7 @@ though a single job could not. The merged result is identical to an unsharded run. The full per-piece output (alignment paths, per-piece metrics) is attached to -the workflow run as an artifact for 30 days. Evaluation does not commit files -to either code branch. +the workflow run as an artifact for 30 days. A maintainer checks the result. Selected final runs are then preserved as downloadable [release assets](https://github.com/pymatchmaker/matchmaker_benchmark/releases). diff --git a/matchmaker_eval/build_site.py b/matchmaker_eval/build_site.py index 41c34ed..6f56779 100644 --- a/matchmaker_eval/build_site.py +++ b/matchmaker_eval/build_site.py @@ -25,7 +25,7 @@ import argparse import shutil -from matchmaker_eval.folds import REPO_ROOT, RESULTS_DIR +from matchmaker_eval.load_folds import REPO_ROOT, RESULTS_DIR DOCS_DIR = REPO_ROOT / "docs" diff --git a/matchmaker_eval/diagnostics.py b/matchmaker_eval/diagnostics.py deleted file mode 100644 index 1ec4611..0000000 --- a/matchmaker_eval/diagnostics.py +++ /dev/null @@ -1,277 +0,0 @@ -"""Frozen diagnostic suites, executed and scored with the benchmark evaluator. - -The data manifest records every input hash. No paths from a developer's machine -are used at evaluation time. Jobs fail on missing inputs or incomplete results. -""" -from pathlib import Path -import argparse -import hashlib -import json -import os -import sys -import time -import urllib.request - -ROOT = Path(__file__).resolve().parents[1] -for p in (ROOT, ROOT / 'matchmaker_eval'): - sys.path.insert(0, str(p)) - -CONFIGS = { - **{f'perturbations-{mode}-{m}': dict(suite='perturbations', input_type=mode, method=m) - for mode, methods in [('audio', ['dixon', 'arzt', 'outerhmm', 'skf']), - ('midi', ['pthmm', 'hmm', 'outerhmm', 'dixon', 'arzt', 'SLT_OLTW', 'dannenberg'])] - for m in methods}, - **{f'repeat_examples-audio-{m}': dict(suite='repeat_examples', input_type='audio', method=m) - for m in ['arzt', 'arzt_multi_fold', 'outerhmm']}, - **{f'folded_batik-audio-{m}': dict(suite='folded_batik', input_type='audio', method=m, - kwargs={'s_j': 1e-5} if m == 'outerhmm' else {}) - for m in ['dixon', 'arzt', 'skf', 'outerhmm', 'arzt_multi_fold']}, - **{f'global_skip-midi-{state}': dict(suite='global_skip', input_type='midi', method='outerhmm', disable_global_skip=state == 'off') - for state in ['on', 'off']}, -} - - -def select_configs(only='', input_type='both'): - methods = set(only.split()) - selected = {name: config for name, config in CONFIGS.items() - if (input_type == 'both' or config['input_type'] == input_type) - and (not methods or config['method'] in methods)} - missing = methods - {config['method'] for config in selected.values()} - if not selected or missing: - raise ValueError(f'No diagnostic configuration for {input_type}: {sorted(missing or methods)}') - return selected - - -def json_value(value): - """Retain model-class identity when serializing effective settings.""" - if isinstance(value, type): - return f'{value.__module__}.{value.__qualname__}' - return float(value) - - -def sha(path): - h = hashlib.sha256() - with Path(path).open('rb') as f: - for chunk in iter(lambda: f.read(1 << 20), b''): - h.update(chunk) - return h.hexdigest() - - -def download(url, path): - path.parent.mkdir(parents=True, exist_ok=True) - for attempt in range(4): - try: - with urllib.request.urlopen(url, timeout=120) as response, path.open('wb') as out: - import shutil - shutil.copyfileobj(response, out) - return - except Exception: - if attempt == 3: - raise - time.sleep(2 ** attempt) - - -def materialize(rel, manifest, root, base_url): - """Fetch a frozen file, reassembling large lossless audio when necessary.""" - meta = manifest['files'][rel] - dest = root / rel - if dest.exists() and sha(dest) == meta['sha256']: - return dest - dest.parent.mkdir(parents=True, exist_ok=True) - if meta.get('parts'): - import shutil - with dest.open('wb') as out: - for part in meta['parts']: - local = root / part['path'] - if not local.exists() or sha(local) != part['sha256']: - download(base_url + part['path'], local) - if sha(local) != part['sha256']: - raise ValueError(f'Corrupt data chunk: {part["path"]}') - with local.open('rb') as f: - shutil.copyfileobj(f, out) - else: - download(base_url + rel, dest) - if sha(dest) != meta['sha256']: - raise ValueError(f'Input hash mismatch: {rel}') - return dest - - -def select_cases(manifest, config, shard=0, shards=1): - if not 1 <= shards <= 32 or not 0 <= shard < shards: - raise ValueError('Invalid shard selection') - cases = [c for c in manifest['cases'] if c['suite'] == config['suite'] and c['input_type'] == config['input_type']] - ids = [c['id'] for c in cases] - if not ids or len(ids) != len(set(ids)): - raise ValueError('Empty or duplicated diagnostic cases') - return [(i, c) for i, c in enumerate(cases) if i % shards == shard] - - -def run_case(case, config, paths, out): - import numpy as np - from matchmaker import Matchmaker - from matchmaker.matchmaker import DEFAULT_KWARGS - from matchmaker.utils.eval import resolve_gt - from matchmaker_eval.eval import run_evaluation - from matchmaker_eval.run_submission import check_follower, piece_time_budget - from matchmaker_eval.utils import TOLERANCES_IN_BEATS - from matchmaker_eval.verify_tracking import TRACKING_THRESHOLDS, score_meter_map, musical_beat_factors - from matchmaker_eval.verify_tracking import check_tracking - - mode, method = config['input_type'], config['method'] - kwargs = dict(DEFAULT_KWARGS[mode][method]) - # The diagnosis tests jumps; the play-through audio registry disables them. - if mode == 'audio' and method == 'outerhmm': - kwargs['s_j'] = 1e-100 - kwargs.update(config.get('kwargs', {})) - out.mkdir(parents=True, exist_ok=True) - with piece_time_budget(2400): - mm = Matchmaker(score_file=str(paths['xml_score']), performance_file=str(paths[f'{mode}_performance']), - method=method, input_type=mode, wait=False, - unfold_score=case['unfold_score'], tempo=case['tempo'], kwargs=kwargs) - check_follower(mm.score_follower) - if config.get('disable_global_skip'): - # S is the skip-from distribution used at every OPHMM update. - # Zero it without changing pitch observations or local transitions. - mm.score_follower.S[:] = 0. - for _ in mm.run(verbose=False): - pass - t, b = resolve_gt(paths['match'], mm.score_part.note_array(), - performance=str(paths[f'{mode}_performance']) if mode == 'midi' else None) - gt = np.column_stack((t, b)) - metrics = run_evaluation(mm, gt=gt, tolerances=TOLERANCES_IN_BEATS, domain='score', - debug=True, save_dir=out, run_name='0', make_plot=False, plot_dist_matrix=False) - wp = mm.score_follower.alignment_path.T - meter = score_meter_map(mm.score_part) - tracking = check_tracking(wp, gt, threshold=TRACKING_THRESHOLDS[mode], segment_duration=30., - beat_factors=musical_beat_factors(gt[:, 1], meter)) - (out/'meter_0.json').write_text(json.dumps(meter, indent=2)+'\n') - # Save directly too: the full path and all annotation points are required. - for name, array in [('wp_0', wp), ('gt_0', gt)]: - np.savetxt(out/(name+'.tsv'), array, delimiter='\t', fmt='%.12g', header='perf_sec\tscore_beat', comments='') - wp = wp[np.argsort(wp[:, 0], kind='stable')] - ix = np.searchsorted(wp[:, 0], gt[:, 0], side='right')-1 - valid = ix >= 0 - error = np.full(len(gt), np.nan) - error[valid] = np.abs(gt[valid, 1]-wp[ix[valid], 1]) - intervals = {} - if 'repeat_metadata' in case: - m = case['repeat_metadata'] - masks = {'before': gt[:, 0] < m['replay_start_sec'], - 'replay': (gt[:, 0] >= m['replay_start_sec']) & (gt[:, 0] < m['replay_end_sec']), - 'after': gt[:, 0] >= m['replay_end_sec']} - for name, mask in masks.items(): - intervals[name] = dict(onsets=int(mask.sum()), within_1_beat=float(np.mean(error[mask] <= 1)), - median_beat_error=float(np.nanmedian(error[mask]))) - return dict(case_id=case['id'], category=case['category'], method=method, input_type=mode, - unfold_score=case['unfold_score'], tempo=case['tempo'], kwargs=kwargs, - disable_global_skip=config.get('disable_global_skip', False), - tracked=bool(tracking['tracked']), max_deviation=float(tracking['max_deviation']), - tracking_criterion={k: tracking[k] for k in ('error_unit', 'threshold', 'window_duration')}, - mean_b=float(np.nanmean(error)), n_events=int(valid.sum()), n_annotated_onsets=len(gt), - metrics=metrics, intervals=intervals) - - -def run(args): - import contextlib - import traceback - from matchmaker_eval.run_submission import environment_info - from matchmaker_eval.fetch_data import frozen_source - pin = frozen_source('diagnostics') - base = f'https://raw.githubusercontent.com/{pin["repository"]}/{pin["commit"]}/diagnostics/' - args.cache.mkdir(parents=True, exist_ok=True) - mp = args.cache/'manifest.json' - if not mp.exists() or sha(mp) != pin['manifest_sha256']: - download(base+'manifest.json', mp) - if sha(mp) != pin['manifest_sha256']: - raise ValueError('Diagnostic manifest hash mismatch') - manifest = json.loads(mp.read_text()) - config = CONFIGS[args.config] - selected = select_cases(manifest, config, args.shard, args.shards) - args.output.mkdir(parents=True, exist_ok=True) - result = dict(config=args.config, definition=config, shard=args.shard, shards=args.shards, - data=pin, environment=environment_info(), github_run_id=os.environ.get('GITHUB_RUN_ID'), - github_run_attempt=os.environ.get('GITHUB_RUN_ATTEMPT'), expected=[c['id'] for _, c in selected], pieces=[], failures=[]) - for i, case in selected: - dest = args.output/f'{i:03d}' - dest.mkdir(exist_ok=True) - try: - keys = ['xml_score', 'match', config['input_type']+'_performance'] - paths = {k: materialize(case['paths'][k], manifest, args.cache, base) for k in keys} - with (dest/'run.log').open('w') as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): - record = run_case(case, config, paths, dest) - record['input_hashes'] = {k: manifest['files'][case['paths'][k]]['sha256'] for k in keys} - record['directory'] = dest.name - (dest/'result.json').write_text(json.dumps(record, indent=2, default=json_value)+'\n') - result['pieces'].append(record) - print(args.config, case['id'], record['tracked'], record['mean_b'], flush=True) - except Exception: - error = traceback.format_exc() - (dest/'error.txt').write_text(error) - result['failures'].append(dict(case_id=case['id'], error=error)) - print(error, flush=True) - (args.output/'metrics.json').write_text(json.dumps(result, indent=2, default=json_value)+'\n') - # Empty shards are valid when a suite contains fewer cases than shards. - (args.output/'metrics.json').write_text(json.dumps(result, indent=2, default=json_value)+'\n') - if result['failures']: - raise SystemExit(f'{len(result["failures"])} diagnostic cases failed') - - -def merge(args): - import shutil - from collections import defaultdict - import numpy as np - manifest = json.loads(args.manifest.read_text()) - records = [json.loads(p.read_text()) for p in args.source.glob('*/metrics.json')] - summary = {}; errors = [] - args.output.mkdir(parents=True, exist_ok=True) - for name, config in select_configs(args.only, args.input_type).items(): - rs = [r for r in records if r['config'] == name] - expected = {c['id'] for _, c in select_cases(manifest, config)} - found = [p['case_id'] for r in rs for p in r['pieces']] - if len(rs) != args.shards or {r['shard'] for r in rs} != set(range(args.shards)) or set(found) != expected or len(found) != len(expected) or any(r['failures'] for r in rs): - errors.append(name) - cells = defaultdict(list) - for r in rs: - for p in r['pieces']: - cells[p['category']].append(p) - summary[name] = {category: dict(total=len(ps), tracked=sum(p['tracked'] for p in ps), - mean_b_tracked=float(np.mean([p['mean_b'] for p in ps if p['tracked']])) if any(p['tracked'] for p in ps) else None, - mean_b_all=float(np.mean([p['mean_b'] for p in ps]))) for category, ps in cells.items()} - provenance = {(r['data']['commit'], r['environment']['benchmark_commit'], - json.dumps({k: v for k, v in r['environment'].items() - if k.startswith('matchmaker')}, sort_keys=True), - r['github_run_id']) for r in records} - if len(provenance) != 1: - errors.append('inconsistent provenance') - for src in args.source.iterdir(): - if src.is_dir(): - shutil.copytree(src, args.output/'raw'/src.name, dirs_exist_ok=True) - shutil.copyfile(args.manifest, args.output/'data_manifest.json') - (args.output/'summary.json').write_text(json.dumps(dict(complete=not errors, incomplete=errors, configurations=summary, - aggregation='For perturbations: arithmetic mean of per-condition MeanAE over tracked conditions; single cases also retain all-case error.', - provenance=[list(p) for p in provenance]), indent=2)+'\n') - if errors: - raise SystemExit('Incomplete diagnostic results: '+', '.join(errors)) - - -def main(): - p = argparse.ArgumentParser(description=__doc__) - sub = p.add_subparsers(dest='command', required=True) - r = sub.add_parser('run') - r.add_argument('--config', choices=CONFIGS, required=True) - r.add_argument('--shard', type=int, default=0) - r.add_argument('--shards', type=int, default=1) - r.add_argument('--output', type=Path, required=True) - r.add_argument('--cache', type=Path, default=Path('diagnostic-data')) - m = sub.add_parser('merge') - m.add_argument('--source', type=Path, required=True) - m.add_argument('--output', type=Path, required=True) - m.add_argument('--manifest', type=Path, required=True) - m.add_argument('--shards', type=int, required=True) - m.add_argument('--only', default='', help='Space-separated method names; empty selects all') - m.add_argument('--input-type', choices=['both', 'midi', 'audio'], default='both') - args = p.parse_args() - (run if args.command == 'run' else merge)(args) - -if __name__ == '__main__': - main() diff --git a/matchmaker_eval/download_data.py b/matchmaker_eval/download_data.py index 73ae5a6..d089ea6 100644 --- a/matchmaker_eval/download_data.py +++ b/matchmaker_eval/download_data.py @@ -19,7 +19,7 @@ import zipfile from urllib.request import urlretrieve -from matchmaker_eval.folds import DATA_ROOT +from matchmaker_eval.load_folds import DATA_ROOT # TODO: update URLs when data hosting is finalized DATASETS = { diff --git a/matchmaker_eval/estimate_perf_tempo.py b/matchmaker_eval/estimate_perf_tempo.py index 08246db..ad42ddd 100644 --- a/matchmaker_eval/estimate_perf_tempo.py +++ b/matchmaker_eval/estimate_perf_tempo.py @@ -15,7 +15,7 @@ import partitura as pt from partitura.score import merge_parts -from matchmaker_eval.folds import DATA_ROOT, nested_dataset_root +from matchmaker_eval.load_folds import DATA_ROOT, nested_dataset_root WORKING_DIR = Path(__file__).parent.parent #: The `example` dataset is the one piece committed to this repository under diff --git a/matchmaker_eval/eval_symbolic.py b/matchmaker_eval/eval_symbolic.py index 0d95cd8..b057cd3 100644 --- a/matchmaker_eval/eval_symbolic.py +++ b/matchmaker_eval/eval_symbolic.py @@ -84,7 +84,7 @@ warnings.filterwarnings("ignore") -from matchmaker_eval.folds import DATA_ROOT, nested_dataset_root +from matchmaker_eval.load_folds import DATA_ROOT, nested_dataset_root DATASET_DIR = { "validation": DATA_ROOT, diff --git a/matchmaker_eval/provenance.py b/matchmaker_eval/evaluation_key.py similarity index 64% rename from matchmaker_eval/provenance.py rename to matchmaker_eval/evaluation_key.py index 4f07115..57f8a7b 100644 --- a/matchmaker_eval/provenance.py +++ b/matchmaker_eval/evaluation_key.py @@ -1,29 +1,21 @@ -"""The evaluation key: one short hash naming the conditions a run was scored under. +"""Evaluation key: a short hash of the conditions a run was scored under. -Two leaderboard rows are only comparable when everything that decides their -numbers — apart from the follower itself — was the same. That is: +The leaderboard ranks two rows together only when everything that decides their +numbers, apart from the follower itself, is the same: fold_sha256 the fold CSV: which pieces, their paths, estimated_bpm - data_sha256 the bytes of every file a piece was scored with - (score, the performance that was streamed, the match / - annotation file), over the whole fold - scoring_sha256 the benchmark's own scoring code: the evaluation and - tracking modules, and the parts of run_submission.py - that decide ground truth and the tracked verdict - matchmaker_scoring_sha256 - Matchmaker's shared score loading and evaluation: - ground truth, beat errors, tracking windows and SPARC - partitura how every score and match file is parsed - -``evaluation_key()`` folds these into ``ek2-<12 hex>``. Same key, same -conditions; a different key means at least one of them changed. The ``ek2`` -prefix is the scheme: if what goes into the key ever changes, the prefix does -too, so a key never silently changes meaning. - -The full ``matchmaker_sha256`` is also recorded, and must agree across shards -of one method's run. It is provenance, not a comparison condition: adding a -follower must not exclude existing methods from the leaderboard. Legacy ek1 -records retain their original meaning and are never relabelled as ek2. + data_sha256 the score, performance and ground-truth files of every piece + scoring_sha256 the benchmark's scoring code: the evaluation and tracking + modules, and the parts of run_submission.py that decide + ground truth and the tracked verdict + matchmaker_sha256 the installed matchmaker sources + partitura the version that parses every score and match file + +``evaluation_key()`` hashes these into ``ek1-<12 hex>``. The ``ek1`` prefix names +which components are included, and changes whenever that set changes. + +Components hash file contents rather than commit ids, so an unrelated commit +(a README edit, a new corpus in the data repository) does not change the key. """ import hashlib @@ -33,10 +25,10 @@ from pathlib import Path from typing import Iterable, Optional -from matchmaker_eval.folds import REPO_ROOT +from matchmaker_eval.load_folds import REPO_ROOT #: Bumped whenever the set of components, or how one is computed, changes. -SCHEME = "ek2" +SCHEME = "ek1" #: Benchmark modules whose every line can move a score. Hashed whole. SCORING_MODULES = ( @@ -50,40 +42,20 @@ #: same source, and the .pyx they are built from is hashed instead. MATCHMAKER_SOURCE_SUFFIXES = (".py", ".pyx", ".pxd", ".yaml", ".yml", ".json") -# Shared score loading and evaluation live here. Method implementations, -# registration and defaults remain in the full-package provenance hash. -MATCHMAKER_SCORING_MODULES = ("matchmaker.py", "utils/eval.py") - #: The fields of the key, in the order they are documented. COMPONENTS = ( "scheme", "fold_sha256", "data_sha256", "scoring_sha256", - "matchmaker_scoring_sha256", + "matchmaker_sha256", "partitura", ) #: The components every shard of one run must share. data_sha256 is the one #: left out: a shard only hashes its own pieces, and merge_shards.py combines #: the per-piece hashes into the fold's. -SHARED_COMPONENTS = tuple(c for c in COMPONENTS if c != "data_sha256") + ( - "matchmaker_sha256", -) - - -def comparison_components(components: dict) -> dict: - """Comparison conditions only, interpreted under the recorded scheme.""" - if components.get("scheme") == "ek1": - names = tuple( - "matchmaker_sha256" if c == "matchmaker_scoring_sha256" else c - for c in COMPONENTS - ) - elif components.get("scheme") == SCHEME: - names = COMPONENTS - else: - return {} - return {name: components.get(name) for name in names} +SHARED_COMPONENTS = tuple(c for c in COMPONENTS if c != "data_sha256") def sha256_bytes(data: bytes) -> str: @@ -178,17 +150,6 @@ def matchmaker_sha256() -> str: return _digest_lines(lines) -def matchmaker_scoring_sha256() -> str: - """Hash shared score loading and evaluation independently of followers.""" - import matchmaker - - root = Path(matchmaker.__file__).resolve().parent - return _digest_lines( - f"{module}\t{file_sha256(root / module)}" - for module in MATCHMAKER_SCORING_MODULES - ) - - def package_version(name: str) -> str: try: return version(name) @@ -203,22 +164,20 @@ def code_components(fold_sha256: str, decisive: dict) -> dict: "fold_sha256": fold_sha256, "scoring_sha256": scoring_sha256(decisive), "matchmaker_sha256": matchmaker_sha256(), - "matchmaker_scoring_sha256": matchmaker_scoring_sha256(), "partitura": package_version("partitura"), } def evaluation_key(components: dict) -> Optional[str]: - """A scheme-qualified key for complete comparison conditions, else None.""" - conditions = comparison_components(components) - if not conditions or not all(conditions.values()): + """``ek1-<12 hex>`` for a complete set of components, else None.""" + if any(not components.get(name) for name in COMPONENTS): return None - canonical = json.dumps(conditions, sort_keys=True) + canonical = json.dumps({name: components[name] for name in COMPONENTS}, sort_keys=True) return f"{components['scheme']}-{sha256_bytes(canonical.encode())[:12]}" def evaluation_record(code: dict, pieces: list) -> dict: """The ``evaluation`` block a metrics.json carries: the key and what made it.""" components = {**code, "data_sha256": data_sha256(pieces)} - components = {name: components.get(name) for name in (*SHARED_COMPONENTS, "data_sha256")} + components = {name: components.get(name) for name in COMPONENTS} return {"key": evaluation_key(components), "components": components} diff --git a/matchmaker_eval/export_details.py b/matchmaker_eval/export_details.py index c1f9a57..98b455c 100644 --- a/matchmaker_eval/export_details.py +++ b/matchmaker_eval/export_details.py @@ -38,7 +38,7 @@ import numpy as np from matchmaker.utils.eval import transfer_positions -from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR +from matchmaker_eval.load_folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR from matchmaker_eval.leaderboard import ACCURACY_COLUMNS, without_nan SUBMISSION_RESULTS = RESULTS_DIR / "submissions" @@ -60,8 +60,8 @@ #: measurement of the follower, so it is excluded here too — otherwise it lands #: in the site's metric table as a boolean among the error statistics. The run's #: count of it is published once, alongside n_tracked. -#: ``data_sha256`` names the bytes a piece was scored with (see provenance.py): -#: provenance, not a measurement. It is published beside the identity fields. +#: ``data_sha256`` names the bytes a piece was scored with (see evaluation_key.py). +#: It records an input, not a measurement, so it sits beside the identity fields. PIECE_IDENTITY = ( "tracking_criterion", "index", diff --git a/matchmaker_eval/fetch_data.py b/matchmaker_eval/fetch_data.py index dcd7e68..6928e40 100644 --- a/matchmaker_eval/fetch_data.py +++ b/matchmaker_eval/fetch_data.py @@ -36,7 +36,7 @@ import yaml -from matchmaker_eval.folds import DATA_ROOT, REPO_ROOT, load_fold, shard_of +from matchmaker_eval.load_folds import DATA_ROOT, REPO_ROOT, load_fold, shard_of CONFIG_PATH = REPO_ROOT / "data" / "data_sources.yaml" CHECKSUM_DIR = REPO_ROOT / "data" / "checksums" @@ -353,7 +353,7 @@ def metadata_path(dataset: str, branch: str = "main") -> Path: caching both to one path would let whichever was fetched first silently stand in for the other. """ - from matchmaker_eval.folds import dataset_root + from matchmaker_eval.load_folds import dataset_root root = dataset_root(dataset) if branch in ("main", "master"): @@ -380,7 +380,7 @@ def fetch_root_metadata(fold: Optional[str], force: bool = False) -> Optional[Pa reasonable shapes; this looks for the root form and returns None when the branch does not use it, so the caller can fall back to the per-dataset one. """ - from matchmaker_eval.folds import DATA_ROOT + from matchmaker_eval.load_folds import DATA_ROOT config = load_config() if not config.get("enabled"): diff --git a/matchmaker_eval/leaderboard.py b/matchmaker_eval/leaderboard.py index f9ffdd3..47c39ca 100644 --- a/matchmaker_eval/leaderboard.py +++ b/matchmaker_eval/leaderboard.py @@ -6,7 +6,7 @@ Reads every ``results/submissions/*/metrics.json`` produced by ``run_submission.py``, keeps the runs made on the **eval** fold, and writes - results/leaderboard.json full records, with per-fold provenance + results/leaderboard.json full records, with each fold's evaluation key results/leaderboard.csv the headline columns, for papers results/leaderboard-.json the same entries ranked on one dataset results/leaderboard-.csv @@ -46,8 +46,8 @@ from matchmaker.utils.eval import TOLERANCES_IN_BEATS -from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR -from matchmaker_eval.provenance import comparison_components +from matchmaker_eval.load_folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR +from matchmaker_eval.evaluation_key import SHARED_COMPONENTS from matchmaker_eval.retract import read_retractions from matchmaker_eval.submission import read_descriptions @@ -76,7 +76,7 @@ def dataset_paths(dataset: str) -> tuple: "skewness", "kurtosis", "smoothness", "median_b_all", "rtf", "feature_latency_ms", "inference_latency_ms", "n_pieces", "n_tracked", "estimated_bpm", "evaluated", - # The conditions the row was scored under (see provenance.py). Cite it + # The conditions the row was scored under (see evaluation_key.py). Cite it # with any number taken from this file. "evaluation_key", ] @@ -293,7 +293,7 @@ def split_by_conditions(rows: list) -> tuple: is the one that reflects them. MIDI and audio stream different files, so their keys always differ in ``data_sha256``: each input type has its own current key, the newest among its rows that share the newest run's code - components (fold, scoring, shared score loading, partitura). Every ranked row, + components (fold, scoring, matchmaker, partitura). Every ranked row, whichever its input type, therefore shares those. A row with any other key — or none, from before keys existed — was scored @@ -311,11 +311,8 @@ def evaluated(row): return row.get("evaluated") or "" def code(row): - return { - name: value - for name, value in comparison_components(row.get("evaluation") or {}).items() - if name != "data_sha256" - } + theirs = row.get("evaluation") or {} + return {name: theirs.get(name) for name in SHARED_COMPONENTS} newest_code = code(max(rows, key=evaluated)) conditions = {} @@ -328,7 +325,7 @@ def code(row): latest = max(same_code, key=evaluated) conditions[input_type] = { "key": latest.get("evaluation_key"), - "components": comparison_components(latest.get("evaluation") or {}), + "components": latest.get("evaluation") or {}, } current, earlier = [], [] @@ -338,11 +335,11 @@ def code(row): current.append(row) continue earlier.append(row) - theirs = comparison_components(row.get("evaluation") or {}) + theirs = row.get("evaluation") or {} # Without a current key of its own input type, only the code components # can be compared: another input type's data hash says nothing here. - ours = comparison_components(reference["components"]) if reference else newest_code - names = set(ours) | set(theirs) if reference else set(newest_code) | set(code(row)) + ours = reference["components"] if reference else newest_code + names = set(ours) | set(theirs) if reference else SHARED_COMPONENTS row["evaluation_changed"] = sorted( name for name in names if ours.get(name) != theirs.get(name) ) if row.get("evaluation_key") else [] diff --git a/matchmaker_eval/folds.py b/matchmaker_eval/load_folds.py similarity index 100% rename from matchmaker_eval/folds.py rename to matchmaker_eval/load_folds.py diff --git a/matchmaker_eval/make_folds.py b/matchmaker_eval/make_folds.py index ad8e090..bd82728 100644 --- a/matchmaker_eval/make_folds.py +++ b/matchmaker_eval/make_folds.py @@ -45,7 +45,7 @@ import csv from collections import Counter, defaultdict -from matchmaker_eval.folds import FOLD_DIR, REPO_ROOT, Piece, load_fold, write_fold +from matchmaker_eval.load_folds import FOLD_DIR, REPO_ROOT, Piece, load_fold, write_fold METADATA_DIR = REPO_ROOT / "data" diff --git a/matchmaker_eval/merge_references.py b/matchmaker_eval/merge_references.py index 2481f2f..62cc41a 100644 --- a/matchmaker_eval/merge_references.py +++ b/matchmaker_eval/merge_references.py @@ -29,7 +29,7 @@ import shutil from collections import defaultdict -from matchmaker_eval.folds import REPO_ROOT +from matchmaker_eval.load_folds import REPO_ROOT from merge_shards import MergeError, merge #: refshard--- diff --git a/matchmaker_eval/merge_shards.py b/matchmaker_eval/merge_shards.py index 75e502b..7558b56 100644 --- a/matchmaker_eval/merge_shards.py +++ b/matchmaker_eval/merge_shards.py @@ -27,8 +27,8 @@ from utils import dataset_summaries, pooled_summaries -from matchmaker_eval.folds import REPO_ROOT -from matchmaker_eval.provenance import SHARED_COMPONENTS, evaluation_record +from matchmaker_eval.load_folds import REPO_ROOT +from matchmaker_eval.evaluation_key import SHARED_COMPONENTS, evaluation_record class MergeError(Exception): diff --git a/matchmaker_eval/preprocess_urmp.py b/matchmaker_eval/preprocess_urmp.py index 8bb3100..c1a78cd 100644 --- a/matchmaker_eval/preprocess_urmp.py +++ b/matchmaker_eval/preprocess_urmp.py @@ -27,7 +27,7 @@ import numpy as np import pandas as pd import soundfile as sf -from matchmaker_eval.folds import DATA_ROOT +from matchmaker_eval.load_folds import DATA_ROOT from matchmaker import Matchmaker WORKING_DIR = Path(__file__).parent.parent diff --git a/matchmaker_eval/preprocess_winterreise.py b/matchmaker_eval/preprocess_winterreise.py index 848a485..14e7a73 100644 --- a/matchmaker_eval/preprocess_winterreise.py +++ b/matchmaker_eval/preprocess_winterreise.py @@ -27,7 +27,7 @@ import numpy as np import pandas as pd import partitura as pt -from matchmaker_eval.folds import DATA_ROOT +from matchmaker_eval.load_folds import DATA_ROOT from matchmaker_eval.utils import source_annotation diff --git a/matchmaker_eval/release_results.py b/matchmaker_eval/release_results.py index b6a8fdb..bbb01c1 100644 --- a/matchmaker_eval/release_results.py +++ b/matchmaker_eval/release_results.py @@ -1,12 +1,10 @@ -"""Preserve completed CI runs in a release, or fetch a published snapshot. +"""Publish completed CI runs as a release, or fetch a published snapshot. -Called by pages.yml; requires the GitHub CLI and GH_TOKEN. Evaluation is never -run here. MATCHMAKER_RESULTS_DIR keeps downloaded/generated files out of the -source checkout. Raw merged artifacts are attached without modifying them. +Called by pages.yml with the GitHub CLI and GH_TOKEN; it never runs a follower. +Results are written to MATCHMAKER_RESULTS_DIR, outside the source checkout. """ import argparse -import hashlib import json import os from pathlib import Path @@ -18,7 +16,8 @@ import zipfile sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -from matchmaker_eval.folds import REPO_ROOT, RESULTS_DIR +from matchmaker_eval.evaluation_key import file_sha256 +from matchmaker_eval.load_folds import REPO_ROOT, RESULTS_DIR SNAPSHOT = "benchmark-snapshot.zip" @@ -43,11 +42,6 @@ def latest(records): return max(candidates, key=lambda r: r["published_at"], default=None) -def digest(path): - with path.open("rb") as stream: - return hashlib.file_digest(stream, "sha256").hexdigest() - - def extract(archive, destination): """Reject paths outside the destination before extracting any member.""" destination = destination.resolve() @@ -68,7 +62,7 @@ def fetch(repo, release, destination): "--pattern", SNAPSHOT, "--pattern", "SHA256SUMS", "--dir", str(work)) hashes = dict(line.split(maxsplit=1)[::-1] for line in (work / "SHA256SUMS").read_text().splitlines()) - if digest(work / SNAPSHOT) != hashes.get(SNAPSHOT): + if file_sha256(work / SNAPSHOT) != hashes.get(SNAPSHOT): raise ValueError("Published snapshot checksum does not match") unpacked = work / "unpacked" extract(work / SNAPSHOT, unpacked) @@ -145,7 +139,7 @@ def publish(repo, tag, run_ids, records, destination): entry_sources = json.loads((destination / "release.json").read_text()).get("entry_sources", {}) else: destination.mkdir(parents=True, exist_ok=False) - # Retain existing public archive URLs during the first release migration. + # With no earlier release, start from the archive tracked in the repository. old_archive = REPO_ROOT / "results" / "archive" if old_archive.exists(): shutil.copytree(old_archive, destination / "archive") @@ -178,13 +172,13 @@ def publish(repo, tag, run_ids, records, destination): for entry in stage_piano(unpacked, destination, run["head_sha"]): entry_sources[entry] = run["id"] saved.append({"id": artifact["id"], "asset": output.name, - "sha256": digest(output)}) + "sha256": file_sha256(output)}) sources.append({"id": run["id"], "url": run["html_url"], "benchmark_commit": run["head_sha"], "branch": run["head_branch"], "attempt": run["run_attempt"], "artifacts": saved}) if not list((destination / "submissions").glob("*/metrics.json")): - raise ValueError("The first release must include a complete piano evaluation") + raise ValueError("A release must include a complete piano evaluation") env = {**os.environ, "MATCHMAKER_RESULTS_DIR": str(destination)} for script in ("export_details.py", "leaderboard.py"): subprocess.run([sys.executable, str(REPO_ROOT / "matchmaker_eval" / script)], @@ -201,19 +195,13 @@ def publish(repo, tag, run_ids, records, destination): str(work / "site")], env=env, check=True) snapshot(destination, assets / SNAPSHOT) checksums = assets / "SHA256SUMS" - checksums.write_text("".join(f"{digest(p)} {p.name}\n" for p in sorted(assets.iterdir()))) - if any(p.stat().st_size >= 2 * 1024**3 for p in assets.iterdir()): - raise ValueError("A result asset exceeds GitHub's 2 GiB limit") + checksums.write_text("".join(f"{file_sha256(p)} {p.name}\n" for p in sorted(assets.iterdir()))) notes = work / "release.md" notes.write_text( f"Benchmark results published from `{commit}`.\n\n" + "\n".join(f"- [Run {s['id']}]({s['url']}), evaluated at `{s['benchmark_commit']}`" for s in sources) - + "\n\nThe run ZIPs contain the original merged outputs, including full paths, " - "meter maps and environment metadata. `benchmark-snapshot.zip` contains " - "the leaderboard, per-piece views, metrics and `release.json`, which identifies " - "the selected run for each entry. Later listed runs replace earlier entries. " - "`SHA256SUMS` covers every attached ZIP.\n" + + "\n" ) # Upload everything as a draft; expose it only after every upload succeeds. gh("release", "create", tag, *(str(p) for p in sorted(assets.iterdir())), diff --git a/matchmaker_eval/retract.py b/matchmaker_eval/retract.py index 06f949d..9a66541 100644 --- a/matchmaker_eval/retract.py +++ b/matchmaker_eval/retract.py @@ -42,7 +42,7 @@ import shutil from datetime import datetime, timezone -from matchmaker_eval.folds import REPO_ROOT, RESULTS_DIR +from matchmaker_eval.load_folds import REPO_ROOT, RESULTS_DIR SUBMISSION_RESULTS = RESULTS_DIR / "submissions" DETAILS_DIR = RESULTS_DIR / "details" diff --git a/matchmaker_eval/run_amt.py b/matchmaker_eval/run_amt.py index 074607f..532a084 100644 --- a/matchmaker_eval/run_amt.py +++ b/matchmaker_eval/run_amt.py @@ -1,71 +1,103 @@ -"""Replay frozen online-AMT MIDI through symbolic followers, using audio GT. +"""Replay frozen online-AMT MIDI through symbolic followers, scored against audio GT. -The transcription model is not executed. Runtime therefore covers the follower -only. MIDI event timestamps are preserved; there is no latency compensation. +The transcription model is not run, so timings cover the follower only. MIDI +event times are used as they are, without latency compensation. """ -from pathlib import Path + import argparse import hashlib import json import sys -ROOT=Path(__file__).resolve().parents[1] -for p in (ROOT,ROOT/'matchmaker_eval'): - sys.path.insert(0,str(p)) -import matchmaker_eval.run_submission as rs -from matchmaker_eval.diagnostics import download,sha -from matchmaker_eval.submission import DECLARATION_KEY -from matchmaker import Matchmaker +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +for p in (ROOT, ROOT / "matchmaker_eval"): + sys.path.insert(0, str(p)) + +import matchmaker_eval.run_submission as rs # noqa: E402 +from matchmaker import Matchmaker # noqa: E402 +from matchmaker_eval.evaluation_key import file_sha256 # noqa: E402 +from matchmaker_eval.run_diagnostics import download # noqa: E402 +from matchmaker_eval.submission import DECLARATION_KEY # noqa: E402 + +N_PIECES = 146 + + +def fetch_verified(url, path, sha256): + if not path.exists() or file_sha256(path) != sha256: + download(url, path) + if file_sha256(path) != sha256: + raise ValueError(f"Hash mismatch: {path.name}") + return path -def load_outputs(cache): +def load_cases(cache): + """The pinned AMT data, its base URL, and one case per piano piece.""" from matchmaker_eval.fetch_data import frozen_source - pin=frozen_source('amt') - base=f'https://raw.githubusercontent.com/{pin["repository"]}/{pin["commit"]}/amt/' - cache.mkdir(parents=True,exist_ok=True) - p=cache/'manifest.json' - if not p.exists() or sha(p)!=pin['manifest_sha256']:download(base+'manifest.json',p) - if sha(p)!=pin['manifest_sha256']:raise ValueError('AMT manifest hash mismatch') - manifest=json.loads(p.read_text());cases=manifest['cases'] - if len(cases)!=146 or len({c['piece_id'] for c in cases})!=146:raise ValueError('Invalid AMT test census') - return pin,base,{c['piece_id']:c for c in cases} + + pin = frozen_source("amt") + base_url = f"https://raw.githubusercontent.com/{pin['repository']}/{pin['commit']}/amt/" + cache.mkdir(parents=True, exist_ok=True) + manifest = fetch_verified(base_url + "manifest.json", cache / "manifest.json", + pin["manifest_sha256"]) + cases = json.loads(manifest.read_text())["cases"] + if len(cases) != N_PIECES or len({c["piece_id"] for c in cases}) != N_PIECES: + raise ValueError("The AMT manifest does not cover the piano fold") + return pin, base_url, {c["piece_id"]: c for c in cases} def main(): - p=argparse.ArgumentParser(description=__doc__) - p.add_argument('--method',choices=['arzt','pthmm','SLT_OLTW'],default='arzt') - p.add_argument('--shard',type=int,default=0) - p.add_argument('--num-shards',type=int,default=1) - p.add_argument('--output',type=Path,required=True) - p.add_argument('--cache',type=Path,default=Path('amt-data')) - a=p.parse_args();pin,base,cases=load_outputs(a.cache) - original=rs.run_piece - def run_piece(method,piece,input_type,index,run_dir,save_plots,estimated_bpm=False): - case=cases[piece.piece_id];midi=a.cache/case['path'] - if not midi.exists() or sha(midi)!=case['sha256']:download(base+case['path'],midi) - if sha(midi)!=case['sha256']:raise ValueError('AMT MIDI hash mismatch') - def build(**kwargs): - kwargs.update(input_type='midi',performance_file=str(midi),method=a.method) + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--method", choices=["arzt", "pthmm", "SLT_OLTW"], default="arzt") + parser.add_argument("--shard", type=int, default=0) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--cache", type=Path, default=Path("amt-data")) + args = parser.parse_args() + pin, base_url, cases = load_cases(args.cache) + score_piece = rs.run_piece + + def run_piece(method, piece, input_type, index, run_dir, save_plots, estimated_bpm=False): + case = cases[piece.piece_id] + midi = fetch_verified(base_url + case["path"], args.cache / case["path"], case["sha256"]) + + # Stream the transcribed MIDI into the symbolic follower... + def matchmaker_on_transcription(**kwargs): + kwargs.update(input_type="midi", performance_file=str(midi), method=args.method) return Matchmaker(**kwargs) - previous=rs.Matchmaker;rs.Matchmaker=build + + original = rs.Matchmaker + rs.Matchmaker = matchmaker_on_transcription try: - # Keep input_type=audio here: use the original recording's GT and - # audio TR threshold, not transcribed-note times or MIDI tolerance. - result=original(method,piece,'audio',index,run_dir,save_plots,False) - finally:rs.Matchmaker=previous - result.update(amt_data_commit=pin['commit'],amt_output_sha256=case['sha256'], - amt_front_end_executed=False,timing_scope='symbolic follower only', - symbolic_method=a.method) - (run_dir/f'{index}.json').write_text(json.dumps(result,indent=2,default=float)+'\n') + # ...but score it as audio: the recording's ground truth and audio TR threshold. + result = score_piece(method, piece, "audio", index, run_dir, save_plots, False) + finally: + rs.Matchmaker = original + + result.update(amt_data_commit=pin["commit"], amt_output_sha256=case["sha256"], + amt_front_end_executed=False, timing_scope="symbolic follower only", + symbolic_method=args.method) + (run_dir / f"{index}.json").write_text(json.dumps(result, indent=2, default=float) + "\n") return result - rs.run_piece=run_piece - rs.builtin_metadata=lambda method,input_type:dict(name='AMT + '+a.method,input_type='audio', - authors=['Matchmaker benchmark'],description='Frozen online AMT output replayed through a symbolic follower.', - **{rs.ESTIMATED_BPM_KEY:False,DECLARATION_KEY:True},kind='reference') - parts=rs.scoring_parts - rs.scoring_parts=lambda:{**parts(),'amt_inputs':pin,'amt_symbolic_method':a.method, - 'amt_runner_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest()} - result=rs.evaluate_submission(builtin=a.method,input_type='audio',fold='eval', - shard=a.shard,num_shards=a.num_shards,run_dir=a.output) - if result['n_failed']:raise SystemExit('Incomplete AMT replay') - -if __name__=='__main__':main() + + rs.run_piece = run_piece + rs.builtin_metadata = lambda method, input_type: { + "name": f"AMT + {args.method}", "input_type": "audio", "kind": "reference", + "authors": ["Matchmaker benchmark"], + "description": "Frozen online AMT output replayed through a symbolic follower.", + rs.ESTIMATED_BPM_KEY: False, DECLARATION_KEY: True, + } + scoring_parts = rs.scoring_parts + rs.scoring_parts = lambda: { + **scoring_parts(), "amt_inputs": pin, "amt_symbolic_method": args.method, + "amt_runner_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + } + result = rs.evaluate_submission(builtin=args.method, input_type="audio", fold="eval", + shard=args.shard, num_shards=args.num_shards, + run_dir=args.output) + if result["n_failed"]: + raise SystemExit("Incomplete AMT replay") + + +if __name__ == "__main__": + main() diff --git a/matchmaker_eval/run_diagnostics.py b/matchmaker_eval/run_diagnostics.py new file mode 100644 index 0000000..7cb5da7 --- /dev/null +++ b/matchmaker_eval/run_diagnostics.py @@ -0,0 +1,319 @@ +"""Run and merge the manuscript diagnostic suites with the benchmark evaluator. + +Inputs come from a pinned manifest in the data repository and are checked +against their hashes. A merge fails when any selected case or shard is missing. +""" + +import argparse +import contextlib +import json +import os +import shutil +import sys +import time +import traceback +import urllib.request +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +for p in (ROOT, ROOT / "matchmaker_eval"): + sys.path.insert(0, str(p)) + +from matchmaker_eval.evaluation_key import file_sha256 # noqa: E402 + +PERTURBATION_METHODS = { + "audio": ["dixon", "arzt", "outerhmm", "skf"], + "midi": ["pthmm", "hmm", "outerhmm", "dixon", "arzt", "SLT_OLTW", "dannenberg"], +} +CONFIGS = { + **{f"perturbations-{t}-{m}": {"suite": "perturbations", "input_type": t, "method": m} + for t, methods in PERTURBATION_METHODS.items() for m in methods}, + **{f"repeat_examples-audio-{m}": {"suite": "repeat_examples", "input_type": "audio", "method": m} + for m in ["arzt", "arzt_multi_fold", "outerhmm"]}, + **{f"folded_batik-audio-{m}": {"suite": "folded_batik", "input_type": "audio", "method": m, + "kwargs": {"s_j": 1e-5} if m == "outerhmm" else {}} + for m in ["dixon", "arzt", "skf", "outerhmm", "arzt_multi_fold"]}, + **{f"global_skip-midi-{s}": {"suite": "global_skip", "input_type": "midi", "method": "outerhmm", + "disable_global_skip": s == "off"} + for s in ["on", "off"]}, +} + + +def select_configs(only="", input_type="both"): + """The configurations for the given methods (all if empty) and input type.""" + methods = set(only.split()) + selected = {name: c for name, c in CONFIGS.items() + if input_type in ("both", c["input_type"]) and (not methods or c["method"] in methods)} + missing = methods - {c["method"] for c in selected.values()} + if not selected or missing: + raise ValueError(f"No diagnostic configuration for {input_type}: {sorted(missing or methods)}") + return selected + + +def select_cases(manifest, config, shard=0, shards=1): + """The (index, case) pairs of one shard, round-robin over the suite's cases.""" + if not 1 <= shards <= 32 or not 0 <= shard < shards: + raise ValueError("Invalid shard selection") + cases = [c for c in manifest["cases"] + if c["suite"] == config["suite"] and c["input_type"] == config["input_type"]] + ids = [c["id"] for c in cases] + if not ids or len(ids) != len(set(ids)): + raise ValueError("Empty or duplicated diagnostic cases") + return [(i, c) for i, c in enumerate(cases) if i % shards == shard] + + +def download(url, path, attempts=4): + path.parent.mkdir(parents=True, exist_ok=True) + for attempt in range(attempts): + try: + with urllib.request.urlopen(url, timeout=120) as response, path.open("wb") as out: + shutil.copyfileobj(response, out) + return + except Exception: + if attempt == attempts - 1: + raise + time.sleep(2 ** attempt) + + +def fetch_input(name, manifest, cache, base_url): + """Download one input into ``cache``, joining it from parts if stored that way.""" + entry = manifest["files"][name] + path = cache / name + if path.exists() and file_sha256(path) == entry["sha256"]: + return path + path.parent.mkdir(parents=True, exist_ok=True) + if entry.get("parts"): + with path.open("wb") as out: + for part in entry["parts"]: + part_path = cache / part["path"] + if not part_path.exists() or file_sha256(part_path) != part["sha256"]: + download(base_url + part["path"], part_path) + if file_sha256(part_path) != part["sha256"]: + raise ValueError(f"Corrupt data chunk: {part['path']}") + out.write(part_path.read_bytes()) + else: + download(base_url + name, path) + if file_sha256(path) != entry["sha256"]: + raise ValueError(f"Input hash mismatch: {name}") + return path + + +def load_manifest(cache): + """The pinned manifest, the pin itself, and the URL its files are served from.""" + from matchmaker_eval.fetch_data import frozen_source + + pin = frozen_source("diagnostics") + base_url = f"https://raw.githubusercontent.com/{pin['repository']}/{pin['commit']}/diagnostics/" + path = cache / "manifest.json" + if not path.exists() or file_sha256(path) != pin["manifest_sha256"]: + download(base_url + "manifest.json", path) + if file_sha256(path) != pin["manifest_sha256"]: + raise ValueError("Diagnostic manifest hash mismatch") + return pin, base_url, json.loads(path.read_text()) + + +def run_case(case, config, paths, out): + import numpy as np + from matchmaker import Matchmaker + from matchmaker.matchmaker import DEFAULT_KWARGS + from matchmaker.utils.eval import resolve_gt + + from matchmaker_eval.eval import run_evaluation + from matchmaker_eval.run_submission import check_follower, piece_time_budget + from matchmaker_eval.utils import TOLERANCES_IN_BEATS + from matchmaker_eval.verify_tracking import ( + TRACKING_THRESHOLDS, check_tracking, musical_beat_factors, score_meter_map, + ) + + input_type, method = config["input_type"], config["method"] + performance = paths[f"{input_type}_performance"] + kwargs = dict(DEFAULT_KWARGS[input_type][method]) + if input_type == "audio" and method == "outerhmm": + kwargs["s_j"] = 1e-100 # the diagnostics test jumps, which the default disables + kwargs.update(config.get("kwargs", {})) + out.mkdir(parents=True, exist_ok=True) + + with piece_time_budget(2400): + mm = Matchmaker(score_file=str(paths["xml_score"]), performance_file=str(performance), + method=method, input_type=input_type, wait=False, + unfold_score=case["unfold_score"], tempo=case["tempo"], kwargs=kwargs) + check_follower(mm.score_follower) + if config.get("disable_global_skip"): + mm.score_follower.S[:] = 0.0 # OPHMM's skip-from distribution + for _ in mm.run(verbose=False): + pass + times, beats = resolve_gt(paths["match"], mm.score_part.note_array(), + performance=str(performance) if input_type == "midi" else None) + gt = np.column_stack((times, beats)) + metrics = run_evaluation(mm, gt=gt, tolerances=TOLERANCES_IN_BEATS, domain="score", + debug=True, save_dir=out, run_name="0", + make_plot=False, plot_dist_matrix=False) + wp = mm.score_follower.alignment_path.T + meter = score_meter_map(mm.score_part) + tracking = check_tracking(wp, gt, threshold=TRACKING_THRESHOLDS[input_type], + segment_duration=30.0, + beat_factors=musical_beat_factors(gt[:, 1], meter)) + + (out / "meter_0.json").write_text(json.dumps(meter, indent=2) + "\n") + for name, array in [("wp_0", wp), ("gt_0", gt)]: + np.savetxt(out / f"{name}.tsv", array, delimiter="\t", fmt="%.12g", + header="perf_sec\tscore_beat", comments="") + + # Beat error at each annotated onset; NaN before the follower's first estimate. + wp = wp[np.argsort(wp[:, 0], kind="stable")] + index = np.searchsorted(wp[:, 0], gt[:, 0], side="right") - 1 + valid = index >= 0 + errors = np.full(len(gt), np.nan) + errors[valid] = np.abs(gt[valid, 1] - wp[index[valid], 1]) + + intervals = {} + if "repeat_metadata" in case: + start = case["repeat_metadata"]["replay_start_sec"] + end = case["repeat_metadata"]["replay_end_sec"] + t = gt[:, 0] + for name, mask in [("before", t < start), ("replay", (t >= start) & (t < end)), + ("after", t >= end)]: + intervals[name] = {"onsets": int(mask.sum()), + "within_1_beat": float(np.mean(errors[mask] <= 1)), + "median_beat_error": float(np.nanmedian(errors[mask]))} + + return { + "case_id": case["id"], "category": case["category"], + "method": method, "input_type": input_type, "kwargs": kwargs, + "unfold_score": case["unfold_score"], "tempo": case["tempo"], + "disable_global_skip": config.get("disable_global_skip", False), + "tracked": bool(tracking["tracked"]), "max_deviation": float(tracking["max_deviation"]), + "tracking_criterion": {k: tracking[k] for k in ("error_unit", "threshold", "window_duration")}, + "mean_b": float(np.nanmean(errors)), "n_events": int(valid.sum()), + "n_annotated_onsets": len(gt), "metrics": metrics, "intervals": intervals, + } + + +def write_json(path, value): + # Model classes in the follower settings are written by name. + def default(v): + return f"{v.__module__}.{v.__qualname__}" if isinstance(v, type) else float(v) + + path.write_text(json.dumps(value, indent=2, default=default) + "\n") + + +def run(args): + from matchmaker_eval.run_submission import environment_info + + args.cache.mkdir(parents=True, exist_ok=True) + pin, base_url, manifest = load_manifest(args.cache) + config = CONFIGS[args.config] + selected = select_cases(manifest, config, args.shard, args.shards) + inputs = ["xml_score", "match", f"{config['input_type']}_performance"] + result = { + "config": args.config, "definition": config, "shard": args.shard, "shards": args.shards, + "data": pin, "environment": environment_info(), + "github_run_id": os.environ.get("GITHUB_RUN_ID"), + "github_run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT"), + "expected": [c["id"] for _, c in selected], "pieces": [], "failures": [], + } + args.output.mkdir(parents=True, exist_ok=True) + write_json(args.output / "metrics.json", result) # also for an empty shard + + for i, case in selected: + case_dir = args.output / f"{i:03d}" + case_dir.mkdir(exist_ok=True) + try: + paths = {k: fetch_input(case["paths"][k], manifest, args.cache, base_url) for k in inputs} + with (case_dir / "run.log").open("w") as log, \ + contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): + record = run_case(case, config, paths, case_dir) + record["input_hashes"] = {k: manifest["files"][case["paths"][k]]["sha256"] for k in inputs} + record["directory"] = case_dir.name + write_json(case_dir / "result.json", record) + result["pieces"].append(record) + print(args.config, case["id"], record["tracked"], record["mean_b"], flush=True) + except Exception: + error = traceback.format_exc() + (case_dir / "error.txt").write_text(error) + result["failures"].append({"case_id": case["id"], "error": error}) + print(error, flush=True) + write_json(args.output / "metrics.json", result) + + if result["failures"]: + raise SystemExit(f"{len(result['failures'])} diagnostic cases failed") + + +def summarize(pieces): + """Per category: how many cases were tracked, and their mean beat error.""" + import numpy as np + + by_category = defaultdict(list) + for piece in pieces: + by_category[piece["category"]].append(piece) + summary = {} + for category, group in by_category.items(): + tracked = [p["mean_b"] for p in group if p["tracked"]] + summary[category] = {"total": len(group), "tracked": len(tracked), + "mean_b_tracked": float(np.mean(tracked)) if tracked else None, + "mean_b_all": float(np.mean([p["mean_b"] for p in group]))} + return summary + + +def merge(args): + manifest = json.loads(args.manifest.read_text()) + records = [json.loads(p.read_text()) for p in args.source.glob("*/metrics.json")] + args.output.mkdir(parents=True, exist_ok=True) + + incomplete, summary = [], {} + for name, config in select_configs(args.only, args.input_type).items(): + own = [r for r in records if r["config"] == name] + found = sorted(p["case_id"] for r in own for p in r["pieces"]) + expected = sorted(c["id"] for _, c in select_cases(manifest, config)) + shards = {r["shard"] for r in own} + if (len(own) != args.shards or shards != set(range(args.shards)) + or found != expected or any(r["failures"] for r in own)): + incomplete.append(name) + summary[name] = summarize([p for r in own for p in r["pieces"]]) + + # All shards must come from one run: the same data, benchmark and matchmaker. + sources = {(r["data"]["commit"], r["environment"]["benchmark_commit"], + json.dumps({k: v for k, v in r["environment"].items() if k.startswith("matchmaker")}, + sort_keys=True), + r["github_run_id"]) for r in records} + if len(sources) != 1: + incomplete.append("shards come from different runs") + + for shard_dir in args.source.iterdir(): + if shard_dir.is_dir(): + shutil.copytree(shard_dir, args.output / "raw" / shard_dir.name, dirs_exist_ok=True) + shutil.copyfile(args.manifest, args.output / "data_manifest.json") + write_json(args.output / "summary.json", { + "complete": not incomplete, "incomplete": incomplete, "configurations": summary, + "sources": [list(s) for s in sources], + }) + if incomplete: + raise SystemExit("Incomplete diagnostic results: " + ", ".join(incomplete)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + commands = parser.add_subparsers(dest="command", required=True) + run_parser = commands.add_parser("run", help="run one shard of one configuration") + run_parser.add_argument("--config", choices=CONFIGS, required=True) + run_parser.add_argument("--shard", type=int, default=0) + run_parser.add_argument("--shards", type=int, default=1) + run_parser.add_argument("--output", type=Path, required=True) + run_parser.add_argument("--cache", type=Path, default=Path("diagnostic-data")) + merge_parser = commands.add_parser("merge", help="check and combine downloaded shards") + merge_parser.add_argument("--source", type=Path, required=True) + merge_parser.add_argument("--output", type=Path, required=True) + merge_parser.add_argument("--manifest", type=Path, required=True) + merge_parser.add_argument("--shards", type=int, required=True) + merge_parser.add_argument("--only", default="", help="method names; empty selects all") + merge_parser.add_argument("--input-type", choices=["both", "midi", "audio"], default="both") + args = parser.parse_args() + if args.command == "run": + run(args) + else: + merge(args) + + +if __name__ == "__main__": + main() diff --git a/matchmaker_eval/run_references.py b/matchmaker_eval/run_references.py index 0562485..cfaf5e9 100644 --- a/matchmaker_eval/run_references.py +++ b/matchmaker_eval/run_references.py @@ -39,7 +39,7 @@ from concurrent.futures import ThreadPoolExecutor from pathlib import Path -from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT, load_fold +from matchmaker_eval.load_folds import LEADERBOARD_FOLD, REPO_ROOT, load_fold from matchmaker_eval.submission import ( BUILTIN_METHODS_PATH, read_descriptions, diff --git a/matchmaker_eval/run_submission.py b/matchmaker_eval/run_submission.py index b5fb313..ab2514a 100644 --- a/matchmaker_eval/run_submission.py +++ b/matchmaker_eval/run_submission.py @@ -55,12 +55,12 @@ from matchmaker.base import OnlineAlignment from matchmaker_eval.fetch_data import FetchError, fetch_for_pieces, load_config -from matchmaker_eval.provenance import ( +from matchmaker_eval.evaluation_key import ( code_components, evaluation_record, piece_data_sha256, ) -from matchmaker_eval.folds import ( +from matchmaker_eval.load_folds import ( LEADERBOARD_FOLD, REPO_ROOT, fold_path, @@ -339,7 +339,7 @@ def scoring_parts() -> dict: The tracked-verdict thresholds and the function that resolves ground truth and calls the evaluation. Anything added here that decides a number belongs - in this dict too; see provenance.py. + in this dict too; see evaluation_key.py. """ return { "TRACKING_THRESHOLD": TRACKING_THRESHOLD, @@ -609,7 +609,7 @@ def evaluate_submission( "timestamp": datetime.now(timezone.utc).isoformat(timespec="seconds"), "environment": environment_info(), # The conditions these numbers were scored under, as one key. Rows - # with the same key are comparable; see provenance.py. On a shard it + # with the same key are comparable; see evaluation_key.py. On a shard it # covers that shard's pieces only, and merge_shards.py recomputes it. "evaluation": evaluation_record( code_components(fold_sha256, scoring_parts()), piece_records diff --git a/matchmaker_eval/symbolic_alignment.py b/matchmaker_eval/symbolic_alignment.py index c4ee06c..d9e2145 100644 --- a/matchmaker_eval/symbolic_alignment.py +++ b/matchmaker_eval/symbolic_alignment.py @@ -44,7 +44,7 @@ compute_ioi_matrix, compute_discrete_pitch_profiles, ) -from matchmaker_eval.folds import nested_dataset_root +from matchmaker_eval.load_folds import nested_dataset_root from matchmaker_eval.utils import save_nparray_to_csv, save_score_following_result from matchmaker.utils.tempo_models import ReactiveTempoModel, KalmanTempoModel diff --git a/matchmaker_eval/test_audio.py b/matchmaker_eval/test_audio.py index 0275239..127320f 100644 --- a/matchmaker_eval/test_audio.py +++ b/matchmaker_eval/test_audio.py @@ -16,7 +16,7 @@ import numpy as np import pandas as pd from matchmaker_eval.eval import run_offline_alignment, run_score_following -from matchmaker_eval.folds import ( +from matchmaker_eval.load_folds import ( DATA_REPO_DATASETS, data_repo_metadata, explain_missing_dataset, diff --git a/matchmaker_eval/test_symbolic.py b/matchmaker_eval/test_symbolic.py index ca5e7ce..220d03c 100644 --- a/matchmaker_eval/test_symbolic.py +++ b/matchmaker_eval/test_symbolic.py @@ -26,7 +26,7 @@ from matchmaker_eval.eval import run_evaluation from matchmaker import Matchmaker from matchmaker.utils.eval import resolve_gt -from matchmaker_eval.folds import ( +from matchmaker_eval.load_folds import ( DATA_REPO_DATASETS, data_repo_metadata, explain_missing_dataset, diff --git a/matchmaker_eval/validate_submission.py b/matchmaker_eval/validate_submission.py index 766757d..157b688 100644 --- a/matchmaker_eval/validate_submission.py +++ b/matchmaker_eval/validate_submission.py @@ -32,7 +32,7 @@ import argparse import re -from matchmaker_eval.folds import REPO_ROOT +from matchmaker_eval.load_folds import REPO_ROOT from matchmaker_eval.submission import ( SubmissionError, load_solution, diff --git a/matchmaker_eval/verify_equivalence.py b/matchmaker_eval/verify_equivalence.py index 311bf7c..52e7401 100644 --- a/matchmaker_eval/verify_equivalence.py +++ b/matchmaker_eval/verify_equivalence.py @@ -42,7 +42,7 @@ from matchmaker.utils.eval import resolve_gt from eval import run_evaluation -from matchmaker_eval.folds import load_fold +from matchmaker_eval.load_folds import load_fold from methods import builtin_methods, default_kwargs, processor_for from utils import TOLERANCES_IN_BEATS diff --git a/matchmaker_eval/verify_tracking.py b/matchmaker_eval/verify_tracking.py index 1ff7104..31b5b3b 100644 --- a/matchmaker_eval/verify_tracking.py +++ b/matchmaker_eval/verify_tracking.py @@ -8,8 +8,8 @@ reaches the final annotation. A piece fails when any window median exceeds the selected beat tolerance. Benchmark callers supply ``beat_factors`` from the reference score: errors are divided by three in compound-meter passages and -by one elsewhere, before the window median is taken. Omitting the factors is -an explicit legacy denominator-note calculation. +by one elsewhere, before the window median is taken. Without the factors, +errors stay in denominator-note beats. Input: wp.tsv Warping path (tab-separated) diff --git a/tests/test_data_folder.py b/tests/test_data_folder.py index c355e76..cb5595f 100644 --- a/tests/test_data_folder.py +++ b/tests/test_data_folder.py @@ -53,7 +53,7 @@ def test_the_pipeline_imports_without_them(self, tmp_path): # A repo tree holding only the config, and nothing dataset-shaped. script = ( "import sys; sys.path[:0] = [r'%s', r'%s']\n" - "import matchmaker_eval.folds as F\n" + "import matchmaker_eval.load_folds as F\n" "from pathlib import Path\n" "F.FOLD_DIR = Path(r'%s')\n" "pieces = F.load_fold('eval', input_type='midi')\n" diff --git a/tests/test_data_paths.py b/tests/test_data_paths.py index d012354..09a01f8 100644 --- a/tests/test_data_paths.py +++ b/tests/test_data_paths.py @@ -20,7 +20,7 @@ @pytest.fixture def data_root(tmp_path, monkeypatch): - import matchmaker_eval.folds as F + import matchmaker_eval.load_folds as F monkeypatch.setattr(F, "DATA_ROOT", tmp_path) return tmp_path @@ -28,7 +28,7 @@ def data_root(tmp_path, monkeypatch): class TestDatasetRoot: def test_the_repository_layout_wins(self, data_root): - from matchmaker_eval.folds import dataset_root + from matchmaker_eval.load_folds import dataset_root (data_root / "asap" / "score").mkdir(parents=True) (data_root / "asap-dataset-matchmaker" / "score").mkdir(parents=True) @@ -36,12 +36,12 @@ def test_the_repository_layout_wins(self, data_root): def test_nothing_on_disk_gives_the_fetch_target(self, data_root): """So a download lands where the folds will look for it.""" - from matchmaker_eval.folds import dataset_root + from matchmaker_eval.load_folds import dataset_root assert dataset_root("asap") == data_root / "asap" def test_a_legacy_copy_in_the_expected_shape_is_reused(self, data_root): - from matchmaker_eval.folds import dataset_root + from matchmaker_eval.load_folds import dataset_root legacy = data_root / "vienna4x22" (legacy / "score").mkdir(parents=True) @@ -55,7 +55,7 @@ def test_a_legacy_copy_in_the_upstream_shape_is_ignored(self, data_root): CSVs name. Returning it sent every path into a differently-shaped tree and the run failed on paths nobody had configured. """ - from matchmaker_eval.folds import dataset_root + from matchmaker_eval.load_folds import dataset_root (data_root / "batik_plays_mozart" / "scores_effective").mkdir(parents=True) assert dataset_root("batik") == data_root / "batik", ( @@ -63,52 +63,39 @@ def test_a_legacy_copy_in_the_upstream_shape_is_ignored(self, data_root): ) def test_an_empty_legacy_directory_is_ignored(self, data_root): - from matchmaker_eval.folds import dataset_root + from matchmaker_eval.load_folds import dataset_root (data_root / "batik_plays_mozart").mkdir() assert dataset_root("batik") == data_root / "batik" def test_local_pieces_come_from_the_repository(self, data_root): - from matchmaker_eval.folds import REPO_ROOT as R, dataset_root + from matchmaker_eval.load_folds import REPO_ROOT as R, dataset_root assert dataset_root("local") == R @pytest.mark.parametrize("layout", ["score", "midi", "match", "audio"]) def test_any_expected_subdirectory_counts(self, data_root, layout): - from matchmaker_eval.folds import has_expected_layout + from matchmaker_eval.load_folds import has_expected_layout d = data_root / "whatever" (d / layout).mkdir(parents=True) assert has_expected_layout(d) def test_a_file_is_not_a_layout(self, data_root): - from matchmaker_eval.folds import has_expected_layout + from matchmaker_eval.load_folds import has_expected_layout f = data_root / "notadir" f.write_text("") assert not has_expected_layout(f) -def test_explicit_revision_overrides_every_fold_branch(tmp_path, monkeypatch): - from matchmaker_eval import fetch_data - - source = tmp_path / "sources.yaml" - source.write_text("branch: main\nbranches:\n eval: eval\n valid: valid\n") - monkeypatch.setattr(fetch_data, "CONFIG_PATH", source) - revision = "a" * 40 - monkeypatch.setenv("MATCHMAKER_DATA_BRANCH", revision) - config = fetch_data.load_config() - for fold in ("eval", "valid", "unlisted"): - assert fetch_data.branch_for(config, fold) == revision - - class TestMissingDataMessage: def test_it_says_how_to_fetch(self, data_root): - from matchmaker_eval.folds import FoldError, load_fold, require_files + from matchmaker_eval.load_folds import FoldError, load_fold, require_files pieces = load_fold("example", input_type="midi") # Point the local dataset somewhere empty so the files are missing. - import matchmaker_eval.folds as F + import matchmaker_eval.load_folds as F monkey = data_root / "nothing" monkey.mkdir() @@ -136,13 +123,13 @@ class TestMetadataRunnerPaths: """ def test_the_root_follows_the_data_dir(self, data_root): - from matchmaker_eval.folds import nested_dataset_root + from matchmaker_eval.load_folds import nested_dataset_root assert nested_dataset_root("asap") == data_root / "asap-dataset-matchmaker" assert nested_dataset_root("batik") == data_root / "batik_plays_mozart" def test_an_unknown_dataset_uses_its_own_name(self, data_root): - from matchmaker_eval.folds import nested_dataset_root + from matchmaker_eval.load_folds import nested_dataset_root assert nested_dataset_root("urmp") == data_root / "urmp" @@ -158,7 +145,7 @@ def test_the_runners_no_longer_hardcode_a_home_directory(self): def test_the_message_names_both_ways_forward(self): from pathlib import Path as P - from matchmaker_eval.folds import explain_missing_dataset + from matchmaker_eval.load_folds import explain_missing_dataset message = explain_missing_dataset("asap", P("/nowhere/x.musicxml")) assert "MATCHMAKER_DATA_DIR" in message @@ -177,19 +164,3 @@ def test_the_runners_point_submitters_at_the_fold_path(self): ) assert done.returncode == 0, done.stderr assert "--fold valid" in done.stdout - - -def test_diagnostic_chunked_input_verified(tmp_path): - import hashlib - from matchmaker_eval.diagnostics import materialize - chunks = [b'first', b'second'] - parts = [] - for i, data in enumerate(chunks): - p = tmp_path/f'p{i}'; p.write_bytes(data) - parts.append(dict(path=p.name, sha256=hashlib.sha256(data).hexdigest())) - m={'files':{'audio.flac':dict(parts=parts,sha256=hashlib.sha256(b''.join(chunks)).hexdigest())}} - out=materialize('audio.flac',m,tmp_path,'https://invalid/') - assert out.read_bytes() == b'firstsecond' - m['files']['audio.flac']['sha256']='wrong' - with pytest.raises(ValueError,match='hash mismatch'): - materialize('audio.flac',m,tmp_path,'https://invalid/') diff --git a/tests/test_estimated_bpm.py b/tests/test_estimated_bpm.py index c45aa97..9dffd77 100644 --- a/tests/test_estimated_bpm.py +++ b/tests/test_estimated_bpm.py @@ -121,14 +121,14 @@ class TestTheFoldCarriesIt: """The tempo is frozen in the fold, beside the paths it belongs to.""" def test_the_example_piece_publishes_one(self): - from matchmaker_eval.folds import load_fold + from matchmaker_eval.load_folds import load_fold piece = load_fold("example", input_type="midi")[0] assert piece.performance_tempo == 58.0 def test_every_eval_row_has_one(self): """A missing value would silently disarm `estimated_bpm: true` runs.""" - from matchmaker_eval.folds import load_fold + from matchmaker_eval.load_folds import load_fold for fold in ("eval", "valid"): blank = [p.piece_id for p in load_fold(fold) if not p.estimated_bpm] @@ -140,19 +140,19 @@ def test_it_is_one_value_per_performance_not_per_container(self): A per-container tempo would have to be two columns, and a follower's audio and MIDI runs would then be measured against different tempi. """ - from matchmaker_eval.folds import FOLD_COLUMNS + from matchmaker_eval.load_folds import FOLD_COLUMNS assert [c for c in FOLD_COLUMNS if "bpm" in c] == ["estimated_bpm"] def test_an_absent_value_reads_as_none(self): - from matchmaker_eval.folds import Piece + from matchmaker_eval.load_folds import Piece piece = Piece("p", "asap", "Bach", "t", "s.musicxml", "p.mid", "", "p.match") assert piece.performance_tempo is None def test_a_non_numeric_value_is_refused(self): """Better a named failure than a follower handed a nonsense tempo.""" - from matchmaker_eval.folds import FoldError, Piece + from matchmaker_eval.load_folds import FoldError, Piece piece = Piece( "p", "asap", "Bach", "t", "s.musicxml", "p.mid", "", "p.match", @@ -166,7 +166,7 @@ class TestOlderFoldsStillLoad: """The column arrived after folds were already in circulation.""" def test_a_fold_without_the_column_loads(self, tmp_path): - from matchmaker_eval.folds import REQUIRED_FOLD_COLUMNS, load_fold + from matchmaker_eval.load_folds import REQUIRED_FOLD_COLUMNS, load_fold csv_path = tmp_path / "old.csv" csv_path.write_text( @@ -178,7 +178,7 @@ def test_a_fold_without_the_column_loads(self, tmp_path): assert piece.performance_tempo is None def test_a_required_column_is_still_required(self, tmp_path): - from matchmaker_eval.folds import FoldError, load_fold + from matchmaker_eval.load_folds import FoldError, load_fold csv_path = tmp_path / "broken.csv" csv_path.write_text("piece_id,dataset\nlocal/x/y,local\n") @@ -196,7 +196,7 @@ class TestMissingTempoFallsBack: def _piece_without_tempo(self): import dataclasses - from matchmaker_eval.folds import load_fold + from matchmaker_eval.load_folds import load_fold piece = load_fold("example", input_type="midi")[0] return dataclasses.replace(piece, estimated_bpm="") @@ -210,7 +210,7 @@ def test_it_runs_anyway(self, tmp_path): assert flat["tracked"] is True def test_a_piece_with_a_tempo_records_that_it_used_one(self, tmp_path): - from matchmaker_eval.folds import load_fold + from matchmaker_eval.load_folds import load_fold from run_submission import run_piece piece = load_fold("example", input_type="midi")[0] @@ -219,7 +219,7 @@ def test_a_piece_with_a_tempo_records_that_it_used_one(self, tmp_path): assert flat["used_estimated_bpm"] is True def test_an_entry_that_never_asked_records_false(self, tmp_path): - from matchmaker_eval.folds import load_fold + from matchmaker_eval.load_folds import load_fold from run_submission import run_piece piece = load_fold("example", input_type="midi")[0] diff --git a/tests/test_evaluation_key.py b/tests/test_evaluation_key.py index 5e2a494..8d75c3e 100644 --- a/tests/test_evaluation_key.py +++ b/tests/test_evaluation_key.py @@ -18,7 +18,7 @@ sys.path.insert(0, str(_p)) import matchmaker_eval.leaderboard as L -from matchmaker_eval import provenance as P +from matchmaker_eval import evaluation_key as P from matchmaker_eval.export_details import export from merge_shards import MergeError, merge @@ -30,12 +30,6 @@ "partitura": "1.9.0", } -CURRENT_CODE = { - **CODE, - "scheme": P.SCHEME, - "matchmaker_scoring_sha256": "e" * 64, -} - class FakePiece: """The parts of folds.Piece the data hash reads.""" @@ -65,14 +59,6 @@ def records(n=3, prefix="h"): class TestTheKey: - def test_follower_source_changes_preserve_comparability_and_provenance(self): - old = P.evaluation_record(CURRENT_CODE, records()) - new = P.evaluation_record({**CURRENT_CODE, "matchmaker_sha256": "new"}, records()) - assert re.fullmatch(r"ek2-[0-9a-f]{12}", new["key"]) - assert old["key"] == new["key"] - assert old["components"]["matchmaker_sha256"] != new["components"]["matchmaker_sha256"] - assert old["key"] != P.evaluation_record(CODE, records())["key"] - def test_it_names_its_scheme_and_is_short(self): key = P.evaluation_record(CODE, records())["key"] assert re.fullmatch(r"ek1-[0-9a-f]{12}", key) @@ -115,25 +101,6 @@ def test_no_key_without_every_code_component(self): class TestTheComponents: - @pytest.mark.parametrize("module", ["matchmaker.py", "utils/eval.py"]) - def test_shared_score_loading_and_evaluation_change_conditions(self, tmp_path, monkeypatch, module): - import matchmaker - - monkeypatch.setattr(matchmaker, "__file__", str(tmp_path / "__init__.py")) - for name in P.MATCHMAKER_SCORING_MODULES: - path = tmp_path / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text("original source") - before = P.matchmaker_scoring_sha256() - full_before = P.matchmaker_sha256() - (tmp_path / "new_follower.py").write_text("new follower") - assert P.matchmaker_sha256() != full_before - assert P.matchmaker_scoring_sha256() == before - (tmp_path / module).write_text("changed shared evaluation") - after = P.matchmaker_scoring_sha256() - assert after != before - assert P.evaluation_record({**CURRENT_CODE, "matchmaker_scoring_sha256": before}, records())["key"] != P.evaluation_record({**CURRENT_CODE, "matchmaker_scoring_sha256": after}, records())["key"] - def test_a_piece_hash_follows_its_bytes(self, tmp_path): piece = FakePiece(tmp_path / "asap") before = P.piece_data_sha256(piece, "midi") @@ -191,13 +158,6 @@ def write_shard(root: Path, index: int, piece: dict, code: dict) -> None: class TestMerging: - def test_shards_still_require_the_same_follower_sources(self, tmp_path): - piece = {"index": 0, "piece_id": "asap/a", "dataset": "asap", "tracked": False, "data_sha256": "h0"} - write_shard(tmp_path / "shards", 0, piece, CURRENT_CODE) - write_shard(tmp_path / "shards", 1, {**piece, "index": 1}, {**CURRENT_CODE, "matchmaker_sha256": "different"}) - with pytest.raises(MergeError, match="matchmaker_sha256"): - merge(tmp_path / "shards", tmp_path / "out") - def test_the_merged_key_is_the_whole_fold_key(self, tmp_path): pieces = [ {"index": 0, "piece_id": "asap/a", "dataset": "asap", "tracked": False, "data_sha256": "h0"}, @@ -267,19 +227,6 @@ def add(record): class TestTheLeaderboard: - def test_adding_a_method_preserves_both_modalities_under_the_same_protocol(self, results): - for name, kind, date, library in ( - ("existing-midi", "midi", "2026-10-01", "old"), - ("existing-audio", "audio", "2026-10-01", "old"), - ("new-midi", "midi", "2026-10-02", "new"), - ): - evaluation = P.evaluation_record({**CURRENT_CODE, "matchmaker_sha256": library}, records(prefix=kind)) - results(entry(name, evaluation["key"], date, evaluation["components"], input_type=kind)) - board = L.build() - assert {row["submission"] for row in board["entries"]} == {"existing-midi", "existing-audio", "new-midi"} - assert board["earlier_conditions"] == [] - assert all("matchmaker_sha256" not in value for value in board["evaluation_conditions"].values()) - def test_only_rows_with_the_newest_key_are_ranked(self, results): results(entry("old-ref", "ek1-aaaaaaaaaaaa", "2026-10-01T00:00:00+00:00", OLD)) results(entry("new-ref", "ek1-bbbbbbbbbbbb", "2026-10-28T00:00:00+00:00", NEW, 0.5)) @@ -384,7 +331,7 @@ def test_nothing_is_archived_without_a_key(self, results): class TestTheDetailExport: - def test_the_data_hash_is_provenance_not_a_metric(self, tmp_path): + def test_the_data_hash_is_an_input_not_a_metric(self, tmp_path): run = tmp_path / "run" run.mkdir() (run / "metrics.json").write_text(json.dumps({ diff --git a/tests/test_merge_shards.py b/tests/test_merge_shards.py index 5e5ec2a..f13c6ac 100644 --- a/tests/test_merge_shards.py +++ b/tests/test_merge_shards.py @@ -5,8 +5,10 @@ which turned every reference method into an unnamed "submission". """ +import hashlib import json import sys +from argparse import Namespace from pathlib import Path import pytest @@ -17,6 +19,7 @@ sys.path.insert(0, str(_p)) from matchmaker_eval.leaderboard import row_from_metrics +from matchmaker_eval import run_diagnostics from merge_shards import MergeError, merge @@ -84,14 +87,9 @@ def test_a_short_merge_stays_partial(self, tmp_path): merged = merge(root, tmp_path / "out") assert merged["partial"] is True - def test_merge_retains_the_meter_and_criterion_needed_to_rescore(self, tmp_path): + def test_the_meter_and_tracking_criterion_are_kept(self, tmp_path): criterion = {"error_unit": "musical_beat", "threshold": 0.1, "window_duration": 30.0} - meter = {"schema": 1, "position_unit": "denominator_note", "changes": [ - {"start_score_beat": 0.0, "numerator": 6, "denominator": 8, - "denominator_notes_per_beat": 3}, - {"start_score_beat": 6.0, "numerator": 4, "denominator": 4, - "denominator_notes_per_beat": 1}, - ]} + meter = {"position_unit": "denominator_note", "changes": []} record = shard_record(0, fold_size=1) record["pieces"][0]["tracking_criterion"] = criterion root = write_shards(tmp_path / "shards", [record]) @@ -122,39 +120,6 @@ def test_a_duplicated_piece_index_is_rejected(self, tmp_path): merge(root, tmp_path / "out") -@pytest.mark.parametrize("missing_case", [False, True]) -def test_diagnostic_merge_requires_every_selected_case(tmp_path, monkeypatch, missing_case): - from argparse import Namespace - from matchmaker_eval import diagnostics - - config = dict(suite="perturbations", input_type="midi", method="chosen") - monkeypatch.setattr(diagnostics, "CONFIGS", { - "chosen-midi": config, "other-midi": {**config, "method": "other"}, - }) - cases = [{"id": name, "suite": "perturbations", "input_type": "midi"} - for name in ("a", "b")] - manifest = tmp_path / "manifest.json" - manifest.write_text(json.dumps({"cases": cases})) - shard = tmp_path / "shards" / "chosen-0" - shard.mkdir(parents=True) - record = dict(config="chosen-midi", shard=0, failures=[], - data={"commit": "data-revision"}, - environment={"benchmark_commit": "code-revision"}, github_run_id="1", - pieces=[dict(case_id=c["id"], category="example", tracked=True, mean_b=0.) - for c in cases[:1 if missing_case else 2]]) - (shard / "metrics.json").write_text(json.dumps(record)) - args = Namespace(source=tmp_path / "shards", output=tmp_path / "out", - manifest=manifest, shards=1, only="chosen", input_type="midi") - if missing_case: - with pytest.raises(SystemExit, match="Incomplete diagnostic results"): - diagnostics.merge(args) - else: - diagnostics.merge(args) - summary = json.loads((args.output / "summary.json").read_text()) - assert summary["complete"] is (not missing_case) - assert list(summary["configurations"]) == ["chosen-midi"] - - class TestMergeReferences: """One references run produces shards for many entries, flat in one dir.""" @@ -223,11 +188,6 @@ def test_unrelated_directories_are_ignored(self, tmp_path): (root / "some-other-artifact").mkdir() assert sorted(group(root)) == ["arzt-audio"] - def test_auxiliary_folds_do_not_default_to_the_piano_destination(self): - from merge_references import output_for_fold - - assert output_for_fold("beyond_piano") != output_for_fold("eval") - @pytest.mark.parametrize("fold,expected", [ ("beyond_piano", ["arzt-audio"]), ("eval", ["arzt-audio", "pthmm-midi"]), @@ -288,52 +248,60 @@ def test_the_count_is_recomputed_from_the_pieces(self, tmp_path): assert merged["n_estimated_bpm"] == 1 -def test_diagnostic_sharding_is_exhaustive_and_disjoint(): - from matchmaker_eval.diagnostics import select_cases - m = {'cases': [dict(id=str(i), suite='perturbations', input_type='audio') for i in range(41)]} - config = {'suite': 'perturbations', 'input_type': 'audio'} - shards = [select_cases(m, config, s, 4) for s in range(4)] - assert sorted(i for batch in shards for i, _ in batch) == list(range(41)) - - -def test_diagnostic_duplicate_cases_rejected(): - from matchmaker_eval.diagnostics import select_cases - c = dict(id='a', suite='perturbations', input_type='audio') - with pytest.raises(ValueError, match='duplicated'): - select_cases({'cases':[c,c]}, {'suite': 'perturbations', 'input_type': 'audio'}) - - -def test_diagnostic_merge_fails_incomplete_and_preserves_evidence(tmp_path): - from argparse import Namespace - from matchmaker_eval.diagnostics import CONFIGS, merge - source=tmp_path/'source';source.mkdir() - manifest=tmp_path/'manifest.json' - cases=[dict(id=k,suite=c['suite'],input_type=c['input_type']) for k,c in CONFIGS.items()] - # Unique IDs per suite/modality are enough; all output shards are absent. - manifest.write_text(json.dumps({'cases':cases})) - with pytest.raises(SystemExit,match='Incomplete'): - merge(Namespace(source=source,output=tmp_path/'out',manifest=manifest,shards=4, - only='',input_type='both')) - assert not json.loads((tmp_path/'out/summary.json').read_text())['complete'] - - -def test_diagnostic_merge_rejects_different_patched_sources(tmp_path, monkeypatch): - from argparse import Namespace - from matchmaker_eval import diagnostics as D - - config = {'suite': 'test', 'input_type': 'midi', 'method': 'test'} - monkeypatch.setattr(D, 'CONFIGS', {'test-midi': config}) - source = tmp_path / 'shards' - manifest = tmp_path / 'manifest.json' - manifest.write_text(json.dumps({'cases': [dict(id=str(i), **config) for i in range(2)]})) - for i in range(2): - folder = source / str(i) - folder.mkdir(parents=True) - record = dict(config='test-midi', shard=i, failures=[], data={'commit': 'data'}, - environment={'benchmark_commit': 'benchmark', 'matchmaker_base_commit': 'base', - 'matchmaker_patches': [{'head': str(i)}]}, github_run_id='run', - pieces=[dict(case_id=str(i), category='test', tracked=True, mean_b=0.)]) - (folder / 'metrics.json').write_text(json.dumps(record)) - with pytest.raises(SystemExit, match='inconsistent provenance'): - D.merge(Namespace(source=source, output=tmp_path / 'out', manifest=manifest, shards=2, - only='', input_type='both')) +class TestDiagnostics: + """The manuscript diagnostics run every selected case exactly once.""" + + def test_shards_cover_every_case_once(self): + manifest = {"cases": [{"id": str(i), "suite": "perturbations", "input_type": "audio"} + for i in range(41)]} + config = {"suite": "perturbations", "input_type": "audio"} + shards = [run_diagnostics.select_cases(manifest, config, s, 4) for s in range(4)] + assert sorted(i for shard in shards for i, _ in shard) == list(range(41)) + + def test_selection_filters_by_method_and_rejects_unknown_ones(self): + selected = run_diagnostics.select_configs("dixon", "midi") + assert selected + assert all(c["method"] == "dixon" and c["input_type"] == "midi" for c in selected.values()) + with pytest.raises(ValueError, match="unknown_method"): + run_diagnostics.select_configs("dixon unknown_method", "midi") + + def test_merge_fails_when_a_selected_case_is_missing(self, tmp_path, monkeypatch): + config = {"suite": "perturbations", "input_type": "midi", "method": "chosen"} + monkeypatch.setattr(run_diagnostics, "CONFIGS", { + "chosen-midi": config, "other-midi": {**config, "method": "other"}, + }) + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({"cases": [ + {"id": name, "suite": "perturbations", "input_type": "midi"} for name in ("a", "b") + ]})) + shard = tmp_path / "shards" / "chosen-0" + shard.mkdir(parents=True) + (shard / "metrics.json").write_text(json.dumps({ + "config": "chosen-midi", "shard": 0, "failures": [], "github_run_id": "1", + "data": {"commit": "data"}, "environment": {"benchmark_commit": "code"}, + "pieces": [{"case_id": "a", "category": "example", "tracked": True, "mean_b": 0.0}], + })) + args = Namespace(source=tmp_path / "shards", output=tmp_path / "out", manifest=manifest, + shards=1, only="chosen", input_type="midi") + + with pytest.raises(SystemExit, match="Incomplete diagnostic results"): + run_diagnostics.merge(args) + summary = json.loads((args.output / "summary.json").read_text()) + assert summary["complete"] is False + assert list(summary["configurations"]) == ["chosen-midi"] + + def test_a_chunked_input_is_reassembled_and_hash_checked(self, tmp_path): + chunks = [b"first", b"second"] + parts = [] + for i, data in enumerate(chunks): + (tmp_path / f"p{i}").write_bytes(data) + parts.append({"path": f"p{i}", "sha256": hashlib.sha256(data).hexdigest()}) + entry = {"parts": parts, "sha256": hashlib.sha256(b"".join(chunks)).hexdigest()} + manifest = {"files": {"audio.flac": entry}} + + out = run_diagnostics.fetch_input("audio.flac", manifest, tmp_path, "https://invalid/") + assert out.read_bytes() == b"firstsecond" + + entry["sha256"] = "wrong" + with pytest.raises(ValueError, match="hash mismatch"): + run_diagnostics.fetch_input("audio.flac", manifest, tmp_path, "https://invalid/") diff --git a/tests/test_musical_beats.py b/tests/test_musical_beats.py index cc4fa2c..db8a93a 100644 --- a/tests/test_musical_beats.py +++ b/tests/test_musical_beats.py @@ -1,62 +1,54 @@ -"""TR follows the ground-truth meter without changing position coordinates.""" +"""TR divides position errors by the reference meter's musical-beat factor.""" + import numpy as np import pytest from partitura.score import Note, Part, TimeSignature -from matchmaker_eval.verify_tracking import musical_beat_factors, score_meter_map -from matchmaker_eval.verify_tracking import check_tracking +from matchmaker_eval.verify_tracking import check_tracking, musical_beat_factors, score_meter_map def score(signatures=((0, 6, 8), (12, 4, 4))): - part = Part('P1', quarter_duration=4) + """6/8 for six denominator-note beats, then 4/4.""" + part = Part("P1", quarter_duration=4) for start, numerator, denominator in signatures: part.add(TimeSignature(numerator, denominator), start=start) - part.add(Note('C', 4, id='n0'), start=0, end=4) - part.add(Note('D', 4, id='n1'), start=12, end=16) - part.add(Note('E', 4, id='n2'), start=24, end=28) + part.add(Note("C", 4, id="n0"), start=0, end=4) + part.add(Note("D", 4, id="n1"), start=12, end=16) + part.add(Note("E", 4, id="n2"), start=24, end=28) return part -def test_meter_changes_and_returns_preserve_score_coordinates(): - part = score() - before = part.note_array().copy() - meter = score_meter_map(part) - # At the change and after a return, use the meter at that score position. - assert np.array_equal(musical_beat_factors([-1, 0, 5.99, 6, 10, 2], meter), [3,3,3,1,1,3]) - assert np.array_equal(part.note_array(), before) +def tracked(wp, gt, part, threshold=1.0): + factors = musical_beat_factors(gt[:, 1], score_meter_map(part)) + return check_tracking(wp, gt, threshold=threshold, beat_factors=factors) -@pytest.mark.parametrize('threshold,error', [(1.,2.0),(.1,.25)]) -@pytest.mark.parametrize('numerator,denominator,tracked', [ - (6,8,True), (9,8,True), (12,16,True), (3,4,False), (3,8,False), -]) -def test_tr_uses_compound_groups_but_not_simple_triple_meter( - threshold, error, numerator, denominator, tracked, -): - gt = np.array([[0.,0.],[1.,1.],[2.,2.]]) - wp = gt.copy();wp[:,1] += error - before = wp.copy() - meter = score_meter_map(score(((0,numerator,denominator),))) - result = check_tracking( - wp, gt, threshold=threshold, beat_factors=musical_beat_factors(gt[:,1], meter), - ) - assert result['tracked'] == tracked - assert np.array_equal(wp,before) - - -def test_change_inside_a_window_is_applied_before_taking_median(): - gt = np.array([[0.,5.0],[1.,5.5],[2.,6.0]]) - wp = gt.copy();wp[:,1] += [2.4,2.4,1.5] - # Two compound onsets are each 0.8 musical beat; the simple onset is 1.5. +def test_factor_follows_the_meter_at_each_position(): meter = score_meter_map(score()) - result = check_tracking(wp,gt,threshold=1.,beat_factors=musical_beat_factors(gt[:,1],meter)) - assert result['tracked'] - assert result['worst_window']['deviation'] == pytest.approx(.8) + # A pickup uses the first meter; a return to an earlier position uses its meter again. + assert musical_beat_factors([-1, 0, 5.99, 6, 10, 2], meter).tolist() == [3, 3, 3, 1, 1, 3] -def test_factor_follows_ground_truth_not_incorrect_predicted_region(): - meter = score_meter_map(score()) - gt = np.array([[0.,6.1],[1.,6.2],[2.,6.3]]) - wp = gt.copy();wp[:,1] -= 2. - # Estimates lie back in compound meter, but ground truth is now in 4/4. - assert not check_tracking(wp,gt,threshold=1.,beat_factors=musical_beat_factors(gt[:,1],meter))['tracked'] +@pytest.mark.parametrize("numerator,denominator,expected", [ + (6, 8, True), (9, 8, True), (12, 16, True), (3, 4, False), (3, 8, False), +]) +def test_only_compound_meters_group_three_beats(numerator, denominator, expected): + gt = np.array([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]) + wp = gt + [0.0, 2.0] + assert tracked(wp, gt, score(((0, numerator, denominator),)))["tracked"] is expected + + +def test_a_meter_change_inside_a_window_applies_per_onset(): + gt = np.array([[0.0, 5.0], [1.0, 5.5], [2.0, 6.0]]) + wp = gt + np.array([[0, 2.4], [0, 2.4], [0, 1.5]]) + # 2.4 / 3 = 0.8 for the two 6/8 onsets, 1.5 for the 4/4 onset: median 0.8. + result = tracked(wp, gt, score()) + assert result["tracked"] + assert result["worst_window"]["deviation"] == pytest.approx(0.8) + + +def test_the_factor_comes_from_the_ground_truth_position(): + gt = np.array([[0.0, 6.1], [1.0, 6.2], [2.0, 6.3]]) + wp = gt - [0.0, 2.0] + # The estimates fall back in 6/8, but the reference is already in 4/4. + assert not tracked(wp, gt, score())["tracked"] diff --git a/tests/test_registry_integration.py b/tests/test_registry_integration.py index 2453318..0c6364b 100644 --- a/tests/test_registry_integration.py +++ b/tests/test_registry_integration.py @@ -268,7 +268,7 @@ class TestFoldPaths: """``--fold`` also takes a path to a CSV, which need not be in the repo.""" def test_fold_file_label_handles_an_external_csv(self, tmp_path): - from matchmaker_eval.folds import REPO_ROOT + from matchmaker_eval.load_folds import REPO_ROOT from run_submission import fold_file_label external = tmp_path / "subset.csv" diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 0d60d92..dea0dff 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -119,17 +119,10 @@ def test_the_run_step_pins_blas_threads(self): class TestMatchmakerPin: """All workflows must install the same matchmaker, or jobs disagree.""" - def test_every_workflow_uses_the_shared_installer(self): - installs = [] + def test_no_workflow_installs_matchmaker_on_its_own(self): + """Every job installs through .github/install_matchmaker.py instead.""" for path in sorted(WORKFLOWS.glob("*.yml")): - workflow = load_workflow(path) - for job in workflow.get("jobs", {}).values(): - commands = "\n".join(s.get("run", "") for s in job.get("steps", [])) - assert "matchmaker.git@" not in commands, path.name - if "run_submission.py" in commands or "merge_references.py" in commands: - assert "python .github/install_matchmaker.py" in commands, path.name - installs.append(path.name) - assert installs + assert "matchmaker.git@" not in path.read_text(), path.name class TestSiteAssembly: @@ -181,16 +174,6 @@ class TestReferencesWorkflow: REFERENCES = WORKFLOWS / "evaluate-references.yml" - def test_diagnostics_select_only_requested_methods_and_input(self): - from matchmaker_eval.diagnostics import select_configs - - selected = select_configs("dixon", "midi") - assert selected - assert all(c["method"] == "dixon" and c["input_type"] == "midi" - for c in selected.values()) - with pytest.raises(ValueError, match="unknown_method"): - select_configs("dixon unknown_method", "midi") - def test_it_uses_the_same_data_route_as_evaluate(self): workflow = load_workflow(self.REFERENCES) steps = steps_of(workflow, "evaluate") @@ -262,8 +245,8 @@ def test_the_root_licence_flags_the_exception(self): ) -class TestStagingBranch: - """Evaluation may run on a staging branch; publishing must not.""" +class TestWorkflowTriggers: + """Full evaluations start by hand; only main publishes.""" def _branches(self, path): workflow = load_workflow(path) @@ -277,12 +260,7 @@ def test_full_evaluations_require_explicit_dispatch(self, path): assert set(trigger) == {"workflow_dispatch"} def test_the_site_publishes_only_from_main(self): - """A staging run must be inspectable before anyone sees it.""" - pages = WORKFLOWS / "pages.yml" - assert self._branches(pages) == ["main"], ( - "publishing from a staging branch would defeat the point of having " - "one: a result could reach the site before it was checked" - ) + assert self._branches(WORKFLOWS / "pages.yml") == ["main"] class TestValidateWorkflow: @@ -317,7 +295,7 @@ def test_the_example_fold_is_committed(self): """--smoke must run with nothing downloaded.""" sys.path.insert(0, str(REPO_ROOT)) sys.path.insert(0, str(REPO_ROOT / "matchmaker_eval")) - from matchmaker_eval.folds import load_fold, missing_files + from matchmaker_eval.load_folds import load_fold, missing_files pieces = load_fold("example", input_type="midi") assert pieces @@ -376,15 +354,13 @@ def read_text(self, name): ) assert R._matchmaker_source() == {} - def test_a_patched_install_records_all_sources_without_a_false_commit(self, tmp_path, monkeypatch): + def test_a_patched_install_records_its_base_and_patches(self, tmp_path, monkeypatch): + import json from matchmaker_eval import run_submission as R - provenance = {"matchmaker_base_commit": "base", "matchmaker_patches": [ - {"base": "parent", "head": "pr-head", "sha256": "patch-hash"}, - ]} + source = {"matchmaker_base_commit": "base", "matchmaker_patches": [{"head": "patch"}]} (tmp_path / "assets").mkdir() - import json - (tmp_path / "assets" / "benchmark-source.json").write_text(json.dumps(provenance)) + (tmp_path / "assets" / "benchmark-source.json").write_text(json.dumps(source)) class LocalInstall: def read_text(self, name): @@ -392,77 +368,69 @@ def read_text(self, name): monkeypatch.setattr("importlib.metadata.distribution", lambda name: LocalInstall()) monkeypatch.setattr("importlib.resources.files", lambda name: tmp_path) - assert R._matchmaker_source() == provenance - assert "matchmaker_commit" not in R._matchmaker_source() + assert R._matchmaker_source() == source class TestReleasedResults: - """A release must identify its evaluated code and preserve a usable snapshot.""" + """A release takes complete runs only and keeps a site-ready snapshot.""" + + RUN = {"status": "completed", "conclusion": "success", + "head_repository": {"full_name": "owner/benchmark"}} @pytest.mark.parametrize("change", [ {"status": "in_progress"}, {"conclusion": "failure"}, {"head_repository": {"full_name": "someone/fork"}}, ]) - def test_only_successful_completed_repository_runs_can_be_released(self, change): + def test_only_successful_runs_of_this_repository_are_released(self, change): from matchmaker_eval.release_results import validate_runs - run = {"status": "completed", "conclusion": "success", "head_branch": "main", - "head_repository": {"full_name": "owner/benchmark"}, "head_sha": "abc"} - validate_runs([run, {**run, "head_branch": "feature", "head_sha": "def"}], "owner/benchmark") + + validate_runs([self.RUN], "owner/benchmark") with pytest.raises(ValueError, match="successful, completed runs"): - validate_runs([{**run, **change}], "owner/benchmark") + validate_runs([{**self.RUN, **change}], "owner/benchmark") - def test_only_complete_results_with_matching_provenance_replace_an_entry(self, tmp_path): + @staticmethod + def _stage(tmp_path, **record): import json from matchmaker_eval.release_results import stage_piano + source = tmp_path / "source" / "method-midi" - source.mkdir(parents=True) - destination = tmp_path / "published" - existing = destination / "submissions" / source.name / "metrics.json" - existing.parent.mkdir(parents=True) - existing.write_text("previous result") - other = destination / "submissions" / "other-midi" / "metrics.json" - other.parent.mkdir() - other.write_text("other result") - record = {"submission": source.name, "fold": "eval", "partial": False, - "n_failed": 0, "n_pieces": 2, "fold_size": 2, - "environment": {"benchmark_commit": "abc"}} - metrics = source / "metrics.json" - metrics.write_text(json.dumps({**record, "partial": True})) - with pytest.raises(ValueError, match="Incomplete"): - stage_piano(source.parent, destination, "abc") - assert existing.read_text() == "previous result" - metrics.write_text(json.dumps(record)) - with pytest.raises(ValueError, match="source run's commit"): - stage_piano(source.parent, destination, "def") - assert existing.read_text() == "previous result" - assert stage_piano(source.parent, destination, "abc") == [source.name] - assert json.loads(existing.read_text()) == record - corrected = {**record, "n_tracked": 2, "environment": {"benchmark_commit": "def"}} - metrics.write_text(json.dumps(corrected)) - stage_piano(source.parent, destination, "def") - assert json.loads(existing.read_text()) == corrected - assert other.read_text() == "other result" - - def test_snapshot_round_trip_preserves_the_site_and_metrics(self, tmp_path, monkeypatch): - import json + source.mkdir(parents=True, exist_ok=True) + complete = {"submission": "method-midi", "fold": "eval", "partial": False, + "n_failed": 0, "n_pieces": 2, "fold_size": 2, + "environment": {"benchmark_commit": "abc"}} + (source / "metrics.json").write_text(json.dumps({**complete, **record})) + return stage_piano(source.parent, tmp_path / "published", "abc") + + def test_a_complete_entry_replaces_only_itself(self, tmp_path): + published = tmp_path / "published" / "submissions" + for name in ("method-midi", "other-midi"): + (published / name).mkdir(parents=True) + (published / name / "metrics.json").write_text("previous") + assert self._stage(tmp_path) == ["method-midi"] + assert (published / "method-midi" / "metrics.json").read_text() != "previous" + assert (published / "other-midi" / "metrics.json").read_text() == "previous" + + @pytest.mark.parametrize("record,message", [ + ({"partial": True}, "Incomplete"), + ({"environment": {"benchmark_commit": "other"}}, "source run's commit"), + ]) + def test_an_incomplete_or_mismatched_entry_is_refused(self, tmp_path, record, message): + with pytest.raises(ValueError, match=message): + self._stage(tmp_path, **record) + + def test_the_site_builds_from_a_snapshot(self, tmp_path, monkeypatch): import build_site - from matchmaker_eval.release_results import snapshot, extract + from matchmaker_eval.release_results import extract, snapshot + results = tmp_path / "results" - entry = results / "submissions" / "method-midi" - entry.mkdir(parents=True) - record = {"submission": "method-midi", "n_tracked": 2} - (entry / "metrics.json").write_text(json.dumps(record)) - (entry / "wp_0.tsv").write_text("0 0\n1 1\n") + (results / "submissions" / "method-midi").mkdir(parents=True) + (results / "submissions" / "method-midi" / "metrics.json").write_text("{}") (results / "leaderboard.json").write_text('{"entries": []}') (results / "release.json").write_text('{"publisher_commit": "abc"}') - bundle = tmp_path / "snapshot.zip" - snapshot(results, bundle) - restored = tmp_path / "restored" - extract(bundle, restored) - assert json.loads((restored / "submissions/method-midi/metrics.json").read_text()) == record - monkeypatch.setattr(build_site, "RESULTS_DIR", restored) - site = tmp_path / "site" - build_site.build(site) - assert (site / "index.html").exists() - assert (site / "release.json").read_bytes() == (results / "release.json").read_bytes() - assert (site / "leaderboard.json").read_bytes() == (results / "leaderboard.json").read_bytes() + snapshot(results, tmp_path / "snapshot.zip") + extract(tmp_path / "snapshot.zip", tmp_path / "restored") + + monkeypatch.setattr(build_site, "RESULTS_DIR", tmp_path / "restored") + build_site.build(tmp_path / "site") + for name in ("index.html", "leaderboard.json", "release.json"): + assert (tmp_path / "site" / name).exists() From 550383394de844077c95d3dfa0735a8750bff379 Mon Sep 17 00:00:00 2001 From: "jiyun.park" Date: Fri, 13 Nov 2026 15:00:28 +0100 Subject: [PATCH 3/3] musical beat changes only --- .github/install_matchmaker.py | 63 ---- .github/workflows/evaluate-amt.yml | 112 ------ .github/workflows/evaluate-diagnostics.yml | 119 ------- .github/workflows/evaluate-offline.yml | 123 ------- .github/workflows/evaluate-references.yml | 193 +++-------- .github/workflows/evaluate.yml | 173 +++++++--- .github/workflows/pages.yml | 58 +--- .github/workflows/tests.yml | 2 +- .github/workflows/validate-submission.yml | 7 +- .gitignore | 22 +- README.md | 14 +- data/builtin_methods.yaml | 9 - data/data_sources.yaml | 9 - docs/index.html | 3 +- docs/maintaining.md | 116 +++---- docs/submitting.md | 45 +-- matchmaker_eval/build_site.py | 5 +- matchmaker_eval/download_data.py | 2 +- matchmaker_eval/estimate_perf_tempo.py | 2 +- matchmaker_eval/eval.py | 73 ++-- matchmaker_eval/eval_symbolic.py | 2 +- matchmaker_eval/export_details.py | 12 +- matchmaker_eval/fetch_data.py | 15 +- matchmaker_eval/{load_folds.py => folds.py} | 1 - matchmaker_eval/leaderboard.py | 11 +- matchmaker_eval/make_folds.py | 2 +- matchmaker_eval/merge_references.py | 40 +-- matchmaker_eval/merge_shards.py | 4 +- matchmaker_eval/preprocess_urmp.py | 2 +- matchmaker_eval/preprocess_winterreise.py | 2 +- .../{evaluation_key.py => provenance.py} | 41 ++- matchmaker_eval/release_results.py | 244 -------------- matchmaker_eval/retract.py | 7 +- matchmaker_eval/run_amt.py | 103 ------ matchmaker_eval/run_diagnostics.py | 319 ------------------ matchmaker_eval/run_offline.py | 132 -------- matchmaker_eval/run_references.py | 2 +- matchmaker_eval/run_submission.py | 55 +-- matchmaker_eval/symbolic_alignment.py | 2 +- matchmaker_eval/test_audio.py | 2 +- matchmaker_eval/test_symbolic.py | 2 +- matchmaker_eval/validate_submission.py | 2 +- matchmaker_eval/verify_equivalence.py | 2 +- tests/test_data_folder.py | 2 +- tests/test_data_paths.py | 28 +- tests/test_estimated_bpm.py | 20 +- tests/test_evaluation_key.py | 4 +- tests/test_merge_shards.py | 84 ----- tests/test_registry_integration.py | 2 +- tests/test_workflows.py | 133 +++----- 50 files changed, 466 insertions(+), 1961 deletions(-) delete mode 100644 .github/install_matchmaker.py delete mode 100644 .github/workflows/evaluate-amt.yml delete mode 100644 .github/workflows/evaluate-diagnostics.yml delete mode 100644 .github/workflows/evaluate-offline.yml rename matchmaker_eval/{load_folds.py => folds.py} (99%) rename matchmaker_eval/{evaluation_key.py => provenance.py} (77%) delete mode 100644 matchmaker_eval/release_results.py delete mode 100644 matchmaker_eval/run_amt.py delete mode 100644 matchmaker_eval/run_diagnostics.py delete mode 100644 matchmaker_eval/run_offline.py diff --git a/.github/install_matchmaker.py b/.github/install_matchmaker.py deleted file mode 100644 index 29753dd..0000000 --- a/.github/install_matchmaker.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Install the same immutable Matchmaker sources in every CI job. - -Pending changes are applied only in a temporary checkout, without creating -commits or changing upstream branches. Remove a patch once it is in BASE. -""" - -import hashlib -import json -import subprocess -import sys -import tempfile -from pathlib import Path - - -REPOSITORY = "https://github.com/pymatchmaker/matchmaker.git" -# develop with #79, #80 and #81: DPDannenberg, its initial-window fix, 3 kHz SPARC. -BASE = "25960ea95aadf1b98d1bc753c8be133e0bc859ff" -PATCHES = ( - # Multi-Fold Arzt: retain the bounded repeat enumeration used by diagnostics. - ("678366b034edc7cb10e3cf71bb1755b1a679e6c1", - "0e673e2bfebd86c1e814ed9f5270b926c053a0ae"), -) - - -def main(): - with tempfile.TemporaryDirectory(prefix="benchmark-matchmaker-") as folder: - source = Path(folder) - - def git(*args, **kwargs): - return subprocess.run( - ["git", "-C", str(source), *args], check=True, **kwargs - ) - - git("init", "--quiet") - git("config", "core.autocrlf", "false") - git("remote", "add", "origin", REPOSITORY) - refs = sorted({BASE, *(ref for pair in PATCHES for ref in pair)}) - git("fetch", "--quiet", "--depth=1", "origin", *refs) - git("checkout", "--quiet", "--detach", BASE) - patches = [] - for base, head in PATCHES: - patch = git("diff", "--binary", base, head, capture_output=True).stdout - git("apply", "--check", "-", input=patch) - git("apply", "-", input=patch) - patches.append({ - "base": base, "head": head, - "sha256": hashlib.sha256(patch).hexdigest(), - }) - provenance = { - "matchmaker_base_commit": BASE, - "matchmaker_patches": patches, - } - manifest = source / "matchmaker" / "assets" / "benchmark-source.json" - manifest.write_text(json.dumps(provenance, indent=2) + "\n") - print(json.dumps(provenance, indent=2), flush=True) - subprocess.run( - [sys.executable, "-m", "pip", "install", *sys.argv[1:], str(source)], - check=True, - ) - - -if __name__ == "__main__": - main() diff --git a/.github/workflows/evaluate-amt.yml b/.github/workflows/evaluate-amt.yml deleted file mode 100644 index 07f3b5f..0000000 --- a/.github/workflows/evaluate-amt.yml +++ /dev/null @@ -1,112 +0,0 @@ -name: Evaluate frozen AMT outputs -on: - workflow_call: - inputs: - shards: - type: string - default: '4' -permissions: - contents: read -jobs: - plan: - runs-on: ubuntu-latest - outputs: - matrix: ${{ steps.plan.outputs.matrix }} - shards: ${{ steps.plan.outputs.shards }} - steps: - - id: plan - env: - SHARDS: ${{ inputs.shards }} - run: | - python - <<'PY' >> "$GITHUB_OUTPUT" - import json,os - n=int(os.environ['SHARDS']) - if not 1 <= n <= 32:raise SystemExit('Use 1–32 shards') - print('matrix='+json.dumps({'method':['arzt','pthmm','SLT_OLTW'],'shard':list(range(n))})) - print('shards='+str(n)) - PY - evaluate: - needs: plan - runs-on: ubuntu-latest - timeout-minutes: 180 - strategy: - fail-fast: false - max-parallel: 8 - matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} - env: - MATCHMAKER_DATA_DIR: ${{ github.workspace }}/benchmark-data - MATCHMAKER_DATA_BRANCH: 03b51262b9bce7993203044fa45c9be9dadebd34 - OMP_NUM_THREADS: '1' - OPENBLAS_NUM_THREADS: '1' - MKL_NUM_THREADS: '1' - NUMBA_NUM_THREADS: '1' - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - cache: pip - - run: | - sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 ffmpeg - python .github/install_matchmaker.py - pip install pyyaml pydantic-settings - - name: Run symbolic follower on frozen transcription - run: | - python matchmaker_eval/run_amt.py --method '${{ matrix.method }}' \ - --shard '${{ matrix.shard }}' --num-shards '${{ needs.plan.outputs.shards }}' --output results/amt - - name: Record installed packages - if: always() - run: mkdir -p results/amt && pip freeze > results/amt/environment.txt - - uses: actions/upload-artifact@v4 - if: always() - with: - name: amt-${{ matrix.method }}-${{ matrix.shard }} - path: results/amt - retention-days: 30 - merge: - needs: [plan,evaluate] - if: always() && needs.plan.result == 'success' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - run: | - python .github/install_matchmaker.py - pip install pyyaml pydantic-settings - - uses: actions/download-artifact@v4 - with: - pattern: amt-* - path: results/shards - - name: Merge and verify complete test set - env: - SHARDS: ${{ needs.plan.outputs.shards }} - run: | - python - <<'PY' - import sys,os,json,shutil - from pathlib import Path - sys.path.insert(0,'matchmaker_eval') - from merge_shards import merge - out=Path('results/amt-reference');out.mkdir(parents=True,exist_ok=True) - errors=[] - for method in ['arzt','pthmm','SLT_OLTW']: - stage=Path('results/staging')/method;stage.mkdir(parents=True,exist_ok=True) - try: - for i in range(int(os.environ['SHARDS'])):shutil.copytree(Path('results/shards')/f'amt-{method}-{i}',stage/str(i)) - r=merge(stage,out/method) - if r['partial'] or r['n_failed'] or r['n_pieces']!=146:raise ValueError('Incomplete AMT reference') - except Exception as e:errors.append(method+': '+str(e)) - shutil.copytree('results/shards',out/'raw-shards') - from matchmaker_eval.fetch_data import frozen_source - (out/'amt-data-pin.json').write_text(json.dumps(frozen_source('amt'),indent=2)) - (out/'verification.json').write_text(json.dumps({'complete':not errors,'errors':errors},indent=2)) - if errors:raise SystemExit(errors) - PY - - uses: actions/upload-artifact@v4 - if: always() - with: - name: benchmark-results-amt-reference - path: results/amt-reference - retention-days: 90 diff --git a/.github/workflows/evaluate-diagnostics.yml b/.github/workflows/evaluate-diagnostics.yml deleted file mode 100644 index a1dbcd9..0000000 --- a/.github/workflows/evaluate-diagnostics.yml +++ /dev/null @@ -1,119 +0,0 @@ -name: Evaluate diagnostic suites -on: - workflow_call: - inputs: - shards: - type: string - default: '4' - only: - type: string - default: '' - input_type: - type: string - default: both -permissions: - contents: read -env: - ONLY: ${{ inputs.only }} - INPUT_TYPE: ${{ inputs.input_type }} -jobs: - plan: - runs-on: ubuntu-latest - outputs: - matrix: ${{ steps.plan.outputs.matrix }} - shards: ${{ steps.plan.outputs.shards }} - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - id: plan - env: - SHARDS: ${{ inputs.shards }} - run: | - python - <<'PY' >> "$GITHUB_OUTPUT" - import json, os - from matchmaker_eval.run_diagnostics import select_configs - n = int(os.environ['SHARDS']) - if not 1 <= n <= 8: raise SystemExit('Use 1–8 shards for diagnostics') - configs = select_configs(os.environ['ONLY'], os.environ['INPUT_TYPE']) - print('matrix='+json.dumps([{'config': c, 'shard': s} for c in configs for s in range(n)])) - print('shards='+str(n)) - PY - evaluate: - needs: plan - runs-on: ubuntu-latest - timeout-minutes: 350 - strategy: - fail-fast: false - max-parallel: 12 - matrix: - job: ${{ fromJSON(needs.plan.outputs.matrix) }} - env: - OMP_NUM_THREADS: '1' - OPENBLAS_NUM_THREADS: '1' - MKL_NUM_THREADS: '1' - NUMEXPR_NUM_THREADS: '1' - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - cache: pip - - name: Install environment - run: | - sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 ffmpeg - python .github/install_matchmaker.py - pip install pyyaml pydantic-settings - - name: Run frozen diagnostic cases - run: | - python matchmaker_eval/run_diagnostics.py run \ - --config '${{ matrix.job.config }}' --shard '${{ matrix.job.shard }}' \ - --shards '${{ needs.plan.outputs.shards }}' --output results/diagnostics - - uses: actions/upload-artifact@v4 - if: always() - with: - name: diagnosis-${{ matrix.job.config }}-${{ matrix.job.shard }} - path: results/diagnostics - if-no-files-found: error - retention-days: 30 - merge: - needs: [plan, evaluate] - if: always() && needs.plan.result == 'success' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - run: pip install numpy pyyaml - - uses: actions/download-artifact@v4 - with: - pattern: diagnosis-* - path: results/shards - - name: Fetch and verify frozen manifest - run: | - python - <<'PY' - import json - from pathlib import Path - from matchmaker_eval.evaluation_key import file_sha256 - from matchmaker_eval.run_diagnostics import download - from matchmaker_eval.fetch_data import frozen_source - p = frozen_source('diagnostics') - dest = Path('results/data_manifest.json') - download(f'https://raw.githubusercontent.com/{p["repository"]}/{p["commit"]}/diagnostics/manifest.json', dest) - assert file_sha256(dest) == p['manifest_sha256'] - PY - - name: Verify completeness and aggregate - run: | - python matchmaker_eval/run_diagnostics.py merge --source results/shards \ - --output results/diagnosis --manifest results/data_manifest.json \ - --shards '${{ needs.plan.outputs.shards }}' --only "$ONLY" --input-type "$INPUT_TYPE" - - uses: actions/upload-artifact@v4 - if: always() - with: - name: benchmark-results-diagnosis - path: results/diagnosis - if-no-files-found: error - retention-days: 90 diff --git a/.github/workflows/evaluate-offline.yml b/.github/workflows/evaluate-offline.yml deleted file mode 100644 index fe26cbc..0000000 --- a/.github/workflows/evaluate-offline.yml +++ /dev/null @@ -1,123 +0,0 @@ -name: Evaluate offline reference -on: - workflow_call: - inputs: - shards: - type: string - default: '8' -permissions: - contents: read -jobs: - plan: - runs-on: ubuntu-latest - outputs: - matrix: ${{ steps.plan.outputs.matrix }} - shards: ${{ steps.plan.outputs.shards }} - steps: - - id: plan - env: - SHARDS: ${{ inputs.shards }} - run: | - python - <<'PY' >> "$GITHUB_OUTPUT" - import json,os - n=int(os.environ['SHARDS']) - if not 1 <= n <= 32: raise SystemExit('Use 1–32 shards') - jobs=[{'fold':fold,'shard':s} for fold in ['eval','beyond_piano'] for s in range(n)] - print('matrix='+json.dumps(jobs));print('shards='+str(n)) - PY - evaluate: - needs: plan - runs-on: ubuntu-latest - timeout-minutes: 350 - strategy: - fail-fast: false - max-parallel: 12 - matrix: - job: ${{ fromJSON(needs.plan.outputs.matrix) }} - env: - MATCHMAKER_DATA_DIR: ${{ github.workspace }}/benchmark-data - MATCHMAKER_DATA_BRANCH: 03b51262b9bce7993203044fa45c9be9dadebd34 - OMP_NUM_THREADS: '1' - OPENBLAS_NUM_THREADS: '1' - MKL_NUM_THREADS: '1' - NUMEXPR_NUM_THREADS: '1' - NUMBA_NUM_THREADS: '1' - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - cache: pip - - name: Install fixed environment - run: | - sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 ffmpeg - python .github/install_matchmaker.py - pip install pyyaml pydantic-settings - - name: Install the offline numerical environment - run: | - # synctoolbox 1.3.2 declares pandas/numba upper bounds it does not - # need, so it is installed without its dependency pins. - pip install 'numpy==1.26.4' 'scipy==1.14.1' 'pandas==2.2.3' 'librosa==0.10.2' 'numba==0.64.0' ipython pretty_midi music21 - pip install --no-deps 'synctoolbox==1.3.2' 'libfmp==1.3.0' - - name: Run offline reference - run: | - python matchmaker_eval/run_offline.py --fold '${{ matrix.job.fold }}' \ - --shard '${{ matrix.job.shard }}' --num-shards '${{ needs.plan.outputs.shards }}' \ - --piece-timeout 2400 --output results/offline - - name: Record installed packages - if: always() - run: mkdir -p results/offline && pip freeze > results/offline/environment.txt - - uses: actions/upload-artifact@v4 - if: always() - with: - name: offline-${{ matrix.job.fold }}-${{ matrix.job.shard }} - path: results/offline - retention-days: 30 - merge: - needs: [plan,evaluate] - if: always() && needs.plan.result == 'success' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - run: | - python .github/install_matchmaker.py - pip install pyyaml pydantic-settings - - uses: actions/download-artifact@v4 - with: - pattern: offline-* - path: results/shards - - name: Merge and verify completeness - env: - SHARDS: ${{ needs.plan.outputs.shards }} - run: | - python - <<'PY' - import sys,os,json,shutil - from pathlib import Path - sys.path.insert(0,'matchmaker_eval') - from merge_shards import merge - errors=[] - output=Path('results/offline-reference');output.mkdir(parents=True,exist_ok=True) - for fold in ['eval','beyond_piano']: - key='offline-'+fold - stage=Path('results/staging')/key;stage.mkdir(parents=True,exist_ok=True) - try: - for i in range(int(os.environ['SHARDS'])): - src=Path('results/shards')/f'{key}-{i}' - shutil.copytree(src,stage/str(i)) - r=merge(stage,output/key) - if r['partial'] or r['n_failed']:raise ValueError('Incomplete cases') - except Exception as e:errors.append(key+': '+str(e)) - shutil.copytree('results/shards',output/'raw-shards') - (output/'verification.json').write_text(json.dumps({'complete':not errors,'errors':errors},indent=2)) - if errors:raise SystemExit(errors) - PY - - uses: actions/upload-artifact@v4 - if: always() - with: - name: benchmark-results-offline - path: results/offline-reference - retention-days: 90 diff --git a/.github/workflows/evaluate-references.yml b/.github/workflows/evaluate-references.yml index 8d54a37..10e1e4f 100644 --- a/.github/workflows/evaluate-references.yml +++ b/.github/workflows/evaluate-references.yml @@ -17,7 +17,7 @@ # Actions -> Evaluate references -> Run workflow # input_type: both shards: 8 # -# Every described entry runs as one job per shard. They queue against the account's +# 15 described entries x 8 shards is 120 jobs. They queue against the account's # concurrency limit rather than all starting at once, so expect this to take a # while; that is the price of every row being measured the same way. name: Evaluate references @@ -36,7 +36,7 @@ on: required: false default: "" fold: - description: "Fold: eval, beyond_piano, diagnostics, offline, or amt_reference" + description: "Fold to evaluate on" required: false default: eval shards: @@ -45,132 +45,26 @@ on: default: "8" permissions: - contents: read + contents: write concurrency: - # Avoid overlapping evaluations of the same branch and fold. - group: evaluate-${{ github.ref }}-${{ github.event.inputs.fold || 'eval' }} + # Shares evaluate.yml's group: both commit results/, and two at once would + # race on the leaderboard. + group: evaluate cancel-in-progress: false env: FOLD: ${{ github.event.inputs.fold || 'eval' }} jobs: - ophmm_playthrough: - name: ophmm comparison / evaluate (${{ matrix.condition }}, ${{ matrix.shard }}) - if: github.event.inputs.fold == 'ophmm_playthrough' - runs-on: ubuntu-latest - timeout-minutes: 180 - strategy: - fail-fast: false - max-parallel: 8 - matrix: - condition: ['on', 'off'] - shard: [0, 1, 2, 3] - env: - OMP_NUM_THREADS: '1' - OPENBLAS_NUM_THREADS: '1' - MKL_NUM_THREADS: '1' - NUMEXPR_NUM_THREADS: '1' - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - name: Install pinned environment - run: | - sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 - python .github/install_matchmaker.py - pip install pyyaml pydantic-settings - - name: Evaluate frozen piano fold - run: | - python matchmaker_eval/run_submission.py --method outerhmm --input-type midi --fold eval \ - --global-transition '${{ matrix.condition }}' \ - --shard '${{ matrix.shard }}' --num-shards 4 --output results/run - pip freeze > results/run/environment.txt - - uses: actions/upload-artifact@v4 - if: always() - with: - name: ophmm-${{ matrix.condition }}-${{ matrix.shard }} - path: results/run - retention-days: 90 - merge_ophmm_playthrough: - name: ophmm comparison / merge - needs: ophmm_playthrough - if: always() && needs.ophmm_playthrough.result != 'skipped' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - run: | - python .github/install_matchmaker.py - pip install pyyaml pydantic-settings - - uses: actions/download-artifact@v4 - with: - pattern: ophmm-* - path: results/shards - - name: Merge both conditions and check coverage - run: | - python - <<'PY' - import json,shutil - from pathlib import Path - from matchmaker_eval.merge_shards import merge - out=Path('results/comparison') - for condition in ('on','off'): - staging=Path('results/staging')/condition - for shard in range(4): - src=Path('results/shards')/f'ophmm-{condition}-{shard}' - meta=json.loads((src/'metrics.json').read_text()) - assert meta['metadata']['global_transition']==condition - if condition=='off': assert all(x['global_transition_nonzero']==0 for x in meta['pieces']) - shutil.copytree(src,staging/str(shard)) - result=merge(staging,out/condition) - assert not result['partial'] and result['n_failed']==0 and result['n_pieces']==146 - shutil.copytree('results/shards',out/'raw-shards') - PY - - uses: actions/upload-artifact@v4 - if: always() - with: - name: ophmm-playthrough-comparison - path: results/comparison - retention-days: 90 - - amt_reference: - name: amt replay - if: github.event.inputs.fold == 'amt_reference' - uses: ./.github/workflows/evaluate-amt.yml - with: - shards: ${{ github.event.inputs.shards || '4' }} - - offline: - if: github.event.inputs.fold == 'offline' - uses: ./.github/workflows/evaluate-offline.yml - with: - shards: ${{ github.event.inputs.shards || '8' }} - - diagnostics: - if: github.event.inputs.fold == 'diagnostics' - uses: ./.github/workflows/evaluate-diagnostics.yml - with: - shards: ${{ github.event.inputs.shards || '4' }} - only: ${{ github.event.inputs.only || '' }} - input_type: ${{ github.event.inputs.input_type || 'both' }} - plan: - name: main / plan - if: github.event.inputs.fold != 'diagnostics' && github.event.inputs.fold != 'offline' && github.event.inputs.fold != 'amt_reference' && github.event.inputs.fold != 'ophmm_playthrough' runs-on: ubuntu-latest outputs: jobs: ${{ steps.plan.outputs.jobs }} count: ${{ steps.plan.outputs.count }} - entries: ${{ steps.plan.outputs.entries }} data_repo: ${{ steps.source.outputs.data_repo }} data_branch: ${{ steps.source.outputs.branch }} num_shards: ${{ steps.plan.outputs.num_shards }} - results_root: ${{ steps.plan.outputs.results_root }} steps: - uses: actions/checkout@v4 @@ -184,7 +78,6 @@ jobs: pip install --quiet pyyaml python - <<'PY' >> "$GITHUB_OUTPUT" import json, os, yaml - from matchmaker_eval.load_folds import load_fold described = yaml.safe_load( open("data/builtin_methods.yaml").read() ) or {} @@ -192,14 +85,6 @@ jobs: types = ("midi", "audio") if wanted == "both" else (wanted,) only = [m for m in os.environ["ONLY"].split() if m] n = int(os.environ["SHARDS"]) - if not 1 <= n <= 32: - raise SystemExit("shards must be between 1 and 32") - fold = os.environ["FOLD"] - pieces = load_fold(fold) - available = {t for t in ("midi", "audio") if any(p.has_performance(t) for p in pieces)} - if wanted != "both" and wanted not in available: - raise SystemExit(f"Fold {fold!r} has no {wanted} performances") - types = tuple(t for t in types if t in available) jobs = [ {"method": method, "input_type": t, "shard": s} @@ -210,11 +95,7 @@ jobs: ] print(f"jobs={json.dumps(jobs)}") print(f"count={len(jobs)}") - entries = sorted({j["method"] + "-" + j["input_type"] for j in jobs}) - print(f"entries={json.dumps(entries)}") print(f"num_shards={n}") - output = f"results/ci/{fold}" - print(f"results_root={output}") PY env: INPUT_TYPE: ${{ github.event.inputs.input_type || 'both' }} @@ -234,7 +115,6 @@ jobs: echo "${{ steps.plan.outputs.count }} shard job(s) to run" evaluate: - name: main / evaluate (${{ matrix.job.method }}, ${{ matrix.job.input_type }}, ${{ matrix.job.shard }}) needs: plan if: needs.plan.outputs.count != '0' runs-on: ${{ vars.BENCHMARK_RUNNER || 'ubuntu-latest' }} @@ -261,8 +141,11 @@ jobs: - name: Install the benchmark environment run: | python -m pip install --upgrade pip - # The shared installer fixes the library sources for every job. - python .github/install_matchmaker.py + # Pinned to the matchmaker 0.4.0 release (tag v0.4.0, main after #73): + # its sources are part of the evaluation key, so every row of a run + # must be scored by the same matchmaker. Move every workflow together + # when the pin changes, and re-run the entries: their keys will change. + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" pip install pyyaml pydantic-settings - name: Check out the benchmark data @@ -338,15 +221,21 @@ jobs: retention-days: 14 merge: - name: main / merge needs: [plan, evaluate] - if: always() && needs.plan.result == 'success' && needs.plan.outputs.count != '0' + if: always() && needs.plan.outputs.count != '0' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - name: Keep preview files outside the code checkout - run: echo "MATCHMAKER_RESULTS_DIR=$RUNNER_TEMP/benchmark-preview" >> "$GITHUB_ENV" + - name: Catch up with anything committed while this run was queued or evaluating + # actions/checkout pins to the commit that existed when this run was + # dispatched, not now. The `evaluate` concurrency group serializes the + # actual pushes, but a run can still sit queued -- or just take a long + # time evaluating -- behind another one that lands a commit in the + # meantime. leaderboard.py rewrites the whole file rather than + # appending, so building on a stale base produces a real content + # conflict at push time instead of a clean fast-forward. + run: git pull - uses: actions/setup-python@v5 with: @@ -354,7 +243,7 @@ jobs: - name: Install what the merge needs run: | - python .github/install_matchmaker.py + pip install --quiet "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" pip install --quiet pyyaml pydantic-settings - uses: actions/download-artifact@v4 @@ -366,40 +255,34 @@ jobs: # One run produces shards for many entries; this regroups them by entry # and merges each separately. An entry missing shards stays partial and # off the leaderboard. - env: - EXPECTED_ENTRIES: ${{ needs.plan.outputs.entries }} - run: python matchmaker_eval/merge_references.py results/refshards --fold "$FOLD" --output "${{ needs.plan.outputs.results_root }}" --expected-entries-json "$EXPECTED_ENTRIES" - - - name: Upload the complete merged results - if: always() - uses: actions/upload-artifact@v4 - with: - name: benchmark-results-${{ env.FOLD }} - path: ${{ needs.plan.outputs.results_root }} - if-no-files-found: error - retention-days: 30 - - - name: Stage the piano results for the leaderboard - if: env.FOLD == 'eval' - run: | - mkdir -p "$MATCHMAKER_RESULTS_DIR/submissions" - cp -a "${{ needs.plan.outputs.results_root }}/." "$MATCHMAKER_RESULTS_DIR/submissions/" + run: python matchmaker_eval/merge_references.py results/refshards - name: Export the per-piece detail - if: env.FOLD == 'eval' run: python matchmaker_eval/export_details.py - name: Rebuild the leaderboard - if: env.FOLD == 'eval' run: python matchmaker_eval/leaderboard.py - name: Assemble the site for review - if: env.FOLD == 'eval' run: python matchmaker_eval/build_site.py _site - uses: actions/upload-artifact@v4 - if: env.FOLD == 'eval' with: name: leaderboard-site path: _site retention-days: 14 + + - name: Commit the results + run: | + git config user.name "matchmaker-benchmark[bot]" + git config user.email "actions@github.com" + git add results/ + if git diff --cached --quiet; then + echo "Leaderboard unchanged." + exit 0 + fi + git commit -m "benchmark: evaluate references on the ${{ env.FOLD }} fold + + Run ${{ github.run_id }}, ${{ needs.plan.outputs.count }} shard jobs." + git pull --rebase --autostash + git push diff --git a/.github/workflows/evaluate.yml b/.github/workflows/evaluate.yml index 6417025..974c7f0 100644 --- a/.github/workflows/evaluate.yml +++ b/.github/workflows/evaluate.yml @@ -7,13 +7,35 @@ # data/data_sources.yaml; the plan job reads it there so the address is written # down once (`fetch_data.py --source`). # -# A maintainer explicitly selects a reviewed submission or built-in method. -# Results are uploaded as artifacts. To publish them, select the completed run -# in Publish leaderboard (see docs/maintaining.md). +# This is the only workflow that writes to the repository, and it runs only on +# `submissions` — on code a maintainer has already reviewed and merged there. +# +# Two branches, on purpose: +# +# submissions a contributor's pull request lands here first. validate- +# submission.yml smoke-tests it on one piece before merge; that +# merge is what this workflow watches for. It diffs +# `submissions/` against its own previous commit, evaluates +# every submission that is new or has changed since — skipping +# ones that are unchanged and already evaluated — and commits +# the result here. Nothing is published from this branch. +# main merging `submissions` into it just carries the already- +# computed results over; nothing is re-evaluated. That merge +# is what publishes (see pages.yml), so it is also the moment +# to read `results/leaderboard.json` on `submissions` first and +# decide whether this batch is ready to go live. +# +# So review has to happen before merging a submission's pull request into +# `submissions` (see docs/maintaining.md#reviewing-a-submission): that merge +# is what starts this workflow, which is the first time the submitted code +# actually runs against the real datasets. To withdraw a result after the +# fact, see matchmaker_eval/retract.py. # # Sharding is what makes this fit: a job on a GitHub runner is capped at 6 # hours, and audio evaluation over 146 pieces does not fit in one. Shards are -# round-robin, so the merged numbers are identical to an unsharded run. +# round-robin, so the merged numbers are identical to an unsharded run. A push +# that brings several new or changed submissions fans out over all of them at +# once — one (submission x shard) matrix, mirroring evaluate-references.yml. # # It also works unchanged on a self-hosted runner that already holds the data: # set the repository variable MATCHMAKER_DATA_DIR to that copy and the checkout @@ -21,10 +43,18 @@ name: Evaluate submissions on: + push: + # `submissions` only, deliberately — see the branch note above. Evaluating + # on `main` too would re-run everything a merge to `main` brings with it; + # `main` only ever receives already-computed results. `branches:` cannot + # take a variable, so the branch is named here. + branches: [submissions] + paths: + - "submissions/**" workflow_dispatch: inputs: submission: - description: "Submission directory (leave empty only when specifying method)" + description: "Submission directory (empty = whatever this push changed)" required: false default: "" method: @@ -47,11 +77,11 @@ on: default: "8" permissions: - contents: read + contents: write concurrency: - # Share the references workflow's lock for the same branch and fold. - group: evaluate-${{ github.ref }}-${{ github.event.inputs.fold || 'eval' }} + # One evaluation at a time: two would race on results/leaderboard.json. + group: evaluate cancel-in-progress: false env: @@ -67,9 +97,10 @@ jobs: num_shards: ${{ steps.plan.outputs.num_shards }} data_repo: ${{ steps.source.outputs.data_repo }} data_branch: ${{ steps.source.outputs.branch }} - results_root: ${{ steps.plan.outputs.results_root }} steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 - uses: actions/setup-python@v5 with: @@ -77,10 +108,17 @@ jobs: - name: Decide what to evaluate id: plan + # A manual `method` dispatch is a single reference row. A manual + # `submission` dispatch is that one directory, changed or not -- + # useful for a forced rerun after a pipeline fix. Otherwise (a push to + # `submissions`, i.e. a submission's pull request just got merged) + # every submissions// directory touched since the previous + # commit on `submissions` is new or changed, and anything not in that + # diff is already evaluated and skipped. run: | pip install --quiet pyyaml python - <<'PY' >> "$GITHUB_OUTPUT" - import json, os + import json, os, subprocess import yaml @@ -88,10 +126,19 @@ jobs: method = os.environ.get("METHOD") or "" submission = os.environ.get("SUBMISSION") or "" - if not 1 <= n <= 32: - raise SystemExit("shards must be between 1 and 32") - if bool(method) == bool(submission): - raise SystemExit("Specify one submission directory or method, not both") + def changed_submissions(before, after): + if not before or before == "0" * 40: + return [] + diff = subprocess.run( + ["git", "diff", "--name-only", before, after], + capture_output=True, text=True, check=True, + ).stdout + found = set() + for line in diff.splitlines(): + parts = line.split("/") + if len(parts) >= 3 and parts[0] == "submissions" and not parts[1].startswith("_"): + found.add(f"submissions/{parts[1]}") + return sorted(found) entries = [] jobs = [] @@ -109,27 +156,40 @@ jobs: for s in range(n) ] else: - input_type = yaml.safe_load(open(f"{submission}/metadata.yaml"))["input_type"] - entry = submission.rstrip("/").split("/")[-1] - entries.append(entry) - jobs += [ - {"target": submission, "entry": entry, "input_type": input_type, "shard": s} - for s in range(n) - ] + if submission: + dirs = [submission] + elif os.environ["EVENT_NAME"] == "push": + dirs = changed_submissions(os.environ.get("BEFORE"), os.environ.get("AFTER")) + else: + dirs = [] + for d in dirs: + metadata_path = f"{d}/metadata.yaml" + if not os.path.exists(metadata_path): + # A directory can show up as "changed" because a pull + # request deleted it -- nothing to evaluate there. + print(f"{d} no longer exists, skipping") + continue + input_type = yaml.safe_load(open(metadata_path))["input_type"] + entry = d.split("/")[-1] + entries.append(entry) + jobs += [ + {"target": d, "entry": entry, "input_type": input_type, "shard": s} + for s in range(n) + ] print(f"jobs={json.dumps(jobs)}") print(f"count={len(jobs)}") print(f"entries={' '.join(entries) or 'none'}") print(f"num_shards={n}") - fold = os.environ["FOLD"] - output = f"results/ci/{fold}" - print(f"results_root={output}") PY env: METHOD: ${{ github.event.inputs.method }} SUBMISSION: ${{ github.event.inputs.submission }} INPUT_TYPE: ${{ github.event.inputs.input_type || 'midi' }} SHARDS: ${{ github.event.inputs.shards || '8' }} + EVENT_NAME: ${{ github.event_name }} + BEFORE: ${{ github.event.before }} + AFTER: ${{ github.sha }} - name: Locate this fold's data id: source @@ -169,8 +229,11 @@ jobs: - name: Install the benchmark environment run: | python -m pip install --upgrade pip - # The shared installer fixes the library sources for every job. - python .github/install_matchmaker.py + # Pinned to the matchmaker 0.4.0 release (tag v0.4.0, main after #73): + # its sources are part of the evaluation key, so every row of a run + # must be scored by the same matchmaker. Move every workflow together + # when the pin changes, and re-run the entries: their keys will change. + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" pip install pyyaml pydantic-settings if [ -d "${{ matrix.job.target }}" ] && [ -s "${{ matrix.job.target }}/requirements.txt" ]; then pip install -r "${{ matrix.job.target }}/requirements.txt" @@ -270,13 +333,21 @@ jobs: merge: needs: [plan, evaluate] - if: always() && needs.plan.result == 'success' && needs.plan.outputs.count != '0' + if: always() && needs.plan.outputs.count != '0' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - name: Keep preview files outside the code checkout - run: echo "MATCHMAKER_RESULTS_DIR=$RUNNER_TEMP/benchmark-preview" >> "$GITHUB_ENV" + - name: Catch up with anything committed while this run was queued or evaluating + # actions/checkout pins to the commit that existed when this run was + # dispatched, not now. The `evaluate` concurrency group serializes the + # actual pushes, but a run can still sit queued -- or just take a long + # time evaluating -- behind another one that lands a commit in the + # meantime (evaluate-references.yml shares this group). leaderboard.py + # rewrites the whole file rather than appending, so building on a + # stale base produces a real content conflict at push time instead of + # a clean fast-forward. + run: git pull - uses: actions/setup-python@v5 with: @@ -286,7 +357,7 @@ jobs: # Merging only recomputes the pooled summary from the shards' alignment # paths, so it needs numpy and the eval helpers, not matchmaker itself. run: | - python .github/install_matchmaker.py + pip install --quiet "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" pip install --quiet pyyaml pydantic-settings - uses: actions/download-artifact@v4 @@ -299,41 +370,41 @@ jobs: # this regroups them by entry (see refshard-- above) and # merges each separately. An entry missing shards stays partial and # off the leaderboard rather than being merged into a bad record. - run: python matchmaker_eval/merge_references.py results/refshards --fold "$FOLD" --output "${{ needs.plan.outputs.results_root }}" - - - name: Upload the complete merged results - if: always() - uses: actions/upload-artifact@v4 - with: - name: benchmark-results-${{ env.FOLD }} - path: ${{ needs.plan.outputs.results_root }} - if-no-files-found: error - retention-days: 30 - - - name: Stage the piano results for the leaderboard - if: env.FOLD == 'eval' - run: | - mkdir -p "$MATCHMAKER_RESULTS_DIR/submissions" - cp -a "${{ needs.plan.outputs.results_root }}/." "$MATCHMAKER_RESULTS_DIR/submissions/" + run: python matchmaker_eval/merge_references.py results/refshards - name: Export the per-piece detail - if: env.FOLD == 'eval' # Dataset breakdowns, per-piece rows and the decimated alignment paths # the leaderboard page plots. Written per entry and loaded on demand. run: python matchmaker_eval/export_details.py - name: Rebuild the leaderboard - if: env.FOLD == 'eval' run: python matchmaker_eval/leaderboard.py - name: Assemble the site for review - if: env.FOLD == 'eval' - # Preview only this run; it does not alter the public leaderboard. + # `submissions` does not publish (see pages.yml), so the only way to + # see what this run did to the leaderboard would otherwise be to read + # JSON. This uploads the real page as an artifact: download it, + # `python -m http.server` inside it, and you are looking at what + # merging `submissions` into `main` would publish. run: python matchmaker_eval/build_site.py _site - uses: actions/upload-artifact@v4 - if: env.FOLD == 'eval' with: name: leaderboard-site path: _site retention-days: 14 + + - name: Commit the results + run: | + git config user.name "matchmaker-benchmark[bot]" + git config user.email "actions@github.com" + git add results/ + if git diff --cached --quiet; then + echo "Leaderboard unchanged." + exit 0 + fi + git commit -m "benchmark: evaluate ${{ needs.plan.outputs.entries }} on the ${{ env.FOLD }} fold + + Run ${{ github.run_id }}, ${{ needs.plan.outputs.num_shards }} shards each." + git pull --rebase --autostash + git push diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index c8863b2..c547bbb 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -1,86 +1,48 @@ # Publish the leaderboard to GitHub Pages. # -# Selected completed runs are preserved in a release before deployment. -# Documentation-only rebuilds reuse the last published result snapshot. +# The site is docs/ plus a copy of results/leaderboard.json, so the page is a +# static read of exactly the file the evaluation workflow committed. name: Publish leaderboard on: push: + # `main` only, deliberately. The `submissions` branch evaluates and commits + # results without publishing them, so a run can be checked or withdrawn + # before it reaches the site. See the note in evaluate.yml. branches: [main] paths: + - "results/leaderboard.json" - "docs/**" - - "matchmaker_eval/build_site.py" - - "matchmaker_eval/release_results.py" - ".github/workflows/pages.yml" workflow_dispatch: - inputs: - source_runs: - description: "Completed CI run IDs, separated by spaces; later runs replace entries (empty = republish)" - required: false - default: "" - release_tag: - description: "New benchmark-* tag when releasing; otherwise existing tag or empty for latest" - required: false - default: "" permissions: - contents: write - actions: read + contents: read pages: write id-token: write concurrency: group: pages - cancel-in-progress: false + cancel-in-progress: true jobs: build: - if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest - outputs: - ready: ${{ steps.results.outputs.ready }} - env: - GH_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Keep published results outside the code checkout - run: echo "MATCHMAKER_RESULTS_DIR=$RUNNER_TEMP/benchmark-published-results" >> "$GITHUB_ENV" - - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - - name: Install result export dependencies - if: inputs.source_runs != '' - run: | - python .github/install_matchmaker.py - pip install pyyaml pydantic-settings - - - name: Preserve selected runs or fetch published results - id: results - env: - SOURCE_RUNS: ${{ inputs.source_runs }} - RELEASE_TAG: ${{ inputs.release_tag }} - run: | - python matchmaker_eval/release_results.py --source-runs "$SOURCE_RUNS" --tag "$RELEASE_TAG" - name: Assemble the site - if: steps.results.outputs.ready == 'true' + # Same script the staging preview uses, so what a maintainer looked at + # on the `submissions` branch is assembled exactly like what goes live. run: python matchmaker_eval/build_site.py _site - uses: actions/configure-pages@v5 - if: steps.results.outputs.ready == 'true' - uses: actions/upload-pages-artifact@v3 - if: steps.results.outputs.ready == 'true' with: path: _site deploy: needs: build - if: needs.build.outputs.ready == 'true' runs-on: ubuntu-latest environment: name: github-pages diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7e220db..a7d4857 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -41,7 +41,7 @@ jobs: # matchmaker_eval/test_audio.py, which tests/test_audio_runner.py loads. run: | python -m pip install --upgrade pip - python .github/install_matchmaker.py + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" pip install pyyaml pydantic-settings tabulate wandb pytest - name: Run the tests diff --git a/.github/workflows/validate-submission.yml b/.github/workflows/validate-submission.yml index 25c37ea..968972f 100644 --- a/.github/workflows/validate-submission.yml +++ b/.github/workflows/validate-submission.yml @@ -54,8 +54,11 @@ jobs: # matchmaker_eval/utils.py, and nothing else. run: | python -m pip install --upgrade pip - # The shared installer fixes the library sources for every job. - python .github/install_matchmaker.py + # Pinned to the matchmaker 0.4.0 release (tag v0.4.0, main after #73): + # its sources are part of the evaluation key, so every row of a run + # must be scored by the same matchmaker. Move every workflow together + # when the pin changes, and re-run the entries: their keys will change. + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" pip install pyyaml pydantic-settings - name: Find the submissions touched by this pull request diff --git a/.gitignore b/.gitignore index 4155576..2d5e45c 100644 --- a/.gitignore +++ b/.gitignore @@ -182,8 +182,26 @@ reports/ *exports/ scripts/ -# Results are published as CI artifacts and release assets. -/results/ +# The top-level results/ directory is the published benchmark record, so it is +# tracked. `*results/` above would otherwise swallow it, and git cannot +# re-include a file whose parent directory is excluded — hence the explicit +# un-ignore of the directory before its contents are filtered. +!/results/ +/results/* +!/results/leaderboard.json +!/results/leaderboard.csv +# Per-dataset boards (linked from the page) and every evaluation key's table: +# pages.yml builds the site from what is committed here. +!/results/leaderboard-*.json +!/results/leaderboard-*.csv +!/results/archive/ +!/results/submissions/ +!/results/details/ +# Per-submission runs: keep the metrics record, drop the reproducible bulk +# (alignment paths and plots, ~8 MB per submission per fold). Those are +# published as workflow artifacts instead. +/results/submissions/*/* +!/results/submissions/*/metrics.json # Assembled leaderboard site (matchmaker_eval/build_site.py) _site/ diff --git a/README.md b/README.md index 36bb9e8..9feefbc 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,6 @@ data** — the evaluation runs on GitHub's runners, which fetch what they need. | **Library** | [matchmaker](https://github.com/pymatchmaker/matchmaker) | | **Metrics** | beat error, ms error, tracking rate, real-time factor | -Full results are published as [Releases](https://github.com/pymatchmaker/matchmaker_benchmark/releases). -See [publishing results](docs/maintaining.md#staging-a-run-before-it-is-published). - ## Submit a score follower ```bash @@ -86,14 +83,13 @@ code; after merge it is evaluated and appears on the leaderboard. │ │ │ fetches its own data, │ │ │ runs 146 pieces in │ │ │ parallel shards, - │ │ │ uploads results for release + │ │ │ commits the leaderboard │ │ │ │ └──────────────── leaderboard on GitHub Pages ◄─────────────────────┘ ``` Review is the trust boundary: CI executes submitted code, it does not sandbox -it. A maintainer starts full evaluation and publication explicitly; -publication runs from `main`. +it. Everything after merge is automatic. ## Folds @@ -238,7 +234,7 @@ matchmaker_eval/ merge_references.py — regroup and merge a sharded multi-method run export_details.py — every pooled metric per dataset, per-piece detail and decimated alignment paths - load_folds.py, make_folds.py — fold definitions and their integrity checks + folds.py, make_folds.py — fold definitions and their integrity checks fetch_data.py — locate a fold's data (--source), check it is all present (--verify), or download just what it needs verify_equivalence.py — proves submissions are scored like built-in methods @@ -266,8 +262,8 @@ docs/ — contributor and maintainer documentation, and the GitHub Pages leaderboard .github/workflows/ validate-submission.yml — pull-request checks (no secrets, read-only token) - evaluate.yml — explicitly dispatched evaluation in parallel shards - pages.yml — preserves selected CI runs in a release and publishes its snapshot + evaluate.yml — post-merge evaluation in parallel shards + pages.yml — publishes the leaderboard ``` ## Acknowledgments diff --git a/data/builtin_methods.yaml b/data/builtin_methods.yaml index 178328d..8003cca 100644 --- a/data/builtin_methods.yaml +++ b/data/builtin_methods.yaml @@ -15,15 +15,6 @@ # leaderboard links each reference's citation to that entry. midi: - dannenberg: - name: Dynamic programming (Bloch and Dannenberg) - authors: ["Bloch and Dannenberg (1985)"] - bib: Bloch1985Real - description: > - Dynamic grouping of individual MIDI notes against score chords, using - a dynamic-programming rating for matched, missing and extra notes. - Reports a match when its rating exceeds the previous maximum. - pthmm: name: Pitch HMM authors: ["Cancino-Chacón et al. (2023)"] diff --git a/data/data_sources.yaml b/data/data_sources.yaml index cca5fda..c765367 100644 --- a/data/data_sources.yaml +++ b/data/data_sources.yaml @@ -35,15 +35,6 @@ branches: # test-only beyond-piano corpora, held with the eval data beyond_piano: eval -# Auxiliary experiments use immutable manifests from the same data repository. -frozen_sources: - diagnostics: - commit: 2840905846c62074555d7be566757ac6fce2d179 - manifest_sha256: 742ca3ab6beab0ce379f20e6f293c07a4a227f2312150a09cf9541e58786ad32 - amt: - commit: 74298e15338a7b0431e96443e965025705736f61 - manifest_sha256: d35985e237869a19455bc4e37d07d92a6776232879d22f8b520b66b258ad3b90 - # Where a fold's / sits inside that repository. Change this if # the repository nests the datasets under a subdirectory, e.g. "data/{dataset}/{path}". layout: "{dataset}/{path}" diff --git a/docs/index.html b/docs/index.html index b185538..a7fbc57 100644 --- a/docs/index.html +++ b/docs/index.html @@ -672,8 +672,7 @@

Submitting

Write one Python file and open a pull request. How to submit · Evaluation protocol · - Download CSV · - Download full results + Download CSV

diff --git a/docs/maintaining.md b/docs/maintaining.md index 949a1ee..0164e35 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -6,9 +6,11 @@ decisions baked into this setup. ## Reviewing a submission CI has already checked structure, metadata and that the follower runs on one -piece. **Review is the trust boundary**: `evaluate.yml` executes the submitted -code on a machine that holds the datasets. Read the code before merging it or -dispatching a full evaluation. +piece. **Review is the trust boundary**: merging a submission's pull request +into `submissions` is what triggers `evaluate.yml`, which executes the +submitted code on a machine that holds the datasets, immediately and with no +further review in between. Nothing sandboxes it. Read the code before you +merge, not after. `validate_submission.py` prints `review` lines for things worth a second look — network access, subprocesses, `.match` file access, reaching for @@ -30,21 +32,20 @@ What to check by hand: interesting research but will take a long time on 146 pieces. The per-piece budget is 15 minutes. -When in doubt, ask in the pull request. See "Staging a run before it is published" -below for the evaluation and publication steps. +When in doubt, ask in the pull request. Merging into `submissions` is what +starts the evaluation — see "Staging a run before it is published" below. ## Running the evaluation -After merge, dispatch **Evaluate submissions** on `main` with the submission -directory. It runs on GitHub's runners and uploads merged results and a preview. -Nobody has to hold the data locally. +After merge, `.github/workflows/evaluate.yml` runs the eval fold on GitHub's own +runners and commits the leaderboard. Nobody has to hold the data locally. ``` plan ──► evaluate (8 parallel shards) ──► merge │ │ │ │ each shard: combines the shards, which submission, check out the data repo, rebuilds the leaderboard, -which input type, verify its slice is present, uploads artifacts +which input type, verify its slice is present, commits results/ how many shards, run it, upload results where the data is ``` @@ -230,30 +231,14 @@ Actions -> Evaluate references -> Run workflow input_type: both only: (empty = all described) shards: 8 ``` -The `fold` input selects what to run. Only `eval` feeds the leaderboard; the -others are archived as artifacts. - -| fold | input_type | shards | what it runs | -| --- | --- | --- | --- | -| `eval` | both | 8 | the piano leaderboard | -| `beyond_piano` | audio | 8 | the non-piano corpora (audio only) | -| `diagnostics` | both | 4 | the manuscript diagnostic suites in `matchmaker_eval/run_diagnostics.py` | -| `offline` | audio | 8 | the offline reference in `matchmaker_eval/run_offline.py` | -| `amt_reference` | midi | 4 | symbolic followers on frozen AMT output, `matchmaker_eval/run_amt.py` | -| `ophmm_playthrough` | midi | 4 (fixed) | MIDI OPHMM with global transitions on and off | - -Each run uploads one `benchmark-results-` artifact with every merged -method directory: `metrics.json`, the full `wp_`/`gt_` paths and the -`meter_.json` maps. - It mirrors `evaluate.yml` exactly — same data checkout, same eight-way round-robin sharding, same merge, same leaderboard rebuild — and fans out over every method described in `data/builtin_methods.yaml`. Both workflows pin `OMP_NUM_THREADS=1` so a runner's core count cannot move the timing columns between one entry and the next. -Every described method runs as one job per shard; the jobs queue against the -account's concurrency limit rather than all starting at once. To evaluate a single +11 described methods x 8 shards is 88 jobs, which queue against the account's +concurrency limit rather than all starting at once. To evaluate a single reference instead, `Evaluate submissions` takes a `method` and `input_type`. Accuracy is unaffected by any of this — an alignment path is a deterministic @@ -315,27 +300,41 @@ differ on their own. ### Staging a run before it is published -Evaluation and publication are separate. Evaluation workflows are dispatched -explicitly and upload merged artifacts and a preview. Publication runs from -`main` after the code has been squash-merged. Reviewed branch runs can be -reused when the merged evaluation logic and data match. - -Inspect the required evaluations, then dispatch **Publish leaderboard** on -`main`: +`submissions` is where evaluation happens; `main` is where it is published. -- `source_runs`: the completed run IDs, separated by spaces. Later listed runs - replace earlier entries for the same method, so put a corrected method's - rerun after the full evaluation. Methods not listed are carried over from the - latest release. -- `release_tag`: a new `benchmark-*` tag. Leave `source_runs` empty to redeploy - that release, or both empty to redeploy the latest one. - -The workflow attaches the selected artifacts, a `benchmark-snapshot.zip` for -the site and `SHA256SUMS` to the release, then deploys. Actions artifacts -expire, so publish final runs before they do. - -A manually dispatched evaluation runs only the requested methods or submission; -publication reuses those outputs and never executes a follower. +| branch | runs the full evaluation | publishes to the site | +| --- | --- | --- | +| `submissions` | yes | **no** | +| `main` | no — just receives the result | yes | + +The order is: + +1. review the code, then merge the submission's pull request into + `submissions`. It is restricted to that one `submissions//` + directory (see `validate-submission.yml`), and CI has only smoke-tested it + on the committed example before this point. +2. That merge is what `evaluate.yml` watches for. It diffs `submissions/` + against its own previous commit and evaluates every directory that is new + or has changed since — including any other submission that was already + waiting there — skipping ones that are unchanged and already evaluated. + This is the first time the submitted code actually runs against the real + datasets, which is why review has to happen at step 1: nothing re-reviews + a submission between merging it and this run. +3. It rebuilds the leaderboard and commits `results/` to `submissions`. + Nothing is published yet — read `results/leaderboard.json` there (or the + `leaderboard-site` artifact for the real page) and rerun or withdraw + anything that looks wrong. +4. When you are satisfied, merge `submissions` into `main`. This is a plain + merge of the already-computed `results/` — it does not re-run anything — + and the resulting commit is what `pages.yml` publishes. + +`pages.yml` is deliberately `main`-only and only triggers on a change to +`results/leaderboard.json`, so nothing reaches the site until step 4 — a bad +run is a branch to fix rather than a page to correct. + +To re-run something already evaluated — after a pipeline bug fix, say — the +diff-based skip in step 2 only applies to the automatic trigger. Dispatch +`evaluate.yml` manually with that submission's name to force it. ### Withdrawing or replacing a published result @@ -343,13 +342,11 @@ A leaderboard row is not a database record. It is derived from `results/submissions//metrics.json` every time `leaderboard.py` runs, so results can always be corrected. -**To replace one**, evaluate the corrected code on main and select that run in -a new result release. Its completed entries replace those entries in the new -snapshot; the previous release and its raw outputs remain available. +**To replace one** — a rerun after a bug fix — just evaluate again. +`run_submission.py` overwrites the same directory and the next rebuild picks up +the new numbers. Nothing needs deleting. -**To withdraw one**, first download the released snapshot to a working directory -and set `MATCHMAKER_RESULTS_DIR` to that directory. Use `retract.py` rather than -deleting by hand: it also +**To withdraw one**, use `retract.py` rather than deleting by hand: it also removes the per-piece detail file, which the site fetches by name and which would otherwise stay readable after the row disappeared. @@ -369,8 +366,6 @@ a result that was on the leaderboard and is not any more is itself a fact about the leaderboard, so it is published rather than quietly erased. The run is moved to `results/retracted//`, so `--reason` is required and `--undo` puts it back. `--purge` deletes instead of archiving, and cannot be undone. -These commands edit the local snapshot only; publish the corrected snapshot -as a new release. `export_details.py` also removes any detail file whose run has gone, so a hand-deleted result cannot leave one behind either. @@ -480,10 +475,9 @@ somewhere else. ## Publishing -`.github/workflows/pages.yml` combines `docs/` with the selected release snapshot -and deploys it to GitHub Pages. A documentation update reuses the latest published -snapshot. `MATCHMAKER_RESULTS_DIR` points the export and site-building scripts -at a temporary directory outside the code checkout. +`.github/workflows/pages.yml` builds the site from `docs/` plus a copy of +`results/leaderboard*.json`, the CSVs and `results/details/`, and deploys it to +GitHub Pages. It runs whenever the leaderboard changes. ### What the site can show @@ -535,6 +529,6 @@ about 1 MB, or 300 KB over the wire once Pages gzips it. `PATH_POINTS` in A Hugging Face Space is a reasonable second surface — sorting and filtering are easier there than in a static page, and it reaches a different audience. It needs nothing new from this repository: a Space can read -`leaderboard.json` from the published Pages site, so it stays a consumer of -the same file. Add a push step here only if +`results/leaderboard.json` straight from the raw GitHub URL, so it stays a +consumer of the same file and cannot drift from it. Add a push step here only if a Space needs to be told to refresh. diff --git a/docs/submitting.md b/docs/submitting.md index d9f00e9..7a59f33 100644 --- a/docs/submitting.md +++ b/docs/submitting.md @@ -1,9 +1,11 @@ # Submitting a score follower The benchmark takes submissions as pull requests **against the `submissions` -branch**, not `main`. You add one directory and CI checks it on the bundled -example. A maintainer reviews and squash-merges the code into `main`, explicitly -runs the full evaluation, and selects the completed run for a result release. +branch**, not `main`. You add one directory, CI checks it, and once a +maintainer reads the code and merges your pull request, that merge itself +evaluates it — along with any other new or changed submission already waiting +on `submissions`. A maintainer publishes the result to the live site by +merging `submissions` into `main` whenever they judge the batch ready. ``` you GitHub maintainer GitHub Actions @@ -12,17 +14,18 @@ runs the full evaluation, and selects the completed run for a result release. ├────────────────►│ structure + contract │ │ │ ├──► smoke test on the ──────┤ │ │ │ committed example │ reads the code │ - │ │ (no data needed) │ and squash-merges │ - │ │ │ into main │ + │ │ (no data needed) │ and merges into │ + │ │ │ `submissions` │ │ │ ├───────────────────►│ │ │ │ fetches its own data, - │ │ │ explicitly evaluates - │ │ │ the selected entry in + │ │ │ evaluates every new or + │ │ │ changed submission in │ │ │ parallel shards, - │ │ │ uploads results - │ │ │ and a preview + │ │ │ commits the result + │ │ │ to `submissions` │ │ │ │ - │ │ ...maintainer checks and releases the results... + │ │ ...whenever ready, the maintainer merges + │ │ `submissions` into `main` to publish... │ │ │ │ └──────────────── leaderboard on GitHub Pages ◄─────────────────────┘ ``` @@ -176,9 +179,10 @@ GitHub will hold the workflow until a maintainer approves the run. ## 6. After merge -A maintainer dispatches **Evaluate submissions** on the merged `main` commit, -specifying your submission directory. It runs on the eval fold in parallel -shards and uploads the result as an artifact. +Merging your pull request into `submissions` is what evaluates it — along +with any other submission already on `submissions` that is new or has +changed since the last time this ran, skipping anything unchanged. It runs on +the eval fold, in parallel shards, and commits the result to `submissions`. It splits the 146 pieces across parallel jobs, each of which fetches only its own share of the data, so the whole thing finishes in well under an hour even @@ -186,19 +190,20 @@ though a single job could not. The merged result is identical to an unsharded run. The full per-piece output (alignment paths, per-piece metrics) is attached to -the workflow run as an artifact for 30 days. +the workflow run as an artifact for 30 days; the summary record stays in +`results/submissions/your-name/metrics.json` on `submissions`. -A maintainer checks the result. Selected final runs are then preserved as downloadable -[release assets](https://github.com/pymatchmaker/matchmaker_benchmark/releases). -The release snapshot supplies the live leaderboard at +This does not publish yet. A maintainer reads the result there and decides +when to merge `submissions` into `main`, which is what actually updates the +live leaderboard at [pymatchmaker.github.io/matchmaker_benchmark](https://pymatchmaker.github.io/matchmaker_benchmark/). ## Updating a submission Open a new pull request against the same directory, still based on -`submissions`. After review and merge, a maintainer evaluates the updated entry -on `main`. A new result release publishes that evaluation; -previous releases remain available. If the change is substantial enough that it +`submissions`. Merging it evaluates your submission again and replaces its +row on `submissions`; the live leaderboard picks up the change the next time +`submissions` merges into `main`. If the change is substantial enough that it is really a different method, submit it under a new name so both can be compared. diff --git a/matchmaker_eval/build_site.py b/matchmaker_eval/build_site.py index 6f56779..68d15ef 100644 --- a/matchmaker_eval/build_site.py +++ b/matchmaker_eval/build_site.py @@ -25,9 +25,10 @@ import argparse import shutil -from matchmaker_eval.load_folds import REPO_ROOT, RESULTS_DIR +from matchmaker_eval.folds import REPO_ROOT DOCS_DIR = REPO_ROOT / "docs" +RESULTS_DIR = REPO_ROOT / "results" class SiteError(Exception): @@ -44,7 +45,7 @@ def build(destination: Path) -> dict: shutil.copytree(DOCS_DIR, destination) summary = {"boards": [], "details": 0, "archives": 0, "missing": []} - for name in ("leaderboard.json", "leaderboard.csv", "release.json"): + for name in ("leaderboard.json", "leaderboard.csv"): source = RESULTS_DIR / name if source.exists(): shutil.copy2(source, destination / name) diff --git a/matchmaker_eval/download_data.py b/matchmaker_eval/download_data.py index d089ea6..73ae5a6 100644 --- a/matchmaker_eval/download_data.py +++ b/matchmaker_eval/download_data.py @@ -19,7 +19,7 @@ import zipfile from urllib.request import urlretrieve -from matchmaker_eval.load_folds import DATA_ROOT +from matchmaker_eval.folds import DATA_ROOT # TODO: update URLs when data hosting is finalized DATASETS = { diff --git a/matchmaker_eval/estimate_perf_tempo.py b/matchmaker_eval/estimate_perf_tempo.py index ad42ddd..08246db 100644 --- a/matchmaker_eval/estimate_perf_tempo.py +++ b/matchmaker_eval/estimate_perf_tempo.py @@ -15,7 +15,7 @@ import partitura as pt from partitura.score import merge_parts -from matchmaker_eval.load_folds import DATA_ROOT, nested_dataset_root +from matchmaker_eval.folds import DATA_ROOT, nested_dataset_root WORKING_DIR = Path(__file__).parent.parent #: The `example` dataset is the one piece committed to this repository under diff --git a/matchmaker_eval/eval.py b/matchmaker_eval/eval.py index 0c99dbf..a5d33eb 100644 --- a/matchmaker_eval/eval.py +++ b/matchmaker_eval/eval.py @@ -302,41 +302,46 @@ def run_score_following( run_name=run_name, level=granularity, ) - # Tracking verification: a scoring error must not silently drop the verdict. - wp_for_check = wp.T - if gt_pairs is not None: - gt_for_check = gt_pairs - else: - score_annots_for_gt = mm.build_score_annotations( - level=granularity, return_type="beats" - ) - min_len = min(len(score_annots_for_gt), len(perf_annotations)) - gt_for_check = np.column_stack( - [perf_annotations[:min_len], score_annots_for_gt[:min_len]] - ) - meter = score_meter_map(mm.score_part) - factors = musical_beat_factors(gt_for_check[:, 1], meter) - threshold = TRACKING_THRESHOLDS[mm.input_type] - tracking = check_tracking(wp_for_check, gt_for_check, threshold=threshold, - beat_factors=factors) - results["tracked"] = tracking["tracked"] - results["max_deviation"] = tracking["max_deviation"] - results["n_failed_segments"] = tracking["n_failed"] - results["tracking_criterion"] = { - key: tracking[key] for key in ("error_unit", "threshold", "window_duration") - } - if save_dir is not None and run_name: - (Path(save_dir) / f"meter_{run_name}.json").write_text(json.dumps(meter, indent=2) + "\n") - - if save_plots and save_dir is not None and run_name: - plot_tracking( - wp_for_check, - gt_for_check, - title=f"{config.method} #{run_name}", - save_path=Path(save_dir) / f"tracking_{run_name}.png", - threshold=threshold, - beat_factors=factors, + # Tracking verification + try: + wp_for_check = wp.T + if gt_pairs is not None: + gt_for_check = gt_pairs + else: + score_annots_for_gt = mm.build_score_annotations( + level=granularity, return_type="beats" + ) + min_len = min(len(score_annots_for_gt), len(perf_annotations)) + gt_for_check = np.column_stack( + [perf_annotations[:min_len], score_annots_for_gt[:min_len]] + ) + meter = score_meter_map(mm.score_part) + factors = musical_beat_factors(gt_for_check[:, 1], meter) + threshold = TRACKING_THRESHOLDS[mm.input_type] + tracking = check_tracking( + wp_for_check, gt_for_check, threshold=threshold, beat_factors=factors ) + results["tracked"] = tracking["tracked"] + results["max_deviation"] = tracking["max_deviation"] + results["n_failed_segments"] = tracking["n_failed"] + results["tracking_criterion"] = { + key: tracking[key] for key in ("error_unit", "threshold", "window_duration") + } + if save_dir is not None and run_name: + meter_path = Path(save_dir) / f"meter_{run_name}.json" + meter_path.write_text(json.dumps(meter, indent=2) + "\n") + + if save_plots and save_dir is not None and run_name: + plot_tracking( + wp_for_check, + gt_for_check, + title=f"{config.method} #{run_name}", + save_path=Path(save_dir) / f"tracking_{run_name}.png", + threshold=threshold, + beat_factors=factors, + ) + except Exception: + pass if save_dir is not None and run_name and not dry_run: with open(Path(save_dir) / f"{run_name}.json", "w") as f: diff --git a/matchmaker_eval/eval_symbolic.py b/matchmaker_eval/eval_symbolic.py index b057cd3..0d95cd8 100644 --- a/matchmaker_eval/eval_symbolic.py +++ b/matchmaker_eval/eval_symbolic.py @@ -84,7 +84,7 @@ warnings.filterwarnings("ignore") -from matchmaker_eval.load_folds import DATA_ROOT, nested_dataset_root +from matchmaker_eval.folds import DATA_ROOT, nested_dataset_root DATASET_DIR = { "validation": DATA_ROOT, diff --git a/matchmaker_eval/export_details.py b/matchmaker_eval/export_details.py index 98b455c..e6acf6e 100644 --- a/matchmaker_eval/export_details.py +++ b/matchmaker_eval/export_details.py @@ -38,11 +38,11 @@ import numpy as np from matchmaker.utils.eval import transfer_positions -from matchmaker_eval.load_folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR +from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT from matchmaker_eval.leaderboard import ACCURACY_COLUMNS, without_nan -SUBMISSION_RESULTS = RESULTS_DIR / "submissions" -DETAILS_DIR = RESULTS_DIR / "details" +SUBMISSION_RESULTS = REPO_ROOT / "results" / "submissions" +DETAILS_DIR = REPO_ROOT / "results" / "details" #: Points kept per polyline. A leaderboard plot is a few hundred pixels wide; #: beyond roughly this many points the extra coordinates are invisible. @@ -60,8 +60,8 @@ #: measurement of the follower, so it is excluded here too — otherwise it lands #: in the site's metric table as a boolean among the error statistics. The run's #: count of it is published once, alongside n_tracked. -#: ``data_sha256`` names the bytes a piece was scored with (see evaluation_key.py). -#: It records an input, not a measurement, so it sits beside the identity fields. +#: ``data_sha256`` names the bytes a piece was scored with (see provenance.py): +#: provenance, not a measurement. It is published beside the identity fields. PIECE_IDENTITY = ( "tracking_criterion", "index", @@ -353,7 +353,7 @@ def main(): # evaluation it follows had already succeeded. print(f"No complete {args.fold}-fold runs to export.") return 0 - print(f"\nwrote {written} file(s) to {DETAILS_DIR}") + print(f"\nwrote {written} file(s) to {DETAILS_DIR.relative_to(REPO_ROOT)}") return 0 diff --git a/matchmaker_eval/fetch_data.py b/matchmaker_eval/fetch_data.py index 6928e40..e9fce0b 100644 --- a/matchmaker_eval/fetch_data.py +++ b/matchmaker_eval/fetch_data.py @@ -36,7 +36,7 @@ import yaml -from matchmaker_eval.load_folds import DATA_ROOT, REPO_ROOT, load_fold, shard_of +from matchmaker_eval.folds import DATA_ROOT, REPO_ROOT, load_fold, shard_of CONFIG_PATH = REPO_ROOT / "data" / "data_sources.yaml" CHECKSUM_DIR = REPO_ROOT / "data" / "checksums" @@ -113,21 +113,12 @@ def load_config() -> dict: value = os.environ.get(variable) if value: config[key] = value - if key == "branch": - # An explicit revision override applies to every selected fold. - config["branches"] = {} # An override of the address implies fetching is wanted, even if the # committed config still has it switched off. config["enabled"] = True return config -def frozen_source(name: str) -> dict: - config = load_config() - return {"repository": f"{config['owner']}/{config['repo']}", - **config["frozen_sources"][name]} - - #: Prefixes GitHub uses for access tokens. If one of these turns up where an #: environment variable *name* belongs, someone has pasted the secret itself. TOKEN_PREFIXES = ("github_pat_", "ghp_", "gho_", "ghs_", "ghu_", "ghr_") @@ -353,7 +344,7 @@ def metadata_path(dataset: str, branch: str = "main") -> Path: caching both to one path would let whichever was fetched first silently stand in for the other. """ - from matchmaker_eval.load_folds import dataset_root + from matchmaker_eval.folds import dataset_root root = dataset_root(dataset) if branch in ("main", "master"): @@ -380,7 +371,7 @@ def fetch_root_metadata(fold: Optional[str], force: bool = False) -> Optional[Pa reasonable shapes; this looks for the root form and returns None when the branch does not use it, so the caller can fall back to the per-dataset one. """ - from matchmaker_eval.load_folds import DATA_ROOT + from matchmaker_eval.folds import DATA_ROOT config = load_config() if not config.get("enabled"): diff --git a/matchmaker_eval/load_folds.py b/matchmaker_eval/folds.py similarity index 99% rename from matchmaker_eval/load_folds.py rename to matchmaker_eval/folds.py index 9730712..1e307b4 100644 --- a/matchmaker_eval/load_folds.py +++ b/matchmaker_eval/folds.py @@ -41,7 +41,6 @@ REPO_ROOT = Path(__file__).resolve().parent.parent FOLD_DIR = REPO_ROOT / "data" / "folds" -RESULTS_DIR = Path(os.environ.get("MATCHMAKER_RESULTS_DIR", REPO_ROOT / "results")) #: Root under which the (undistributed) datasets are expected. DATA_ROOT = Path(os.environ.get("MATCHMAKER_DATA_DIR", "~/data")).expanduser() diff --git a/matchmaker_eval/leaderboard.py b/matchmaker_eval/leaderboard.py index 47c39ca..4201a2b 100644 --- a/matchmaker_eval/leaderboard.py +++ b/matchmaker_eval/leaderboard.py @@ -6,7 +6,7 @@ Reads every ``results/submissions/*/metrics.json`` produced by ``run_submission.py``, keeps the runs made on the **eval** fold, and writes - results/leaderboard.json full records, with each fold's evaluation key + results/leaderboard.json full records, with per-fold provenance results/leaderboard.csv the headline columns, for papers results/leaderboard-.json the same entries ranked on one dataset results/leaderboard-.csv @@ -46,11 +46,12 @@ from matchmaker.utils.eval import TOLERANCES_IN_BEATS -from matchmaker_eval.load_folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR -from matchmaker_eval.evaluation_key import SHARED_COMPONENTS +from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT +from matchmaker_eval.provenance import SHARED_COMPONENTS from matchmaker_eval.retract import read_retractions from matchmaker_eval.submission import read_descriptions +RESULTS_DIR = REPO_ROOT / "results" SUBMISSION_RESULTS = RESULTS_DIR / "submissions" LEADERBOARD_JSON = RESULTS_DIR / "leaderboard.json" LEADERBOARD_CSV = RESULTS_DIR / "leaderboard.csv" @@ -76,7 +77,7 @@ def dataset_paths(dataset: str) -> tuple: "skewness", "kurtosis", "smoothness", "median_b_all", "rtf", "feature_latency_ms", "inference_latency_ms", "n_pieces", "n_tracked", "estimated_bpm", "evaluated", - # The conditions the row was scored under (see evaluation_key.py). Cite it + # The conditions the row was scored under (see provenance.py). Cite it # with any number taken from this file. "evaluation_key", ] @@ -586,7 +587,7 @@ def main(): written = write(leaderboard) print(render_table(leaderboard)) - print(f"\nwrote {', '.join(written)} to {RESULTS_DIR}") + print(f"\nwrote {', '.join(written)} to {RESULTS_DIR.relative_to(REPO_ROOT)}") return 0 diff --git a/matchmaker_eval/make_folds.py b/matchmaker_eval/make_folds.py index bd82728..ad8e090 100644 --- a/matchmaker_eval/make_folds.py +++ b/matchmaker_eval/make_folds.py @@ -45,7 +45,7 @@ import csv from collections import Counter, defaultdict -from matchmaker_eval.load_folds import FOLD_DIR, REPO_ROOT, Piece, load_fold, write_fold +from matchmaker_eval.folds import FOLD_DIR, REPO_ROOT, Piece, load_fold, write_fold METADATA_DIR = REPO_ROOT / "data" diff --git a/matchmaker_eval/merge_references.py b/matchmaker_eval/merge_references.py index 62cc41a..b006d31 100644 --- a/matchmaker_eval/merge_references.py +++ b/matchmaker_eval/merge_references.py @@ -24,12 +24,11 @@ sys.path.insert(0, str(_path)) import argparse -import json import re import shutil from collections import defaultdict -from matchmaker_eval.load_folds import REPO_ROOT +from matchmaker_eval.folds import REPO_ROOT from merge_shards import MergeError, merge #: refshard--- @@ -90,30 +89,6 @@ def merge_all(download_dir: Path, output_root: Path, staging: Path) -> dict: return report -def output_for_fold(fold: str) -> Path: - """Keep auxiliary folds from replacing the published piano records.""" - return DEFAULT_OUTPUT if fold == "eval" else REPO_ROOT / "results" / "runs" / fold - - -def check_fold(download_dir: Path, expected: str) -> None: - """Validate the entire batch before any existing result is overwritten.""" - for entry, shards in group(download_dir).items(): - for shard in shards: - actual = json.loads((shard / "metrics.json").read_text()).get("fold") - if actual != expected: - raise MergeError(f"{entry}: expected fold {expected!r}, found {actual!r}") - - -def check_expected_entries(download_dir: Path, expected: list) -> None: - """An entirely missing method is a failed batch, not a smaller benchmark.""" - found = set(group(download_dir)) - if found != set(expected): - raise MergeError( - f"reference entries differ from plan: missing={sorted(set(expected)-found)}, " - f"unexpected={sorted(found-set(expected))}" - ) - - def main(): parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument( @@ -122,11 +97,9 @@ def main(): parser.add_argument( "--output", type=Path, - default=None, - help="where merged records go (default depends on --fold)", + default=DEFAULT_OUTPUT, + help=f"where merged records go (default: {DEFAULT_OUTPUT})", ) - parser.add_argument("--fold", default="eval", help="fold to merge; non-eval folds are isolated") - parser.add_argument("--expected-entries-json", help="JSON array of every entry planned by CI") parser.add_argument( "--staging", type=Path, @@ -137,10 +110,7 @@ def main(): staging = args.staging or (args.download_dir.parent / "refgrouped") try: - if args.expected_entries_json is not None: - check_expected_entries(args.download_dir, json.loads(args.expected_entries_json)) - check_fold(args.download_dir, args.fold) - report = merge_all(args.download_dir, args.output or output_for_fold(args.fold), staging) + report = merge_all(args.download_dir, args.output, staging) except MergeError as e: print(f"\n{e}", file=sys.stderr) return 1 @@ -161,7 +131,7 @@ def main(): f"{info['n_tracked']:>8} {status}" ) print(f"\n{len(report) - incomplete}/{len(report)} entry(ies) complete.") - return 1 if incomplete else 0 + return 0 if __name__ == "__main__": diff --git a/matchmaker_eval/merge_shards.py b/matchmaker_eval/merge_shards.py index 7558b56..75e502b 100644 --- a/matchmaker_eval/merge_shards.py +++ b/matchmaker_eval/merge_shards.py @@ -27,8 +27,8 @@ from utils import dataset_summaries, pooled_summaries -from matchmaker_eval.load_folds import REPO_ROOT -from matchmaker_eval.evaluation_key import SHARED_COMPONENTS, evaluation_record +from matchmaker_eval.folds import REPO_ROOT +from matchmaker_eval.provenance import SHARED_COMPONENTS, evaluation_record class MergeError(Exception): diff --git a/matchmaker_eval/preprocess_urmp.py b/matchmaker_eval/preprocess_urmp.py index c1a78cd..8bb3100 100644 --- a/matchmaker_eval/preprocess_urmp.py +++ b/matchmaker_eval/preprocess_urmp.py @@ -27,7 +27,7 @@ import numpy as np import pandas as pd import soundfile as sf -from matchmaker_eval.load_folds import DATA_ROOT +from matchmaker_eval.folds import DATA_ROOT from matchmaker import Matchmaker WORKING_DIR = Path(__file__).parent.parent diff --git a/matchmaker_eval/preprocess_winterreise.py b/matchmaker_eval/preprocess_winterreise.py index 14e7a73..848a485 100644 --- a/matchmaker_eval/preprocess_winterreise.py +++ b/matchmaker_eval/preprocess_winterreise.py @@ -27,7 +27,7 @@ import numpy as np import pandas as pd import partitura as pt -from matchmaker_eval.load_folds import DATA_ROOT +from matchmaker_eval.folds import DATA_ROOT from matchmaker_eval.utils import source_annotation diff --git a/matchmaker_eval/evaluation_key.py b/matchmaker_eval/provenance.py similarity index 77% rename from matchmaker_eval/evaluation_key.py rename to matchmaker_eval/provenance.py index 57f8a7b..533d2bc 100644 --- a/matchmaker_eval/evaluation_key.py +++ b/matchmaker_eval/provenance.py @@ -1,21 +1,30 @@ -"""Evaluation key: a short hash of the conditions a run was scored under. +"""The evaluation key: one short hash naming the conditions a run was scored under. -The leaderboard ranks two rows together only when everything that decides their -numbers, apart from the follower itself, is the same: +Two leaderboard rows are only comparable when everything that decides their +numbers — apart from the follower itself — was the same. That is: fold_sha256 the fold CSV: which pieces, their paths, estimated_bpm - data_sha256 the score, performance and ground-truth files of every piece - scoring_sha256 the benchmark's scoring code: the evaluation and tracking - modules, and the parts of run_submission.py that decide - ground truth and the tracked verdict - matchmaker_sha256 the installed matchmaker sources - partitura the version that parses every score and match file - -``evaluation_key()`` hashes these into ``ek1-<12 hex>``. The ``ek1`` prefix names -which components are included, and changes whenever that set changes. - -Components hash file contents rather than commit ids, so an unrelated commit -(a README edit, a new corpus in the data repository) does not change the key. + data_sha256 the bytes of every file a piece was scored with + (score, the performance that was streamed, the match / + annotation file), over the whole fold + scoring_sha256 the benchmark's own scoring code: the evaluation and + tracking modules, and the parts of run_submission.py + that decide ground truth and the tracked verdict + matchmaker_sha256 the installed matchmaker sources. They hold the ground + truth resolution, the beat errors, the tracking + windows and SPARC, and the reference followers + partitura how every score and match file is parsed + +``evaluation_key()`` folds these into ``ek1-<12 hex>``. Same key, same +conditions; a different key means at least one of them changed. The ``ek1`` +prefix is the scheme: if what goes into the key ever changes, the prefix does +too, so a key never silently changes meaning. + +Content hashes, not commits, on purpose. A data-repository commit changes when +an unrelated corpus is added; a matchmaker commit changes when a follower +nobody evaluated is edited in a way that does not touch the sources (a README); +the benchmark commit changes with every results commit. The bytes that were +actually read are what decide the numbers, so they are what is hashed. """ import hashlib @@ -25,7 +34,7 @@ from pathlib import Path from typing import Iterable, Optional -from matchmaker_eval.load_folds import REPO_ROOT +from matchmaker_eval.folds import REPO_ROOT #: Bumped whenever the set of components, or how one is computed, changes. SCHEME = "ek1" diff --git a/matchmaker_eval/release_results.py b/matchmaker_eval/release_results.py deleted file mode 100644 index bbb01c1..0000000 --- a/matchmaker_eval/release_results.py +++ /dev/null @@ -1,244 +0,0 @@ -"""Publish completed CI runs as a release, or fetch a published snapshot. - -Called by pages.yml with the GitHub CLI and GH_TOKEN; it never runs a follower. -Results are written to MATCHMAKER_RESULTS_DIR, outside the source checkout. -""" - -import argparse -import json -import os -from pathlib import Path -import re -import shutil -import subprocess -import sys -import tempfile -import zipfile - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -from matchmaker_eval.evaluation_key import file_sha256 -from matchmaker_eval.load_folds import REPO_ROOT, RESULTS_DIR - -SNAPSHOT = "benchmark-snapshot.zip" - - -def gh(*args): - return subprocess.check_output(["gh", *args], text=True).strip() - - -def api(path): - return json.loads(gh("api", path)) - - -def releases(repo): - pages = json.loads(gh("api", "--paginate", "--slurp", f"repos/{repo}/releases")) - return [release for page in pages for release in page] - - -def latest(records): - candidates = [r for r in records if r["tag_name"].startswith("benchmark-") - and not r["draft"] and not r["prerelease"] - and any(a["name"] == SNAPSHOT for a in r["assets"])] - return max(candidates, key=lambda r: r["published_at"], default=None) - - -def extract(archive, destination): - """Reject paths outside the destination before extracting any member.""" - destination = destination.resolve() - with zipfile.ZipFile(archive) as bundle: - for member in bundle.infolist(): - target = (destination / member.filename).resolve() - if not target.is_relative_to(destination) or member.filename.startswith("/"): - raise ValueError(f"Unsafe archive path: {member.filename}") - bundle.extractall(destination) - - -def fetch(repo, release, destination): - if release["draft"] or release["prerelease"]: - raise ValueError("Select a published benchmark release") - with tempfile.TemporaryDirectory() as directory: - work = Path(directory) - gh("release", "download", release["tag_name"], "--repo", repo, - "--pattern", SNAPSHOT, "--pattern", "SHA256SUMS", "--dir", str(work)) - hashes = dict(line.split(maxsplit=1)[::-1] - for line in (work / "SHA256SUMS").read_text().splitlines()) - if file_sha256(work / SNAPSHOT) != hashes.get(SNAPSHOT): - raise ValueError("Published snapshot checksum does not match") - unpacked = work / "unpacked" - extract(work / SNAPSHOT, unpacked) - if not (unpacked / "leaderboard.json").is_file(): - raise ValueError("Published snapshot has no leaderboard") - if destination.exists(): - shutil.rmtree(destination) - shutil.copytree(unpacked, destination) - - -def validate_runs(runs, repo): - if not runs or any(r["status"] != "completed" or r["conclusion"] != "success" - or r["head_repository"]["full_name"] != repo for r in runs): - raise ValueError("Only successful, completed runs from this repository can be released") - - -def stage_piano(source, destination, commit): - """Later selected runs replace complete entries; other methods are retained.""" - metrics_paths = sorted(source.glob("*/metrics.json")) - if not metrics_paths: - raise ValueError("Piano artifact contains no merged entries") - for path in metrics_paths: - record = json.loads(path.read_text()) - entry = path.parent.name - if (record.get("submission") != entry or record.get("fold") != "eval" - or record.get("partial") is not False or record.get("n_failed") != 0 - or not record.get("fold_size") - or record.get("n_pieces") != record["fold_size"]): - raise ValueError(f"Incomplete or invalid piano entry: {entry}") - if record.get("environment", {}).get("benchmark_commit") != commit: - raise ValueError(f"Result does not identify its source run's commit: {entry}") - for path in metrics_paths: - target = destination / "submissions" / path.parent.name - if target.exists(): - shutil.rmtree(target) - shutil.copytree(path.parent, target) - return [path.parent.name for path in metrics_paths] - - -def snapshot(results, output): - """Store website data and metrics; full paths stay in the original run ZIPs.""" - with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as bundle: - for path in sorted(results.rglob("*")): - if not path.is_file(): - continue - relative = path.relative_to(results) - if relative.parts[0] == "submissions" and path.name != "metrics.json": - continue - bundle.write(path, str(relative)) - - -def publish(repo, tag, run_ids, records, destination): - if not re.fullmatch(r"benchmark-[A-Za-z0-9][A-Za-z0-9._-]*", tag): - raise ValueError("Use a new result tag such as benchmark-v1") - if any(r["tag_name"] == tag for r in records): - raise ValueError(f"Release {tag} already exists; published results are never overwritten") - if not run_ids or any(not re.fullmatch(r"[0-9]+", run) for run in run_ids): - raise ValueError("source_runs must contain numeric run IDs separated by spaces") - if len(set(run_ids)) != len(run_ids): - raise ValueError("Select each source run only once") - runs = [api(f"repos/{repo}/actions/runs/{run}") for run in run_ids] - validate_runs(runs, repo) - commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, text=True).strip() - subprocess.run(["git", "merge-base", "--is-ancestor", commit, "origin/main"], - cwd=REPO_ROOT, check=True) - if any(ref["ref"] == f"refs/tags/{tag}" - for ref in api(f"repos/{repo}/git/matching-refs/tags/{tag}")): - raise ValueError(f"Tag {tag} already exists; choose a new result version") - - base = latest(records) - entry_sources = {} - if base: - fetch(repo, base, destination) - entry_sources = json.loads((destination / "release.json").read_text()).get("entry_sources", {}) - else: - destination.mkdir(parents=True, exist_ok=False) - # With no earlier release, start from the archive tracked in the repository. - old_archive = REPO_ROOT / "results" / "archive" - if old_archive.exists(): - shutil.copytree(old_archive, destination / "archive") - - with tempfile.TemporaryDirectory() as directory: - work = Path(directory) - assets = work / "assets" - assets.mkdir() - sources = [] - for run in runs: - pages = json.loads(gh("api", "--paginate", "--slurp", - f"repos/{repo}/actions/runs/{run['id']}/artifacts")) - artifacts = [a for page in pages for a in page["artifacts"] - if a["name"].startswith("benchmark-results-") - or a["name"] == "ophmm-playthrough-comparison"] - if not artifacts or any(a["expired"] for a in artifacts): - raise ValueError(f"Run {run['id']} has no available complete result artifact") - saved = [] - for artifact in artifacts: - name = artifact["name"] - if not re.fullmatch(r"[A-Za-z0-9_-]+", name): - raise ValueError(f"Unexpected artifact name: {name}") - output = assets / f"run-{run['id']}-{name}.zip" - with output.open("wb") as stream: - subprocess.run(["gh", "api", f"repos/{repo}/actions/artifacts/{artifact['id']}/zip"], - stdout=stream, check=True) - if name == "benchmark-results-eval": - unpacked = work / str(artifact["id"]) - extract(output, unpacked) - for entry in stage_piano(unpacked, destination, run["head_sha"]): - entry_sources[entry] = run["id"] - saved.append({"id": artifact["id"], "asset": output.name, - "sha256": file_sha256(output)}) - sources.append({"id": run["id"], "url": run["html_url"], - "benchmark_commit": run["head_sha"], "branch": run["head_branch"], - "attempt": run["run_attempt"], "artifacts": saved}) - - if not list((destination / "submissions").glob("*/metrics.json")): - raise ValueError("A release must include a complete piano evaluation") - env = {**os.environ, "MATCHMAKER_RESULTS_DIR": str(destination)} - for script in ("export_details.py", "leaderboard.py"): - subprocess.run([sys.executable, str(REPO_ROOT / "matchmaker_eval" / script)], - env=env, check=True) - board = json.loads((destination / "leaderboard.json").read_text()) - if not board["entries"] or board["skipped"]: - raise ValueError("The leaderboard is empty or contains invalid entries") - manifest = {"tag": tag, "publisher_commit": commit, "source_runs": sources, - "entry_sources": entry_sources, - "base_release": base["html_url"] if base else None, - "evaluation_keys": board["evaluation_keys"]} - (destination / "release.json").write_text(json.dumps(manifest, indent=2) + "\n") - subprocess.run([sys.executable, str(REPO_ROOT / "matchmaker_eval" / "build_site.py"), - str(work / "site")], env=env, check=True) - snapshot(destination, assets / SNAPSHOT) - checksums = assets / "SHA256SUMS" - checksums.write_text("".join(f"{file_sha256(p)} {p.name}\n" for p in sorted(assets.iterdir()))) - notes = work / "release.md" - notes.write_text( - f"Benchmark results published from `{commit}`.\n\n" - + "\n".join(f"- [Run {s['id']}]({s['url']}), evaluated at `{s['benchmark_commit']}`" - for s in sources) - + "\n" - ) - # Upload everything as a draft; expose it only after every upload succeeds. - gh("release", "create", tag, *(str(p) for p in sorted(assets.iterdir())), - "--repo", repo, "--target", commit, "--title", tag, - "--notes-file", str(notes), "--draft", "--latest=false") - gh("release", "edit", tag, "--repo", repo, "--draft=false", "--latest=false") - return tag - - -def main(): - parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY")) - parser.add_argument("--tag", default="") - parser.add_argument("--source-runs", default="", help="space-separated completed CI run IDs") - args = parser.parse_args() - if not args.repo or not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repo): - parser.error("Set GITHUB_REPOSITORY or --repo owner/repository") - if RESULTS_DIR.resolve().is_relative_to(REPO_ROOT): - parser.error("Set MATCHMAKER_RESULTS_DIR to a directory outside the source checkout") - try: - records = releases(args.repo) - if args.source_runs: - tag = publish(args.repo, args.tag, args.source_runs.split(), records, RESULTS_DIR) - else: - release = next((r for r in records if r["tag_name"] == args.tag), None) if args.tag else latest(records) - if args.tag and release is None: - raise ValueError(f"Release {args.tag} was not found") - tag = release["tag_name"] if release else "" - if release: - fetch(args.repo, release, RESULTS_DIR) - if os.environ.get("GITHUB_OUTPUT"): - with open(os.environ["GITHUB_OUTPUT"], "a") as stream: - stream.write(f"ready={'true' if tag else 'false'}\ntag={tag}\n") - print(f"Results: {tag}" if tag else "No benchmark release yet; leave the existing website unchanged.") - except (ValueError, subprocess.CalledProcessError) as error: - parser.exit(1, f"{error}\n") - - -if __name__ == "__main__": - main() diff --git a/matchmaker_eval/retract.py b/matchmaker_eval/retract.py index 9a66541..e13586f 100644 --- a/matchmaker_eval/retract.py +++ b/matchmaker_eval/retract.py @@ -42,8 +42,9 @@ import shutil from datetime import datetime, timezone -from matchmaker_eval.load_folds import REPO_ROOT, RESULTS_DIR +from matchmaker_eval.folds import REPO_ROOT +RESULTS_DIR = REPO_ROOT / "results" SUBMISSION_RESULTS = RESULTS_DIR / "submissions" DETAILS_DIR = RESULTS_DIR / "details" RETRACTED_PATH = RESULTS_DIR / "retracted.json" @@ -133,7 +134,7 @@ def retract(entry: str, reason: str, archive: bool = True) -> dict: if destination.exists(): shutil.rmtree(destination) shutil.move(str(run_dir), str(destination)) - record["archived"] = str(destination.relative_to(RESULTS_DIR)) + record["archived"] = str(destination.relative_to(REPO_ROOT)) else: shutil.rmtree(run_dir) @@ -162,7 +163,7 @@ def undo(entry: str) -> None: destination = SUBMISSION_RESULTS / entry if destination.exists(): raise RetractionError( - f"{destination} already exists — " + f"{destination.relative_to(REPO_ROOT)} already exists — " "remove or rename it before restoring." ) destination.parent.mkdir(parents=True, exist_ok=True) diff --git a/matchmaker_eval/run_amt.py b/matchmaker_eval/run_amt.py deleted file mode 100644 index 532a084..0000000 --- a/matchmaker_eval/run_amt.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Replay frozen online-AMT MIDI through symbolic followers, scored against audio GT. - -The transcription model is not run, so timings cover the follower only. MIDI -event times are used as they are, without latency compensation. -""" - -import argparse -import hashlib -import json -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -for p in (ROOT, ROOT / "matchmaker_eval"): - sys.path.insert(0, str(p)) - -import matchmaker_eval.run_submission as rs # noqa: E402 -from matchmaker import Matchmaker # noqa: E402 -from matchmaker_eval.evaluation_key import file_sha256 # noqa: E402 -from matchmaker_eval.run_diagnostics import download # noqa: E402 -from matchmaker_eval.submission import DECLARATION_KEY # noqa: E402 - -N_PIECES = 146 - - -def fetch_verified(url, path, sha256): - if not path.exists() or file_sha256(path) != sha256: - download(url, path) - if file_sha256(path) != sha256: - raise ValueError(f"Hash mismatch: {path.name}") - return path - - -def load_cases(cache): - """The pinned AMT data, its base URL, and one case per piano piece.""" - from matchmaker_eval.fetch_data import frozen_source - - pin = frozen_source("amt") - base_url = f"https://raw.githubusercontent.com/{pin['repository']}/{pin['commit']}/amt/" - cache.mkdir(parents=True, exist_ok=True) - manifest = fetch_verified(base_url + "manifest.json", cache / "manifest.json", - pin["manifest_sha256"]) - cases = json.loads(manifest.read_text())["cases"] - if len(cases) != N_PIECES or len({c["piece_id"] for c in cases}) != N_PIECES: - raise ValueError("The AMT manifest does not cover the piano fold") - return pin, base_url, {c["piece_id"]: c for c in cases} - - -def main(): - parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - parser.add_argument("--method", choices=["arzt", "pthmm", "SLT_OLTW"], default="arzt") - parser.add_argument("--shard", type=int, default=0) - parser.add_argument("--num-shards", type=int, default=1) - parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--cache", type=Path, default=Path("amt-data")) - args = parser.parse_args() - pin, base_url, cases = load_cases(args.cache) - score_piece = rs.run_piece - - def run_piece(method, piece, input_type, index, run_dir, save_plots, estimated_bpm=False): - case = cases[piece.piece_id] - midi = fetch_verified(base_url + case["path"], args.cache / case["path"], case["sha256"]) - - # Stream the transcribed MIDI into the symbolic follower... - def matchmaker_on_transcription(**kwargs): - kwargs.update(input_type="midi", performance_file=str(midi), method=args.method) - return Matchmaker(**kwargs) - - original = rs.Matchmaker - rs.Matchmaker = matchmaker_on_transcription - try: - # ...but score it as audio: the recording's ground truth and audio TR threshold. - result = score_piece(method, piece, "audio", index, run_dir, save_plots, False) - finally: - rs.Matchmaker = original - - result.update(amt_data_commit=pin["commit"], amt_output_sha256=case["sha256"], - amt_front_end_executed=False, timing_scope="symbolic follower only", - symbolic_method=args.method) - (run_dir / f"{index}.json").write_text(json.dumps(result, indent=2, default=float) + "\n") - return result - - rs.run_piece = run_piece - rs.builtin_metadata = lambda method, input_type: { - "name": f"AMT + {args.method}", "input_type": "audio", "kind": "reference", - "authors": ["Matchmaker benchmark"], - "description": "Frozen online AMT output replayed through a symbolic follower.", - rs.ESTIMATED_BPM_KEY: False, DECLARATION_KEY: True, - } - scoring_parts = rs.scoring_parts - rs.scoring_parts = lambda: { - **scoring_parts(), "amt_inputs": pin, "amt_symbolic_method": args.method, - "amt_runner_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), - } - result = rs.evaluate_submission(builtin=args.method, input_type="audio", fold="eval", - shard=args.shard, num_shards=args.num_shards, - run_dir=args.output) - if result["n_failed"]: - raise SystemExit("Incomplete AMT replay") - - -if __name__ == "__main__": - main() diff --git a/matchmaker_eval/run_diagnostics.py b/matchmaker_eval/run_diagnostics.py deleted file mode 100644 index 7cb5da7..0000000 --- a/matchmaker_eval/run_diagnostics.py +++ /dev/null @@ -1,319 +0,0 @@ -"""Run and merge the manuscript diagnostic suites with the benchmark evaluator. - -Inputs come from a pinned manifest in the data repository and are checked -against their hashes. A merge fails when any selected case or shard is missing. -""" - -import argparse -import contextlib -import json -import os -import shutil -import sys -import time -import traceback -import urllib.request -from collections import defaultdict -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -for p in (ROOT, ROOT / "matchmaker_eval"): - sys.path.insert(0, str(p)) - -from matchmaker_eval.evaluation_key import file_sha256 # noqa: E402 - -PERTURBATION_METHODS = { - "audio": ["dixon", "arzt", "outerhmm", "skf"], - "midi": ["pthmm", "hmm", "outerhmm", "dixon", "arzt", "SLT_OLTW", "dannenberg"], -} -CONFIGS = { - **{f"perturbations-{t}-{m}": {"suite": "perturbations", "input_type": t, "method": m} - for t, methods in PERTURBATION_METHODS.items() for m in methods}, - **{f"repeat_examples-audio-{m}": {"suite": "repeat_examples", "input_type": "audio", "method": m} - for m in ["arzt", "arzt_multi_fold", "outerhmm"]}, - **{f"folded_batik-audio-{m}": {"suite": "folded_batik", "input_type": "audio", "method": m, - "kwargs": {"s_j": 1e-5} if m == "outerhmm" else {}} - for m in ["dixon", "arzt", "skf", "outerhmm", "arzt_multi_fold"]}, - **{f"global_skip-midi-{s}": {"suite": "global_skip", "input_type": "midi", "method": "outerhmm", - "disable_global_skip": s == "off"} - for s in ["on", "off"]}, -} - - -def select_configs(only="", input_type="both"): - """The configurations for the given methods (all if empty) and input type.""" - methods = set(only.split()) - selected = {name: c for name, c in CONFIGS.items() - if input_type in ("both", c["input_type"]) and (not methods or c["method"] in methods)} - missing = methods - {c["method"] for c in selected.values()} - if not selected or missing: - raise ValueError(f"No diagnostic configuration for {input_type}: {sorted(missing or methods)}") - return selected - - -def select_cases(manifest, config, shard=0, shards=1): - """The (index, case) pairs of one shard, round-robin over the suite's cases.""" - if not 1 <= shards <= 32 or not 0 <= shard < shards: - raise ValueError("Invalid shard selection") - cases = [c for c in manifest["cases"] - if c["suite"] == config["suite"] and c["input_type"] == config["input_type"]] - ids = [c["id"] for c in cases] - if not ids or len(ids) != len(set(ids)): - raise ValueError("Empty or duplicated diagnostic cases") - return [(i, c) for i, c in enumerate(cases) if i % shards == shard] - - -def download(url, path, attempts=4): - path.parent.mkdir(parents=True, exist_ok=True) - for attempt in range(attempts): - try: - with urllib.request.urlopen(url, timeout=120) as response, path.open("wb") as out: - shutil.copyfileobj(response, out) - return - except Exception: - if attempt == attempts - 1: - raise - time.sleep(2 ** attempt) - - -def fetch_input(name, manifest, cache, base_url): - """Download one input into ``cache``, joining it from parts if stored that way.""" - entry = manifest["files"][name] - path = cache / name - if path.exists() and file_sha256(path) == entry["sha256"]: - return path - path.parent.mkdir(parents=True, exist_ok=True) - if entry.get("parts"): - with path.open("wb") as out: - for part in entry["parts"]: - part_path = cache / part["path"] - if not part_path.exists() or file_sha256(part_path) != part["sha256"]: - download(base_url + part["path"], part_path) - if file_sha256(part_path) != part["sha256"]: - raise ValueError(f"Corrupt data chunk: {part['path']}") - out.write(part_path.read_bytes()) - else: - download(base_url + name, path) - if file_sha256(path) != entry["sha256"]: - raise ValueError(f"Input hash mismatch: {name}") - return path - - -def load_manifest(cache): - """The pinned manifest, the pin itself, and the URL its files are served from.""" - from matchmaker_eval.fetch_data import frozen_source - - pin = frozen_source("diagnostics") - base_url = f"https://raw.githubusercontent.com/{pin['repository']}/{pin['commit']}/diagnostics/" - path = cache / "manifest.json" - if not path.exists() or file_sha256(path) != pin["manifest_sha256"]: - download(base_url + "manifest.json", path) - if file_sha256(path) != pin["manifest_sha256"]: - raise ValueError("Diagnostic manifest hash mismatch") - return pin, base_url, json.loads(path.read_text()) - - -def run_case(case, config, paths, out): - import numpy as np - from matchmaker import Matchmaker - from matchmaker.matchmaker import DEFAULT_KWARGS - from matchmaker.utils.eval import resolve_gt - - from matchmaker_eval.eval import run_evaluation - from matchmaker_eval.run_submission import check_follower, piece_time_budget - from matchmaker_eval.utils import TOLERANCES_IN_BEATS - from matchmaker_eval.verify_tracking import ( - TRACKING_THRESHOLDS, check_tracking, musical_beat_factors, score_meter_map, - ) - - input_type, method = config["input_type"], config["method"] - performance = paths[f"{input_type}_performance"] - kwargs = dict(DEFAULT_KWARGS[input_type][method]) - if input_type == "audio" and method == "outerhmm": - kwargs["s_j"] = 1e-100 # the diagnostics test jumps, which the default disables - kwargs.update(config.get("kwargs", {})) - out.mkdir(parents=True, exist_ok=True) - - with piece_time_budget(2400): - mm = Matchmaker(score_file=str(paths["xml_score"]), performance_file=str(performance), - method=method, input_type=input_type, wait=False, - unfold_score=case["unfold_score"], tempo=case["tempo"], kwargs=kwargs) - check_follower(mm.score_follower) - if config.get("disable_global_skip"): - mm.score_follower.S[:] = 0.0 # OPHMM's skip-from distribution - for _ in mm.run(verbose=False): - pass - times, beats = resolve_gt(paths["match"], mm.score_part.note_array(), - performance=str(performance) if input_type == "midi" else None) - gt = np.column_stack((times, beats)) - metrics = run_evaluation(mm, gt=gt, tolerances=TOLERANCES_IN_BEATS, domain="score", - debug=True, save_dir=out, run_name="0", - make_plot=False, plot_dist_matrix=False) - wp = mm.score_follower.alignment_path.T - meter = score_meter_map(mm.score_part) - tracking = check_tracking(wp, gt, threshold=TRACKING_THRESHOLDS[input_type], - segment_duration=30.0, - beat_factors=musical_beat_factors(gt[:, 1], meter)) - - (out / "meter_0.json").write_text(json.dumps(meter, indent=2) + "\n") - for name, array in [("wp_0", wp), ("gt_0", gt)]: - np.savetxt(out / f"{name}.tsv", array, delimiter="\t", fmt="%.12g", - header="perf_sec\tscore_beat", comments="") - - # Beat error at each annotated onset; NaN before the follower's first estimate. - wp = wp[np.argsort(wp[:, 0], kind="stable")] - index = np.searchsorted(wp[:, 0], gt[:, 0], side="right") - 1 - valid = index >= 0 - errors = np.full(len(gt), np.nan) - errors[valid] = np.abs(gt[valid, 1] - wp[index[valid], 1]) - - intervals = {} - if "repeat_metadata" in case: - start = case["repeat_metadata"]["replay_start_sec"] - end = case["repeat_metadata"]["replay_end_sec"] - t = gt[:, 0] - for name, mask in [("before", t < start), ("replay", (t >= start) & (t < end)), - ("after", t >= end)]: - intervals[name] = {"onsets": int(mask.sum()), - "within_1_beat": float(np.mean(errors[mask] <= 1)), - "median_beat_error": float(np.nanmedian(errors[mask]))} - - return { - "case_id": case["id"], "category": case["category"], - "method": method, "input_type": input_type, "kwargs": kwargs, - "unfold_score": case["unfold_score"], "tempo": case["tempo"], - "disable_global_skip": config.get("disable_global_skip", False), - "tracked": bool(tracking["tracked"]), "max_deviation": float(tracking["max_deviation"]), - "tracking_criterion": {k: tracking[k] for k in ("error_unit", "threshold", "window_duration")}, - "mean_b": float(np.nanmean(errors)), "n_events": int(valid.sum()), - "n_annotated_onsets": len(gt), "metrics": metrics, "intervals": intervals, - } - - -def write_json(path, value): - # Model classes in the follower settings are written by name. - def default(v): - return f"{v.__module__}.{v.__qualname__}" if isinstance(v, type) else float(v) - - path.write_text(json.dumps(value, indent=2, default=default) + "\n") - - -def run(args): - from matchmaker_eval.run_submission import environment_info - - args.cache.mkdir(parents=True, exist_ok=True) - pin, base_url, manifest = load_manifest(args.cache) - config = CONFIGS[args.config] - selected = select_cases(manifest, config, args.shard, args.shards) - inputs = ["xml_score", "match", f"{config['input_type']}_performance"] - result = { - "config": args.config, "definition": config, "shard": args.shard, "shards": args.shards, - "data": pin, "environment": environment_info(), - "github_run_id": os.environ.get("GITHUB_RUN_ID"), - "github_run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT"), - "expected": [c["id"] for _, c in selected], "pieces": [], "failures": [], - } - args.output.mkdir(parents=True, exist_ok=True) - write_json(args.output / "metrics.json", result) # also for an empty shard - - for i, case in selected: - case_dir = args.output / f"{i:03d}" - case_dir.mkdir(exist_ok=True) - try: - paths = {k: fetch_input(case["paths"][k], manifest, args.cache, base_url) for k in inputs} - with (case_dir / "run.log").open("w") as log, \ - contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): - record = run_case(case, config, paths, case_dir) - record["input_hashes"] = {k: manifest["files"][case["paths"][k]]["sha256"] for k in inputs} - record["directory"] = case_dir.name - write_json(case_dir / "result.json", record) - result["pieces"].append(record) - print(args.config, case["id"], record["tracked"], record["mean_b"], flush=True) - except Exception: - error = traceback.format_exc() - (case_dir / "error.txt").write_text(error) - result["failures"].append({"case_id": case["id"], "error": error}) - print(error, flush=True) - write_json(args.output / "metrics.json", result) - - if result["failures"]: - raise SystemExit(f"{len(result['failures'])} diagnostic cases failed") - - -def summarize(pieces): - """Per category: how many cases were tracked, and their mean beat error.""" - import numpy as np - - by_category = defaultdict(list) - for piece in pieces: - by_category[piece["category"]].append(piece) - summary = {} - for category, group in by_category.items(): - tracked = [p["mean_b"] for p in group if p["tracked"]] - summary[category] = {"total": len(group), "tracked": len(tracked), - "mean_b_tracked": float(np.mean(tracked)) if tracked else None, - "mean_b_all": float(np.mean([p["mean_b"] for p in group]))} - return summary - - -def merge(args): - manifest = json.loads(args.manifest.read_text()) - records = [json.loads(p.read_text()) for p in args.source.glob("*/metrics.json")] - args.output.mkdir(parents=True, exist_ok=True) - - incomplete, summary = [], {} - for name, config in select_configs(args.only, args.input_type).items(): - own = [r for r in records if r["config"] == name] - found = sorted(p["case_id"] for r in own for p in r["pieces"]) - expected = sorted(c["id"] for _, c in select_cases(manifest, config)) - shards = {r["shard"] for r in own} - if (len(own) != args.shards or shards != set(range(args.shards)) - or found != expected or any(r["failures"] for r in own)): - incomplete.append(name) - summary[name] = summarize([p for r in own for p in r["pieces"]]) - - # All shards must come from one run: the same data, benchmark and matchmaker. - sources = {(r["data"]["commit"], r["environment"]["benchmark_commit"], - json.dumps({k: v for k, v in r["environment"].items() if k.startswith("matchmaker")}, - sort_keys=True), - r["github_run_id"]) for r in records} - if len(sources) != 1: - incomplete.append("shards come from different runs") - - for shard_dir in args.source.iterdir(): - if shard_dir.is_dir(): - shutil.copytree(shard_dir, args.output / "raw" / shard_dir.name, dirs_exist_ok=True) - shutil.copyfile(args.manifest, args.output / "data_manifest.json") - write_json(args.output / "summary.json", { - "complete": not incomplete, "incomplete": incomplete, "configurations": summary, - "sources": [list(s) for s in sources], - }) - if incomplete: - raise SystemExit("Incomplete diagnostic results: " + ", ".join(incomplete)) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - commands = parser.add_subparsers(dest="command", required=True) - run_parser = commands.add_parser("run", help="run one shard of one configuration") - run_parser.add_argument("--config", choices=CONFIGS, required=True) - run_parser.add_argument("--shard", type=int, default=0) - run_parser.add_argument("--shards", type=int, default=1) - run_parser.add_argument("--output", type=Path, required=True) - run_parser.add_argument("--cache", type=Path, default=Path("diagnostic-data")) - merge_parser = commands.add_parser("merge", help="check and combine downloaded shards") - merge_parser.add_argument("--source", type=Path, required=True) - merge_parser.add_argument("--output", type=Path, required=True) - merge_parser.add_argument("--manifest", type=Path, required=True) - merge_parser.add_argument("--shards", type=int, required=True) - merge_parser.add_argument("--only", default="", help="method names; empty selects all") - merge_parser.add_argument("--input-type", choices=["both", "midi", "audio"], default="both") - args = parser.parse_args() - if args.command == "run": - run(args) - else: - merge(args) - - -if __name__ == "__main__": - main() diff --git a/matchmaker_eval/run_offline.py b/matchmaker_eval/run_offline.py deleted file mode 100644 index e2ac636..0000000 --- a/matchmaker_eval/run_offline.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Reproduce the manuscript offline reference through the common benchmark. - -Non-causal chroma CENS + DLNCO / MrMsDTW, with the original fixed settings. -No online leaderboard publishing; the workflow archives complete reference results. -""" -import sys -import time -from pathlib import Path - -BENCH = Path(__file__).resolve().parents[1] -for p in (BENCH, BENCH / "matchmaker_eval"): - sys.path.insert(0, str(p)) - -import librosa # noqa: E402 -import numpy as np # noqa: E402 -from partitura.io.exportmidi import get_ppq # noqa: E402 -from synctoolbox.dtw.mrmsdtw import sync_via_mrmsdtw # noqa: E402 -from synctoolbox.feature.dlnco import pitch_onset_features_to_DLNCO # noqa: E402 -from synctoolbox.feature.pitch_onset import audio_to_pitch_onset_features # noqa: E402 - -import run_submission as rs # noqa: E402 -from matchmaker_eval.submission import DECLARATION_KEY # noqa: E402 -from matchmaker import Matchmaker # noqa: E402 -from matchmaker.utils.misc import generate_score_audio # noqa: E402 - -FEATURE_RATE = 50 -STEP_WEIGHTS = np.array([1.5, 1.5, 2.0]) -THRESHOLD_REC = 10 ** 6 -FEATURE_SR = 22050 - - -def safe_chroma_cens(y, sr, hop_length, chunk_sec=60.0, pad_sec=4.0): - total_len = len(y) - chunk_samples = int(chunk_sec * sr) - pad_samples = int(pad_sec * sr) - if total_len <= chunk_samples + pad_samples: - return librosa.feature.chroma_cens(y=y, sr=sr, hop_length=hop_length) - out = [] - start = 0 - while start < total_len: - end = min(start + chunk_samples, total_len) - left = max(0, start - pad_samples) - right = min(total_len, end + pad_samples) - c = librosa.feature.chroma_cens(y=y[left:right], sr=sr, hop_length=hop_length) - fc = left + np.arange(c.shape[1]) * hop_length - out.append(c[:, (fc >= start) & (fc < end)]) - start = end - return np.concatenate(out, axis=1) - -def features(audio, sr): - hop = sr // FEATURE_RATE - chroma = safe_chroma_cens(y=audio, sr=sr, hop_length=hop) - onset = audio_to_pitch_onset_features(f_audio=audio, Fs=sr) - dlnco = pitch_onset_features_to_DLNCO( - f_peaks=onset, feature_rate=FEATURE_RATE, - feature_sequence_length=chroma.shape[1], visualize=False) - return chroma, dlnco - - -def offline_path(mm, perf_path): - sr0 = mm.sample_rate - score_audio = generate_score_audio(mm.score_part, mm.tempo, sr0).astype(np.float64) - sr = FEATURE_SR - if sr != sr0: - score_audio = librosa.resample(score_audio, orig_sr=sr0, target_sr=sr) - perf_audio, _ = librosa.load(str(perf_path), sr=sr) - c1, o1 = features(score_audio, sr) - c2, o2 = features(perf_audio.astype(np.float64), sr) - wp = sync_via_mrmsdtw(f_chroma1=c1, f_onset1=o1, f_chroma2=c2, f_onset2=o2, - input_feature_rate=FEATURE_RATE, verbose=False, - step_weights=STEP_WEIGHTS, threshold_rec=THRESHOLD_REC) - hop = sr // FEATURE_RATE # the frame period is hop / sr exactly - score_sec = wp[0].astype(float) * hop / sr - perf_sec = wp[1].astype(float) * hop / sr - tick = get_ppq(mm.score_part) - beats = mm.score_part.beat_map(score_sec * tick * (mm.tempo / 60)) - order = np.argsort(perf_sec, kind="stable") - return perf_sec[order], np.asarray(beats, dtype=float)[order] - - - -def run_piece(method, piece, input_type, index, run_dir, save_plots, estimated_bpm=False): - import json - from matchmaker_eval.verify_tracking import score_meter_map, musical_beat_factors - mm = Matchmaker(score_file=str(piece.score_path), performance_file=str(piece.performance_path(input_type)), - input_type=input_type, method="arzt", wait=False, unfold_score=True) - t0 = time.perf_counter() - perf_sec, beats = offline_path(mm, piece.performance_path(input_type)) - mm.alignment_duration = time.perf_counter()-t0 - mm.score_follower._alignment_path = list(zip(perf_sec.tolist(), beats.tolist())) - mm._has_run = True - perf, score_beat = rs.resolve_gt(piece.match_path, mm.score_part.note_array(), performance=None) - gt = np.column_stack([perf, score_beat]) - metrics = rs.run_evaluation(mm, gt=gt, tolerances=rs.TOLERANCES_IN_BEATS, domain="score", - debug=True, save_dir=run_dir, run_name=str(index), - plot_dist_matrix=False, make_plot=False) - meter = score_meter_map(mm.score_part) - (run_dir/f"meter_{index}.json").write_text(json.dumps(meter,indent=2)+"\n") - tracking = rs.check_tracking(np.column_stack([perf_sec,beats]), gt, - segment_duration=rs.SEGMENT_DURATION, - threshold=rs.TRACKING_THRESHOLD[input_type], - beat_factors=musical_beat_factors(gt[:,1],meter)) - metrics.update(tracked=bool(tracking["tracked"]), max_deviation=float(tracking["max_deviation"]), - n_failed_segments=int(tracking["n_failed"]), - tracking_criterion={k:tracking[k] for k in ("error_unit","threshold","window_duration")}, - used_estimated_bpm=False, - offline=True, - offline_settings=dict(feature_rate=FEATURE_RATE, render_tempo="score", - feature_sample_rate=FEATURE_SR, step_weights=STEP_WEIGHTS.tolist(), threshold_rec=THRESHOLD_REC)) - (run_dir/f"{index}.json").write_text(json.dumps(metrics,indent=2,default=float)+"\n") - return metrics - - -def offline_metadata(method, input_type): - return {"name":"Offline (DLNCO + MrMsDTW)", "authors":["synctoolbox"], "input_type":input_type, - "description":"Non-causal MrMsDTW of performance and rendered score audio; chroma CENS + DLNCO.", - rs.ESTIMATED_BPM_KEY:False, "url":"https://github.com/meinardmueller/synctoolbox", - DECLARATION_KEY:True, "kind":"reference"} - - -def main(): - import hashlib - original_parts=rs.scoring_parts - rs.scoring_parts=lambda: {**original_parts(), "offline_source_sha256":hashlib.sha256(Path(__file__).read_bytes()).hexdigest()} - rs.run_piece=run_piece - rs.builtin_metadata=offline_metadata - if "--method" not in sys.argv: - sys.argv += ["--method","offline","--input-type","audio"] - return rs.main() - -if __name__ == "__main__": - sys.exit(main()) diff --git a/matchmaker_eval/run_references.py b/matchmaker_eval/run_references.py index cfaf5e9..0562485 100644 --- a/matchmaker_eval/run_references.py +++ b/matchmaker_eval/run_references.py @@ -39,7 +39,7 @@ from concurrent.futures import ThreadPoolExecutor from pathlib import Path -from matchmaker_eval.load_folds import LEADERBOARD_FOLD, REPO_ROOT, load_fold +from matchmaker_eval.folds import LEADERBOARD_FOLD, REPO_ROOT, load_fold from matchmaker_eval.submission import ( BUILTIN_METHODS_PATH, read_descriptions, diff --git a/matchmaker_eval/run_submission.py b/matchmaker_eval/run_submission.py index ab2514a..482d667 100644 --- a/matchmaker_eval/run_submission.py +++ b/matchmaker_eval/run_submission.py @@ -47,20 +47,20 @@ from eval import run_evaluation from utils import TOLERANCES_IN_BEATS, dataset_summaries, pooled_summaries -from matchmaker_eval.verify_tracking import ( - TRACKING_THRESHOLDS, check_tracking, plot_tracking, musical_beat_factors, score_meter_map, +from verify_tracking import ( + TRACKING_THRESHOLDS, check_tracking, musical_beat_factors, plot_tracking, score_meter_map, ) from matchmaker import Matchmaker from matchmaker.base import OnlineAlignment from matchmaker_eval.fetch_data import FetchError, fetch_for_pieces, load_config -from matchmaker_eval.evaluation_key import ( +from matchmaker_eval.provenance import ( code_components, evaluation_record, piece_data_sha256, ) -from matchmaker_eval.load_folds import ( +from matchmaker_eval.folds import ( LEADERBOARD_FOLD, REPO_ROOT, fold_path, @@ -133,12 +133,11 @@ def sha256_of(path: Path) -> str: def _matchmaker_source() -> dict: - """The git sources Matchmaker was installed from, if known. + """The git ref and commit matchmaker was installed from, if it was. ``pip install git+...@`` leaves a direct_url.json beside the package - naming the ref asked for and the commit it resolved to. CI may instead - install a temporary checkout with pinned patches; its packaged manifest - identifies every source commit without claiming it is one upstream commit. + naming the ref asked for and the commit it resolved to. A release install + has none, and then there is nothing to add. """ try: import json @@ -147,13 +146,7 @@ def _matchmaker_source() -> dict: raw = distribution("pymatchmaker").read_text("direct_url.json") if not raw: return {} - direct_url = json.loads(raw) - if "dir_info" in direct_url: - from importlib.resources import files - - manifest = files("matchmaker").joinpath("assets/benchmark-source.json") - return json.loads(manifest.read_text()) if manifest.is_file() else {} - vcs = direct_url.get("vcs_info") or {} + vcs = (json.loads(raw).get("vcs_info") or {}) found = {} if vcs.get("commit_id"): found["matchmaker_commit"] = vcs["commit_id"] @@ -219,19 +212,8 @@ def check_follower(follower) -> None: ) -def set_global_transition(mm, setting): - """Override only MIDI OPHMM's global transition factor when requested.""" - if setting is None: - return - if setting not in ("on", "off") or mm.method != "outerhmm" or mm.input_type != "midi": - raise SubmissionError("--global-transition applies only to MIDI outerhmm") - if setting == "off": - mm.score_follower.S[:] = 0.0 - - def run_piece( - method, piece, input_type, index, run_dir, save_plots, estimated_bpm=False, - global_transition=None, + method, piece, input_type, index, run_dir, save_plots, estimated_bpm=False ): """Run and score one piece, returning the shared metric fields. @@ -262,7 +244,6 @@ def run_piece( tempo=tempo, ) check_follower(mm.score_follower) - set_global_transition(mm, global_transition) list(mm.run(verbose=False)) wp = mm.score_follower.alignment_path @@ -323,9 +304,6 @@ def run_piece( # Whether this piece actually got a measured tempo. False both when the # entry never asked and when it asked and the fold had none — the run # summary separates the two, since only the second is worth reporting. - if global_transition is not None: - metrics["global_transition"] = global_transition - metrics["global_transition_nonzero"] = int(np.count_nonzero(mm.score_follower.S)) metrics["used_estimated_bpm"] = tempo is not None with open(run_dir / f"{index}.json", "w") as f: @@ -339,7 +317,7 @@ def scoring_parts() -> dict: The tracked-verdict thresholds and the function that resolves ground truth and calls the evaluation. Anything added here that decides a number belongs - in this dict too; see evaluation_key.py. + in this dict too; see provenance.py. """ return { "TRACKING_THRESHOLD": TRACKING_THRESHOLD, @@ -393,7 +371,6 @@ def evaluate_submission( builtin: Optional[str] = None, skip_missing: bool = False, fetch: bool = True, - global_transition: Optional[str] = None, ) -> dict: """Run a submission — or a built-in method — over a fold or one shard of it. @@ -419,12 +396,6 @@ def evaluate_submission( input_type = input_type or registered_input_type name = directory.name - if global_transition is not None: - if builtin != "outerhmm" or input_type != "midi" or global_transition not in ("on", "off"): - raise SubmissionError("--global-transition applies only to MIDI outerhmm") - name += "-global-" + global_transition - metadata = {**metadata, "global_transition": global_transition} - # Declared by the entry, not chosen here: a follower is given the tempo # only if it said it uses one, and the run is labelled accordingly. estimated_bpm = bool(metadata.get(ESTIMATED_BPM_KEY, False)) @@ -535,7 +506,6 @@ def evaluate_submission( run_dir, save_plots, estimated_bpm=estimated_bpm, - **({"global_transition": global_transition} if global_transition is not None else {}), ) except Exception as e: # One broken piece must not void a whole run: record it as an @@ -609,7 +579,7 @@ def evaluate_submission( "timestamp": datetime.now(timezone.utc).isoformat(timespec="seconds"), "environment": environment_info(), # The conditions these numbers were scored under, as one key. Rows - # with the same key are comparable; see evaluation_key.py. On a shard it + # with the same key are comparable; see provenance.py. On a shard it # covers that shard's pieces only, and merge_shards.py recomputes it. "evaluation": evaluation_record( code_components(fold_sha256, scoring_parts()), piece_records @@ -701,8 +671,6 @@ def main(): default=1, help="split the fold into this many shards (merge them with merge_shards.py)", ) - parser.add_argument("--global-transition", choices=("on", "off"), default=None, - help="MIDI OPHMM global transitions (default: unchanged)") args = parser.parse_args() try: @@ -719,7 +687,6 @@ def main(): fetch=not args.no_fetch, shard=args.shard, num_shards=args.num_shards, - global_transition=args.global_transition, ) except SubmissionError as e: print(f"\nSubmission error: {e}", file=sys.stderr) diff --git a/matchmaker_eval/symbolic_alignment.py b/matchmaker_eval/symbolic_alignment.py index d9e2145..c4ee06c 100644 --- a/matchmaker_eval/symbolic_alignment.py +++ b/matchmaker_eval/symbolic_alignment.py @@ -44,7 +44,7 @@ compute_ioi_matrix, compute_discrete_pitch_profiles, ) -from matchmaker_eval.load_folds import nested_dataset_root +from matchmaker_eval.folds import nested_dataset_root from matchmaker_eval.utils import save_nparray_to_csv, save_score_following_result from matchmaker.utils.tempo_models import ReactiveTempoModel, KalmanTempoModel diff --git a/matchmaker_eval/test_audio.py b/matchmaker_eval/test_audio.py index 127320f..0275239 100644 --- a/matchmaker_eval/test_audio.py +++ b/matchmaker_eval/test_audio.py @@ -16,7 +16,7 @@ import numpy as np import pandas as pd from matchmaker_eval.eval import run_offline_alignment, run_score_following -from matchmaker_eval.load_folds import ( +from matchmaker_eval.folds import ( DATA_REPO_DATASETS, data_repo_metadata, explain_missing_dataset, diff --git a/matchmaker_eval/test_symbolic.py b/matchmaker_eval/test_symbolic.py index 220d03c..ca5e7ce 100644 --- a/matchmaker_eval/test_symbolic.py +++ b/matchmaker_eval/test_symbolic.py @@ -26,7 +26,7 @@ from matchmaker_eval.eval import run_evaluation from matchmaker import Matchmaker from matchmaker.utils.eval import resolve_gt -from matchmaker_eval.load_folds import ( +from matchmaker_eval.folds import ( DATA_REPO_DATASETS, data_repo_metadata, explain_missing_dataset, diff --git a/matchmaker_eval/validate_submission.py b/matchmaker_eval/validate_submission.py index 157b688..766757d 100644 --- a/matchmaker_eval/validate_submission.py +++ b/matchmaker_eval/validate_submission.py @@ -32,7 +32,7 @@ import argparse import re -from matchmaker_eval.load_folds import REPO_ROOT +from matchmaker_eval.folds import REPO_ROOT from matchmaker_eval.submission import ( SubmissionError, load_solution, diff --git a/matchmaker_eval/verify_equivalence.py b/matchmaker_eval/verify_equivalence.py index 52e7401..311bf7c 100644 --- a/matchmaker_eval/verify_equivalence.py +++ b/matchmaker_eval/verify_equivalence.py @@ -42,7 +42,7 @@ from matchmaker.utils.eval import resolve_gt from eval import run_evaluation -from matchmaker_eval.load_folds import load_fold +from matchmaker_eval.folds import load_fold from methods import builtin_methods, default_kwargs, processor_for from utils import TOLERANCES_IN_BEATS diff --git a/tests/test_data_folder.py b/tests/test_data_folder.py index cb5595f..c355e76 100644 --- a/tests/test_data_folder.py +++ b/tests/test_data_folder.py @@ -53,7 +53,7 @@ def test_the_pipeline_imports_without_them(self, tmp_path): # A repo tree holding only the config, and nothing dataset-shaped. script = ( "import sys; sys.path[:0] = [r'%s', r'%s']\n" - "import matchmaker_eval.load_folds as F\n" + "import matchmaker_eval.folds as F\n" "from pathlib import Path\n" "F.FOLD_DIR = Path(r'%s')\n" "pieces = F.load_fold('eval', input_type='midi')\n" diff --git a/tests/test_data_paths.py b/tests/test_data_paths.py index 09a01f8..548f8ae 100644 --- a/tests/test_data_paths.py +++ b/tests/test_data_paths.py @@ -20,7 +20,7 @@ @pytest.fixture def data_root(tmp_path, monkeypatch): - import matchmaker_eval.load_folds as F + import matchmaker_eval.folds as F monkeypatch.setattr(F, "DATA_ROOT", tmp_path) return tmp_path @@ -28,7 +28,7 @@ def data_root(tmp_path, monkeypatch): class TestDatasetRoot: def test_the_repository_layout_wins(self, data_root): - from matchmaker_eval.load_folds import dataset_root + from matchmaker_eval.folds import dataset_root (data_root / "asap" / "score").mkdir(parents=True) (data_root / "asap-dataset-matchmaker" / "score").mkdir(parents=True) @@ -36,12 +36,12 @@ def test_the_repository_layout_wins(self, data_root): def test_nothing_on_disk_gives_the_fetch_target(self, data_root): """So a download lands where the folds will look for it.""" - from matchmaker_eval.load_folds import dataset_root + from matchmaker_eval.folds import dataset_root assert dataset_root("asap") == data_root / "asap" def test_a_legacy_copy_in_the_expected_shape_is_reused(self, data_root): - from matchmaker_eval.load_folds import dataset_root + from matchmaker_eval.folds import dataset_root legacy = data_root / "vienna4x22" (legacy / "score").mkdir(parents=True) @@ -55,7 +55,7 @@ def test_a_legacy_copy_in_the_upstream_shape_is_ignored(self, data_root): CSVs name. Returning it sent every path into a differently-shaped tree and the run failed on paths nobody had configured. """ - from matchmaker_eval.load_folds import dataset_root + from matchmaker_eval.folds import dataset_root (data_root / "batik_plays_mozart" / "scores_effective").mkdir(parents=True) assert dataset_root("batik") == data_root / "batik", ( @@ -63,26 +63,26 @@ def test_a_legacy_copy_in_the_upstream_shape_is_ignored(self, data_root): ) def test_an_empty_legacy_directory_is_ignored(self, data_root): - from matchmaker_eval.load_folds import dataset_root + from matchmaker_eval.folds import dataset_root (data_root / "batik_plays_mozart").mkdir() assert dataset_root("batik") == data_root / "batik" def test_local_pieces_come_from_the_repository(self, data_root): - from matchmaker_eval.load_folds import REPO_ROOT as R, dataset_root + from matchmaker_eval.folds import REPO_ROOT as R, dataset_root assert dataset_root("local") == R @pytest.mark.parametrize("layout", ["score", "midi", "match", "audio"]) def test_any_expected_subdirectory_counts(self, data_root, layout): - from matchmaker_eval.load_folds import has_expected_layout + from matchmaker_eval.folds import has_expected_layout d = data_root / "whatever" (d / layout).mkdir(parents=True) assert has_expected_layout(d) def test_a_file_is_not_a_layout(self, data_root): - from matchmaker_eval.load_folds import has_expected_layout + from matchmaker_eval.folds import has_expected_layout f = data_root / "notadir" f.write_text("") @@ -91,11 +91,11 @@ def test_a_file_is_not_a_layout(self, data_root): class TestMissingDataMessage: def test_it_says_how_to_fetch(self, data_root): - from matchmaker_eval.load_folds import FoldError, load_fold, require_files + from matchmaker_eval.folds import FoldError, load_fold, require_files pieces = load_fold("example", input_type="midi") # Point the local dataset somewhere empty so the files are missing. - import matchmaker_eval.load_folds as F + import matchmaker_eval.folds as F monkey = data_root / "nothing" monkey.mkdir() @@ -123,13 +123,13 @@ class TestMetadataRunnerPaths: """ def test_the_root_follows_the_data_dir(self, data_root): - from matchmaker_eval.load_folds import nested_dataset_root + from matchmaker_eval.folds import nested_dataset_root assert nested_dataset_root("asap") == data_root / "asap-dataset-matchmaker" assert nested_dataset_root("batik") == data_root / "batik_plays_mozart" def test_an_unknown_dataset_uses_its_own_name(self, data_root): - from matchmaker_eval.load_folds import nested_dataset_root + from matchmaker_eval.folds import nested_dataset_root assert nested_dataset_root("urmp") == data_root / "urmp" @@ -145,7 +145,7 @@ def test_the_runners_no_longer_hardcode_a_home_directory(self): def test_the_message_names_both_ways_forward(self): from pathlib import Path as P - from matchmaker_eval.load_folds import explain_missing_dataset + from matchmaker_eval.folds import explain_missing_dataset message = explain_missing_dataset("asap", P("/nowhere/x.musicxml")) assert "MATCHMAKER_DATA_DIR" in message diff --git a/tests/test_estimated_bpm.py b/tests/test_estimated_bpm.py index 9dffd77..c45aa97 100644 --- a/tests/test_estimated_bpm.py +++ b/tests/test_estimated_bpm.py @@ -121,14 +121,14 @@ class TestTheFoldCarriesIt: """The tempo is frozen in the fold, beside the paths it belongs to.""" def test_the_example_piece_publishes_one(self): - from matchmaker_eval.load_folds import load_fold + from matchmaker_eval.folds import load_fold piece = load_fold("example", input_type="midi")[0] assert piece.performance_tempo == 58.0 def test_every_eval_row_has_one(self): """A missing value would silently disarm `estimated_bpm: true` runs.""" - from matchmaker_eval.load_folds import load_fold + from matchmaker_eval.folds import load_fold for fold in ("eval", "valid"): blank = [p.piece_id for p in load_fold(fold) if not p.estimated_bpm] @@ -140,19 +140,19 @@ def test_it_is_one_value_per_performance_not_per_container(self): A per-container tempo would have to be two columns, and a follower's audio and MIDI runs would then be measured against different tempi. """ - from matchmaker_eval.load_folds import FOLD_COLUMNS + from matchmaker_eval.folds import FOLD_COLUMNS assert [c for c in FOLD_COLUMNS if "bpm" in c] == ["estimated_bpm"] def test_an_absent_value_reads_as_none(self): - from matchmaker_eval.load_folds import Piece + from matchmaker_eval.folds import Piece piece = Piece("p", "asap", "Bach", "t", "s.musicxml", "p.mid", "", "p.match") assert piece.performance_tempo is None def test_a_non_numeric_value_is_refused(self): """Better a named failure than a follower handed a nonsense tempo.""" - from matchmaker_eval.load_folds import FoldError, Piece + from matchmaker_eval.folds import FoldError, Piece piece = Piece( "p", "asap", "Bach", "t", "s.musicxml", "p.mid", "", "p.match", @@ -166,7 +166,7 @@ class TestOlderFoldsStillLoad: """The column arrived after folds were already in circulation.""" def test_a_fold_without_the_column_loads(self, tmp_path): - from matchmaker_eval.load_folds import REQUIRED_FOLD_COLUMNS, load_fold + from matchmaker_eval.folds import REQUIRED_FOLD_COLUMNS, load_fold csv_path = tmp_path / "old.csv" csv_path.write_text( @@ -178,7 +178,7 @@ def test_a_fold_without_the_column_loads(self, tmp_path): assert piece.performance_tempo is None def test_a_required_column_is_still_required(self, tmp_path): - from matchmaker_eval.load_folds import FoldError, load_fold + from matchmaker_eval.folds import FoldError, load_fold csv_path = tmp_path / "broken.csv" csv_path.write_text("piece_id,dataset\nlocal/x/y,local\n") @@ -196,7 +196,7 @@ class TestMissingTempoFallsBack: def _piece_without_tempo(self): import dataclasses - from matchmaker_eval.load_folds import load_fold + from matchmaker_eval.folds import load_fold piece = load_fold("example", input_type="midi")[0] return dataclasses.replace(piece, estimated_bpm="") @@ -210,7 +210,7 @@ def test_it_runs_anyway(self, tmp_path): assert flat["tracked"] is True def test_a_piece_with_a_tempo_records_that_it_used_one(self, tmp_path): - from matchmaker_eval.load_folds import load_fold + from matchmaker_eval.folds import load_fold from run_submission import run_piece piece = load_fold("example", input_type="midi")[0] @@ -219,7 +219,7 @@ def test_a_piece_with_a_tempo_records_that_it_used_one(self, tmp_path): assert flat["used_estimated_bpm"] is True def test_an_entry_that_never_asked_records_false(self, tmp_path): - from matchmaker_eval.load_folds import load_fold + from matchmaker_eval.folds import load_fold from run_submission import run_piece piece = load_fold("example", input_type="midi")[0] diff --git a/tests/test_evaluation_key.py b/tests/test_evaluation_key.py index 8d75c3e..0156826 100644 --- a/tests/test_evaluation_key.py +++ b/tests/test_evaluation_key.py @@ -18,7 +18,7 @@ sys.path.insert(0, str(_p)) import matchmaker_eval.leaderboard as L -from matchmaker_eval import evaluation_key as P +from matchmaker_eval import provenance as P from matchmaker_eval.export_details import export from merge_shards import MergeError, merge @@ -331,7 +331,7 @@ def test_nothing_is_archived_without_a_key(self, results): class TestTheDetailExport: - def test_the_data_hash_is_an_input_not_a_metric(self, tmp_path): + def test_the_data_hash_is_provenance_not_a_metric(self, tmp_path): run = tmp_path / "run" run.mkdir() (run / "metrics.json").write_text(json.dumps({ diff --git a/tests/test_merge_shards.py b/tests/test_merge_shards.py index f13c6ac..8d9ba14 100644 --- a/tests/test_merge_shards.py +++ b/tests/test_merge_shards.py @@ -5,10 +5,8 @@ which turned every reference method into an unnamed "submission". """ -import hashlib import json import sys -from argparse import Namespace from pathlib import Path import pytest @@ -19,7 +17,6 @@ sys.path.insert(0, str(_p)) from matchmaker_eval.leaderboard import row_from_metrics -from matchmaker_eval import run_diagnostics from merge_shards import MergeError, merge @@ -188,28 +185,6 @@ def test_unrelated_directories_are_ignored(self, tmp_path): (root / "some-other-artifact").mkdir() assert sorted(group(root)) == ["arzt-audio"] - @pytest.mark.parametrize("fold,expected", [ - ("beyond_piano", ["arzt-audio"]), - ("eval", ["arzt-audio", "pthmm-midi"]), - ]) - def test_wrong_fold_or_missing_method_cannot_overwrite_results( - self, tmp_path, monkeypatch, fold, expected, - ): - from merge_references import main - - root = self._flat_download(tmp_path, ["arzt-audio"]) - published = tmp_path / "published" / "arzt-audio" - published.mkdir(parents=True) - record = published / "metrics.json" - record.write_text('{"previous": true}') - monkeypatch.setattr(sys, "argv", [ - "merge_references.py", str(root), "--fold", fold, - "--expected-entries-json", json.dumps(expected), - "--output", str(published.parent), - ]) - assert main() == 1 - assert record.read_text() == '{"previous": true}' - class TestTheTempoLabelSurvivesMerging: """A sharded run must not lose the fact that it was given the tempo.""" @@ -246,62 +221,3 @@ def test_the_count_is_recomputed_from_the_pieces(self, tmp_path): root = write_shards(tmp_path / "shards", [one, two]) merged = merge(root, tmp_path / "merged") assert merged["n_estimated_bpm"] == 1 - - -class TestDiagnostics: - """The manuscript diagnostics run every selected case exactly once.""" - - def test_shards_cover_every_case_once(self): - manifest = {"cases": [{"id": str(i), "suite": "perturbations", "input_type": "audio"} - for i in range(41)]} - config = {"suite": "perturbations", "input_type": "audio"} - shards = [run_diagnostics.select_cases(manifest, config, s, 4) for s in range(4)] - assert sorted(i for shard in shards for i, _ in shard) == list(range(41)) - - def test_selection_filters_by_method_and_rejects_unknown_ones(self): - selected = run_diagnostics.select_configs("dixon", "midi") - assert selected - assert all(c["method"] == "dixon" and c["input_type"] == "midi" for c in selected.values()) - with pytest.raises(ValueError, match="unknown_method"): - run_diagnostics.select_configs("dixon unknown_method", "midi") - - def test_merge_fails_when_a_selected_case_is_missing(self, tmp_path, monkeypatch): - config = {"suite": "perturbations", "input_type": "midi", "method": "chosen"} - monkeypatch.setattr(run_diagnostics, "CONFIGS", { - "chosen-midi": config, "other-midi": {**config, "method": "other"}, - }) - manifest = tmp_path / "manifest.json" - manifest.write_text(json.dumps({"cases": [ - {"id": name, "suite": "perturbations", "input_type": "midi"} for name in ("a", "b") - ]})) - shard = tmp_path / "shards" / "chosen-0" - shard.mkdir(parents=True) - (shard / "metrics.json").write_text(json.dumps({ - "config": "chosen-midi", "shard": 0, "failures": [], "github_run_id": "1", - "data": {"commit": "data"}, "environment": {"benchmark_commit": "code"}, - "pieces": [{"case_id": "a", "category": "example", "tracked": True, "mean_b": 0.0}], - })) - args = Namespace(source=tmp_path / "shards", output=tmp_path / "out", manifest=manifest, - shards=1, only="chosen", input_type="midi") - - with pytest.raises(SystemExit, match="Incomplete diagnostic results"): - run_diagnostics.merge(args) - summary = json.loads((args.output / "summary.json").read_text()) - assert summary["complete"] is False - assert list(summary["configurations"]) == ["chosen-midi"] - - def test_a_chunked_input_is_reassembled_and_hash_checked(self, tmp_path): - chunks = [b"first", b"second"] - parts = [] - for i, data in enumerate(chunks): - (tmp_path / f"p{i}").write_bytes(data) - parts.append({"path": f"p{i}", "sha256": hashlib.sha256(data).hexdigest()}) - entry = {"parts": parts, "sha256": hashlib.sha256(b"".join(chunks)).hexdigest()} - manifest = {"files": {"audio.flac": entry}} - - out = run_diagnostics.fetch_input("audio.flac", manifest, tmp_path, "https://invalid/") - assert out.read_bytes() == b"firstsecond" - - entry["sha256"] = "wrong" - with pytest.raises(ValueError, match="hash mismatch"): - run_diagnostics.fetch_input("audio.flac", manifest, tmp_path, "https://invalid/") diff --git a/tests/test_registry_integration.py b/tests/test_registry_integration.py index 0c6364b..2453318 100644 --- a/tests/test_registry_integration.py +++ b/tests/test_registry_integration.py @@ -268,7 +268,7 @@ class TestFoldPaths: """``--fold`` also takes a path to a CSV, which need not be in the repo.""" def test_fold_file_label_handles_an_external_csv(self, tmp_path): - from matchmaker_eval.load_folds import REPO_ROOT + from matchmaker_eval.folds import REPO_ROOT from run_submission import fold_file_label external = tmp_path / "subset.csv" diff --git a/tests/test_workflows.py b/tests/test_workflows.py index dea0dff..481e874 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -119,10 +119,22 @@ def test_the_run_step_pins_blas_threads(self): class TestMatchmakerPin: """All workflows must install the same matchmaker, or jobs disagree.""" - def test_no_workflow_installs_matchmaker_on_its_own(self): - """Every job installs through .github/install_matchmaker.py instead.""" + def _pins(self) -> dict: + import re + + found = {} for path in sorted(WORKFLOWS.glob("*.yml")): - assert "matchmaker.git@" not in path.read_text(), path.name + for match in re.finditer(r"matchmaker\.git@([\w./-]+)", path.read_text()): + found.setdefault(path.name, set()).add(match.group(1)) + return found + + def test_every_workflow_pins_the_same_ref(self): + refs = {ref for refs in self._pins().values() for ref in refs} + assert len(refs) == 1, ( + f"workflows install different matchmaker refs: {sorted(refs)}. " + "A partial revert leaves the merge job on a different version " + "from the shards." + ) class TestSiteAssembly: @@ -174,6 +186,12 @@ class TestReferencesWorkflow: REFERENCES = WORKFLOWS / "evaluate-references.yml" + def test_it_shares_the_leaderboard_concurrency_group(self): + """Two workflows committing results/ at once would race.""" + mine = load_workflow(self.REFERENCES)["concurrency"]["group"] + theirs = load_workflow(EVALUATE)["concurrency"]["group"] + assert mine == theirs + def test_it_uses_the_same_data_route_as_evaluate(self): workflow = load_workflow(self.REFERENCES) steps = steps_of(workflow, "evaluate") @@ -245,22 +263,32 @@ def test_the_root_licence_flags_the_exception(self): ) -class TestWorkflowTriggers: - """Full evaluations start by hand; only main publishes.""" +class TestStagingBranch: + """Evaluation may run on a staging branch; publishing must not.""" def _branches(self, path): workflow = load_workflow(path) trigger = workflow.get(True) or workflow.get("on") return trigger["push"]["branches"] - @pytest.mark.parametrize("path", [EVALUATE, WORKFLOWS / "evaluate-references.yml"]) - def test_full_evaluations_require_explicit_dispatch(self, path): - workflow = load_workflow(path) - trigger = workflow.get(True) or workflow.get("on") - assert set(trigger) == {"workflow_dispatch"} + def test_evaluation_runs_on_the_staging_branch(self): + assert "submissions" in self._branches(EVALUATE) + assert "main" not in self._branches(EVALUATE) def test_the_site_publishes_only_from_main(self): - assert self._branches(WORKFLOWS / "pages.yml") == ["main"] + """A staging run must be inspectable before anyone sees it.""" + pages = WORKFLOWS / "pages.yml" + assert self._branches(pages) == ["main"], ( + "publishing from a staging branch would defeat the point of having " + "one: a result could reach the site before it was checked" + ) + + def test_a_results_only_commit_does_not_re_trigger_evaluation(self): + """Committing results/ must not start another evaluation.""" + workflow = load_workflow(EVALUATE) + trigger = workflow.get(True) or workflow.get("on") + paths = trigger["push"]["paths"] + assert not any(p.startswith("results") for p in paths) class TestValidateWorkflow: @@ -295,7 +323,7 @@ def test_the_example_fold_is_committed(self): """--smoke must run with nothing downloaded.""" sys.path.insert(0, str(REPO_ROOT)) sys.path.insert(0, str(REPO_ROOT / "matchmaker_eval")) - from matchmaker_eval.load_folds import load_fold, missing_files + from matchmaker_eval.folds import load_fold, missing_files pieces = load_fold("example", input_type="midi") assert pieces @@ -353,84 +381,3 @@ def read_text(self, name): "importlib.metadata.distribution", lambda name: NoDirectUrl() ) assert R._matchmaker_source() == {} - - def test_a_patched_install_records_its_base_and_patches(self, tmp_path, monkeypatch): - import json - from matchmaker_eval import run_submission as R - - source = {"matchmaker_base_commit": "base", "matchmaker_patches": [{"head": "patch"}]} - (tmp_path / "assets").mkdir() - (tmp_path / "assets" / "benchmark-source.json").write_text(json.dumps(source)) - - class LocalInstall: - def read_text(self, name): - return '{"url": "file:///tmp/source", "dir_info": {}}' - - monkeypatch.setattr("importlib.metadata.distribution", lambda name: LocalInstall()) - monkeypatch.setattr("importlib.resources.files", lambda name: tmp_path) - assert R._matchmaker_source() == source - - -class TestReleasedResults: - """A release takes complete runs only and keeps a site-ready snapshot.""" - - RUN = {"status": "completed", "conclusion": "success", - "head_repository": {"full_name": "owner/benchmark"}} - - @pytest.mark.parametrize("change", [ - {"status": "in_progress"}, {"conclusion": "failure"}, - {"head_repository": {"full_name": "someone/fork"}}, - ]) - def test_only_successful_runs_of_this_repository_are_released(self, change): - from matchmaker_eval.release_results import validate_runs - - validate_runs([self.RUN], "owner/benchmark") - with pytest.raises(ValueError, match="successful, completed runs"): - validate_runs([{**self.RUN, **change}], "owner/benchmark") - - @staticmethod - def _stage(tmp_path, **record): - import json - from matchmaker_eval.release_results import stage_piano - - source = tmp_path / "source" / "method-midi" - source.mkdir(parents=True, exist_ok=True) - complete = {"submission": "method-midi", "fold": "eval", "partial": False, - "n_failed": 0, "n_pieces": 2, "fold_size": 2, - "environment": {"benchmark_commit": "abc"}} - (source / "metrics.json").write_text(json.dumps({**complete, **record})) - return stage_piano(source.parent, tmp_path / "published", "abc") - - def test_a_complete_entry_replaces_only_itself(self, tmp_path): - published = tmp_path / "published" / "submissions" - for name in ("method-midi", "other-midi"): - (published / name).mkdir(parents=True) - (published / name / "metrics.json").write_text("previous") - assert self._stage(tmp_path) == ["method-midi"] - assert (published / "method-midi" / "metrics.json").read_text() != "previous" - assert (published / "other-midi" / "metrics.json").read_text() == "previous" - - @pytest.mark.parametrize("record,message", [ - ({"partial": True}, "Incomplete"), - ({"environment": {"benchmark_commit": "other"}}, "source run's commit"), - ]) - def test_an_incomplete_or_mismatched_entry_is_refused(self, tmp_path, record, message): - with pytest.raises(ValueError, match=message): - self._stage(tmp_path, **record) - - def test_the_site_builds_from_a_snapshot(self, tmp_path, monkeypatch): - import build_site - from matchmaker_eval.release_results import extract, snapshot - - results = tmp_path / "results" - (results / "submissions" / "method-midi").mkdir(parents=True) - (results / "submissions" / "method-midi" / "metrics.json").write_text("{}") - (results / "leaderboard.json").write_text('{"entries": []}') - (results / "release.json").write_text('{"publisher_commit": "abc"}') - snapshot(results, tmp_path / "snapshot.zip") - extract(tmp_path / "snapshot.zip", tmp_path / "restored") - - monkeypatch.setattr(build_site, "RESULTS_DIR", tmp_path / "restored") - build_site.build(tmp_path / "site") - for name in ("index.html", "leaderboard.json", "release.json"): - assert (tmp_path / "site" / name).exists()