From d7aa8706c87db4ca6457f204bd7f55e14f4f12d3 Mon Sep 17 00:00:00 2001 From: "jiyun.park" Date: Mon, 16 Nov 2026 15:07:18 +0100 Subject: [PATCH 1/2] Publish results as releases, add experiment folds, pin matchmaker 0.5.0 - Evaluation uploads merged results as artifacts instead of committing results/; Publish leaderboard turns selected runs into a benchmark-* release and deploys the site from its snapshot. - Evaluate references can run the diagnostics, offline and AMT reference folds, each uploading one benchmark-results- artifact. - Pin every workflow to the matchmaker 0.5.0 release and describe the dannenberg reference. --- .github/workflows/evaluate-amt.yml | 111 +++++++++ .github/workflows/evaluate-diagnostics.yml | 101 +++++++++ .github/workflows/evaluate-offline.yml | 117 ++++++++++ .github/workflows/evaluate-references.yml | 103 ++++----- .github/workflows/evaluate.yml | 146 ++---------- .github/workflows/pages.yml | 53 ++++- .github/workflows/tests.yml | 10 +- .github/workflows/validate-submission.yml | 31 +-- README.md | 9 +- data/builtin_methods.yaml | 9 + data/data_sources.yaml | 6 + docs/maintaining.md | 92 ++++---- docs/submitting.md | 31 ++- matchmaker_eval/build_site.py | 3 +- matchmaker_eval/export_details.py | 8 +- matchmaker_eval/fetch_data.py | 8 + matchmaker_eval/folds.py | 1 + matchmaker_eval/leaderboard.py | 5 +- matchmaker_eval/release_results.py | 165 ++++++++++++++ matchmaker_eval/retract.py | 7 +- matchmaker_eval/run_amt.py | 91 ++++++++ matchmaker_eval/run_diagnostics.py | 250 +++++++++++++++++++++ matchmaker_eval/run_offline.py | 132 +++++++++++ tests/test_merge_shards.py | 17 ++ tests/test_workflows.py | 42 +++- 25 files changed, 1225 insertions(+), 323 deletions(-) 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 matchmaker_eval/release_results.py create mode 100644 matchmaker_eval/run_amt.py create mode 100644 matchmaker_eval/run_diagnostics.py create mode 100644 matchmaker_eval/run_offline.py diff --git a/.github/workflows/evaluate-amt.yml b/.github/workflows/evaluate-amt.yml new file mode 100644 index 0000000..eb5a456 --- /dev/null +++ b/.github/workflows/evaluate-amt.yml @@ -0,0 +1,111 @@ +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']) + 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 + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" + 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: | + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" + pip install pyyaml pydantic-settings + - uses: actions/download-artifact@v4 + with: + pattern: amt-* + path: results/shards + - name: Merge the shards + env: + SHARDS: ${{ needs.plan.outputs.shards }} + run: | + python - <<'PY' + import json + import os + import shutil + import sys + from pathlib import Path + + sys.path.insert(0, 'matchmaker_eval') + from merge_shards import merge + from matchmaker_eval.fetch_data import frozen_source + + out = Path('results/amt-reference') + out.mkdir(parents=True, exist_ok=True) + for method in ['arzt', 'pthmm', 'SLT_OLTW']: + stage = Path('results/staging') / method + for i in range(int(os.environ['SHARDS'])): + shutil.copytree(Path('results/shards') / f'amt-{method}-{i}', stage / str(i)) + merge(stage, out / method) + shutil.copytree('results/shards', out / 'raw-shards') + (out / 'amt-data-pin.json').write_text(json.dumps(frozen_source('amt'), indent=2)) + PY + - uses: actions/upload-artifact@v4 + 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..721e1fc --- /dev/null +++ b/.github/workflows/evaluate-diagnostics.yml @@ -0,0 +1,101 @@ +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']) + 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 + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" + 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 + 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 + - uses: actions/download-artifact@v4 + with: + pattern: diagnosis-* + path: results/shards + - name: Aggregate + run: | + python matchmaker_eval/run_diagnostics.py merge --source results/shards \ + --output results/diagnosis + - uses: actions/upload-artifact@v4 + with: + name: benchmark-results-diagnosis + path: results/diagnosis + retention-days: 90 diff --git a/.github/workflows/evaluate-offline.yml b/.github/workflows/evaluate-offline.yml new file mode 100644 index 0000000..65d9d52 --- /dev/null +++ b/.github/workflows/evaluate-offline.yml @@ -0,0 +1,117 @@ +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']) + 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 + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" + pip install pyyaml pydantic-settings + - name: Install the offline numerical environment + run: | + 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: | + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" + pip install pyyaml pydantic-settings + - uses: actions/download-artifact@v4 + with: + pattern: offline-* + path: results/shards + - name: Merge the shards + env: + SHARDS: ${{ needs.plan.outputs.shards }} + run: | + python - <<'PY' + import os + import shutil + import sys + from pathlib import Path + + sys.path.insert(0, 'matchmaker_eval') + from merge_shards import merge + + 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 + for i in range(int(os.environ['SHARDS'])): + shutil.copytree(Path('results/shards') / f'{key}-{i}', stage / str(i)) + merge(stage, output / key) + shutil.copytree('results/shards', output / 'raw-shards') + PY + - uses: actions/upload-artifact@v4 + 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..fcdafac 100644 --- a/.github/workflows/evaluate-references.yml +++ b/.github/workflows/evaluate-references.yml @@ -1,25 +1,4 @@ -# Evaluate matchmaker's built-in methods on GitHub's runners. -# -# The reference rows are what a submission is trying to beat, so they have to be -# measured the way submissions are measured. Until this workflow existed they -# were produced by run_references.py on whoever's laptop was free, which made -# them a different kind of measurement from the rows they are compared against: -# different CPU, different thread count, different corpus on disk. -# -# Everything here mirrors evaluate.yml - the same data checkout, the same -# eight-way round-robin sharding, the same merge and the same leaderboard -# rebuild. The only difference is that it fans out over every described method -# instead of one submission. -# -# Which methods run comes from data/builtin_methods.yaml: a method matchmaker -# has but nobody has described yet is not a leaderboard row, so it is not run. -# -# 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 -# 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. +# Evaluate the built-in methods described in data/builtin_methods.yaml. name: Evaluate references on: @@ -36,7 +15,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,11 +24,10 @@ 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. + # Shares evaluate.yml's group: one evaluation runs at a time. group: evaluate cancel-in-progress: false @@ -57,7 +35,28 @@ env: FOLD: ${{ github.event.inputs.fold || 'eval' }} jobs: + amt_reference: + 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: + if: github.event.inputs.fold != 'diagnostics' && github.event.inputs.fold != 'offline' && github.event.inputs.fold != 'amt_reference' runs-on: ubuntu-latest outputs: jobs: ${{ steps.plan.outputs.jobs }} @@ -141,11 +140,7 @@ 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" + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" pip install pyyaml pydantic-settings - name: Check out the benchmark data @@ -198,8 +193,7 @@ jobs: --num-shards ${{ needs.plan.outputs.num_shards }} - name: Run the shard - # Pinned to one BLAS thread so a runner's core count cannot change what - # the timing columns report between one reference and the next. + # One BLAS thread keeps the timing columns comparable across runners. env: OMP_NUM_THREADS: "1" OPENBLAS_NUM_THREADS: "1" @@ -222,28 +216,18 @@ 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. 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: python-version: "3.12" - name: Install what the merge needs run: | - pip install --quiet "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" + pip install --quiet "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" pip install --quiet pyyaml pydantic-settings - uses: actions/download-artifact@v4 @@ -252,10 +236,16 @@ jobs: path: results/refshards - name: Merge each reference - # 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 + run: python matchmaker_eval/merge_references.py results/refshards --output "results/ci/$FOLD" + + - uses: actions/upload-artifact@v4 + with: + name: benchmark-results-${{ env.FOLD }} + path: results/ci/${{ env.FOLD }} + retention-days: 30 + + - name: Stage the results for the preview + run: cp -a "results/ci/$FOLD/." results/submissions/ - name: Export the per-piece detail run: python matchmaker_eval/export_details.py @@ -271,18 +261,3 @@ jobs: 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..f2025bc 100644 --- a/.github/workflows/evaluate.yml +++ b/.github/workflows/evaluate.yml @@ -1,53 +1,8 @@ -# Full evaluation, after merge — on GitHub's own runners. -# -# Contributors download nothing. The data lives in its own public repository, -# pymatchmaker/matchmaker-benchmark-data, laid out exactly as the benchmark -# expects — so a checkout of it *is* MATCHMAKER_DATA_DIR and no file is -# downloaded piece by piece. Which repository and branch a fold reads is -# 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. -# -# 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. -# -# 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 -# is skipped. Set BENCHMARK_RUNNER to the runner's label. +# Evaluate new or changed submissions after they merge into `submissions`. 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/**" @@ -77,10 +32,10 @@ on: default: "8" permissions: - contents: write + contents: read concurrency: - # One evaluation at a time: two would race on results/leaderboard.json. + # One evaluation at a time, shared with evaluate-references.yml. group: evaluate cancel-in-progress: false @@ -108,13 +63,6 @@ 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" @@ -165,8 +113,6 @@ jobs: 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"] @@ -193,9 +139,6 @@ jobs: - name: Locate this fold's data id: source - # data/data_sources.yaml maps a fold to a branch of the data - # repository. Reading it here means the address is not repeated in this - # file, so moving or renaming the data repository stays a one-line edit. run: | eval "$(python matchmaker_eval/fetch_data.py --source --fold "$FOLD")" echo "data_repo=${owner}/${repo}" >> "$GITHUB_OUTPUT" @@ -229,26 +172,13 @@ 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" + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.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" fi - name: Check out the benchmark data - # The data repository's layout is the one MATCHMAKER_DATA_DIR expects, - # so this checkout is the whole data step: one shallow clone of the - # branch this fold reads, and nothing fetched file by file. - # - # MATCHMAKER_DATA_TOKEN is only needed while the data repository is - # private. Add it as a repository secret with read access to that repo; - # once the repository is public, delete the secret and this keeps - # working. Skipped entirely when MATCHMAKER_DATA_DIR is set to a copy - # the runner already holds. if: vars.MATCHMAKER_DATA_DIR == '' uses: actions/checkout@v4 with: @@ -267,9 +197,6 @@ jobs: fi - name: Check this shard's files are all present - # Names anything the fold asks for that the checkout did not provide, - # before spending an hour discovering it piece by piece. Allowed to - # fail so the fetch below can fill the gap. id: verify continue-on-error: true run: | @@ -280,9 +207,6 @@ jobs: --num-shards ${{ needs.plan.outputs.num_shards }} - name: Fetch anything the checkout did not provide - # The checkout is the fast path, not the only one. A fold whose data is - # not all in that branch — or a dataset served from somewhere else via - # `url_template` — is downloaded file by file into the same directory. if: steps.verify.outcome == 'failure' env: MATCHMAKER_DATA_TOKEN: ${{ secrets.MATCHMAKER_DATA_TOKEN }} @@ -295,8 +219,6 @@ jobs: --num-shards ${{ needs.plan.outputs.num_shards }} - name: Confirm the data is complete - # The hard gate: whichever route got the files here, the shard does not - # start until everything the fold names is on disk. if: steps.verify.outcome == 'failure' run: | python matchmaker_eval/fetch_data.py --verify \ @@ -306,12 +228,8 @@ jobs: --num-shards ${{ needs.plan.outputs.num_shards }} - name: Run the shard - # `target` is either a submission directory or `--method X --input-type Y` - # for a built-in reference, so it is deliberately unquoted. - # - # One BLAS thread, matching evaluate-references.yml: a runner's core - # count would otherwise move the timing columns between one entry and - # the next, and those columns are compared across entries. + # `target` may hold several arguments, so it is unquoted. + # One BLAS thread keeps the timing columns comparable across runners. env: OMP_NUM_THREADS: "1" OPENBLAS_NUM_THREADS: "1" @@ -338,26 +256,13 @@ jobs: 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 - - uses: actions/setup-python@v5 with: python-version: "3.12" - name: Install what the merge needs - # 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" + pip install --quiet "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" pip install --quiet pyyaml pydantic-settings - uses: actions/download-artifact@v4 @@ -366,26 +271,24 @@ jobs: path: results/refshards - name: Merge each submission - # One run can bring shards for several new or changed submissions; - # 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 --output "results/ci/$FOLD" + + - uses: actions/upload-artifact@v4 + with: + name: benchmark-results-${{ env.FOLD }} + path: results/ci/${{ env.FOLD }} + retention-days: 30 + + - name: Stage the results for the preview + run: cp -a "results/ci/$FOLD/." results/submissions/ - name: Export the per-piece detail - # 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 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. run: python matchmaker_eval/build_site.py _site - uses: actions/upload-artifact@v4 @@ -393,18 +296,3 @@ jobs: 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..b4ba727 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -1,48 +1,77 @@ -# 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. +# Publish selected runs as a release and deploy the leaderboard from its 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/**" - ".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: runs-on: ubuntu-latest + outputs: + ready: ${{ steps.results.outputs.ready }} + env: + GH_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@v4 + - 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 + run: | + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" + 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..ea630bf 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,7 +1,4 @@ -# Unit tests for the benchmark code (tests/). -# -# Read-only: no secrets, no data download, no writes. Runs on every pull -# request into main or submissions and on pushes to main. +# Unit tests for the benchmark code. name: Tests on: @@ -36,12 +33,9 @@ jobs: sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 - name: Install the test environment - # Same matchmaker pin as the other workflows (tests/test_workflows.py - # checks that they agree). tabulate and wandb are imported by - # 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" + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.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 968972f..5083ddd 100644 --- a/.github/workflows/validate-submission.yml +++ b/.github/workflows/validate-submission.yml @@ -1,14 +1,4 @@ -# Pull-request gate for submissions. -# -# Runs on `pull_request`, deliberately NOT on `pull_request_target`: this job -# executes code from the pull request, so it must never be given the repository -# secrets or a writable token. It runs on an ephemeral runner with a read-only -# token, and it cannot touch the leaderboard. -# -# What this proves: the submission is well-formed and its follower runs. What it -# cannot prove: that the code is safe or that the eval fold was not used for -# tuning. Those are the maintainer's job at review time — see -# docs/eval-protocol.md. +# Runs on `pull_request`, not `pull_request_target`: it executes untrusted code without secrets. name: Validate submission on: @@ -47,18 +37,9 @@ jobs: sudo apt-get install -y --no-install-recommends fluidsynth libsndfile1 - name: Install the benchmark environment - # Deliberately not `-r requirements.txt`: that file covers the full - # benchmark, including madmom (a slow source build), pyaudio and - # python-rtmidi (live devices, useless on a runner) and wandb. The - # submission path needs matchmaker plus the two imports in - # 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" + pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" pip install pyyaml pydantic-settings - name: Find the submissions touched by this pull request @@ -71,12 +52,6 @@ jobs: echo "Submissions touched: ${dirs:-none}" - name: A pull request into `submissions` may touch only one submission - # Contributor submissions target `submissions` (see docs/submitting.md), - # never `main` directly, so this is the gate that keeps a contributor's - # pull request confined to their own submissions// directory -- - # no pipeline changes, no workflow changes, no other submitter's - # directory. Benchmark changes are a maintainer's pull request into - # `main`, which this check does not apply to. if: github.base_ref == 'submissions' run: | other=$(git diff --name-only "origin/${{ github.base_ref }}...HEAD" \ @@ -106,8 +81,6 @@ jobs: done - name: Validate and smoke-test - # The example fold is the single piece committed under resources/, so - # this needs no dataset download. if: steps.changed.outputs.dirs != '' run: | python matchmaker_eval/validate_submission.py ${{ steps.changed.outputs.dirs }} --smoke diff --git a/README.md b/README.md index 9feefbc..0f6bebf 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ data** — the evaluation runs on GitHub's runners, which fetch what they need. git clone https://github.com/pymatchmaker/matchmaker_benchmark.git cd matchmaker_benchmark conda env create -f environment.yml && conda activate matchmaker-benchmark -pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" +pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" cp -r submissions/_template submissions/your-name ``` @@ -83,13 +83,14 @@ 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 the results │ │ │ │ └──────────────── leaderboard on GitHub Pages ◄─────────────────────┘ ``` Review is the trust boundary: CI executes submitted code, it does not sandbox -it. Everything after merge is automatic. +it. Evaluation after merge is automatic; a maintainer publishes results in +batches as GitHub releases (see [publishing results](docs/maintaining.md#staging-a-run-before-it-is-published)). ## Folds @@ -263,7 +264,7 @@ docs/ — contributor and maintainer documentation, and the .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 + pages.yml — publishes selected runs as a release and the leaderboard ``` ## 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..1207ef7 100644 --- a/data/data_sources.yaml +++ b/data/data_sources.yaml @@ -35,6 +35,12 @@ branches: # test-only beyond-piano corpora, held with the eval data beyond_piano: eval +frozen_sources: + diagnostics: + commit: 3427d8db589f6a9cd860492676eac31eb4d2ee5d + amt: + commit: 3427d8db589f6a9cd860492676eac31eb4d2ee5d + # 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/maintaining.md b/docs/maintaining.md index 0164e35..b549874 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -38,14 +38,15 @@ starts the evaluation — see "Staging a run before it is published" below. ## 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. +runners and uploads the merged results as an artifact. 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 results how many shards, run it, upload results where the data is ``` @@ -231,7 +232,21 @@ Actions -> Evaluate references -> Run workflow input_type: both only: (empty = all described) shards: 8 ``` -It mirrors `evaluate.yml` exactly — same data checkout, same eight-way +The `fold` input selects what to run. Only `eval` feeds the leaderboard; the +experiment folds below only upload 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` | + +The experiment folds each upload one `benchmark-results-` artifact with +the merged results, full paths and `meter_.json` maps. + +It mirrors `evaluate.yml` exactly — same data checkout, same 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 @@ -300,41 +315,34 @@ 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: +`submissions` is where evaluation happens; a GitHub release is what is +published. -1. review the code, then merge the submission's pull request into +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. + or has changed since, skipping ones that are unchanged. This is the first + time the submitted code runs against the real datasets, which is why review + has to happen at step 1. +3. The run uploads `benchmark-results-eval` (the merged records and full paths) + and a `leaderboard-site` preview. Nothing is committed and nothing is + published yet; rerun anything that looks wrong. +4. When a batch is ready, dispatch **Publish leaderboard** on `main`: + - `source_runs`: the completed run IDs, separated by spaces. Later listed + runs replace earlier entries for the same method. Entries 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 and a `benchmark-snapshot.zip` + for the site to the release, then deploys it. Actions artifacts + expire after 30 days, so publish runs before then. + +To re-run something already evaluated, dispatch `evaluate.yml` manually with +that submission's name. ### Withdrawing or replacing a published result @@ -342,11 +350,12 @@ 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** — a rerun after a bug fix — evaluate again and include +that run in the next release; it replaces the entry in the new snapshot. -**To withdraw one**, use `retract.py` rather than deleting by hand: it also +**To withdraw one**, download the latest release's `benchmark-snapshot.zip`, +unpack it, point `MATCHMAKER_RESULTS_DIR` at it, and 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. @@ -368,7 +377,8 @@ to `results/retracted//`, so `--reason` is required and `--undo` puts it back. `--purge` deletes instead of archiving, and cannot be undone. `export_details.py` also removes any detail file whose run has gone, so a -hand-deleted result cannot leave one behind either. +hand-deleted result cannot leave one behind either. Publish the corrected +snapshot as a new release. ### By hand @@ -475,9 +485,9 @@ 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` builds the site from `docs/` plus the leaderboard +files, CSVs and details of a release snapshot, and deploys it to GitHub Pages. +Documentation changes redeploy the latest release. ### What the site can show @@ -529,6 +539,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 +`leaderboard.json` from the published Pages site, 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 7a59f33..e2bc7c5 100644 --- a/docs/submitting.md +++ b/docs/submitting.md @@ -4,8 +4,8 @@ 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. +on `submissions`. A maintainer publishes results to the live site in batches, +as a GitHub release, whenever they judge a batch ready. ``` you GitHub maintainer GitHub Actions @@ -21,11 +21,11 @@ merging `submissions` into `main` whenever they judge the batch ready. │ │ │ evaluates every new or │ │ │ changed submission in │ │ │ parallel shards, - │ │ │ commits the result - │ │ │ to `submissions` + │ │ │ uploads the result + │ │ │ as an artifact │ │ │ │ - │ │ ...whenever ready, the maintainer merges - │ │ `submissions` into `main` to publish... + │ │ ...whenever ready, the maintainer publishes + │ │ the batch as a release... │ │ │ │ └──────────────── leaderboard on GitHub Pages ◄─────────────────────┘ ``` @@ -38,7 +38,7 @@ cd matchmaker_benchmark conda env create -f environment.yml conda activate matchmaker-benchmark -pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.4.0" +pip install "pymatchmaker @ git+https://github.com/pymatchmaker/matchmaker.git@v0.5.0" ``` You do not need to download any dataset to write and test a submission — the @@ -182,28 +182,25 @@ GitHub will hold the workflow until a maintainer approves the run. 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`. +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 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 merged record and the full per-piece output (alignment paths, per-piece +metrics) are attached to the workflow run as an artifact for 30 days. -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 +This does not publish yet. A maintainer reads the result and adds the run to +the next GitHub release, 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`. 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`. Merging it evaluates your submission again, and the next +release replaces its row on the live leaderboard. 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..b44acef 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): diff --git a/matchmaker_eval/export_details.py b/matchmaker_eval/export_details.py index e6acf6e..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. @@ -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.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..d8b5c21 100644 --- a/matchmaker_eval/fetch_data.py +++ b/matchmaker_eval/fetch_data.py @@ -113,12 +113,20 @@ def load_config() -> dict: value = os.environ.get(variable) if value: config[key] = value + if key == "branch": + 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..82d8c18 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.folds import LEADERBOARD_FOLD, REPO_ROOT, RESULTS_DIR 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" @@ -587,7 +586,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/release_results.py b/matchmaker_eval/release_results.py new file mode 100644 index 0000000..b60fe80 --- /dev/null +++ b/matchmaker_eval/release_results.py @@ -0,0 +1,165 @@ +"""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 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-")] + return max(candidates, key=lambda r: r["published_at"], default=None) + + +def extract(archive, destination): + with zipfile.ZipFile(archive) as bundle: + bundle.extractall(destination) + + +def fetch(repo, release, destination): + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + gh("release", "download", release["tag_name"], "--repo", repo, + "--pattern", SNAPSHOT, "--dir", str(work)) + if destination.exists(): + shutil.rmtree(destination) + extract(work / SNAPSHOT, destination) + + +def stage_piano(source, destination): + """Later selected runs replace their entries; other methods are retained.""" + entries = [] + for path in sorted(source.glob("*/metrics.json")): + target = destination / "submissions" / path.parent.name + if target.exists(): + shutil.rmtree(target) + shutil.copytree(path.parent, target) + entries.append(path.parent.name) + return entries + + +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): + runs = [api(f"repos/{repo}/actions/runs/{run}") for run in run_ids] + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, text=True).strip() + + base = latest(records) + entry_sources = {} + if base: + fetch(repo, base, destination) + entry_sources = json.loads((destination / "release.json").read_text())["entry_sources"] + else: + destination.mkdir(parents=True) + 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-")] + for artifact in artifacts: + output = assets / f"run-{run['id']}-{artifact['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 artifact["name"] == "benchmark-results-eval": + unpacked = work / str(artifact["id"]) + extract(output, unpacked) + for entry in stage_piano(unpacked, destination): + entry_sources[entry] = run["id"] + sources.append({"id": run["id"], "url": run["html_url"], + "benchmark_commit": run["head_sha"]}) + + 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()) + manifest = {"tag": tag, "publisher_commit": commit, "source_runs": sources, + "entry_sources": entry_sources, + "evaluation_keys": board["evaluation_keys"]} + (destination / "release.json").write_text(json.dumps(manifest, indent=2) + "\n") + snapshot(destination, assets / SNAPSHOT) + 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" + ) + gh("release", "create", tag, *(str(p) for p in sorted(assets.iterdir())), + "--repo", repo, "--target", commit, "--title", tag, "--notes-file", str(notes)) + 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() + + records = releases(args.repo) + if args.source_runs: + tag = publish(args.repo, args.tag, args.source_runs.split(), records, RESULTS_DIR) + else: + if args.tag: + release = next(r for r in records if r["tag_name"] == args.tag) + else: + release = latest(records) + 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.") + + +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..74b5095 --- /dev/null +++ b/matchmaker_eval/run_amt.py @@ -0,0 +1,91 @@ +"""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.run_diagnostics import download # noqa: E402 +from matchmaker_eval.submission import DECLARATION_KEY # noqa: E402 + + +def fetch_cached(url, path): + if not path.exists(): + download(url, path) + 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_cached(base_url + "manifest.json", cache / "manifest.json") + cases = json.loads(manifest.read_text())["cases"] + 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_cached(base_url + case["path"], args.cache / case["path"]) + + 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: + 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(), + } + rs.evaluate_submission(builtin=args.method, input_type="audio", fold="eval", + shard=args.shard, num_shards=args.num_shards, + run_dir=args.output) + + +if __name__ == "__main__": + main() diff --git a/matchmaker_eval/run_diagnostics.py b/matchmaker_eval/run_diagnostics.py new file mode 100644 index 0000000..c4bb912 --- /dev/null +++ b/matchmaker_eval/run_diagnostics.py @@ -0,0 +1,250 @@ +"""Run and merge the manuscript diagnostic suites with the benchmark evaluator. + +Inputs come from a manifest pinned to one commit of the data repository. +""" + +import argparse +import contextlib +import json +import os +import shutil +import sys +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)) + +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()) + return {name: c for name, c in CONFIGS.items() + if input_type in ("both", c["input_type"]) and (not methods or c["method"] in methods)} + + +def select_cases(manifest, config, shard=0, shards=1): + """The (index, case) pairs of one shard, round-robin over the suite's cases.""" + cases = [c for c in manifest["cases"] + if c["suite"] == config["suite"] and c["input_type"] == config["input_type"]] + return [(i, c) for i, c in enumerate(cases) if i % shards == shard] + + +def download(url, path): + path.parent.mkdir(parents=True, exist_ok=True) + with urllib.request.urlopen(url, timeout=120) as response, path.open("wb") as out: + shutil.copyfileobj(response, out) + + +def fetch_input(name, cache, base_url): + """Download one input into ``cache`` unless it is already there.""" + path = cache / name + if not path.exists(): + download(base_url + name, path) + 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(): + download(base_url + "manifest.json", path) + 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="") + + 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): + 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"), + "pieces": [], "failures": [], + } + args.output.mkdir(parents=True, exist_ok=True) + + 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], 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["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) + + +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): + records = [json.loads(p.read_text()) for p in args.source.glob("*/metrics.json")] + args.output.mkdir(parents=True, exist_ok=True) + + pieces = defaultdict(list) + for record in records: + pieces[record["config"]].extend(record["pieces"]) + summary = {name: summarize(group) for name, group in sorted(pieces.items())} + + 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) + write_json(args.output / "summary.json", {"configurations": summary}) + + +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="combine downloaded shards") + merge_parser.add_argument("--source", type=Path, required=True) + merge_parser.add_argument("--output", type=Path, required=True) + 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 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/tests/test_merge_shards.py b/tests/test_merge_shards.py index 8d9ba14..20728ee 100644 --- a/tests/test_merge_shards.py +++ b/tests/test_merge_shards.py @@ -17,6 +17,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 @@ -221,3 +222,19 @@ 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_input_type(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()) diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 481e874..6a52ffa 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -187,7 +187,7 @@ class TestReferencesWorkflow: REFERENCES = WORKFLOWS / "evaluate-references.yml" def test_it_shares_the_leaderboard_concurrency_group(self): - """Two workflows committing results/ at once would race.""" + """The two evaluation workflows run one at a time.""" mine = load_workflow(self.REFERENCES)["concurrency"]["group"] theirs = load_workflow(EVALUATE)["concurrency"]["group"] assert mine == theirs @@ -331,11 +331,7 @@ def test_the_example_fold_is_committed(self): class TestRunProvenance: - """A published row should say which matchmaker produced it. - - The version string is "0.3.0" on every branch, so while the workflows - install from a feature branch it cannot distinguish one run from another. - """ + """A published row should say which matchmaker produced it.""" def test_the_environment_records_the_benchmark_commit(self): import sys as _sys @@ -381,3 +377,37 @@ def read_text(self, name): "importlib.metadata.distribution", lambda name: NoDirectUrl() ) assert R._matchmaker_source() == {} + +class TestReleasedResults: + """A release replaces the entries it brings and keeps a site-ready snapshot.""" + + def test_a_staged_entry_replaces_only_itself(self, tmp_path): + from matchmaker_eval.release_results import stage_piano + + source = tmp_path / "source" / "method-midi" + source.mkdir(parents=True) + (source / "metrics.json").write_text("new") + 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 stage_piano(source.parent, tmp_path / "published") == ["method-midi"] + assert (published / "method-midi" / "metrics.json").read_text() == "new" + assert (published / "other-midi" / "metrics.json").read_text() == "previous" + + 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": []}') + 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"): + assert (tmp_path / "site" / name).exists() From 68611e36fd018d2dbd0bb35abcf9df3d2c9e93e3 Mon Sep 17 00:00:00 2001 From: "jiyun.park" Date: Wed, 18 Nov 2026 10:13:32 +0100 Subject: [PATCH 2/2] Address review: publish only successful runs, and only from main; per-experiment method lists; OPHMM global transitions off in the main benchmark and perturbations --- .github/workflows/evaluate-amt.yml | 22 +++++++++--- .github/workflows/evaluate-diagnostics.yml | 16 +++++---- .github/workflows/evaluate-offline.yml | 11 +++--- .github/workflows/evaluate.yml | 2 ++ .github/workflows/pages.yml | 1 + .github/workflows/validate-submission.yml | 2 ++ data/amt_methods.yaml | 1 + data/diagnosis_methods.yaml | 8 +++++ docs/maintaining.md | 7 ++-- matchmaker_eval/merge_references.py | 2 +- matchmaker_eval/release_results.py | 2 ++ matchmaker_eval/run_amt.py | 5 ++- matchmaker_eval/run_diagnostics.py | 41 +++++++++++----------- matchmaker_eval/run_submission.py | 9 +++++ tests/test_estimated_bpm.py | 38 ++++++++++++++++++++ tests/test_workflows.py | 8 +++++ 16 files changed, 136 insertions(+), 39 deletions(-) create mode 100644 data/amt_methods.yaml create mode 100644 data/diagnosis_methods.yaml diff --git a/.github/workflows/evaluate-amt.yml b/.github/workflows/evaluate-amt.yml index eb5a456..8edbd43 100644 --- a/.github/workflows/evaluate-amt.yml +++ b/.github/workflows/evaluate-amt.yml @@ -14,15 +14,25 @@ jobs: 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: | + pip install --quiet pyyaml python - <<'PY' >> "$GITHUB_OUTPUT" - import json,os - n=int(os.environ['SHARDS']) - print('matrix='+json.dumps({'method':['arzt','pthmm','SLT_OLTW'],'shard':list(range(n))})) - print('shards='+str(n)) + import json + import os + + import yaml + + methods = yaml.safe_load(open("data/amt_methods.yaml"))["midi"] + shards = int(os.environ["SHARDS"]) + print("matrix=" + json.dumps({"method": methods, "shard": list(range(shards))})) + print(f"shards={shards}") PY evaluate: needs: plan @@ -90,13 +100,15 @@ jobs: import sys from pathlib import Path + import yaml + sys.path.insert(0, 'matchmaker_eval') from merge_shards import merge from matchmaker_eval.fetch_data import frozen_source out = Path('results/amt-reference') out.mkdir(parents=True, exist_ok=True) - for method in ['arzt', 'pthmm', 'SLT_OLTW']: + for method in yaml.safe_load(open('data/amt_methods.yaml'))['midi']: stage = Path('results/staging') / method for i in range(int(os.environ['SHARDS'])): shutil.copytree(Path('results/shards') / f'amt-{method}-{i}', stage / str(i)) diff --git a/.github/workflows/evaluate-diagnostics.yml b/.github/workflows/evaluate-diagnostics.yml index 721e1fc..5a33a5b 100644 --- a/.github/workflows/evaluate-diagnostics.yml +++ b/.github/workflows/evaluate-diagnostics.yml @@ -31,13 +31,17 @@ jobs: env: SHARDS: ${{ inputs.shards }} run: | + pip install --quiet pyyaml python - <<'PY' >> "$GITHUB_OUTPUT" - import json, os + import json + import os + from matchmaker_eval.run_diagnostics import select_configs - n = int(os.environ['SHARDS']) - 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)) + + shards = int(os.environ["SHARDS"]) + 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(shards)])) + print(f"shards={shards}") PY evaluate: needs: plan @@ -85,7 +89,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.12' - - run: pip install numpy + - run: pip install numpy pyyaml - uses: actions/download-artifact@v4 with: pattern: diagnosis-* diff --git a/.github/workflows/evaluate-offline.yml b/.github/workflows/evaluate-offline.yml index 65d9d52..a0a4194 100644 --- a/.github/workflows/evaluate-offline.yml +++ b/.github/workflows/evaluate-offline.yml @@ -19,10 +19,13 @@ jobs: SHARDS: ${{ inputs.shards }} run: | python - <<'PY' >> "$GITHUB_OUTPUT" - import json,os - n=int(os.environ['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)) + import json + import os + + shards = int(os.environ["SHARDS"]) + jobs = [{"fold": fold, "shard": s} for fold in ["eval", "beyond_piano"] for s in range(shards)] + print("matrix=" + json.dumps(jobs)) + print(f"shards={shards}") PY evaluate: needs: plan diff --git a/.github/workflows/evaluate.yml b/.github/workflows/evaluate.yml index f2025bc..466317e 100644 --- a/.github/workflows/evaluate.yml +++ b/.github/workflows/evaluate.yml @@ -148,6 +148,7 @@ jobs: evaluate: needs: plan if: needs.plan.outputs.count != '0' + # On a self-hosted runner, set BENCHMARK_RUNNER to its label and MATCHMAKER_DATA_DIR to its data copy. runs-on: ${{ vars.BENCHMARK_RUNNER || 'ubuntu-latest' }} timeout-minutes: 350 strategy: @@ -179,6 +180,7 @@ jobs: fi - name: Check out the benchmark data + # MATCHMAKER_DATA_TOKEN grants read access to the data repository if it is private. if: vars.MATCHMAKER_DATA_DIR == '' uses: actions/checkout@v4 with: diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index b4ba727..2199b5c 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -30,6 +30,7 @@ concurrency: jobs: build: + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest outputs: ready: ${{ steps.results.outputs.ready }} diff --git a/.github/workflows/validate-submission.yml b/.github/workflows/validate-submission.yml index 5083ddd..5a24665 100644 --- a/.github/workflows/validate-submission.yml +++ b/.github/workflows/validate-submission.yml @@ -52,6 +52,7 @@ jobs: echo "Submissions touched: ${dirs:-none}" - name: A pull request into `submissions` may touch only one submission + # Keeps contributor pull requests out of the pipeline, the workflows and other submissions. if: github.base_ref == 'submissions' run: | other=$(git diff --name-only "origin/${{ github.base_ref }}...HEAD" \ @@ -81,6 +82,7 @@ jobs: done - name: Validate and smoke-test + # Proves the follower runs; code safety and eval-fold tuning remain the reviewer's job. if: steps.changed.outputs.dirs != '' run: | python matchmaker_eval/validate_submission.py ${{ steps.changed.outputs.dirs }} --smoke diff --git a/data/amt_methods.yaml b/data/amt_methods.yaml new file mode 100644 index 0000000..3ccd7fd --- /dev/null +++ b/data/amt_methods.yaml @@ -0,0 +1 @@ +midi: [arzt, pthmm, SLT_OLTW] diff --git a/data/diagnosis_methods.yaml b/data/diagnosis_methods.yaml new file mode 100644 index 0000000..9074c1c --- /dev/null +++ b/data/diagnosis_methods.yaml @@ -0,0 +1,8 @@ +perturbations: + midi: [OPTM, OTM, SLT_OLTW, SL_OLTW, arzt, dannenberg, dixon, hmm, outerhmm, pfkorz, pthmm] + audio: [arzt, arzt_tempo, dixon, outerhmm, pfkorz, skf] +repeat_examples: + midi: [OPTM, OTM, SLT_OLTW, SL_OLTW, arzt, dannenberg, dixon, hmm, outerhmm, pfkorz, pthmm] + audio: [arzt, arzt_multi_fold, arzt_tempo, dixon, outerhmm, pfkorz, skf] +folded_batik: + audio: [arzt, arzt_multi_fold, arzt_tempo, dixon, outerhmm, pfkorz, skf] diff --git a/docs/maintaining.md b/docs/maintaining.md index b549874..24fe581 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -243,6 +243,8 @@ experiment folds below only upload artifacts. | `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` | +The methods the `diagnostics` and `amt_reference` folds run are listed in +`data/diagnosis_methods.yaml` and `data/amt_methods.yaml`. The experiment folds each upload one `benchmark-results-` artifact with the merged results, full paths and `meter_.json` maps. @@ -252,7 +254,7 @@ 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 +Each method and shard is one job; 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`. @@ -316,7 +318,8 @@ differ on their own. ### Staging a run before it is published `submissions` is where evaluation happens; a GitHub release is what is -published. +published. `evaluate.yml` runs from `submissions`, so fast-forward it to +`main` after changing the pipeline. 1. Review the code, then merge the submission's pull request into `submissions`. It is restricted to that one `submissions//` diff --git a/matchmaker_eval/merge_references.py b/matchmaker_eval/merge_references.py index b006d31..45b1a8d 100644 --- a/matchmaker_eval/merge_references.py +++ b/matchmaker_eval/merge_references.py @@ -131,7 +131,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/release_results.py b/matchmaker_eval/release_results.py index b60fe80..9860c30 100644 --- a/matchmaker_eval/release_results.py +++ b/matchmaker_eval/release_results.py @@ -79,6 +79,8 @@ def snapshot(results, output): def publish(repo, tag, run_ids, records, destination): runs = [api(f"repos/{repo}/actions/runs/{run}") for run in run_ids] + if any(run["conclusion"] != "success" for run in runs): + raise ValueError("Only successful runs can be published") commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, text=True).strip() base = latest(records) diff --git a/matchmaker_eval/run_amt.py b/matchmaker_eval/run_amt.py index 74b5095..f7c211d 100644 --- a/matchmaker_eval/run_amt.py +++ b/matchmaker_eval/run_amt.py @@ -10,6 +10,8 @@ import sys from pathlib import Path +import yaml + ROOT = Path(__file__).resolve().parents[1] for p in (ROOT, ROOT / "matchmaker_eval"): sys.path.insert(0, str(p)) @@ -40,7 +42,8 @@ def load_cases(cache): def main(): parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - parser.add_argument("--method", choices=["arzt", "pthmm", "SLT_OLTW"], default="arzt") + methods = yaml.safe_load((ROOT / "data" / "amt_methods.yaml").read_text())["midi"] + parser.add_argument("--method", choices=methods, 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) diff --git a/matchmaker_eval/run_diagnostics.py b/matchmaker_eval/run_diagnostics.py index c4bb912..6d4e3dd 100644 --- a/matchmaker_eval/run_diagnostics.py +++ b/matchmaker_eval/run_diagnostics.py @@ -14,26 +14,20 @@ from collections import defaultdict from pathlib import Path +import yaml + ROOT = Path(__file__).resolve().parents[1] for p in (ROOT, ROOT / "matchmaker_eval"): sys.path.insert(0, str(p)) -PERTURBATION_METHODS = { - "audio": ["dixon", "arzt", "outerhmm", "skf"], - "midi": ["pthmm", "hmm", "outerhmm", "dixon", "arzt", "SLT_OLTW", "dannenberg"], -} +EXPERIMENTS = yaml.safe_load((ROOT / "data" / "diagnosis_methods.yaml").read_text()) 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"]}, + f"{suite}-{t}-{m}": {"suite": suite, "input_type": t, "method": m} + for suite, types in EXPERIMENTS.items() + for t, methods in types.items() + for m in methods } +CONFIGS["folded_batik-audio-outerhmm"]["kwargs"] = {"s_j": 1e-5} def select_configs(only="", input_type="both"): @@ -45,8 +39,15 @@ def select_configs(only="", input_type="both"): def select_cases(manifest, config, shard=0, shards=1): """The (index, case) pairs of one shard, round-robin over the suite's cases.""" - cases = [c for c in manifest["cases"] - if c["suite"] == config["suite"] and c["input_type"] == config["input_type"]] + cases = [] + for case in manifest["cases"]: + # K.282 replaces BWV 858 as the repetition case, for both modalities. + if case["id"] == "synthetic/Section_Repetition/bwv858-two_jump-m9-10_m17-27-bpm_65": + continue + if case["suite"] == "repeat_examples": + case = {**case, "input_type": config["input_type"]} + if case["suite"] == config["suite"] and case["input_type"] == config["input_type"]: + cases.append(case) return [(i, c) for i, c in enumerate(cases) if i % shards == shard] @@ -91,9 +92,10 @@ def run_case(case, config, paths, out): input_type, method = config["input_type"], config["method"] performance = paths[f"{input_type}_performance"] + repeat = config["suite"] == "repeat_examples" 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["s_j"] = 1e-100 if repeat else 0.0 kwargs.update(config.get("kwargs", {})) out.mkdir(parents=True, exist_ok=True) @@ -102,8 +104,8 @@ def run_case(case, config, paths, out): 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 + if input_type == "midi" and method == "outerhmm" and not repeat: + mm.score_follower.S[:] = 0.0 for _ in mm.run(verbose=False): pass times, beats = resolve_gt(paths["match"], mm.score_part.note_array(), @@ -144,7 +146,6 @@ def run_case(case, config, paths, out): "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()), diff --git a/matchmaker_eval/run_submission.py b/matchmaker_eval/run_submission.py index 482d667..d8f5960 100644 --- a/matchmaker_eval/run_submission.py +++ b/matchmaker_eval/run_submission.py @@ -52,6 +52,7 @@ ) from matchmaker import Matchmaker +from matchmaker.matchmaker import DEFAULT_KWARGS from matchmaker.base import OnlineAlignment from matchmaker_eval.fetch_data import FetchError, fetch_for_pieces, load_config @@ -233,6 +234,9 @@ def run_piece( then visible rather than assumed. """ tempo = piece.performance_tempo if estimated_bpm else None + kwargs = None + if method == "outerhmm" and input_type == "audio": + kwargs = {**DEFAULT_KWARGS["audio"][method], "s_j": 0.0} mm = Matchmaker( score_file=str(piece.score_path), @@ -242,8 +246,11 @@ def run_piece( wait=False, unfold_score=True, tempo=tempo, + kwargs=kwargs, ) check_follower(mm.score_follower) + if method == "outerhmm" and mm.input_type == "midi": + mm.score_follower.S[:] = 0.0 # play-through evaluation uses local transitions list(mm.run(verbose=False)) wp = mm.score_follower.alignment_path @@ -305,6 +312,8 @@ def run_piece( # 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. metrics["used_estimated_bpm"] = tempo is not None + if method == "outerhmm": + metrics["global_transition_enabled"] = False with open(run_dir / f"{index}.json", "w") as f: json.dump(metrics, f, indent=4, default=float) diff --git a/tests/test_estimated_bpm.py b/tests/test_estimated_bpm.py index c45aa97..42086a8 100644 --- a/tests/test_estimated_bpm.py +++ b/tests/test_estimated_bpm.py @@ -299,3 +299,41 @@ def test_the_offline_path_leaves_the_tempo_blank(self, tmp_path): "match/Chopin_op10_no3_p08.match,1\n" ) assert list(read_metadata_rows("vienna", path))[0].estimated_bpm == "" + + +def test_playthrough_midi_ophmm_disables_global_transition(tmp_path, monkeypatch): + import numpy as np + from matchmaker_eval import run_submission as rs + from matchmaker_eval.folds import load_fold + + original = rs.Matchmaker + def matchmaker(**kwargs): + mm = original(**kwargs) + assert np.any(mm.score_follower.S > 0) + run = mm.run + def checked_run(**options): + assert np.all(mm.score_follower.S == 0) + return run(**options) + mm.run = checked_run + return mm + monkeypatch.setattr(rs, "Matchmaker", matchmaker) + piece = load_fold("example", input_type="midi")[0] + metrics = rs.run_piece("outerhmm", piece, "midi", 1, tmp_path, False) + assert metrics["global_transition_enabled"] is False + + +def test_playthrough_audio_ophmm_disables_global_transition(tmp_path, monkeypatch): + import numpy as np + from matchmaker_eval import run_submission as rs + from matchmaker_eval.folds import load_fold + + original = rs.Matchmaker + def matchmaker(**kwargs): + assert kwargs["kwargs"]["s_j"] == 0.0 + mm = original(**kwargs) + assert np.all(mm.score_follower.S == 0) + return mm + monkeypatch.setattr(rs, "Matchmaker", matchmaker) + piece = load_fold("example", input_type="audio")[0] + metrics = rs.run_piece("outerhmm", piece, "audio", 1, tmp_path, False) + assert metrics["global_transition_enabled"] is False diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 6a52ffa..6d276ac 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -411,3 +411,11 @@ def test_the_site_builds_from_a_snapshot(self, tmp_path, monkeypatch): build_site.build(tmp_path / "site") for name in ("index.html", "leaderboard.json"): assert (tmp_path / "site" / name).exists() + + @pytest.mark.parametrize("status,conclusion", [("in_progress", None), ("completed", "failure"), + ("completed", "cancelled")]) + def test_unfinished_or_failed_run_is_not_published(self, tmp_path, monkeypatch, status, conclusion): + from matchmaker_eval import release_results + monkeypatch.setattr(release_results, "api", lambda path: {"status": status, "conclusion": conclusion}) + with pytest.raises(ValueError, match="successful runs"): + release_results.publish("test/repo", "benchmark-test", ["1"], [], tmp_path)