dettato 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dettato/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Dettato: multi-instrument audio-to-MIDI transcription by KobiMusic.
2
+
3
+ >>> import dettato
4
+ >>> result = dettato.transcribe("song.mp3")
5
+ >>> result.save_midi("song.mid")
6
+ """
7
+ from .pipeline import Dettato, Track, Transcription, transcribe
8
+
9
+ __version__ = "2.0.0"
10
+ __all__ = ["Dettato", "Track", "Transcription", "transcribe", "__version__"]
dettato/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
dettato/audio.py ADDED
@@ -0,0 +1,58 @@
1
+ """Reading audio files: one decode at the file's own rate, mono, then resampled for each model.
2
+
3
+ The transcriber, the evidence model and the grouper work on 16 kHz audio; the drum model on 44.1 kHz audio and only when the
4
+ source itself was recorded at 40 kHz or more.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import subprocess
9
+ from dataclasses import dataclass
10
+
11
+ import numpy as np
12
+
13
+ EXTENSIONS = (".wav", ".mp3", ".flac", ".ogg", ".m4a", ".aiff", ".aif", ".opus")
14
+
15
+
16
+ @dataclass
17
+ class Audio:
18
+ samples: np.ndarray # float32 mono at `rate`
19
+ rate: int
20
+
21
+ @property
22
+ def seconds(self) -> float:
23
+ return len(self.samples) / self.rate
24
+
25
+ def at(self, rate: int) -> np.ndarray:
26
+ """The audio resampled to ``rate`` (float32 mono)."""
27
+ if rate == self.rate:
28
+ return self.samples
29
+ import soxr
30
+
31
+ return soxr.resample(self.samples, self.rate, rate, quality="HQ").astype(np.float32)
32
+
33
+
34
+ def _ffmpeg(path: str) -> Audio:
35
+ rate = _probe_rate(path) or 44100
36
+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-ar", str(rate), "-"],
37
+ capture_output=True, check=True).stdout
38
+ return Audio(np.frombuffer(raw, np.float32).copy(), rate)
39
+
40
+
41
+ def _probe_rate(path: str) -> int | None:
42
+ try:
43
+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=sample_rate",
44
+ "-of", "csv=p=0", path], capture_output=True, text=True, check=True).stdout
45
+ return int(out.strip().split(",")[0].split()[0])
46
+ except Exception: # noqa: BLE001
47
+ return None
48
+
49
+
50
+ def load(path: str) -> Audio:
51
+ """Any audio file -> mono float32 at its own sample rate (soundfile first, ffmpeg for anything it cannot read)."""
52
+ try:
53
+ import soundfile as sf
54
+
55
+ x, rate = sf.read(path, dtype="float32", always_2d=True)
56
+ return Audio(x.mean(1).astype(np.float32), int(rate))
57
+ except Exception: # noqa: BLE001
58
+ return _ffmpeg(path)
dettato/cli.py ADDED
@@ -0,0 +1,62 @@
1
+ """dettato FILE_OR_FOLDER ... -o OUT_DIR
2
+
3
+ Writes OUT_DIR/<name>.mid (one track per instrument + a drum track) and OUT_DIR/<name>.json (a summary) for every audio file.
4
+ Folders are searched recursively and their structure is kept under OUT_DIR."""
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import json
9
+ import os
10
+ import sys
11
+ import time
12
+
13
+ from .audio import EXTENSIONS
14
+
15
+
16
+ def gather(inputs):
17
+ out = []
18
+ for p in inputs:
19
+ if os.path.isdir(p):
20
+ for root, _, files in sorted(os.walk(p)):
21
+ for f in sorted(files):
22
+ if f.lower().endswith(EXTENSIONS):
23
+ full = os.path.join(root, f)
24
+ out.append((os.path.splitext(os.path.relpath(full, p))[0], full))
25
+ else:
26
+ out.append((os.path.splitext(os.path.basename(p))[0], p))
27
+ return out
28
+
29
+
30
+ def main(argv=None):
31
+ ap = argparse.ArgumentParser(prog="dettato", description="Audio to multi-track MIDI.")
32
+ ap.add_argument("inputs", nargs="+", help="audio files or folders")
33
+ ap.add_argument("-o", "--out", default="dettato_out", help="output folder (default: dettato_out)")
34
+ ap.add_argument("--device", default=None, help="cuda, cpu, cuda:1, ... (default: cuda if available)")
35
+ a = ap.parse_args(argv)
36
+ songs = gather(a.inputs)
37
+ if not songs:
38
+ sys.exit("no audio files found")
39
+ from .pipeline import Dettato
40
+
41
+ model = Dettato.from_pretrained(a.device)
42
+ print(f"dettato: {len(songs)} file(s) on {model.device}", flush=True)
43
+ failed = 0
44
+ for name, path in songs:
45
+ t0 = time.time()
46
+ try:
47
+ res = model.transcribe(path)
48
+ except Exception as e: # noqa: BLE001
49
+ failed += 1
50
+ print(f"FAILED {path}: {e!r}", flush=True)
51
+ continue
52
+ base = os.path.join(a.out, name)
53
+ res.save_midi(base + ".mid")
54
+ with open(base + ".json", "w") as fh:
55
+ json.dump(res.summary(), fh, indent=1)
56
+ tracks = ", ".join(f"{t.name} ({len(t.notes)})" for t in res.tracks)
57
+ print(f"{name}: {res.seconds:.0f} s in {time.time() - t0:.0f} s -> {base}.mid: {tracks}", flush=True)
58
+ sys.exit(1 if failed else 0)
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()
@@ -0,0 +1,6 @@
1
+ """Drum stage: drum-kit and orchestral percussion (timpani by pitch) from 44.1 kHz audio. See ``infer.py``."""
2
+ from .features import SR, features
3
+ from .infer import FPS, MIN_SOURCE_RATE, DrumTranscriber, peaks
4
+ from .model import KEYS, TIMPANI_KEYS, DrumNet, OrchestralExpert
5
+
6
+ __all__ = ["DrumTranscriber", "DrumNet", "OrchestralExpert", "features", "peaks", "KEYS", "TIMPANI_KEYS", "MIN_SOURCE_RATE", "FPS", "SR"]
@@ -0,0 +1,100 @@
1
+ """Input features of the drum model: 280 log-power bands per 10 ms frame, from 44.1 kHz mono audio.
2
+
3
+ lo (128) mel bands 20 Hz - 7.8 kHz (16 kHz signal, 512-point STFT)
4
+ hi (32) mel bands 7.8 - 20 kHz (44.1 kHz signal, 1411-point STFT)
5
+ cq (120) log-frequency bands, 24 per octave from 36.7 Hz (D1) to 1.14 kHz (16 kHz signal, 6144-point STFT):
6
+ fine enough in the low register to tell timpani pitches a semitone apart
7
+
8
+ All three come from one level normalisation (the recording brought to an RMS of -18 dBFS) and use log(power + 1e-5).
9
+ The high band is why the model needs a source recorded at 40 kHz or more.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import numpy as np
14
+ import torch
15
+
16
+ SR = 44100
17
+ FLOOR = 1e-5
18
+ N_LO, N_HI, N_CQ = 128, 32, 120
19
+ N_BANDS = N_LO + N_HI + N_CQ # 280
20
+ CQ_BPO, CQ_FMIN, CQ_NFFT = 24, 36.708, 6144
21
+
22
+
23
+ def _hz_to_mel(f):
24
+ return 2595.0 * np.log10(1.0 + np.asarray(f) / 700.0)
25
+
26
+
27
+ def _mel_to_hz(m):
28
+ return 700.0 * (10.0 ** (np.asarray(m) / 2595.0) - 1.0)
29
+
30
+
31
+ def mel_filterbank(sr: int, n_fft: int, n_mels: int, fmin: float, fmax: float) -> np.ndarray:
32
+ """Slaney-normalised triangular mel filters, (n_mels, n_fft // 2 + 1) float32."""
33
+ n_bins = n_fft // 2 + 1
34
+ fft_freqs = np.linspace(0, sr / 2, n_bins)
35
+ mel_pts = _mel_to_hz(np.linspace(_hz_to_mel(fmin), _hz_to_mel(fmax), n_mels + 2))
36
+ fb = np.zeros((n_mels, n_bins), dtype=np.float32)
37
+ for i in range(n_mels):
38
+ lo, ctr, hi = mel_pts[i], mel_pts[i + 1], mel_pts[i + 2]
39
+ up = (fft_freqs - lo) / max(ctr - lo, 1e-9)
40
+ down = (hi - fft_freqs) / max(hi - ctr, 1e-9)
41
+ fb[i] = np.maximum(0.0, np.minimum(up, down))
42
+ fb *= (2.0 / (mel_pts[2:] - mel_pts[:-2]))[:, None].astype(np.float32)
43
+ return fb
44
+
45
+
46
+ def logfreq_filterbank(sr: int = 16000, n_fft: int = CQ_NFFT, fmin: float = CQ_FMIN, bpo: int = CQ_BPO, n: int = N_CQ) -> np.ndarray:
47
+ """Triangular log-frequency filters (each sums to 1), (n, n_fft // 2 + 1) float32. A band narrower than about two FFT bins
48
+ reads the spectrum by linear interpolation at its centre instead."""
49
+ freqs = np.arange(n_fft // 2 + 1) * sr / n_fft
50
+ c = fmin * 2.0 ** (np.arange(-1, n + 1) / bpo)
51
+ fb = np.zeros((n, len(freqs)), np.float32)
52
+ for k in range(n):
53
+ lo, ce, hi = c[k], c[k + 1], c[k + 2]
54
+ w = np.maximum(0.0, np.minimum((freqs - lo) / (ce - lo), (hi - freqs) / (hi - ce)))
55
+ if w.sum() < 1.0:
56
+ j = ce * n_fft / sr
57
+ j0 = int(np.floor(j))
58
+ a = j - j0
59
+ w = np.zeros_like(w)
60
+ w[j0] = 1 - a
61
+ w[j0 + 1] = a
62
+ fb[k] = w / w.sum()
63
+ return fb
64
+
65
+
66
+ _FILTERS: dict[str, torch.Tensor] = {}
67
+
68
+
69
+ def _filters(name: str) -> torch.Tensor:
70
+ if not _FILTERS:
71
+ _FILTERS["lo"] = torch.from_numpy(mel_filterbank(sr=16000, n_fft=512, n_mels=N_LO, fmin=20.0, fmax=7800.0))
72
+ _FILTERS["hi"] = torch.from_numpy(mel_filterbank(sr=SR, n_fft=1411, n_mels=N_HI, fmin=7800.0, fmax=20000.0))
73
+ _FILTERS["cq"] = torch.from_numpy(logfreq_filterbank())
74
+ return _FILTERS[name]
75
+
76
+
77
+ def _logspec(x: np.ndarray, n_fft: int, hop: int, fb: torch.Tensor) -> np.ndarray:
78
+ s = torch.stft(torch.from_numpy(np.ascontiguousarray(x, dtype=np.float32)), n_fft, hop_length=hop, win_length=n_fft,
79
+ window=torch.hann_window(n_fft), center=True, return_complex=True, pad_mode="constant")
80
+ return torch.log(fb @ (s.abs() ** 2) + FLOOR).T.numpy()
81
+
82
+
83
+ def level_gain(x: np.ndarray) -> float:
84
+ """The gain that brings x to an RMS of -18 dBFS."""
85
+ rms = float(np.sqrt(np.mean(np.asarray(x, np.float64) ** 2))) + 1e-9
86
+ return 10 ** (-18 / 20) / rms
87
+
88
+
89
+ def features(x44: np.ndarray) -> np.ndarray:
90
+ """Mono audio at 44.1 kHz -> (T, 280) float16 features [lo | hi | cq] at 100 frames per second."""
91
+ import soxr
92
+
93
+ x44 = np.asarray(x44, np.float32)
94
+ x = (x44 * level_gain(x44)).astype(np.float32)
95
+ x16 = soxr.resample(x, SR, 16000).astype(np.float32)
96
+ lo = _logspec(x16, 512, 160, _filters("lo"))
97
+ hi = _logspec(x, 1411, SR // 100, _filters("hi"))
98
+ cq = _logspec(x16, CQ_NFFT, 160, _filters("cq"))
99
+ T = min(len(x16) // 160, len(lo), len(hi), len(cq))
100
+ return np.concatenate([lo[:T], hi[:T], cq[:T]], 1).astype(np.float16)
dettato/drums/infer.py ADDED
@@ -0,0 +1,142 @@
1
+ """Drum transcription: 44.1 kHz audio -> drum hits on GM drum keys (timpani on keys 41-53, the key being the drum's pitch).
2
+
3
+ from dettato.drums import DrumTranscriber
4
+ drums = DrumTranscriber.from_pretrained("cuda") # or "cpu"
5
+ hits = drums.transcribe(audio_44k) # [{"onset", "offset", "pitch", "is_drum", "velocity"}, ...]
6
+ drums.last_info # {"router": 0.03, "model": "drum-kit"}
7
+
8
+ Two models and a router:
9
+
10
+ drum-kit ``DrumNet``: pop, rock, jazz, electronic music with a drum kit
11
+ orchestral three ``OrchestralExpert`` models, averaged: timpani by pitch and concert percussion
12
+
13
+ The router (the experts' mean, one value per recording, computed from the whole recording) picks the orchestral model when it
14
+ is at least 0.5, else the drum-kit model. Hits are the local peaks of each key's onset probability at or above the threshold
15
+ at 50 frames per second, at least 3 frames apart per key; the orchestral model adds its timpani hits, leaving out one that
16
+ repeats a key already hit within 40 ms. Every hit is written 100 ms long.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from .. import hub
24
+ from .features import SR, features
25
+ from .model import KEYS, TIMPANI_KEYS, DrumNet, OrchestralExpert
26
+
27
+ MIN_SOURCE_RATE = 40000 # the drum model reads the 7.8-20 kHz band: sources recorded below this rate are not transcribed
28
+ FPS = 50 # output frame rate
29
+
30
+
31
+ def peaks(prob: np.ndarray, th: float, gap: int = 3) -> tuple[np.ndarray, np.ndarray]:
32
+ """(T, L) onset probabilities -> (frames, lanes) of the local maxima >= th, at least ``gap`` frames apart per lane."""
33
+ T, L = prob.shape
34
+ left = np.vstack([prob[:1], prob[:-1]])
35
+ right = np.vstack([prob[1:], prob[-1:]])
36
+ cand = (prob >= th) & (prob >= left) & (prob >= right)
37
+ last = np.full(L, -10, np.int64)
38
+ fr, ln = [], []
39
+ for t in np.nonzero(cand.any(1))[0]:
40
+ m = cand[t] & (t - last > gap - 1)
41
+ for lane in np.nonzero(m)[0]:
42
+ fr.append(int(t))
43
+ ln.append(int(lane))
44
+ last = np.where(m, t, last)
45
+ return np.array(fr, int), np.array(ln, int)
46
+
47
+
48
+ def _split(state: dict, prefix: str) -> dict:
49
+ return {k[len(prefix):]: v for k, v in state.items() if k.startswith(prefix)}
50
+
51
+
52
+ class DrumTranscriber:
53
+ """The drum stage. ``last_info`` holds the router value and the model that ran for the last ``transcribe`` call."""
54
+
55
+ def __init__(self, config: dict, state: dict, device: str | torch.device = "cpu"):
56
+ assert config.get("model_type") == "dettato-drums", config.get("model_type")
57
+ assert config["keys"] == KEYS and config["timpani_keys"] == TIMPANI_KEYS and config["sample_rate"] == SR
58
+ self.config = config
59
+ self.device = torch.device(device)
60
+ th = config["thresholds"]
61
+ self.th_kit, self.th_drum, self.th_timpani, self.th_router = th["drum_kit"], th["orchestral_drum"], th["timpani"], th["router"]
62
+ self.kit = DrumNet(config["drum_kit"])
63
+ self.kit.load_state_dict(_split(state, "drum_kit."))
64
+ self.kit.to(self.device).eval()
65
+ self.experts = []
66
+ for i in range(config["orchestral"]["n_models"]):
67
+ ex = OrchestralExpert(config["drum_kit"], **config["orchestral"]["adapter"])
68
+ ex.load_state_dict(_split(state, f"orchestral.{i}."))
69
+ self.experts.append(ex.to(self.device).eval())
70
+ self.last_info: dict = {}
71
+
72
+ @classmethod
73
+ def from_pretrained(cls, device: str | torch.device = "cpu") -> "DrumTranscriber":
74
+ """The released weights (``kobimusic/dettato-drums``)."""
75
+ return cls(hub.load_config("drums"), hub.load_state("drums"), device)
76
+
77
+ def n_params(self) -> int:
78
+ return sum(p.numel() for m in [self.kit, *self.experts] for p in m.parameters())
79
+
80
+ def _autocast(self):
81
+ return torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda")
82
+
83
+ @torch.no_grad()
84
+ def probabilities(self, feats: np.ndarray) -> dict:
85
+ """(T, 280) features -> router value, the drum-kit model's onset / velocity probabilities and the orchestral models'
86
+ (averaged) drum / timpani / velocity probabilities, all at 50 fps."""
87
+ T = feats.shape[0] // 2 * 2
88
+ x = torch.from_numpy(np.ascontiguousarray(feats[:T], dtype=np.float32))[None].to(self.device)
89
+ with self._autocast():
90
+ zk, vk = self.kit(x[..., :160])
91
+ outs = []
92
+ for ex in self.experts:
93
+ with self._autocast():
94
+ o = ex(x)
95
+ base = o["base"][0].float()
96
+ # the corrected drum logits are formed as the base logits plus the correction, as during training
97
+ drum = torch.sigmoid(base + (o["drum"][0].float() - base))
98
+ outs.append((float(torch.sigmoid(o["router"][0].float())), drum.cpu().numpy(),
99
+ torch.sigmoid(o["timpani"][0].float()).cpu().numpy(), torch.sigmoid(o["velocity"][0].float()).cpu().numpy()))
100
+ n = min(o[1].shape[0] for o in outs)
101
+ return {"router": float(np.mean([o[0] for o in outs])),
102
+ "kit": torch.sigmoid(zk[0].float()).cpu().numpy(), "kit_vel": torch.sigmoid(vk[0].float()).cpu().numpy(),
103
+ "drum": np.mean([o[1][:n] for o in outs], 0), "timpani": np.mean([o[2][:n] for o in outs], 0),
104
+ "vel": np.mean([o[3][:n] for o in outs], 0)}
105
+
106
+ def decode(self, P: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray, str]:
107
+ """-> (onset seconds, key, velocity 0-1, which model: "drum-kit" / "orchestral")"""
108
+ if P["router"] < self.th_router:
109
+ fr, ln = peaks(P["kit"], self.th_kit)
110
+ return fr / FPS, np.array([KEYS[lane] for lane in ln], np.int64), P["kit_vel"][fr, ln], "drum-kit"
111
+ fd, ld = peaks(P["drum"], self.th_drum)
112
+ on, ks, vs = list(fd / FPS), [KEYS[lane] for lane in ld], list(P["vel"][fd, ld])
113
+ seen: dict[int, list] = {}
114
+ for o, k in zip(on, ks):
115
+ seen.setdefault(k, []).append(o)
116
+ ft, lt = peaks(P["timpani"], self.th_timpani)
117
+ for f, lane in zip(ft, lt):
118
+ o, k = f / FPS, TIMPANI_KEYS[int(lane)]
119
+ if any(abs(o - q) <= 0.04 for q in seen.get(k, [])):
120
+ continue
121
+ on.append(o)
122
+ ks.append(k)
123
+ vs.append(float(np.clip(P["timpani"][f, lane], 0.3, 1.0)))
124
+ order = np.argsort(on, kind="stable")
125
+ return np.array(on)[order], np.array(ks, np.int64)[order], np.array(vs)[order], "orchestral"
126
+
127
+ def transcribe(self, audio: np.ndarray, sr: int = SR) -> list[dict]:
128
+ """Mono audio (from a source recorded at >= 40 kHz) -> drum hits sorted by onset. Audio at another rate than 44.1 kHz is
129
+ resampled first."""
130
+ x = np.asarray(audio, np.float32)
131
+ if sr != SR:
132
+ import soxr
133
+
134
+ x = soxr.resample(x, sr, SR, quality="HQ").astype(np.float32)
135
+ if len(x) < SR // 10:
136
+ self.last_info = {"router": None, "model": None}
137
+ return []
138
+ P = self.probabilities(features(x).astype(np.float32))
139
+ on, keys, vel, which = self.decode(P)
140
+ self.last_info = {"router": P["router"], "model": which}
141
+ return [{"onset": round(float(a), 4), "offset": round(float(a) + 0.1, 4), "pitch": int(k), "is_drum": True,
142
+ "velocity": round(float(np.clip(v, 0.05, 1.0)), 3)} for a, k, v in zip(on, keys, vel)]
dettato/drums/model.py ADDED
@@ -0,0 +1,285 @@
1
+ """The drum networks.
2
+
3
+ ``DrumNet`` (188,764 parameters) reads the 160 mel bands of ``features.py`` (lo + hi) at 100 fps and writes, at 50 fps, one
4
+ onset logit and one velocity logit per drum key of the GM range 27-87:
5
+
6
+ stem 2-D CNN over (time, band); time is halved once, the bands are pooled 8x
7
+ collapse a bidirectional GRU across the bands of every frame -> one 88-d vector per frame
8
+ temporal depthwise temporal conv block, residual bidirectional GRU, song-level content attention
9
+ heads one small bidirectional GRU per drum family (kick / snare / hats + ride / toms + crashes / shakers), each predicting
10
+ only its own keys; every other key comes from a shared linear head; velocity from a low-rank linear head
11
+
12
+ ``OrchestralExpert`` = a ``DrumNet`` + a pitch-resolving low band (the 120 ``cq`` bands) + an adapter (bidirectional GRU and
13
+ self-attention) that corrects the drum logits for concert percussion and adds 13 timpani logits, one per key 41-53 (the key of a
14
+ timpani hit is its pitch). Its router reads the adapter's states pooled over the whole recording and gives one number per
15
+ recording: the probability that it is orchestral music, which decides whether the expert or the plain ``DrumNet`` transcribes it.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ N_MEL = 160 # lo + hi bands
24
+ N_CQ = 120
25
+ KEYS = list(range(27, 88)) # drum keys (GM numbering) of the drum logits
26
+ TIMPANI_KEYS = list(range(41, 54)) # keys of the timpani logits (key = pitch)
27
+
28
+
29
+ def _act(name):
30
+ return {"relu": nn.ReLU, "silu": nn.SiLU, "gelu": nn.GELU}[name]()
31
+
32
+
33
+ class Res2d(nn.Module):
34
+ """Residual separable block: depthwise 3x3 -> BN -> act -> pointwise -> BN, added to the input."""
35
+
36
+ def __init__(self, c, act="relu"):
37
+ super().__init__()
38
+ self.dw = nn.Conv2d(c, c, 3, padding=1, groups=c)
39
+ self.bn1 = nn.BatchNorm2d(c)
40
+ self.pw1 = nn.Conv2d(c, c, 1)
41
+ self.act = _act(act)
42
+ self.bn2 = nn.BatchNorm2d(c)
43
+
44
+ def forward(self, x):
45
+ return x + self.bn2(self.pw1(self.act(self.bn1(self.dw(x)))))
46
+
47
+
48
+ class Stem(nn.Module):
49
+ """A comma-separated layer spec: ``cN`` 3x3 conv to N channels (+ BN, act), ``r`` residual block, ``pTF`` max-pool (T, F)."""
50
+
51
+ def __init__(self, cin, spec, act="relu"):
52
+ super().__init__()
53
+ layers, c, self.tdiv, self.fdiv = [], cin, 1, 1
54
+ for tok in spec.split(","):
55
+ kind, arg = tok.strip()[0], tok.strip()[1:]
56
+ if kind == "c":
57
+ n = int(arg)
58
+ layers += [nn.Conv2d(c, n, 3, padding=1), nn.BatchNorm2d(n), _act(act)]
59
+ c = n
60
+ elif kind == "r":
61
+ layers.append(Res2d(c, act))
62
+ elif kind == "p":
63
+ t, f = int(arg[0]), int(arg[1:])
64
+ layers.append(nn.MaxPool2d((t, f)))
65
+ self.tdiv *= t
66
+ self.fdiv *= f
67
+ else:
68
+ raise ValueError(f"unknown stem layer {tok!r}")
69
+ self.net = nn.Sequential(*layers)
70
+ self.cout = c
71
+
72
+ def forward(self, x):
73
+ return self.net(x)
74
+
75
+
76
+ class BandGRU(nn.Module):
77
+ """(B, C, T, F) -> (B, T, W): a bidirectional GRU scans the F bands of every frame; its two final states and its mean output
78
+ are projected to W."""
79
+
80
+ def __init__(self, c, w, m):
81
+ super().__init__()
82
+ self.rnn = nn.GRU(c, m, batch_first=True, bidirectional=True)
83
+ self.proj = nn.Linear(4 * m, w)
84
+
85
+ def forward(self, h):
86
+ B, C, T, Fq = h.shape
87
+ with torch.autocast(h.device.type, enabled=False):
88
+ z = h.permute(0, 2, 3, 1).reshape(B * T, Fq, C).float()
89
+ out, hn = self.rnn(z)
90
+ z = torch.cat([hn[0], hn[1], out.mean(1)], -1)
91
+ return self.proj(z).view(B, T, -1)
92
+
93
+
94
+ class ConvBlock(nn.Module):
95
+ """Depthwise temporal conv (kernel k) -> BN -> SiLU -> pointwise, residual. On (B, T, W)."""
96
+
97
+ def __init__(self, w, k=15, d=1):
98
+ super().__init__()
99
+ self.dw = nn.Conv1d(w, w, k, padding=d * (k // 2), dilation=d, groups=w)
100
+ self.bn = nn.BatchNorm1d(w)
101
+ self.pw = nn.Conv1d(w, w, 1)
102
+
103
+ def forward(self, x):
104
+ h = x.transpose(1, 2)
105
+ return x + self.pw(F.silu(self.bn(self.dw(h)))).transpose(1, 2)
106
+
107
+
108
+ class GRUBlock(nn.Module):
109
+ """LayerNorm -> bidirectional GRU (h per direction) -> linear back to W, residual."""
110
+
111
+ def __init__(self, w, h=48):
112
+ super().__init__()
113
+ self.rnn = nn.GRU(w, h, batch_first=True, bidirectional=True)
114
+ self.out = nn.Linear(2 * h, w)
115
+ self.norm = nn.LayerNorm(w)
116
+
117
+ def forward(self, x):
118
+ with torch.autocast(x.device.type, enabled=False):
119
+ y, _ = self.rnn(self.norm(x.float()))
120
+ return x + self.out(y)
121
+
122
+
123
+ class SongAttention(nn.Module):
124
+ """Self-attention over the whole input, content only (no positions), residual."""
125
+
126
+ def __init__(self, w, da=32, heads=2):
127
+ super().__init__()
128
+ self.n = nn.LayerNorm(w)
129
+ self.qkv = nn.Linear(w, 3 * da)
130
+ self.o = nn.Linear(da, w)
131
+ self.da, self.heads = da, heads
132
+
133
+ def forward(self, x):
134
+ B, T, _ = x.shape
135
+ q, k, v = self.qkv(self.n(x)).view(B, T, 3, self.heads, self.da // self.heads).permute(2, 0, 3, 1, 4)
136
+ a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(B, T, self.da)
137
+ return x + self.o(a)
138
+
139
+
140
+ def _temporal_block(spec, w):
141
+ t = spec["t"]
142
+ if t == "tb":
143
+ return ConvBlock(w, spec.get("k", 15), spec.get("d", 1))
144
+ if t == "gru":
145
+ return GRUBlock(w, spec.get("h", 48))
146
+ if t == "attn":
147
+ return SongAttention(w, spec.get("da", 32), spec.get("heads", 2))
148
+ raise ValueError(f"unknown temporal block {t!r}")
149
+
150
+
151
+ class FamilyHeads(nn.Module):
152
+ """Onset logits: one bidirectional GRU + linear head per key family (each predicts only its family's keys); the other keys
153
+ come from a shared linear head."""
154
+
155
+ def __init__(self, w, K, groups, h=24):
156
+ super().__init__()
157
+ self.groups = groups
158
+ self.towers = nn.ModuleList([nn.GRU(w, h, batch_first=True, bidirectional=True) for _ in groups])
159
+ self.heads = nn.ModuleList([nn.Linear(2 * h + w, len(g)) for g in groups])
160
+ self.rest = nn.Linear(w, K)
161
+ self.register_buffer("idx", torch.tensor([l for g in groups for l in g]))
162
+
163
+ def forward(self, h):
164
+ z = self.rest(h).float()
165
+ with torch.autocast(h.device.type, enabled=False):
166
+ hf = h.float()
167
+ parts = [hd(torch.cat([tw(hf)[0], hf], -1)) for tw, hd in zip(self.towers, self.heads)]
168
+ return z.index_copy(-1, self.idx, torch.cat(parts, -1))
169
+
170
+
171
+ class DrumNet(nn.Module):
172
+ """(B, T, 160) mel features at 100 fps -> (onset logits, velocity logits), each (B, T/2, 61) at 50 fps."""
173
+
174
+ def __init__(self, cfg):
175
+ super().__init__()
176
+ self.cfg = cfg
177
+ K = len(KEYS)
178
+ self.stem = Stem(1, cfg["stem"], cfg.get("act", "relu"))
179
+ assert self.stem.tdiv == 2, "the stem must halve time once"
180
+ w = cfg["w"]
181
+ assert cfg.get("collapse", "fgru") == "fgru"
182
+ self.collapse = BandGRU(self.stem.cout, w, cfg["collapse_m"])
183
+ blocks = []
184
+ for spec in cfg["temporal"]:
185
+ blocks += [_temporal_block(spec, w) for _ in range(spec.get("n", 1))]
186
+ self.temporal = nn.ModuleList(blocks)
187
+ groups = [[KEYS.index(k) for k in g] for g in cfg["towers"]]
188
+ self.on = FamilyHeads(w, K, groups, cfg.get("tower_h", 24))
189
+ self.vel = nn.Sequential(nn.Linear(w, 16), nn.Linear(16, K))
190
+
191
+ def embed(self, x):
192
+ """(B, T, 160) -> frame embeddings (B, T/2, W)."""
193
+ return self.collapse(self.stem(((x + 5.0) / 3.0)[:, None]))
194
+
195
+ def trunk(self, c):
196
+ """frame embeddings -> (trunk states, onset logits, velocity logits)"""
197
+ h = c
198
+ for b in self.temporal:
199
+ h = b(h)
200
+ return h, self.on(h), self.vel(h)
201
+
202
+ def embed_long(self, x, chunk=8000, margin=200):
203
+ """``embed`` on a long input in windows of ``chunk`` frames with ``margin`` frames of context each side (more than the
204
+ stem's receptive field): bounded memory, the same result up to float rounding."""
205
+ T = x.shape[1]
206
+ parts, s = [], 0
207
+ while s < T:
208
+ a, b = max(0, s - margin), min(T, s + chunk + margin)
209
+ h = self.embed(x[:, a:b])
210
+ lo = (s - a) // 2
211
+ parts.append(h[:, lo:lo + (min(s + chunk, T) - s) // 2])
212
+ s += chunk
213
+ return torch.cat(parts, 1)
214
+
215
+ def forward(self, x, long_above=9000):
216
+ c = self.embed_long(x) if x.shape[1] > long_above else self.embed(x)
217
+ _, z, v = self.trunk(c)
218
+ return z, v
219
+
220
+
221
+ class CQBranch(nn.Module):
222
+ """(B, T, 120) log-frequency bands at 100 fps -> (B, T/2, d). The input is stacked with itself shifted up a fifth (14 bands)
223
+ and an octave (24 bands), so a timpani's principal tone and its strongest overtones meet in one column."""
224
+
225
+ def __init__(self, d=128, c=32):
226
+ super().__init__()
227
+ self.c1 = nn.Conv2d(3, 24, (5, 7), padding=(2, 3))
228
+ self.c2 = nn.Conv2d(24, c, (3, 5), stride=(2, 1), padding=(1, 2))
229
+ self.c3 = nn.Conv2d(c, c, (3, 5), padding=(1, 2))
230
+ self.n1, self.n2, self.n3 = nn.GroupNorm(4, 24), nn.GroupNorm(4, c), nn.GroupNorm(4, c)
231
+ self.proj = nn.Linear(c * N_CQ, d)
232
+
233
+ def forward(self, xc):
234
+ xc = xc.float()
235
+ xc = (xc - xc.mean(dim=(1, 2), keepdim=True)) / 4.0 # level-free
236
+ lo = xc.amin(dim=(1, 2), keepdim=True)
237
+
238
+ def shift(k):
239
+ return torch.cat([xc[..., k:], lo.expand(-1, xc.shape[1], k)], -1)
240
+
241
+ z = torch.stack([xc, shift(14), shift(24)], 1) # (B, 3, T, F)
242
+ z = F.silu(self.n1(self.c1(z)))
243
+ z = F.silu(self.n2(self.c2(z)))
244
+ z = F.silu(self.n3(self.c3(z))) + z
245
+ B, C, T, Fq = z.shape
246
+ return F.silu(self.proj(z.permute(0, 2, 1, 3).reshape(B, T, C * Fq)))
247
+
248
+
249
+ class OrchestralExpert(nn.Module):
250
+ """A ``DrumNet`` plus the cq branch and an adapter. (B, T, 280) -> per frame at 50 fps: the DrumNet's own onset logits, the
251
+ adapter's correction to them, timpani logits (13), velocity logits, and one router logit per input."""
252
+
253
+ def __init__(self, base_cfg, d=192, h=128, layers=2, heads=4, cq_d=128):
254
+ super().__init__()
255
+ self.base = DrumNet(base_cfg)
256
+ K = len(KEYS)
257
+ self.cq = CQBranch(cq_d)
258
+ self.inp = nn.Linear(base_cfg["w"] + cq_d + K, d)
259
+ self.rnn = nn.GRU(d, h, num_layers=layers, batch_first=True, bidirectional=True)
260
+ self.heads = heads
261
+ self.qkv = nn.Linear(2 * h, 3 * 2 * h)
262
+ self.ao = nn.Linear(2 * h, 2 * h)
263
+ self.ln = nn.LayerNorm(2 * h)
264
+ self.delta = nn.Linear(2 * h, K)
265
+ self.timp = nn.Linear(2 * h, len(TIMPANI_KEYS))
266
+ self.gate = nn.Sequential(nn.Linear(2 * h, 64), nn.SiLU(), nn.Linear(64, 1))
267
+
268
+ def forward(self, x, chunk=8000, margin=200):
269
+ T = x.shape[1] // 2 * 2
270
+ x = x[:, :T]
271
+ xm = x[..., :N_MEL]
272
+ c = self.base.embed_long(xm, chunk, margin) if T > chunk + 2 * margin else self.base.embed(xm)
273
+ h0, z0, v0 = self.base.trunk(c)
274
+ cq = self.cq(x[..., N_MEL:])
275
+ n = min(h0.shape[1], cq.shape[1])
276
+ h0, z0, v0, cq = h0[:, :n], z0[:, :n], v0[:, :n], cq[:, :n]
277
+ a = F.silu(self.inp(torch.cat([h0.float(), cq, torch.sigmoid(z0.float())], -1)))
278
+ r, _ = self.rnn(a)
279
+ B, Tn, D = r.shape
280
+ q, k, v = self.qkv(r).view(B, Tn, 3, self.heads, D // self.heads).permute(2, 0, 3, 1, 4)
281
+ att = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(B, Tn, D)
282
+ r = self.ln(r + self.ao(att))
283
+ router = self.gate(r.float().mean(1))[:, 0] # one decision per input (a whole recording)
284
+ return {"base": z0.float(), "drum": z0.float() + self.delta(r).float(), "timpani": self.timp(r).float(),
285
+ "velocity": v0.float(), "router": router}