diff --git a/submissions/bjork-gudmundsdottir-hmm/README.md b/submissions/bjork-gudmundsdottir-hmm/README.md new file mode 100644 index 0000000..7d20b5a --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/README.md @@ -0,0 +1,164 @@ +# Transcribe twice, follow with a pitch HMM + +Team Björk Guðmundsdóttir (Matthias Nagl, Klaus Lex, Kevin Eberl), Music +Informatics WS26, JKU Linz. + +Our third audio score follower. Like our second one +(`bjork-gudmundsdottir-dual`), it turns the audio into notes with two +streaming piano transcribers: a slower one whose notes decide where in the +score the performer is, and a faster one whose notes decide when the next +chord comes. The transcribers and their weights are unchanged. The follower +changes in two places: + +1. **Where:** Matchmaker's pitch HMM (`pthmm`) takes the place of the + event-level online time warping. +2. **When:** a fast chord only counts if its pitch fits the score chord it + would move to. + +## Why + +Both changes come from the validation fold. + +- **The time warping runs ahead on repeated chords.** In the Vienna 4x22 + excerpt of Chopin's op. 38, which is built from repeated chords, the + event-level online time warping was ahead of the played chord on 15 % of + the chords and never behind, and it reached the end of the score 11 + seconds before the pianist did. It only moves forward, so every extra note + of the transcriber can push it on and nothing pulls it back. With the + notes of our transcriber without lookahead it lost 6 validation pieces + over 6 runs (3 training seeds, 2 ways of forming chords). Where we traced + it, it ran ahead within the first seconds and never came back. The pitch + HMM keeps probability on the neighbouring score positions and can move + back. On the same notes it lost 2. +- **The fast layer counted chords without looking at them.** In + `bjork-gudmundsdottir-dual` every fast chord moved the output one score + chord further. A false note of the fast transcriber, or the second half of + a spread chord, then put the output a whole chord too far until the slow + follower caught up. That made the mean error on two of the four Vienna + 4x22 validation pieces worse than in our first submission, although the + median was better. + +## How it works + +1. **Transcription** (`DualProcessor` in `solution.py`, unchanged). One + log-filtered spectrogram (4096-sample window, hop 882, 50 frames per + second) is computed one frame at a time and fed to two networks of our + own transcriber (`transcriber_b/stream.py`, numpy). Both have 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`: 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. +2. **Following where** (`TranscriptionFollower`). The anchor's onsets within + 35 ms of the first note of a chord form one chord. Each chord, as a + vector over the 88 keys, is one observation of the pitch HMM. The HMM is + Matchmaker's `PitchHMM` with its default arguments: one state per score + chord, one inserted state between two chords, the same pitch profiles, + start distribution and transition density. +3. **Banded step** (`banded_pitch_hmm.py`). Matchmaker's step multiplies + with the full transition matrix, so its time grows with the square of the + score length (13 to 16 ms per chord at 3,700 to 4,000 states on our + machine). Ours + does the same arithmetic on the 768 states before and after the current + one. A single transition cannot reach further than that in double + precision, so only probability left over further away from earlier steps + is dropped. On the 20 validation pieces, with the chords of five + different transcriptions (107,070 chords), it ended in the same state as + Matchmaker's step after every chord. +4. **Following when** (`DualFollower`). The fast onsets are grouped into + chords at their first note (35 ms). A fast chord that starts more than + 35 ms after the anchor's last chord moves the reported position one score + chord further, if one of its notes has a pitch of that score chord. A + fast chord that does not fit is ignored. When the anchor takes its next + chord, the count starts again from there. +5. **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 for +each of our three submissions: + +| | Tracked | Mean of per-piece median beat errors | Mean of per-piece mean beat errors | Within 0.1 beat | Within 0.5 beat | +|---|---|---|---|---|---| +| `bjork-gudmundsdottir` | 20/20 | 0.085 | 0.183 | 0.667 | 0.919 | +| `bjork-gudmundsdottir-dual` | 20/20 | 0.023 | 0.159 | 0.792 | 0.924 | +| this submission | 20/20 | 0.013 | 0.096 | 0.867 | 0.952 | + +The mean error is lower than in `bjork-gudmundsdottir` on all 20 pieces and +lower than in `bjork-gudmundsdottir-dual` on 19. Real-time factor about 0.16 +(two pieces at a time on a 2-core machine). + +What these numbers do not show: + +- Both changes were developed on these 20 pieces, after a close look at two + of them, so this is not an unbiased estimate. Neither change has a tuned + setting. +- The pitch HMM fails in its own way: it can fall behind for a while and + come back. One validation piece (`asap/Piano_Sonatas_10-1/Hou02M`) has a + higher mean error than in `bjork-gudmundsdottir-dual` for that reason + (0.145 against 0.095 beats). With other notes than the ones used here it + lost a validation piece like that (with the notes of our first + submission's transcriber, and with one of three training seeds of our + transcriber without lookahead). +- All 6 Batik validation pieces are tracked by all three submissions, so the + validation fold says nothing about Batik. + +## What we saw of the evaluation fold + +After our first two entries had been evaluated, we read the public +leaderboard, its rows per dataset only. Our entries lose pieces on Batik, +and with the same AMT notes Matchmaker's pitch HMM loses none there while +its Arzt follower does. That was our reason to try the pitch HMM. We did not +open the per-piece evaluation results, and we never ran anything on the +evaluation fold. The choice was made on the validation fold, as described +above. We asked the course organisers before submitting an entry that the +leaderboard prompted, and they agreed. + +## Training data + +Both networks are the ones of `bjork-gudmundsdottir-dual`, 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 | +| `banded_pitch_hmm.py` | Matchmaker's pitch HMM with the banded step | 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. `banded_pitch_hmm.py` builds its model with two functions +of `matchmaker.prob.hmm` and follows Matchmaker's `PitchHMM`. + +## References + +- J. Park, C. Cancino-Chacón, S. Chiruthapudi and J. Nam. Matchmaker: An + open-source library for real-time piano score following and systematic + evaluation. ISMIR 2025. (The pitch HMM `pthmm` and the benchmark.) +- 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-hmm/anchor.npz b/submissions/bjork-gudmundsdottir-hmm/anchor.npz new file mode 100644 index 0000000..07d7b62 Binary files /dev/null and b/submissions/bjork-gudmundsdottir-hmm/anchor.npz differ diff --git a/submissions/bjork-gudmundsdottir-hmm/asap_in_maestro.csv b/submissions/bjork-gudmundsdottir-hmm/asap_in_maestro.csv new file mode 100644 index 0000000..6093996 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/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-hmm/banded_pitch_hmm.py b/submissions/bjork-gudmundsdottir-hmm/banded_pitch_hmm.py new file mode 100644 index 0000000..b8910c6 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/banded_pitch_hmm.py @@ -0,0 +1,102 @@ +"""Matchmaker's PitchHMM (the MIDI method `pthmm`) with a forward step whose cost does not grow with the score. + +The model is the one `matchmaker.prob.PitchHMM` builds with its default +arguments (`has_insertions=True`, `piano_range=True`): + +- States: one per score chord and one "inserted" state between two chords, + at the position halfway between them. +- Observation: a chord as a vector over the 88 keys. Its probability in a + state is the product over the keys of p (key played) or 1 - p (not + played), with the pitch profiles of + `matchmaker.prob.hmm.compute_discrete_pitch_profiles`. +- Transition from state i: a left-skewed Gumbel density (scale 1) over the + target state, with its mode two states further for a chord state and one + state further for an inserted state, so always at the next chord. Every + row is divided by its sum over all states. The density is exactly zero in + double precision from 7 states past the mode on, and from about 745 states + before it. +- Start: `matchmaker.prob.hmm.init_dist`. + +Matchmaker's step multiplies the forward variable with the full transition +matrix (number of states squared) and evaluates the observation in every +state. This step does the same arithmetic on the states within REACH of the +current one and leaves the others at zero. REACH is above the 745 states a +single transition can reach at all, so the only thing dropped is probability +left over further away than that from earlier steps. The memory is one block +of (2 REACH + 1) squared numbers per parity of the window start instead of +the full matrix. + +We compared the state after every chord with Matchmaker's PitchHMM on the 20 +validation pieces, with the chords of five different transcriptions +(107,070 chords): never a different state, forward variables equal to 8e-16. +""" + +import numpy as np +from matchmaker.prob.hmm import compute_discrete_pitch_profiles, init_dist +from scipy.stats import gumbel_l + +REACH = 768 # states on each side of the current one that a step uses +LEFT, RIGHT = 760, 8 # the transition density is exactly zero outside these offsets from its mode +NORMALISER_FLOOR = 1e-6 # as in hiddenmarkov.forward_algorithm_step + + +class BandedPitchHMM: + def __init__(self, score_note_array): + # as PitchHMM._build_hmm_modules + onsets = np.unique(score_note_array["onset_beat"]) + chord_pitches = [score_note_array["pitch"][score_note_array["onset_beat"] == onset] for onset in onsets] + self.profiles = compute_discrete_pitch_profiles(chord_pitches=chord_pitches, piano_range=True, inserted_states=True) + self.score_positions = np.insert(onsets, np.arange(1, len(onsets)), onsets[:-1] + 0.5 * np.diff(onsets)) + n = self.n_states = len(self.score_positions) + self.initial = init_dist(n_states=n, dist=gumbel_l) + + # Row i of Matchmaker's stable_transition_matrix(scale=1.0, inserted_states=True) is + # gumbel_l.pdf(j, loc=i + 2) for even i and gumbel_l.pdf(j, loc=i + 1) for odd i, over + # the target states j = 0 .. n - 1, divided by its sum. + offsets = np.arange(-LEFT, RIGHT + 1) + self.kernel = gumbel_l.pdf(offsets, loc=0, scale=1.0) + if self.kernel[0] != 0.0 or self.kernel[-1] != 0.0: + raise RuntimeError("the transition density is not zero at the edges of the kernel") + shift = np.where(np.arange(n) % 2 == 0, 2, 1) # mode of row i is i + shift[i] + mode = np.arange(n) + shift + cumulative = np.concatenate(([0.0], np.cumsum(self.kernel))) + first = np.clip(-mode, -LEFT, RIGHT + 1) # offset of target state 0 + last = np.clip(n - 1 - mode, -LEFT - 1, RIGHT) # offset of target state n - 1 + self.row_scale = 1.0 / (cumulative[last + LEFT + 1] - cumulative[first + LEFT]) + + # blocks[p][a, b]: density of the step from state lo + a to state lo + b, for lo of parity p + width = min(2 * REACH + 1, n) + a, b = np.arange(width)[:, None], np.arange(width)[None, :] + self.blocks = [] + for parity in (0, 1): + offset = b - a - np.where((a + parity) % 2 == 0, 2, 1) + inside = (offset >= -LEFT) & (offset <= RIGHT) + self.blocks.append(np.where(inside, self.kernel[np.clip(offset, -LEFT, RIGHT) + LEFT], 0.0)) + + self.forward = None + self.current_index = 0 + + def _observation(self, vector, lo, hi): + """Probability of the chord in the states lo .. hi - 1, as compute_bernoulli_pitch_probabilities.""" + profiles = self.profiles[lo:hi] + return np.prod(np.where(vector > 0, profiles, 1.0 - profiles), axis=1) + + def step(self, vector): + """One chord (88 keys, 1 where a note starts). Sets current_index to the most likely state.""" + vector = np.asarray(vector) + n = self.n_states + if self.forward is None: + lo, hi = 0, min(n, 2 * REACH + 1) # the start distribution is zero from about state 70 on + prior = self.initial[lo:hi] + else: + lo, hi = max(0, self.current_index - REACH), min(n, self.current_index + REACH + 1) + source = self.forward[lo:hi] * self.row_scale[lo:hi] + prior = np.dot(self.blocks[lo % 2][: hi - lo, : hi - lo].T, source) + updated = self._observation(vector, lo, hi) * prior + updated /= max(updated.sum(), NORMALISER_FLOOR) + self.forward = np.zeros(n) + self.forward[lo:hi] = updated + self.current_index = lo + int(np.argmax(updated)) + + def get_current_position(self): + return float(self.score_positions[self.current_index]) diff --git a/submissions/bjork-gudmundsdottir-hmm/fast.npz b/submissions/bjork-gudmundsdottir-hmm/fast.npz new file mode 100644 index 0000000..3940e18 Binary files /dev/null and b/submissions/bjork-gudmundsdottir-hmm/fast.npz differ diff --git a/submissions/bjork-gudmundsdottir-hmm/metadata.yaml b/submissions/bjork-gudmundsdottir-hmm/metadata.yaml new file mode 100644 index 0000000..0ad3c51 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/metadata.yaml @@ -0,0 +1,61 @@ +name: Transcribe twice, follow with a pitch HMM (two streaming transcribers + banded pitch HMM) +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, as in our second submission + (bjork-gudmundsdottir-dual). One looks 5 frames ahead (notes final after + 166 ms), the other does not (46 ms). New here: Matchmaker's pitch HMM + (pthmm, default arguments, with a banded forward step) follows the slower, + more reliable notes and decides where in the score the performer is, in + place of the event-level online time warping. The faster notes decide when + the next chords come: a fast chord moves the position one score chord + further, now only if one of its pitches belongs to that 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. The weights are the ones of + bjork-gudmundsdottir-dual. + +# Required declaration. See docs/eval-protocol.md, and "notes" below for what +# we saw of the evaluation fold. +eval_fold_untouched: true + +notes: > + What we saw of the evaluation fold: after our first two entries had been + evaluated we read the public leaderboard, its rows per dataset only. Our + entries lose pieces on Batik, and with the same AMT notes Matchmaker's + pitch HMM loses none there while its Arzt follower does. That was our + reason to try the pitch HMM in place of the Arzt follower. We did not open + the per-piece evaluation results and never ran anything on the evaluation + fold. The choice was made on the validation fold: with the notes of our + transcriber without lookahead the Arzt follower lost 6 pieces over 6 runs + and the pitch HMM 2, and a trace of the Chopin op. 38 excerpt showed the + Arzt follower running ahead on repeated chords. We asked the course + organisers before submitting an entry that the leaderboard prompted, and + they agreed. Validation fold, one run: 20 of 20 performances tracked, mean + of the per-piece median beat errors 0.013 beats (bjork-gudmundsdottir-dual + 0.023, bjork-gudmundsdottir 0.085), mean of the per-piece mean beat errors + 0.096 (0.159, 0.183). Both changes were developed on the validation fold, + after a close look at two of its pieces, so these numbers are not an + unbiased estimate. Neither change has a tuned setting: the pitch HMM runs + with Matchmaker's default arguments, and the banded step uses the 768 + states on each side of the current one because a single transition cannot + reach further in double precision. It ended in the same state as + Matchmaker's PitchHMM after every one of 107,070 validation chords. + Real-time factor about 0.16 on the validation fold (two pieces at a time on + a 2-core machine). diff --git a/submissions/bjork-gudmundsdottir-hmm/requirements.txt b/submissions/bjork-gudmundsdottir-hmm/requirements.txt new file mode 100644 index 0000000..bee6816 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/requirements.txt @@ -0,0 +1,2 @@ +# No dependencies beyond the benchmark environment: numpy, and for the pitch +# HMM scipy and two helper functions of matchmaker.prob.hmm. diff --git a/submissions/bjork-gudmundsdottir-hmm/settings.json b/submissions/bjork-gudmundsdottir-hmm/settings.json new file mode 100644 index 0000000..6c15395 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/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-hmm/solution.py b/submissions/bjork-gudmundsdottir-hmm/solution.py new file mode 100644 index 0000000..3268e79 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/solution.py @@ -0,0 +1,337 @@ +"""Team Björk Guðmundsdóttir (Music Informatics WS26, JKU Linz): transcribe twice, follow with a pitch HMM. + +Our second submission (bjork-gudmundsdottir-dual) runs two streaming piano +transcribers side by side: a slower one whose notes decide where in the +score the performer is, and a faster one whose notes decide when the next +chord comes. This one keeps the two transcribers and changes the follower in +two places: + +1. Processor (unchanged from bjork-gudmundsdottir-dual): 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. Where (new): the anchor's onsets within 35 ms form a chord. Every chord + goes to Matchmaker's pitch HMM (the MIDI method `pthmm`, default + arguments) instead of the event-level online time warping of our first + two submissions. banded_pitch_hmm.py computes the same forward step on + the states near the current one only, so its cost does not grow with the + score. The anchor alone decides the score position. +3. When (new: the pitch check): the fast onsets are grouped into chords at + their first note (35 ms). A fast chord that starts more than 35 ms after + the anchor's last chord moves the output one score chord further, but + only if one of its notes has a pitch of that score chord. A fast chord + that does not fit is ignored. When the anchor takes its next chord, the + count starts again from there, so the fast notes can never move the + anchor itself. +4. Between chords the position moves on at the tempo the anchor followed + over the last 4 seconds, as in bjork-gudmundsdottir. + +Files next to this one (see README.md): + banded_pitch_hmm.py the pitch HMM with the banded step + 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.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") + + +def _banded_pitch_hmm(): + """BandedPitchHMM from banded_pitch_hmm.py next to this file.""" + if "banded_pitch_hmm" not in sys.modules: + spec = importlib.util.spec_from_file_location("banded_pitch_hmm", HERE / "banded_pitch_hmm.py") + module = importlib.util.module_from_spec(spec) + sys.modules["banded_pitch_hmm"] = module + spec.loader.exec_module(module) + return sys.modules["banded_pitch_hmm"].BandedPitchHMM + + +tb = _transcriber_stream() +BandedPitchHMM = _banded_pitch_hmm() +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 bjork-gudmundsdottir with a pitch HMM inside instead of the event OLTW.""" + + 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) + # Matchmaker's MIDI `pthmm` (PitchHMM, default arguments), with a banded forward step. + self.inner = BandedPitchHMM(score_note_array) + 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 fast onsets time the chords after the anchor's last chord, if their pitch fits.""" + + 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) + self.fast_keys = [] # the keys (pitch - 21) of that chord's notes so far + + def step(self, features_) -> None: + anchor, fast = features_ + super().step(anchor) + started = time.perf_counter() + for onset, pitch in fast[1:]: + if not self.fast_times or onset - self.fast_times[-1] > CHORD_THRESHOLD: + self.fast_times.append(float(onset)) + self.fast_keys.append(set()) + self.fast_keys[-1].add(int(pitch) - LOWEST_KEY) + if self.chord_times: + t_k, b_k = self.chord_times[-1], self.chord_beats[-1] + k = max(int(np.searchsorted(self.score_positions, b_k, side="right")) - 1, 0) + last = len(self.score_positions) - 1 + new, last_time = 0, None + for j in range(bisect.bisect_right(self.fast_times, t_k + CHORD_THRESHOLD), len(self.fast_times)): + if k + new + 1 > last: + break + wanted = self.reference_features[k + new + 1] # the score chord this fast chord would move to + if any(0 <= key < 88 and wanted[key] > 0 for key in self.fast_keys[j]): + new, last_time = new + 1, self.fast_times[j] + if new > 0: + target = float(self.score_positions[k + new]) + elapsed = min(max(self.current_perf_time - last_time, 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-hmm", + 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-hmm/transcriber_b/__init__.py b/submissions/bjork-gudmundsdottir-hmm/transcriber_b/__init__.py new file mode 100644 index 0000000..faa7095 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/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-hmm/transcriber_b/features.py b/submissions/bjork-gudmundsdottir-hmm/transcriber_b/features.py new file mode 100644 index 0000000..434938b --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/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-hmm/transcriber_b/stream.py b/submissions/bjork-gudmundsdottir-hmm/transcriber_b/stream.py new file mode 100644 index 0000000..ef26dc0 --- /dev/null +++ b/submissions/bjork-gudmundsdottir-hmm/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)