diff --git a/submissions/bjork-gudmundsdottir-dual/README.md b/submissions/bjork-gudmundsdottir-dual/README.md new file mode 100644 index 0000000..f55d10c --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/README.md @@ -0,0 +1,110 @@ +# Transcribe twice and follow + +Team Björk Guðmundsdóttir (Matthias Nagl, Klaus Lex, Kevin Eberl), Music +Informatics WS26, JKU Linz. + +An audio score follower in two steps, like our first submission +(`bjork-gudmundsdottir`): piano transcription turns the audio into notes while +it arrives, and a symbolic follower aligns those notes to the score. What is +new is that two transcribers run side by side. The slower one decides where +in the score the performer is, the faster one decides when the next chord +comes. + +## Why two transcribers + +A transcriber that looks 5 frames ahead finds notes reliably, but it knows a +note only about 166 ms after it is played. Our first submission bridges that +delay by moving on at the followed tempo between notes. A transcriber without +lookahead knows a note after 46 ms, but when we followed its notes alone, the +follower lost some validation pieces in the first seconds: it ran ahead on +the first few chords, and a follower that only moves forward cannot undo +that. Here the fast notes never move the follower itself. They only time the +chords that come after the slow follower's last chord. + +## How it works + +1. **Transcription** (`DualProcessor` in `solution.py`). One log-filtered + spectrogram (4096-sample window, hop 882, 50 frames per second, the same + features as madmom's note CNN) is computed one frame at a time and fed to + two networks of our own transcriber (`transcriber_b/stream.py`, numpy). + Both have the same architecture: 5 blocks of 3x3 convolutions, a + one-directional GRU with 256 units, and sigmoid heads for onset, sounding + note and offset of the 88 keys (1.5 million parameters). + - `anchor.npz`: each convolution block sees one future frame, so 5 + frames of lookahead. A note starts where the onset activation of a key + is at least 0.5, higher than one frame earlier and at least as high as + one frame later, and the key has not started a note in the last 50 ms. + Onsets are final 166 ms after their frame. + - `fast.npz`: no lookahead. The same rule without the condition on the + next frame. Onsets are final 46 ms after their frame (half the window). + + Every onset keeps the time of the frame it belongs to. +2. **Following where** (`TranscriptionFollower`, unchanged from + `bjork-gudmundsdottir`). The anchor's onsets within 35 ms of the first + note of a chord form one chord, as in Matchmaker's `ChordOnsetProcessor`. + Each chord goes to Matchmaker's `OnlineTimeWarpingArztEvent` with the + settings of Matchmaker's MIDI `arzt` follower. +3. **Following when** (`DualFollower`). The fast onsets are grouped into + chords at their first note (35 ms). Every fast chord that starts more than + 35 ms after the anchor's last chord moves the reported position one score + chord further than the anchor's last chord. When the anchor takes its next + chord, the count starts again from there, so a wrong fast note only + matters until then. +4. **Reported position.** From the last chord (fast or anchor), the position + moves on at the tempo the anchor followed over the last 4 seconds (at most + 8 beats per second, for at most 1.5 seconds after the chord), as in + `bjork-gudmundsdottir`. + +## Validation fold + +One run of the benchmark's own runner on the 20 validation performances, +seed 0 pair (the pair we fixed before running it): + +| | Tracked | Mean of per-piece median beat errors | Within 0.1 beat | Within 0.05 beat | +|---|---|---|---|---| +| `bjork-gudmundsdottir` | 20/20 | 0.085 | 0.667 | 0.470 | +| this submission | 20/20 | 0.023 | 0.792 | 0.733 | + +Real-time factor about 0.13 (two pieces at a time on a 2-core machine). The rule that combines the two transcribers was designed after we had seen +validation results of the fast transcriber alone, so these numbers are not an +unbiased estimate. No setting was tuned on the validation fold: the onset +thresholds come from the MAESTRO validation split, everything else from +`bjork-gudmundsdottir`. The output jumps from chord to chord more than our +first submission's, so it is less smooth. + +## Training data + +Both networks were trained by us on the MAESTRO v3.0.0 train split only. The +MAESTRO validation split chose the checkpoint (best onset F1) and the onset +threshold (0.5 for both). ASAP's audio are MAESTRO recordings: all 42 ASAP +recordings of the benchmark folds (10 valid, 32 eval) are in MAESTRO's test +split, listed in `asap_in_maestro.csv` with their MAESTRO file names. That +split was never prepared or read, and our data preparation stops if any of +the 42 appears in the train or validation split. We used MAESTRO with the +agreement of the course instructor. Batik and Vienna 4x22 are not part of +MAESTRO. + +## Files + +| File | What it is | Licence | +|---|---|---| +| `solution.py` | Processor, both followers and registration | Apache-2.0 | +| `transcriber_b/` | Our transcriber's spectrogram and frame-by-frame numpy network | Apache-2.0 | +| `anchor.npz` | Weights of the network with lookahead, trained by us | CC BY-NC-SA 4.0 | +| `fast.npz` | Weights of the network without lookahead, trained by us | CC BY-NC-SA 4.0 | +| `settings.json` | Both onset thresholds and the weights' sha256 | | +| `asap_in_maestro.csv` | The 42 benchmark recordings in MAESTRO's test split | | +| `requirements.txt` | No dependencies beyond the benchmark environment | | + +The weights carry CC BY-NC-SA 4.0 because MAESTRO, their training data, is +licensed under it. + +## References + +- C. Hawthorne et al. Enabling Factorized Piano Music Modeling and Generation + with the MAESTRO Dataset. ICLR 2019. +- C. Hawthorne et al. Onsets and Frames: Dual-Objective Piano Transcription. + ISMIR 2018. (Our sounding-note head also gets the onset probabilities, as + there.) +- R. Kelz, S. Böck and G. Widmer. Deep Polyphonic ADSR Piano Note + Transcription. ICASSP 2019. (The spectrogram features.) diff --git a/submissions/bjork-gudmundsdottir-dual/anchor.npz b/submissions/bjork-gudmundsdottir-dual/anchor.npz new file mode 100644 index 0000000..07d7b62 Binary files /dev/null and b/submissions/bjork-gudmundsdottir-dual/anchor.npz differ diff --git a/submissions/bjork-gudmundsdottir-dual/asap_in_maestro.csv b/submissions/bjork-gudmundsdottir-dual/asap_in_maestro.csv new file mode 100644 index 0000000..6093996 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/asap_in_maestro.csv @@ -0,0 +1,43 @@ +fold,piece_id,maestro_audio_stem,maestro_split +valid,asap/Piano_Sonatas_10-1/Hou02M,MIDI-Unprocessed_09_R1_2011_MID--AUDIO_R1-D3_13_Track13_wav,test +valid,asap/Prelude_bwv_862/Song04M,MIDI-Unprocessed_13_R1_2008_01-04_ORIG_MID--AUDIO_13_R1_2008_wav--1,test +valid,asap/Prelude_bwv_891/Duepree06M,MIDI-Unprocessed_03_R1_2008_01-04_ORIG_MID--AUDIO_03_R1_2008_wav--1,test +valid,asap/Fugue_bwv_858/VuV01M,MIDI-Unprocessed_R1_D1-1-8_mid--AUDIO-from_mp3_02_R1_2015_wav--1,test +valid,asap/Prelude_bwv_863/LeeN01M,MIDI-Unprocessed_R1_D1-1-8_mid--AUDIO-from_mp3_07_R1_2015_wav--1,test +valid,asap/Piano_Sonatas_5-1/Colafelice02M,MIDI-Unprocessed_23_R1_2011_MID--AUDIO_R1-D9_03_Track03_wav,test +valid,asap/Fugue_bwv_863/Shychko01M,MIDI-Unprocessed_11_R1_2011_MID--AUDIO_R1-D4_07_Track07_wav,test +valid,asap/Transcendental_Etudes_10/CaoJ03M,MIDI-Unprocessed_065_PIANO065_MID--AUDIO-split_07-07-17_Piano-e_3-01_wav--3,test +valid,asap/Prelude_bwv_873/Lisiecki13M,MIDI-Unprocessed_11_R3_2008_01-04_ORIG_MID--AUDIO_11_R3_2008_wav--1,test +valid,asap/Transcendental_Etudes_3/Huang14M,MIDI-Unprocessed_04_R3_2008_01-07_ORIG_MID--AUDIO_04_R3_2008_wav--3,test +eval,asap/Fugue_bwv_858/Zhang01M,MIDI-Unprocessed_07_R1_2011_MID--AUDIO_R1-D3_02_Track02_wav,test +eval,asap/Fugue_bwv_862/Song04M,MIDI-Unprocessed_13_R1_2008_01-04_ORIG_MID--AUDIO_13_R1_2008_wav--1,test +eval,asap/Fugue_bwv_863/LeeN01M,MIDI-Unprocessed_R1_D1-1-8_mid--AUDIO-from_mp3_07_R1_2015_wav--1,test +eval,asap/Fugue_bwv_863/TongB01M,MIDI-Unprocessed_056_PIANO056_MID--AUDIO-split_07-07-17_Piano-e_1-05_wav--1,test +eval,asap/Fugue_bwv_873/Lisiecki13M,MIDI-Unprocessed_11_R3_2008_01-04_ORIG_MID--AUDIO_11_R3_2008_wav--1,test +eval,asap/Fugue_bwv_891/Duepree06M,MIDI-Unprocessed_03_R1_2008_01-04_ORIG_MID--AUDIO_03_R1_2008_wav--1,test +eval,asap/Prelude_bwv_858/VuV01M,MIDI-Unprocessed_R1_D1-1-8_mid--AUDIO-from_mp3_02_R1_2015_wav--1,test +eval,asap/Prelude_bwv_858/Zhang01M,MIDI-Unprocessed_07_R1_2011_MID--AUDIO_R1-D3_02_Track02_wav,test +eval,asap/Prelude_bwv_863/Shychko01M,MIDI-Unprocessed_11_R1_2011_MID--AUDIO_R1-D4_07_Track07_wav,test +eval,asap/Prelude_bwv_863/TongB01M,MIDI-Unprocessed_056_PIANO056_MID--AUDIO-split_07-07-17_Piano-e_1-05_wav--1,test +eval,asap/Prelude_bwv_891/BLINOV04M,MIDI-Unprocessed_XP_03_R1_2004_01-02_ORIG_MID--AUDIO_03_R1_2004_01_Track01_wav,test +eval,asap/Piano_Sonatas_12-1/Kleisen05M,MIDI-Unprocessed_06_R1_2008_01-04_ORIG_MID--AUDIO_06_R1_2008_wav--2,test +eval,asap/Piano_Sonatas_16-1/BuiJL02M,MIDI-Unprocessed_046_PIANO046_MID--AUDIO-split_07-06-17_Piano-e_2-02_wav--2,test +eval,asap/Piano_Sonatas_16-1/Khmara05M,MIDI-Unprocessed_05_R1_2008_01-04_ORIG_MID--AUDIO_05_R1_2008_wav--2,test +eval,asap/Piano_Sonatas_16-1/LeeSH02M,MIDI-Unprocessed_049_PIANO049_MID--AUDIO-split_07-06-17_Piano-e_2-06_wav--2,test +eval,asap/Piano_Sonatas_16-1/Woo05M,MIDI-Unprocessed_17_R1_2008_01-04_ORIG_MID--AUDIO_17_R1_2008_wav--2,test +eval,asap/Piano_Sonatas_18-4/ChenGuang06M,MIDI-UNPROCESSED_04-05_R1_2014_MID--AUDIO_04_R1_2014_wav--2,test +eval,asap/Piano_Sonatas_18-4/KOLESO06M,MIDI-Unprocessed_XP_15_R1_2004_03_ORIG_MID--AUDIO_15_R1_2004_03_Track03_wav,test +eval,asap/Piano_Sonatas_3-2/MiyashitaM04M,MIDI-Unprocessed_R1_D1-9-12_mid--AUDIO-from_mp3_09_R1_2015_wav--2,test +eval,asap/Piano_Sonatas_5-1/SunD02M,MIDI-Unprocessed_R1_D2-13-20_mid--AUDIO-from_mp3_16_R1_2015_wav--2,test +eval,asap/Piano_Sonatas_8-3/Na06M,MIDI-Unprocessed_09_R1_2009_01-04_ORIG_MID--AUDIO_09_R1_2009_09_R1_2009_03_WAV,test +eval,asap/Piano_Sonatas_9-3/Tysman05M,MIDI-Unprocessed_17_R1_2009_01-03_ORIG_MID--AUDIO_17_R1_2009_17_R1_2009_01_WAV,test +eval,asap/Etudes_op_10_12/Bult-ItoS04M,MIDI-Unprocessed_R1_D1-1-8_mid--AUDIO-from_mp3_05_R1_2015_wav--4,test +eval,asap/Etudes_op_10_12/HuNY03M,MIDI-Unprocessed_R1_D2-21-22_mid--AUDIO-from_mp3_22_R1_2015_wav--3,test +eval,asap/Etudes_op_10_12/LuoJ08M,MIDI-Unprocessed_R1_D1-1-8_mid--AUDIO-from_mp3_06_R1_2015_wav--6,test +eval,asap/Etudes_op_10_12/WuuE06M,MIDI-Unprocessed_R1_D1-9-12_mid--AUDIO-from_mp3_11_R1_2015_wav--3,test +eval,asap/Etudes_op_10_12/ZhangYunling02M,MIDI-Unprocessed_07_R1_2011_MID--AUDIO_R1-D3_03_Track03_wav,test +eval,asap/Transcendental_Etudes_10/Huang17M,MIDI-Unprocessed_04_R3_2008_01-07_ORIG_MID--AUDIO_04_R3_2008_wav--6,test +eval,asap/Transcendental_Etudes_10/LeungM06M,MIDI-Unprocessed_Recital17-19_MID--AUDIO_19_R1_2018_wav--3,test +eval,asap/Preludes_op_23_6/Nikiforov14M,MIDI-Unprocessed_12_R3_2008_01-04_ORIG_MID--AUDIO_12_R3_2008_wav--3,test +eval,asap/Toccata/DupreeF13M,MIDI-UNPROCESSED_19-20_R1_2014_MID--AUDIO_19_R1_2014_wav--8,test +eval,asap/Toccata_repeat/WangY07M,MIDI-UNPROCESSED_11-13_R1_2014_MID--AUDIO_13_R1_2014_wav--4,test diff --git a/submissions/bjork-gudmundsdottir-dual/fast.npz b/submissions/bjork-gudmundsdottir-dual/fast.npz new file mode 100644 index 0000000..3940e18 Binary files /dev/null and b/submissions/bjork-gudmundsdottir-dual/fast.npz differ diff --git a/submissions/bjork-gudmundsdottir-dual/metadata.yaml b/submissions/bjork-gudmundsdottir-dual/metadata.yaml new file mode 100644 index 0000000..66c5703 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/metadata.yaml @@ -0,0 +1,47 @@ +name: Transcribe twice and follow (two streaming transcribers + event OLTW) +authors: + - Matthias Nagl + - Klaus Lex + - Kevin Eberl +affiliation: Johannes Kepler University Linz (Music Informatics WS26) +input_type: audio +description: > + Two causal piano transcribers of our own, computed frame by frame in numpy, + turn the audio into notes while it arrives. One looks 5 frames ahead (notes + final after 166 ms), the other does not (notes final after 46 ms). + Matchmaker's event-level online time warping on the slower, more reliable + notes decides where in the score the performer is, as in our first + submission (bjork-gudmundsdottir). The faster notes only decide when the + next chords come: each new fast chord moves the position one score chord + past the slow follower's last chord, until the slow follower takes its next + chord. Between notes the position moves on at the followed tempo. +license: Apache-2.0 for the code. anchor.npz and fast.npz hold weights we trained on MAESTRO v3, under CC BY-NC-SA 4.0 because of the training data, see README.md. + +# How this submission was developed. +tuned_on: [valid] +external_data: > + Both transcribers are trained by us on the MAESTRO v3.0.0 train split only + (Hawthorne et al., ICLR 2019), with the MAESTRO validation split for early + stopping and the onset thresholds. ASAP's audio are MAESTRO recordings: all + 42 ASAP recordings of the benchmark folds (10 valid, 32 eval) are in + MAESTRO's test split, listed in asap_in_maestro.csv. That split was never + prepared or read, and our data preparation stops if any of the 42 appears in + the train or validation split. We used MAESTRO with the agreement of the + course instructor. No other data. + +# Required declaration. See docs/eval-protocol.md. +eval_fold_untouched: true + +notes: > + numpy only, weights load from two npz files (5.6 MB each, 1.5 million + parameters per network) at import. Real-time factor about 0.13 on the + validation fold (two pieces at a time on a 2-core machine). Validation fold, + one run: 20 of 20 performances tracked, mean of the per-piece median beat + errors 0.023 beats (bjork-gudmundsdottir: 0.085). The rule that combines the + two transcribers was designed after we had seen validation results of the + fast transcriber alone, which lost pieces at the start, so the validation + numbers are not an unbiased estimate. It adds no new settings: the onset + thresholds come from the MAESTRO validation split and the follower settings + from bjork-gudmundsdottir. We trained three seeds of each network. The + submitted pair (seed 0) was fixed before the combination was run on the + validation fold. diff --git a/submissions/bjork-gudmundsdottir-dual/requirements.txt b/submissions/bjork-gudmundsdottir-dual/requirements.txt new file mode 100644 index 0000000..e3bca3d --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/requirements.txt @@ -0,0 +1 @@ +# No dependencies beyond the benchmark environment (numpy only). diff --git a/submissions/bjork-gudmundsdottir-dual/settings.json b/submissions/bjork-gudmundsdottir-dual/settings.json new file mode 100644 index 0000000..6c15395 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/settings.json @@ -0,0 +1,24 @@ +{ + "anchor": { + "onset_threshold": 0.5, + "onset_rule": "peak", + "weights": "transcriber_b/weights/maestro-seed0.npz", + "weights_sha256": "9a53dca7cadf81e1b45c298300a415c64e496cda8d6399829ffd0964f23923cc", + "dev_summary": "transcriber_b/runs/dev_eval/maestro-seed0/summary.json", + "run": "maestro-seed0", + "epoch": 79, + "seed": 0, + "lookahead_frames": 5 + }, + "fast": { + "onset_threshold": 0.5, + "onset_rule": "rising", + "weights": "transcriber_b/weights/maestro_la0-seed0.npz", + "weights_sha256": "60475fc7d10e0bfed8bbe4be7e882cb34d7b875b8ec5b759b37902e5cf81fa25", + "dev_summary": "transcriber_b/runs/dev_eval/maestro_la0-seed0/summary.json", + "run": "maestro_la0-seed0", + "epoch": 76, + "seed": 0, + "lookahead_frames": 0 + } +} diff --git a/submissions/bjork-gudmundsdottir-dual/solution.py b/submissions/bjork-gudmundsdottir-dual/solution.py new file mode 100644 index 0000000..b8eaead --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/solution.py @@ -0,0 +1,309 @@ +"""Team Björk Guðmundsdóttir (Music Informatics WS26, JKU Linz): transcribe twice, then follow. + +Our first submission (bjork-gudmundsdottir) follows the notes of one +streaming transcriber that needs 5 frames of future context, so it knows a +note about 170 ms after it is played. This one adds a second transcriber +without that lookahead and uses its notes only for timing: + +1. Processor: one spectrogram frame at a time (transcriber_b/features.py, + frame k centred on sample 882 k, 50 frames per second), fed to two + networks of our own transcriber (transcriber_b/stream.py, numpy): + - anchor.npz: the network with 5 frames of lookahead. A note starts where + the onset activation of a key is at least the threshold, higher than + one frame earlier and at least as high as one frame later, and the key + has not started a note in the last 50 ms. Onsets are final 166 ms after + their frame. + - fast.npz: the network without lookahead. The same rule without the + condition on the next frame. Onsets are final 46 ms after their frame + (half the 4096-sample window). + Every onset keeps the time of the frame it belongs to. +2. Follower: the follower of bjork-gudmundsdottir, on the anchor's onsets + alone, decides the score position (chords of 35 ms into Matchmaker's + event-level online time warping, moved on at the followed tempo). The + fast onsets only time the chords after it: every fast chord (grouped at + its first note) that starts more than 35 ms after the anchor's last chord + moves the output one score chord further than the anchor's last chord, + and the position moves on from that fast chord. When the anchor takes its + next chord, the count starts again from there, so the fast notes can + never move the anchor itself. + +Files next to this one (see README.md): + transcriber_b/ numpy copies of our transcriber's features.py and stream.py + anchor.npz weights of the network with lookahead (trained by us) + fast.npz weights of the network without lookahead (trained by us) + settings.json both onset thresholds (chosen on the MAESTRO validation split) and sha256s +""" + +import bisect +import importlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +from matchmaker import register_method +from matchmaker.base import OnlineAlignment +from matchmaker.dp import OnlineTimeWarpingArztEvent +from matchmaker.features.midi import onset_pianoroll +from matchmaker.features.processor import Processor + +HERE = Path(__file__).resolve().parent + + +def _transcriber_stream(): + """transcriber_b.stream from the copy next to this file (the benchmark does not put it on sys.path).""" + if "transcriber_b" not in sys.modules: + package = HERE / "transcriber_b" + spec = importlib.util.spec_from_file_location( + "transcriber_b", package / "__init__.py", submodule_search_locations=[str(package)]) + module = importlib.util.module_from_spec(spec) + sys.modules["transcriber_b"] = module + spec.loader.exec_module(module) + return importlib.import_module("transcriber_b.stream") + + +tb = _transcriber_stream() +features = importlib.import_module("transcriber_b.features") +SETTINGS = json.loads((HERE / "settings.json").read_text()) + +MIN_GAP_FRAMES = 2 # 50 ms at 50 frames per second, as in bjork-gudmundsdottir +CHORD_THRESHOLD = 0.035 # seconds, Matchmaker's ChordOnsetProcessor +LOWEST_KEY = 21 # MIDI pitch of the first of the 88 keys + + +class OnsetStream: + """One network and its causal onset rule. + + peak=True: frame t is decided once frame t + 1 is known (needs a peak). + peak=False: frame t is decided at once (a rising activation is enough). + """ + + def __init__(self, network, threshold, peak): + self.network, self.threshold, self.peak = network, threshold, peak + self.trace = None # set to a list to record the onset activations (checks only) + self.reset() + + def reset(self): + self.network.reset() + self.act_index = -1 # index of the newest activation frame + self.before = None # onset activations one frame before the frame being decided + self.now = None # onset activations of the newest frame (peak rule: the frame being decided) + self.last_onset = np.full(88, -(10**9)) + + @property + def horizon(self): + """Onsets up to this time (seconds) are final.""" + return (self.act_index - (1 if self.peak else 0)) / features.FPS + + def push(self, spectrum): + """One spectrogram frame in, the onsets it decides out [(time, pitch)].""" + act = self.network.push(spectrum) + if act is None: + return [] + self.act_index += 1 + onset = act[:, 1] + if self.trace is not None: + self.trace.append(onset.copy()) + if self.peak: + found = [] + if self.before is not None: + found = self._decide(self.act_index - 1, self.now, self.before, self.now >= onset) + self.before, self.now = self.now, onset + return found + found = [] + if self.now is not None: + found = self._decide(self.act_index, onset, self.now, np.ones(88, bool)) + self.now = onset + return found + + def _decide(self, t, current, previous, extra): + keys = np.flatnonzero( + (current >= self.threshold) & (current > previous) & extra & (t - self.last_onset >= MIN_GAP_FRAMES) + ) + self.last_onset[keys] = t + return [(t / features.FPS, float(key + LOWEST_KEY)) for key in keys] + + +class DualProcessor(Processor): + """Audio in, two onset streams out. + + Returns, for every block of audio, (anchor rows, fast rows): arrays whose + first row is (horizon, -1) and whose other rows are (onset time, MIDI + pitch) of the onsets found in this block. + """ + + def __init__(self, sample_rate, hop_length, anchor_threshold, fast_threshold): + super().__init__() + if sample_rate != features.SAMPLE_RATE: + raise ValueError(f"the transcriber needs {features.SAMPLE_RATE} Hz audio, got {sample_rate}") + self.hop_length = hop_length + # The stream hands over n_fft samples per block: the newest hop and the + # one before it. Only the newest hop is new, so only that is used. + self.n_fft = 2 * hop_length + self.spectrogram, anchor, _ = tb.load(HERE / "anchor.npz") + _, fast, _ = tb.load(HERE / "fast.npz") # the spectrogram does not depend on the weights + self.anchor = OnsetStream(anchor, anchor_threshold, peak=True) + self.fast = OnsetStream(fast, fast_threshold, peak=False) + self.reset() + + def reset(self): + self.anchor.reset() + self.fast.reset() + half = features.FRAME // 2 + # Frame k is centred on sample HOP * k, so frame 0 needs half a frame + # of zeros before the recording starts (features.frames_of does the same). + self.audio = np.zeros(half, np.float32) + self.audio_start = -half # sample index of self.audio[0] + self.received = 0 + self.next_frame = 0 + + def __call__(self, data): + samples, perf_time = data + new = np.asarray(samples[-self.hop_length :], dtype=np.float32) + self.audio = np.concatenate((self.audio, new)) + self.received += len(new) + + anchor_onsets, fast_onsets = [], [] + half = features.FRAME // 2 + while self.next_frame * features.HOP + half <= self.received: + start = self.next_frame * features.HOP - half - self.audio_start + spectrum = self.spectrogram.frame(self.audio[start : start + features.FRAME]) + self.next_frame += 1 + anchor_onsets.extend(self.anchor.push(spectrum)) + fast_onsets.extend(self.fast.push(spectrum)) + + keep_from = self.next_frame * features.HOP - half # first sample the next frame needs + if keep_from > self.audio_start: + self.audio = self.audio[keep_from - self.audio_start :] + self.audio_start = keep_from + + anchor = np.asarray([(self.anchor.horizon, -1.0)] + anchor_onsets, dtype=np.float64) + fast = np.asarray([(self.fast.horizon, -1.0)] + fast_onsets, dtype=np.float64) + return (anchor, fast), perf_time + + +class TranscriptionFollower(OnlineAlignment): + """The follower of our first submission, bjork-gudmundsdottir, unchanged.""" + + def __init__(self, score_note_array, queue, config): + features_, positions = onset_pianoroll(score_note_array, onset_key="onset_beat", piano_range=True) + super().__init__(features_, positions, queue) + # The same follower and settings as Matchmaker's MIDI `arzt` + # (window of 30 events, 5 at the start, step size 5, cosine distance). + self.inner = OnlineTimeWarpingArztEvent(reference_features=features_, score_positions=positions) + self.tempo_window = config["tempo_window"] + self.extrapolation_cap = config["extrapolation_cap"] + self.max_speed = config["max_speed"] + self.chord_notes = [] + self.chord_time = None + self.chord_times = [] # onset time of every chord given to the follower + self.chord_beats = [] # the follower's position after that chord + self.beat = float(positions[0]) + self.latency_stats = {"total_latency": 0.0, "total_frames": 0} + self.calls = 0 + + def _flush_chord(self): + vector = np.zeros(88, dtype=np.float32) + for pitch in self.chord_notes: + key = pitch - LOWEST_KEY + if 0 <= key < 88: + vector[key] = 1.0 + self.inner.step(vector) + self.chord_times.append(self.chord_time) + self.chord_beats.append(float(self.inner.get_current_position())) + self.chord_notes, self.chord_time = [], None + + def _beat_at(self, t): + """The follower's position at time t, as a step function over chords.""" + k = int(np.searchsorted(self.chord_times, t, side="right")) - 1 + return self.chord_beats[max(k, 0)] + + def _speed(self): + t_k, b_k = self.chord_times[-1], self.chord_beats[-1] + span = min(self.tempo_window, t_k - self.chord_times[0]) + if span <= 0: + return 0.0 + return float(np.clip((b_k - self._beat_at(t_k - span)) / span, 0.0, self.max_speed)) + + def step(self, features_) -> None: + started = time.perf_counter() + horizon = float(features_[0, 0]) + for onset, pitch in features_[1:]: + if self.chord_time is not None and onset - self.chord_time > CHORD_THRESHOLD: + self._flush_chord() + self.chord_notes.append(int(pitch)) + if self.chord_time is None: + self.chord_time = float(onset) + if self.chord_time is not None and horizon - self.chord_time > CHORD_THRESHOLD: + self._flush_chord() + + if self.chord_times: + t_k, b_k = self.chord_times[-1], self.chord_beats[-1] + elapsed = min(max(self.current_perf_time - t_k, 0.0), self.extrapolation_cap) + self.beat = b_k + self._speed() * elapsed + self.current_index = max(int(np.searchsorted(self.score_positions, b_k, side="right")) - 1, 0) + + self.calls += 1 + self.latency_stats["total_latency"] += time.perf_counter() - started + self.latency_stats["total_frames"] = self.calls + + def get_current_position(self) -> float: + return self.beat + + +class DualFollower(TranscriptionFollower): + """The follower above on the anchor's onsets, the fast onsets time the chords after it.""" + + def __init__(self, score_note_array, queue, config): + super().__init__(score_note_array, queue, config) + self.fast_times = [] # start of every fast chord (grouped at its first note) + + def step(self, features_) -> None: + anchor, fast = features_ + super().step(anchor) + started = time.perf_counter() + for onset in fast[1:, 0]: + if not self.fast_times or onset - self.fast_times[-1] > CHORD_THRESHOLD: + self.fast_times.append(float(onset)) + if self.chord_times: + t_k, b_k = self.chord_times[-1], self.chord_beats[-1] + new = len(self.fast_times) - bisect.bisect_right(self.fast_times, t_k + CHORD_THRESHOLD) + if new > 0: + k = max(int(np.searchsorted(self.score_positions, b_k, side="right")) - 1, 0) + target = float(self.score_positions[min(k + new, len(self.score_positions) - 1)]) + elapsed = min(max(self.current_perf_time - self.fast_times[-1], 0.0), self.extrapolation_cap) + self.beat = target + self._speed() * elapsed + self.latency_stats["total_latency"] += time.perf_counter() - started + + +def build_processor(mm): + return DualProcessor(mm.sample_rate, mm.hop_length, mm.config["anchor_threshold"], mm.config["fast_threshold"]) + + +def build_reference(mm): + """The score's notes, as Matchmaker uses them for MIDI followers.""" + return mm.score_part.note_array() + + +def build_follower(mm): + return DualFollower(mm.reference_features, mm.stream.queue, mm.config) + + +register_method( + "bjork-gudmundsdottir-dual", + input_type="audio", + build_follower=build_follower, + build_processor=build_processor, + build_reference=build_reference, + default_kwargs={ + # chosen on the MAESTRO validation split, never on the benchmark folds + "anchor_threshold": float(SETTINGS["anchor"]["onset_threshold"]), + "fast_threshold": float(SETTINGS["fast"]["onset_threshold"]), + # moving on between chords, as in bjork-gudmundsdottir + "tempo_window": 4.0, # seconds of the follower's path the tempo is read from + "extrapolation_cap": 1.5, # seconds after a chord beyond which the position stops moving + "max_speed": 8.0, # beats per second + }, +) diff --git a/submissions/bjork-gudmundsdottir-dual/transcriber_b/__init__.py b/submissions/bjork-gudmundsdottir-dual/transcriber_b/__init__.py new file mode 100644 index 0000000..faa7095 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/transcriber_b/__init__.py @@ -0,0 +1 @@ +"""numpy copy of transcriber_b (features.py, stream.py) for the method.""" diff --git a/submissions/bjork-gudmundsdottir-dual/transcriber_b/features.py b/submissions/bjork-gudmundsdottir-dual/transcriber_b/features.py new file mode 100644 index 0000000..434938b --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/transcriber_b/features.py @@ -0,0 +1,130 @@ +"""Log-filtered spectrogram at 50 frames per second, in numpy and in PyTorch. + +The same features madmom computes for its 2019 note CNN, written here from +the definition so that nothing of madmom (code or data) is needed: + +- frames of 4096 samples, Hann window, hop 882 samples (50 fps at 44.1 kHz), + frame k centred on sample 882 k, zeros outside the recording; +- magnitude of the first 2048 FFT bins; +- triangular filters on a logarithmic frequency axis, 24 bands per octave from + 30 Hz to 10 kHz, centres on the grid 440 Hz * 2^(n / 24), each mapped to the + nearest FFT bin, duplicates removed, every filter normalised to area 1 + (144 bands); +- log10(1 + x). + +``tests/test_features.py`` checks the filterbank and window against the ones +stored in ``transcriber/notes_cnn_2019.npz`` when that file is present. +""" + +import numpy as np + +SAMPLE_RATE = 44100 +FPS = 50 +HOP = SAMPLE_RATE // FPS # 882 +FRAME = 4096 +NUM_BINS = FRAME // 2 +BANDS_PER_OCTAVE = 24 +FMIN, FMAX, FREF = 30.0, 10000.0, 440.0 + + +def log_frequencies(bands_per_octave=BANDS_PER_OCTAVE, fmin=FMIN, fmax=FMAX, fref=FREF): + left = np.floor(np.log2(fmin / fref) * bands_per_octave) + right = np.ceil(np.log2(fmax / fref) * bands_per_octave) + freqs = fref * 2.0 ** (np.arange(left, right) / bands_per_octave) + return freqs[(freqs >= fmin) & (freqs <= fmax)] + + +def frequencies_to_bins(freqs, bin_freqs): + """Nearest FFT bin of every frequency, duplicates removed.""" + idx = np.clip(bin_freqs.searchsorted(freqs), 1, len(bin_freqs) - 1) + left, right = bin_freqs[idx - 1], bin_freqs[idx] + idx = idx - (freqs - left < right - freqs) + return np.unique(idx) + + +def filterbank(frame=FRAME, sample_rate=SAMPLE_RATE): + """(NUM_BINS, num_bands) float32 triangular filterbank.""" + num_bins = frame // 2 + bin_freqs = np.fft.fftfreq(frame, 1.0 / sample_rate)[:num_bins] + bins = frequencies_to_bins(log_frequencies(), bin_freqs) + filters = [] + for start, center, stop in zip(bins[:-2], bins[1:-1], bins[2:]): + if stop - start < 2: # too narrow for a triangle: a single bin + center, stop = start, start + 1 + tri = np.zeros(stop - start) + c = center - start + tri[:c] = np.linspace(0, 1, c, endpoint=False) + tri[c:] = np.linspace(1, 0, stop - start - c, endpoint=False) + tri /= tri.sum() + band = np.zeros(num_bins) + band[start:stop] = tri + filters.append(band) + return np.stack(filters, axis=1).astype(np.float32) + + +def window(frame=FRAME): + return np.hanning(frame).astype(np.float32) + + +def num_frames(num_samples): + return int(np.ceil(num_samples / HOP)) + + +class Spectrogram: + """numpy features: one frame at a time (streaming) or a whole recording.""" + + def __init__(self, window_=None, filterbank_=None): + self.window = window() if window_ is None else np.asarray(window_, np.float32) + self.filterbank = filterbank() if filterbank_ is None else np.asarray(filterbank_, np.float32) + self.num_bins = self.filterbank.shape[0] + self.num_bands = self.filterbank.shape[1] + + def frame(self, samples): + """Features of one frame of FRAME samples.""" + spectrum = np.fft.rfft(np.asarray(samples, np.float32) * self.window)[: self.num_bins] + return np.log10(np.abs(spectrum).astype(np.float32) @ self.filterbank + 1.0).astype(np.float32) + + def frames_of(self, audio, chunk=512): + """(num_frames, num_bands) for a whole recording, same numbers as frame().""" + audio = np.asarray(audio, np.float32) + n = num_frames(len(audio)) + padded = np.concatenate([np.zeros(FRAME // 2, np.float32), audio, np.zeros(FRAME, np.float32)]) + frames = np.lib.stride_tricks.sliding_window_view(padded, FRAME)[::HOP][:n] + out = np.empty((n, self.num_bands), np.float32) + for s in range(0, n, chunk): + spec = np.fft.rfft(frames[s:s + chunk] * self.window, axis=1)[:, : self.num_bins] + out[s:s + chunk] = np.log10(np.abs(spec).astype(np.float32) @ self.filterbank + 1.0) + return out + + +class TorchSpectrogram: + """The same features in PyTorch, for batches on the GPU during training.""" + + def __init__(self, device="cpu"): + import torch + + self.torch = torch + self.window = torch.from_numpy(window()).to(device) + self.filterbank = torch.from_numpy(filterbank()).to(device) + + def to(self, device): + self.window = self.window.to(device) + self.filterbank = self.filterbank.to(device) + return self + + def __call__(self, padded, n_frames): + """Features of a batch whose audio is already padded. + + padded: (B, L) float tensor whose sample FRAME // 2 is the centre of + frame 0; it must hold at least (n_frames - 1) * HOP + FRAME samples. + Returns (B, n_frames, num_bands). + """ + frames = padded.unfold(-1, FRAME, HOP)[:, :n_frames] # (B, n, FRAME) + spec = self.torch.fft.rfft(frames.float() * self.window, dim=-1)[..., :NUM_BINS].abs() + return self.torch.log10(spec @ self.filterbank + 1.0) + + +def pad_recording(audio): + """Recording padded the way frames_of pads it, for TorchSpectrogram.""" + audio = np.asarray(audio, np.float32) + return np.concatenate([np.zeros(FRAME // 2, np.float32), audio, np.zeros(FRAME, np.float32)]), num_frames(len(audio)) diff --git a/submissions/bjork-gudmundsdottir-dual/transcriber_b/stream.py b/submissions/bjork-gudmundsdottir-dual/transcriber_b/stream.py new file mode 100644 index 0000000..ef26dc0 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-dual/transcriber_b/stream.py @@ -0,0 +1,240 @@ +"""numpy inference for our transcriber: offline and frame by frame. + +Needs only numpy and the npz file written by ``export.py``. The interface +follows ``transcriber/stream_cnn.py``: + +- ``Spectrogram`` (from features.py): ``frame(samples)`` gives one + spectrogram frame from FRAME samples; frame k is centred on sample 882 k and + can be computed once audio up to sample 882 k + 2048 has arrived. +- ``StreamingTranscriber.push(frame)`` takes spectrogram frame k and returns + the (88, 3) activations (sounding, onset, offset) of frame k - LOOKAHEAD, + or None while the network fills up. ``flush()`` returns the remaining + frames at the end of a file (a live follower never needs it). +- ``OfflineTranscriber.activations(spec)`` computes a whole recording at once + and gives the same numbers (tests/test_stream.py). + +Edges: every convolution pads its input with zeros in time, in training and +here alike. The streaming version starts each layer with the same zero +columns and ``flush()`` feeds the same zero columns at the end, so streaming +and offline agree on every frame, the first and the last included. + +Load both with ``load(path)``. +""" + +import json + +import numpy as np + +from transcriber_b.features import Spectrogram + + +def _sigmoid(x): + return 0.5 * (1.0 + np.tanh(0.5 * x)) # = 1 / (1 + exp(-x)), without overflow warnings + + +class Weights: + """Arrays of an exported model, arranged for numpy.""" + + def __init__(self, z): + self.meta = json.loads(str(z["meta"])) + cfg = self.cfg = self.meta["model"] + self.in_scale, self.in_shift = z["input_scale"].astype(np.float32), z["input_shift"].astype(np.float32) + self.convs = [] + for i in range(len(cfg["channels"])): + w = z[f"conv{i}_w"].astype(np.float32) # (Cout, Cin, 3, 3), batch norm folded in + cout, cin = w.shape[:2] + kernel = w.transpose(2, 3, 1, 0).reshape(9 * cin, cout) # rows ordered (time, band, channel) + self.convs.append({ + "kernel": np.ascontiguousarray(kernel), "bias": z[f"conv{i}_b"].astype(np.float32), + "past": 2 - cfg["lookahead"][i], "future": cfg["lookahead"][i], "pool": i in cfg["pool_after"], + }) + self.proj_w = np.ascontiguousarray(z["proj_w"].T.astype(np.float32)) # (flat, hidden) + self.proj_b = z["proj_b"].astype(np.float32) + self.rnn = cfg["rnn"] + self.layers = [] + for i in range(cfg["rnn_layers"]): + self.layers.append(tuple(z[f"rnn{i}_{k}"].astype(np.float32) for k in ("w_ih", "w_hh", "b_ih", "b_hh"))) + self.onset = (z["onset_w"].T.astype(np.float32), z["onset_b"].astype(np.float32)) + self.frame = (z["frame_w"].T.astype(np.float32), z["frame_b"].astype(np.float32)) + self.offset = (z["offset_w"].T.astype(np.float32), z["offset_b"].astype(np.float32)) + self.hidden = cfg["hidden"] + self.lookahead = sum(cfg["lookahead"]) + + +def _conv_patches(xpad, n_bands): + """xpad: (t + 2, bands + 2, C) -> (t * bands, 9 C), rows ordered (time, band, channel).""" + v = np.lib.stride_tricks.sliding_window_view(xpad, (3, 3), axis=(0, 1)) # (t, bands, C, 3, 3) + t = v.shape[0] + return v.transpose(0, 1, 3, 4, 2).reshape(t * n_bands, -1) + + +def _after_conv(y, conv): + y = np.maximum(y, 0.0) + if conv["pool"]: + b = y.shape[-2] // 2 * 2 + y = y[..., :b, :].reshape(*y.shape[:-2], b // 2, 2, y.shape[-1]).max(axis=-2) + return y + + +def _rnn_step_pre(kind, w_hh, b_hh, gi, state): + """One recurrent step (PyTorch's GRU or LSTM equations) given gi = W_ih x + b_ih.""" + if kind == "gru": + h = state + gh = w_hh @ h + b_hh + n3 = len(b_hh) // 3 + r = _sigmoid(gi[:n3] + gh[:n3]) + z = _sigmoid(gi[n3:2 * n3] + gh[n3:2 * n3]) + n = np.tanh(gi[2 * n3:] + r * gh[2 * n3:]) + h = (1.0 - z) * n + z * h + return h, h + h, c = state + g = gi + w_hh @ h + b_hh + n4 = len(b_hh) // 4 + i, f, gg, o = _sigmoid(g[:n4]), _sigmoid(g[n4:2 * n4]), np.tanh(g[2 * n4:3 * n4]), _sigmoid(g[3 * n4:]) + c = f * c + i * gg + h = o * np.tanh(c) + return h, (h, c) + + +def _rnn_step(kind, layer, x, state): + w_ih, w_hh, b_ih, b_hh = layer + return _rnn_step_pre(kind, w_hh, b_hh, w_ih @ x + b_ih, state) + + +def _heads(w, h): + onset = _sigmoid(h @ w.onset[0] + w.onset[1]) + frame = _sigmoid(np.concatenate([h, onset], axis=-1) @ w.frame[0] + w.frame[1]) + offset = _sigmoid(h @ w.offset[0] + w.offset[1]) + return np.stack([frame, onset, offset], axis=-1).astype(np.float32) + + +def _initial_state(w): + zero = np.zeros(w.hidden, np.float32) + return [zero if w.rnn == "gru" else (zero, zero) for _ in w.layers] + + +class OfflineTranscriber: + def __init__(self, weights): + self.w = weights + + def conv_features(self, spec, chunk=1024): + w = self.w + x = (spec.astype(np.float32) * w.in_scale + w.in_shift)[:, :, None] # (T, bands, 1) + for conv in w.convs: + t, bands, _ = x.shape + xpad = np.pad(x, ((conv["past"], conv["future"]), (1, 1), (0, 0))) + out = [] + for s in range(0, t, chunk): + patches = _conv_patches(xpad[s:s + min(chunk, t - s) + 2], bands) + y = (patches @ conv["kernel"] + conv["bias"]).reshape(-1, bands, conv["kernel"].shape[1]) + out.append(_after_conv(y, conv)) + x = np.concatenate(out) + flat = x.transpose(0, 2, 1).reshape(x.shape[0], -1) # channel-major, then band, as in PyTorch + return np.maximum(flat @ w.proj_w + w.proj_b, 0.0) + + def activations(self, spec): + """(T, bands) spectrogram -> (T, 88, 3) activations.""" + w = self.w + x = self.conv_features(spec) + for layer in w.layers: + w_ih, w_hh, b_ih, b_hh = layer + gi = x @ w_ih.T + b_ih # input part for all frames at once + state = _initial_state(w)[0] + out = np.empty((len(x), w.hidden), np.float32) + for t in range(len(x)): + out[t], state = _rnn_step_pre(w.rnn, w_hh, b_hh, gi[t], state) + x = out + return _heads(w, x) + + def transcribe(self, audio, spectrogram=None): + """44.1 kHz mono audio -> (frames, 88, 3) activations.""" + spectrogram = spectrogram or Spectrogram() + return self.activations(spectrogram.frames_of(audio)) + + +class _ConvStream: + """One convolution layer, newest time step only.""" + + def __init__(self, conv, bands_in, channels_in): + self.conv = conv + self.zero = np.zeros((bands_in, channels_in), np.float32) + self.reset() + + def reset(self): + self.buf = [self.zero] * self.conv["past"] + + def _compute(self, window): + xpad = np.pad(np.stack(window), ((0, 0), (1, 1), (0, 0))) + bands = xpad.shape[1] - 2 + y = (_conv_patches(xpad, bands) @ self.conv["kernel"] + self.conv["bias"]) + return _after_conv(y, self.conv) + + def push(self, x): + self.buf.append(x) + if len(self.buf) < 3: + return None + y = self._compute(self.buf[-3:]) + self.buf = self.buf[-2:] + return y + + def finish(self): + """Outputs that need the zero padding at the end of the file.""" + out = [] + for _ in range(self.conv["future"]): + y = self.push(self.zero) + if y is not None: + out.append(y) + return out + + +class StreamingTranscriber: + def __init__(self, weights): + self.w = w = weights + self.lookahead = w.lookahead + self.layers, bands, channels = [], w.cfg["n_bands"], 1 + for conv in w.convs: + self.layers.append(_ConvStream(conv, bands, channels)) + channels = conv["kernel"].shape[1] + bands = bands // 2 if conv["pool"] else bands + self.reset() + + def reset(self): + for layer in self.layers: + layer.reset() + self.state = _initial_state(self.w) + + def _tail(self, x): + """Projection, recurrent step and heads for one frame of conv output (bands, C).""" + w = self.w + h = np.maximum(x.T.reshape(-1) @ w.proj_w + w.proj_b, 0.0) + for i, layer in enumerate(w.layers): + h, self.state[i] = _rnn_step(w.rnn, layer, h, self.state[i]) + return _heads(w, h) + + def push(self, frame): + w = self.w + x = (np.asarray(frame, np.float32) * w.in_scale + w.in_shift)[:, None] + for layer in self.layers: + x = layer.push(x) + if x is None: + return None + return self._tail(x) + + def flush(self): + pending = [] + for layer in self.layers: + produced = [] + for x in pending: + y = layer.push(x) + if y is not None: + produced.append(y) + produced.extend(layer.finish()) + pending = produced + return [self._tail(x) for x in pending] + + +def load(path): + """(Spectrogram, StreamingTranscriber, OfflineTranscriber) from an exported npz file.""" + with np.load(path) as z: + weights = Weights(z) + return Spectrogram(), StreamingTranscriber(weights), OfflineTranscriber(weights)