Split any YouTube song into stems
TypeScript
feat: mel-band roformer vocals engine, float32 stems, soxr resampling
Daniel Ravinae90f00683196
diff --git a/.gitignore b/.gitignoreindex c29191e..42a1205 100644--- a/.gitignore+++ b/.gitignore@@ -5,3 +5,6 @@ extraslistening-list.md*.log.DS_Store++__pycache__/+*.pycdiff --git a/python/roformer.py b/python/roformer.pynew file mode 100644index 0000000..af0028b--- /dev/null+++ b/python/roformer.py@@ -0,0 +1,289 @@+import argparse+import json+import os+import struct+import sys+import time+import urllib.request+import wave++import numpy as np+import torch++CKPT_NAME = "MelBandRoformer.ckpt"+CKPT_URL = "https://huggingface.co/KimberleyJSN/melbandroformer/resolve/main/MelBandRoformer.ckpt"++# KimberleyJensen mel-band roformer vocal model (SDR vocals 10.98 on Multisong).+# https://github.com/ZFTurbo/Music-Source-Separation-Training+PARAMS = dict(+ dim=384,+ depth=6,+ stereo=True,+ num_stems=1,+ time_transformer_depth=1,+ freq_transformer_depth=1,+ num_bands=60,+ dim_head=64,+ heads=8,+ attn_dropout=0,+ ff_dropout=0,+ flash_attn=True,+ dim_freqs_in=1025,+ sample_rate=44100,+ stft_n_fft=2048,+ stft_hop_length=441,+ stft_win_length=2048,+ stft_normalized=False,+ mask_estimator_depth=2,+ multi_stft_resolution_loss_weight=1.0,+ multi_stft_resolutions_window_sizes=(4096, 2048, 1024, 512, 256),+ multi_stft_hop_size=147,+ multi_stft_normalized=False,+)+CHUNK_SIZE = 352800 # 8s at 44100+NUM_OVERLAP = 2+# batching >1 triggers pathological MPS paths (same runtime as fp32), so 1 it is+BATCH_SIZE = 1+MIN_CKPT_BYTES = 500_000_000+++def emit(**kwargs):+ print(json.dumps(kwargs), flush=True)+++def fail(message):+ emit(type="error", message=str(message))+ sys.exit(1)+++def load_wav(path):+ try:+ with wave.open(path, "rb") as w:+ sr = w.getframerate()+ channels = w.getnchannels()+ width = w.getsampwidth()+ frames = w.readframes(w.getnframes())+ except Exception as e:+ fail(f"cannot read wav {path}: {e}")+ if width == 2:+ audio = np.frombuffer(frames, dtype="<i2").astype(np.float32) / 32768.0+ elif width == 4:+ audio = np.frombuffer(frames, dtype="<f4").astype(np.float32)+ else:+ fail(f"unsupported sample width {width}")+ if channels == 0:+ fail("empty wav")+ return audio.reshape(-1, channels).T, sr+++def save_wav_f32(path, data, sr):+ """write a 32-bit float wav (fmt tag 3); values above 1.0 are preserved"""+ channels, _ = data.shape+ payload = data.T.astype("<f4").tobytes()+ block_align = channels * 4+ header = b"RIFF" + struct.pack("<I", 36 + len(payload)) + b"WAVE"+ header += b"fmt " + struct.pack(+ "<IHHIIHH", 16, 3, channels, sr, sr * block_align, block_align, 32+ )+ header += b"data" + struct.pack("<I", len(payload))+ with open(path, "wb") as f:+ f.write(header)+ f.write(payload)+++def download_checkpoint(dest):+ """download the checkpoint with resume support and progress emits"""+ if os.path.exists(dest):+ return+ part = dest + ".part"+ os.makedirs(os.path.dirname(dest), exist_ok=True)+ start = 0+ headers = {"User-Agent": "stemkit"}+ if os.path.exists(part):+ start = os.path.getsize(part)+ headers["Range"] = f"bytes={start}-"+ req = urllib.request.Request(CKPT_URL, headers=headers)+ last_emit = 0.0+ try:+ with urllib.request.urlopen(req, timeout=60) as res:+ total = int(res.headers.get("Content-Length", 0)) + (+ start if res.status == 206 else 0+ )+ mode = "ab" if res.status == 206 and start > 0 else "wb"+ with open(part, mode) as f:+ while True:+ chunk = res.read(1 << 20)+ if not chunk:+ break+ f.write(chunk)+ now = time.time()+ if now - last_emit >= 1.0 and total > 0:+ pct = int(f.tell() / total * 100)+ emit(+ type="progress",+ stage="separate",+ pct=0,+ message=f"Downloading vocals engine ({total // (1024 * 1024)}MB): {pct}%",+ )+ last_emit = now+ except Exception as e:+ fail(f"vocals engine download failed: {e}")+ if os.path.getsize(part) < MIN_CKPT_BYTES:+ fail(f"vocals engine download incomplete ({os.path.getsize(part)} bytes)")+ os.replace(part, dest)+ emit(type="progress", stage="separate", pct=0, message="Vocals engine downloaded")+++def resolve_device():+ if torch.cuda.is_available():+ return "cuda", True+ if torch.backends.mps.is_available():+ return "mps", True+ return "cpu", False+++def load_model(ckpt_path, device, use_half):+ from models.bs_roformer.mel_band_roformer import MelBandRoformer++ model = MelBandRoformer(**PARAMS)+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)+ if isinstance(ckpt, dict) and "state_dict" in ckpt:+ ckpt = ckpt["state_dict"]+ model.load_state_dict(ckpt, strict=True)+ model.to(device)+ if use_half:+ model.half()+ # band_split accumulates large stft magnitudes and overflows fp16+ model.band_split.to(torch.float32)+ model.eval()+ return model+++def separate(model, mix, device, use_half, on_progress):+ """chunked inference with overlap; mix is a (2, n) tensor on device"""+ total = mix.shape[-1]+ step = CHUNK_SIZE // NUM_OVERLAP+ border = CHUNK_SIZE - step+ fade_size = CHUNK_SIZE // 10+ length_init = total+ if length_init > 2 * border and border > 0:+ mix = torch.nn.functional.pad(mix, (border, border), mode="reflect")++ window = torch.ones(CHUNK_SIZE, device=device)+ window[:fade_size] = torch.linspace(0, 1, fade_size, device=device)+ window[-fade_size:] = torch.linspace(1, 0, fade_size, device=device)++ result = torch.zeros(mix.shape, device=device)+ counter = torch.zeros(mix.shape, device=device)++ with torch.inference_mode():+ i = 0+ batch_data = []+ batch_locations = []+ while i < mix.shape[-1]:+ part = mix[:, i : i + CHUNK_SIZE]+ chunk_len = part.shape[-1]+ pad_mode = "reflect" if chunk_len > CHUNK_SIZE // 2 else "constant"+ part = torch.nn.functional.pad(part, (0, CHUNK_SIZE - chunk_len), mode=pad_mode, value=0)+ if use_half:+ part = part.to(torch.float16)+ batch_data.append(part)+ batch_locations.append((i, chunk_len))+ i += step+ if len(batch_data) >= BATCH_SIZE or i >= mix.shape[-1]:+ arr = torch.stack(batch_data, dim=0)+ x = model(arr)+ for j, (start, seg_len) in enumerate(batch_locations):+ win = window[:seg_len].clone()+ if start == 0:+ win[:fade_size] = 1+ elif i >= mix.shape[-1]:+ win[-fade_size:] = 1+ result[..., start : start + seg_len] += x[j, :, :seg_len].float() * win+ counter[..., start : start + seg_len] += win+ batch_data.clear()+ batch_locations.clear()+ on_progress(i / mix.shape[-1])++ est = result / counter.clamp(min=1e-8)+ if length_init > 2 * border and border > 0:+ est = est[..., border:-border]+ return est+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--input", required=True)+ parser.add_argument("--out", required=True)+ parser.add_argument("--ckpt-dir", required=True)+ parser.add_argument("--device", default="auto")+ args = parser.parse_args()++ vendor = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vendor")+ sys.path.insert(0, vendor)++ ckpt_path = os.path.join(args.ckpt_dir, CKPT_NAME)+ if not os.path.exists(ckpt_path):+ emit(type="progress", stage="separate", pct=0, message="Downloading vocals engine (913MB, one time)")+ download_checkpoint(ckpt_path)++ if args.device == "auto":+ device, use_half = resolve_device()+ else:+ device = args.device+ use_half = device in ("cuda", "mps")+ emit(type="progress", stage="separate", pct=0, message=f"loading vocals engine on {device}")++ started = time.time()+ try:+ model = load_model(ckpt_path, device, use_half)+ except Exception as e:+ fail(f"vocals engine load failed: {e}")++ audio, sr = load_wav(args.input)+ if audio.shape[0] == 1:+ audio = np.repeat(audio, 2, axis=0)+ mix = torch.from_numpy(audio).to(device)++ last_emit = 0.0++ def on_progress(frac):+ nonlocal last_emit+ now = time.time()+ if now - last_emit >= 0.5:+ emit(type="progress", stage="separate", pct=min(99, int(frac * 100)))+ last_emit = now++ emit(type="progress", stage="separate", pct=0, message="separating")+ try:+ est = separate(model, mix, device, use_half, on_progress)+ except Exception as e:+ if device == "mps":+ emit(type="progress", stage="separate", pct=0, message=f"gpu failed ({e}), falling back to cpu")+ device = "cpu"+ use_half = False+ try:+ model = load_model(ckpt_path, device, use_half)+ except Exception as e2:+ fail(f"vocals engine load failed on cpu: {e2}")+ mix = mix.to("cpu").float()+ est = separate(model, mix, device, use_half, on_progress)+ else:+ fail(f"separation failed: {e}")++ vocals = est.cpu().numpy()+ if np.isnan(vocals).any():+ fail("separation produced invalid audio")+ os.makedirs(args.out, exist_ok=True)+ save_wav_f32(os.path.join(args.out, "vocals.wav"), vocals, sr)+ emit(type="stem", name="vocals")+ emit(+ type="done",+ stems=["vocals"],+ out_dir=args.out,+ seconds=round(time.time() - started, 1),+ )+++if __name__ == "__main__":+ main()diff --git a/python/separate.py b/python/separate.pyindex dcf74a3..b0e2813 100644--- a/python/separate.py+++ b/python/separate.py@@ -1,5 +1,6 @@import argparseimport json+import structimport sysimport timeimport wave@@ -37,17 +38,19 @@ def load_wav(path):return audio, sr-def save_wav(path, data, sr):- interleaved = data.T- peak = max(1e-9, float(np.abs(interleaved).max()))- if peak > 1.0:- interleaved = interleaved / peak * 0.999- pcm = (interleaved * 32767.0).astype("<i2")- with wave.open(path, "wb") as w:- w.setnchannels(pcm.shape[1])- w.setsampwidth(2)- w.setframerate(sr)- w.writeframes(pcm.tobytes())+def save_wav_f32(path, data, sr):+ """write a 32-bit float wav (fmt tag 3); values above 1.0 are preserved"""+ channels, _ = data.shape+ payload = data.T.astype("<f4").tobytes()+ block_align = channels * 4+ header = b"RIFF" + struct.pack("<I", 36 + len(payload)) + b"WAVE"+ header += b"fmt " + struct.pack(+ "<IHHIIHH", 16, 3, channels, sr, sr * block_align, block_align, 32+ )+ header += b"data" + struct.pack("<I", len(payload))+ with open(path, "wb") as f:+ f.write(header)+ f.write(payload)def main():@@ -114,10 +117,10 @@ def main():audio, sr = load_wav(args.input)target_sr = model.samplerateif sr != target_sr:+ import torchaudio+t = torch.from_numpy(audio)- t = torch.nn.functional.interpolate(- t.unsqueeze(0), scale_factor=target_sr / sr, mode="linear", align_corners=False- ).squeeze(0)+ t = torchaudio.functional.resample(t, sr, target_sr)audio = t.numpy()sr = target_srif audio.shape[0] == 1:@@ -178,7 +181,7 @@ def main():if wanted is not None and name not in wanted:continuepath = os.path.join(args.out, f"{name}.wav")- save_wav(path, out_cpu[i], sr)+ save_wav_f32(path, out_cpu[i], sr)written.append(name)emit(type="stem", name=name)diff --git a/python/vendor/mel_bank_44100_2048_60.npy b/python/vendor/mel_bank_44100_2048_60.npynew file mode 100644index 0000000..85d216dBinary files /dev/null and b/python/vendor/mel_bank_44100_2048_60.npy differdiff --git a/python/vendor/models/bs_roformer/__init__.py b/python/vendor/models/bs_roformer/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/python/vendor/models/bs_roformer/attend.py b/python/vendor/models/bs_roformer/attend.pynew file mode 100644index 0000000..d6dc4b3--- /dev/null+++ b/python/vendor/models/bs_roformer/attend.py@@ -0,0 +1,126 @@+from functools import wraps+from packaging import version+from collections import namedtuple++import os+import torch+from torch import nn, einsum+import torch.nn.functional as F++from einops import rearrange, reduce++# constants++FlashAttentionConfig = namedtuple('FlashAttentionConfig', ['enable_flash', 'enable_math', 'enable_mem_efficient'])++# helpers++def exists(val):+ return val is not None++def default(v, d):+ return v if exists(v) else d++def once(fn):+ called = False+ @wraps(fn)+ def inner(x):+ nonlocal called+ if called:+ return+ called = True+ return fn(x)+ return inner++print_once = once(print)++# main class++class Attend(nn.Module):+ def __init__(+ self,+ dropout = 0.,+ flash = False,+ scale = None+ ):+ super().__init__()+ self.scale = scale+ self.dropout = dropout+ self.attn_dropout = nn.Dropout(dropout)++ self.flash = flash+ assert not (flash and version.parse(torch.__version__) < version.parse('2.0.0')), 'in order to use flash attention, you must be using pytorch 2.0 or above'++ # determine efficient attention configs for cuda and cpu++ self.cpu_config = FlashAttentionConfig(True, True, True)+ self.cuda_config = None++ if not torch.cuda.is_available() or not flash:+ return++ device_properties = torch.cuda.get_device_properties(torch.device('cuda'))+ device_version = version.parse(f'{device_properties.major}.{device_properties.minor}')++ if device_version >= version.parse('8.0'):+ if os.name == 'nt':+ print_once('Windows OS detected, using math or mem efficient attention if input tensor is on cuda')+ self.cuda_config = FlashAttentionConfig(False, True, True)+ else:+ print_once('GPU Compute Capability equal or above 8.0, using flash attention if input tensor is on cuda')+ self.cuda_config = FlashAttentionConfig(True, False, False)+ else:+ print_once('GPU Compute Capability below 8.0, using math or mem efficient attention if input tensor is on cuda')+ self.cuda_config = FlashAttentionConfig(False, True, True)++ def flash_attn(self, q, k, v):+ _, heads, q_len, _, k_len, is_cuda, device = *q.shape, k.shape[-2], q.is_cuda, q.device++ if exists(self.scale):+ default_scale = q.shape[-1] ** -0.5+ q = q * (self.scale / default_scale)++ # Check if there is a compatible device for flash attention++ config = self.cuda_config if is_cuda else self.cpu_config++ # pytorch 2.0 flash attn: q, k, v, mask, dropout, softmax_scale++ with torch.backends.cuda.sdp_kernel(**config._asdict()):+ out = F.scaled_dot_product_attention(+ q, k, v,+ dropout_p = self.dropout if self.training else 0.+ )++ return out++ def forward(self, q, k, v):+ """+ einstein notation+ b - batch+ h - heads+ n, i, j - sequence length (base sequence length, source, target)+ d - feature dimension+ """++ q_len, k_len, device = q.shape[-2], k.shape[-2], q.device++ scale = default(self.scale, q.shape[-1] ** -0.5)++ if self.flash:+ return self.flash_attn(q, k, v)++ # similarity++ sim = einsum(f"b h i d, b h j d -> b h i j", q, k) * scale++ # attention++ attn = sim.softmax(dim=-1)+ attn = self.attn_dropout(attn)++ # aggregate values++ out = einsum(f"b h i j, b h j d -> b h i d", attn, v)++ return outdiff --git a/python/vendor/models/bs_roformer/mel_band_roformer.py b/python/vendor/models/bs_roformer/mel_band_roformer.pynew file mode 100644index 0000000..4a3227e--- /dev/null+++ b/python/vendor/models/bs_roformer/mel_band_roformer.py@@ -0,0 +1,793 @@+from functools import partial+import os++import numpy as np++import torch+from torch import nn, einsum, tensor, Tensor+from torch.nn import Module, ModuleList+import torch.nn.functional as F++from models.bs_roformer.attend import Attend++from torch.utils.checkpoint import checkpoint++from beartype.typing import Tuple, Optional, List, Callable+from beartype import beartype++from rotary_embedding_torch import RotaryEmbedding++from einops import rearrange, pack, unpack, reduce, repeat+from einops.layers.torch import Rearrange++try:+ from PoPE_pytorch import PoPE, flash_attn_with_pope+ _HAS_POPE = True+except Exception:+ PoPE = None+ flash_attn_with_pope = None+ _HAS_POPE = False++# helper functions++def exists(val):+ return val is not None+++def default(v, d):+ return v if exists(v) else d+++def pack_one(t, pattern):+ return pack([t], pattern)+++def unpack_one(t, ps, pattern):+ return unpack(t, ps, pattern)[0]+++def pad_at_dim(t, pad, dim=-1, value=0.):+ dims_from_right = (- dim - 1) if dim < 0 else (t.ndim - dim - 1)+ zeros = ((0, 0) * dims_from_right)+ return F.pad(t, (*zeros, *pad), value=value)+++def l2norm(t):+ return F.normalize(t, dim=-1, p=2)+++# norm++class RMSNorm(Module):+ def __init__(self, dim):+ super().__init__()+ self.scale = dim ** 0.5+ self.gamma = nn.Parameter(torch.ones(dim))++ def forward(self, x):+ return F.normalize(x, dim=-1) * self.scale * self.gamma+++# attention++class FeedForward(Module):+ def __init__(+ self,+ dim,+ mult=4,+ dropout=0.+ ):+ super().__init__()+ dim_inner = int(dim * mult)+ self.net = nn.Sequential(+ RMSNorm(dim),+ nn.Linear(dim, dim_inner),+ nn.GELU(),+ nn.Dropout(dropout),+ nn.Linear(dim_inner, dim),+ nn.Dropout(dropout)+ )++ def forward(self, x):+ return self.net(x)+++class Attention(Module):+ def __init__(+ self,+ dim,+ heads=8,+ dim_head=64,+ dropout=0.,+ rotary_embed=None,+ flash=True,+ pope_embed=None,+ ):+ super().__init__()+ self.heads = heads+ self.scale = dim_head ** -0.5+ dim_inner = heads * dim_head++ self.rotary_embed = rotary_embed+ self.pope_embed = pope_embed+ assert not (self.rotary_embed is not None and self.pope_embed is not None), \+ "cannot have both rotary and pope embeddings"++ self.attend = Attend(flash=flash, dropout=dropout)++ self.norm = RMSNorm(dim)+ self.to_qkv = nn.Linear(dim, dim_inner * 3, bias=False)++ self.to_gates = nn.Linear(dim, heads)++ self.to_out = nn.Sequential(+ nn.Linear(dim_inner, dim, bias=False),+ nn.Dropout(dropout)+ )++ def forward(self, x):+ x = self.norm(x)++ q, k, v = rearrange(self.to_qkv(x), 'b n (qkv h d) -> qkv b h n d', qkv=3, h=self.heads)++ if exists(self.pope_embed):+ assert _HAS_POPE, "PoPE requested but PoPE_pytorch is not installed"+ out = flash_attn_with_pope(+ q, k, v,+ pos_emb=self.pope_embed(q.shape[-2]),+ softmax_scale=self.scale+ )+ elif exists(self.rotary_embed):+ q = self.rotary_embed.rotate_queries_or_keys(q)+ k = self.rotary_embed.rotate_queries_or_keys(k)+ out = self.attend(q, k, v)+ else:+ out = self.attend(q, k, v)++ gates = self.to_gates(x)+ out = out * rearrange(gates, 'b n h -> b h n 1').sigmoid()++ out = rearrange(out, 'b h n d -> b n (h d)')+ return self.to_out(out)+++class LinearAttention(Module):+ """+ this flavor of linear attention proposed in https://arxiv.org/abs/2106.09681 by El-Nouby et al.+ """++ @beartype+ def __init__(+ self,+ *,+ dim,+ dim_head=32,+ heads=8,+ scale=8,+ flash=False,+ dropout=0.+ ):+ super().__init__()+ dim_inner = dim_head * heads+ self.norm = RMSNorm(dim)++ self.to_qkv = nn.Sequential(+ nn.Linear(dim, dim_inner * 3, bias=False),+ Rearrange('b n (qkv h d) -> qkv b h d n', qkv=3, h=heads)+ )++ self.temperature = nn.Parameter(torch.ones(heads, 1, 1))++ self.attend = Attend(+ scale=scale,+ dropout=dropout,+ flash=flash+ )++ self.to_out = nn.Sequential(+ Rearrange('b h d n -> b n (h d)'),+ nn.Linear(dim_inner, dim, bias=False)+ )++ def forward(+ self,+ x+ ):+ x = self.norm(x)++ q, k, v = self.to_qkv(x)++ q, k = map(l2norm, (q, k))+ q = q * self.temperature.exp()++ out = self.attend(q, k, v)++ return self.to_out(out)+++class Transformer(Module):+ def __init__(+ self,+ *,+ dim,+ depth,+ dim_head=64,+ heads=8,+ attn_dropout=0.,+ ff_dropout=0.,+ ff_mult=4,+ norm_output=True,+ rotary_embed=None,+ pope_embed=None,+ flash_attn=True,+ linear_attn=False,+ ):+ super().__init__()+ self.layers = ModuleList([])++ for _ in range(depth):+ if linear_attn:+ attn = LinearAttention(+ dim=dim,+ dim_head=dim_head,+ heads=heads,+ dropout=attn_dropout,+ flash=flash_attn+ )+ else:+ attn = Attention(+ dim=dim,+ dim_head=dim_head,+ heads=heads,+ dropout=attn_dropout,+ rotary_embed=rotary_embed,+ pope_embed=pope_embed,+ flash=flash_attn+ )++ self.layers.append(ModuleList([+ attn,+ FeedForward(dim=dim, mult=ff_mult, dropout=ff_dropout)+ ]))++ self.norm = RMSNorm(dim) if norm_output else nn.Identity()++ def forward(self, x):++ for attn, ff in self.layers:+ x = attn(x) + x+ x = ff(x) + x++ return self.norm(x)+++# bandsplit module++class BandSplit(Module):+ @beartype+ def __init__(+ self,+ dim,+ dim_inputs: Tuple[int, ...]+ ):+ super().__init__()+ self.dim_inputs = dim_inputs+ self.to_features = ModuleList([])++ for dim_in in dim_inputs:+ net = nn.Sequential(+ RMSNorm(dim_in),+ nn.Linear(dim_in, dim)+ )++ self.to_features.append(net)++ def forward(self, x):+ x = x.split(self.dim_inputs, dim=-1)++ outs = []+ for split_input, to_feature in zip(x, self.to_features):+ split_output = to_feature(split_input)+ outs.append(split_output)++ return torch.stack(outs, dim=-2)+++def MLP(+ dim_in,+ dim_out,+ dim_hidden=None,+ depth=1,+ activation=nn.Tanh+):+ dim_hidden = default(dim_hidden, dim_in)++ net = []+ dims = (dim_in, *((dim_hidden,) * depth), dim_out)++ for ind, (layer_dim_in, layer_dim_out) in enumerate(zip(dims[:-1], dims[1:])):+ is_last = ind == (len(dims) - 2)++ net.append(nn.Linear(layer_dim_in, layer_dim_out))++ if is_last:+ continue++ net.append(activation())++ return nn.Sequential(*net)+++class MaskEstimator(Module):+ @beartype+ def __init__(+ self,+ dim,+ dim_inputs: Tuple[int, ...],+ depth,+ mlp_expansion_factor=4+ ):+ super().__init__()+ self.dim_inputs = dim_inputs+ self.to_freqs = ModuleList([])+ dim_hidden = dim * mlp_expansion_factor++ for dim_in in dim_inputs:+ net = []++ mlp = nn.Sequential(+ MLP(dim, dim_in * 2, dim_hidden=dim_hidden, depth=depth),+ nn.GLU(dim=-1)+ )++ self.to_freqs.append(mlp)++ def forward(self, x):+ x = x.unbind(dim=-2)++ outs = []++ for band_features, mlp in zip(x, self.to_freqs):+ freq_out = mlp(band_features)+ outs.append(freq_out)++ return torch.cat(outs, dim=-1)+++# main class++class MelBandRoformer(Module):++ @beartype+ def __init__(+ self,+ dim,+ *,+ depth,+ stereo=False,+ num_stems=1,+ time_transformer_depth=2,+ freq_transformer_depth=2,+ linear_transformer_depth=0,+ num_bands=60,+ dim_head=64,+ heads=8,+ attn_dropout=0.1,+ ff_dropout=0.1,+ flash_attn=True,+ dim_freqs_in=1025,+ sample_rate=44100, # needed for mel filter bank from librosa+ stft_n_fft=2048,+ stft_hop_length=512,+ # 10ms at 44100Hz, from sections 4.1, 4.4 in the paper - @faroit recommends // 2 or // 4 for better reconstruction+ stft_win_length=2048,+ stft_normalized=False,+ stft_window_fn: Optional[Callable] = None,+ zero_dc = True,+ mask_estimator_depth=1,+ multi_stft_resolution_loss_weight=1.,+ multi_stft_resolutions_window_sizes: Tuple[int, ...] = (4096, 2048, 1024, 512, 256),+ multi_stft_hop_size=147,+ multi_stft_normalized=False,+ multi_stft_window_fn: Callable = torch.hann_window,+ match_input_audio_length=False, # if True, pad output tensor to match length of input tensor+ mlp_expansion_factor=4,+ use_torch_checkpoint=False,+ skip_connection=False,+ use_pope: bool = False,+ ):+ super().__init__()++ self.stereo = stereo+ self.audio_channels = 2 if stereo else 1+ self.num_stems = num_stems+ self.use_torch_checkpoint = use_torch_checkpoint+ self.skip_connection = skip_connection++ self.layers = ModuleList([])++ transformer_kwargs = dict(+ dim=dim,+ heads=heads,+ dim_head=dim_head,+ attn_dropout=attn_dropout,+ ff_dropout=ff_dropout,+ flash_attn=flash_attn,+ )++ if use_pope:+ assert _HAS_POPE, "PoPE requested but PoPE_pytorch is not installed"+ time_pope_embed = PoPE(dim=dim_head, heads=heads)+ freq_pope_embed = PoPE(dim=dim_head, heads=heads)+ time_rotary_embed = None+ freq_rotary_embed = None+ else:+ time_rotary_embed = RotaryEmbedding(dim=dim_head)+ freq_rotary_embed = RotaryEmbedding(dim=dim_head)+ time_pope_embed = freq_pope_embed = None++ for _ in range(depth):+ tran_modules = []+ if linear_transformer_depth > 0:+ tran_modules.append(Transformer(depth=linear_transformer_depth, linear_attn=True, **transformer_kwargs))+ tran_modules.append(+ Transformer(+ depth=time_transformer_depth,+ rotary_embed=time_rotary_embed,+ pope_embed=time_pope_embed,+ **transformer_kwargs+ )+ )+ tran_modules.append(+ Transformer(+ depth=freq_transformer_depth,+ rotary_embed=freq_rotary_embed,+ pope_embed=freq_pope_embed,+ **transformer_kwargs+ )+ )+ self.layers.append(nn.ModuleList(tran_modules))++ self.stft_window_fn = partial(default(stft_window_fn, torch.hann_window), stft_win_length)++ self.stft_kwargs = dict(+ n_fft=stft_n_fft,+ hop_length=stft_hop_length,+ win_length=stft_win_length,+ normalized=stft_normalized+ )++ freqs = torch.stft(torch.randn(1, 4096), **self.stft_kwargs, window=torch.ones(stft_n_fft), return_complex=True).shape[1]++ # create mel filter bank+ # precomputed with librosa.filters.mel(sr, n_fft, n_mels) and shipped+ # alongside so librosa is not a runtime dependency++ bank_path = os.path.join(+ os.path.dirname(__file__), '..', '..', f'mel_bank_{sample_rate}_{stft_n_fft}_{num_bands}.npy'+ )+ mel_filter_bank_numpy = np.load(bank_path)++ mel_filter_bank = torch.from_numpy(mel_filter_bank_numpy)++ # for some reason, it doesn't include the first freq? just force a value for now++ mel_filter_bank[0][0] = 1.++ # In some systems/envs we get 0.0 instead of ~1.9e-18 in the last position,+ # so let's force a positive value++ mel_filter_bank[-1, -1] = 1.++ # binary as in paper (then estimated masks are averaged for overlapping regions)++ freqs_per_band = mel_filter_bank > 0+ assert freqs_per_band.any(dim=0).all(), 'all frequencies need to be covered by all bands for now'++ repeated_freq_indices = repeat(torch.arange(freqs), 'f -> b f', b=num_bands)+ freq_indices = repeated_freq_indices[freqs_per_band]++ if stereo:+ freq_indices = repeat(freq_indices, 'f -> f s', s=2)+ freq_indices = freq_indices * 2 + torch.arange(2)+ freq_indices = rearrange(freq_indices, 'f s -> (f s)')++ self.register_buffer('freq_indices', freq_indices, persistent=False)+ self.register_buffer('freqs_per_band', freqs_per_band, persistent=False)++ num_freqs_per_band = reduce(freqs_per_band, 'b f -> b', 'sum')+ num_bands_per_freq = reduce(freqs_per_band, 'b f -> f', 'sum')++ self.register_buffer('num_freqs_per_band', num_freqs_per_band, persistent=False)+ self.register_buffer('num_bands_per_freq', num_bands_per_freq, persistent=False)++ # band split and mask estimator++ freqs_per_bands_with_complex = tuple(2 * f * self.audio_channels for f in num_freqs_per_band.tolist())++ self.band_split = BandSplit(+ dim=dim,+ dim_inputs=freqs_per_bands_with_complex+ )++ self.mask_estimators = nn.ModuleList([])++ for _ in range(num_stems):+ mask_estimator = MaskEstimator(+ dim=dim,+ dim_inputs=freqs_per_bands_with_complex,+ depth=mask_estimator_depth,+ mlp_expansion_factor=mlp_expansion_factor,+ )++ self.mask_estimators.append(mask_estimator)++ # whether to zero out dc++ self.zero_dc = zero_dc++ # for the multi-resolution stft loss++ self.multi_stft_resolution_loss_weight = multi_stft_resolution_loss_weight+ self.multi_stft_resolutions_window_sizes = multi_stft_resolutions_window_sizes+ self.multi_stft_n_fft = stft_n_fft+ self.multi_stft_window_fn = multi_stft_window_fn++ self.multi_stft_kwargs = dict(+ hop_length=multi_stft_hop_size,+ normalized=multi_stft_normalized+ )++ self.match_input_audio_length = match_input_audio_length++ def forward(+ self,+ raw_audio,+ target=None,+ active_stem_ids=None,+ return_loss_breakdown=False+ ):+ """+ einops++ b - batch+ f - freq+ t - time+ s - audio channel (1 for mono, 2 for stereo)+ n - number of 'stems'+ c - complex (2)+ d - feature dimension+ """++ device = raw_audio.device++ if raw_audio.ndim == 2:+ raw_audio = rearrange(raw_audio, 'b t -> b 1 t')++ batch, channels, raw_audio_length = raw_audio.shape++ istft_length = raw_audio_length if self.match_input_audio_length else None++ assert (not self.stereo and channels == 1) or (+ self.stereo and channels == 2), 'stereo needs to be set to True if passing in audio signal that is stereo (channel dimension of 2). also need to be False if mono (channel dimension of 1)'++ # to stft++ raw_audio, batch_audio_channel_packed_shape = pack_one(raw_audio, '* t')++ # fft ops run in fp32 (half precision fft is not supported on MPS);+ # the attention stack may run in fp16 (see band_split note below)+ model_dtype = next(self.layers[0].parameters()).dtype++ stft_window = self.stft_window_fn(device=device)++ stft_repr = torch.stft(raw_audio.float(), **self.stft_kwargs, window=stft_window, return_complex=True)+ stft_repr = torch.view_as_real(stft_repr)++ stft_repr = unpack_one(stft_repr, batch_audio_channel_packed_shape, '* f t c')++ # merge stereo / mono into the frequency, with frequency leading dimension, for band splitting+ stft_repr = rearrange(stft_repr,'b s f t c -> b (f s) t c')++ # index out all frequencies for all frequency ranges across bands ascending in one go++ batch_arange = torch.arange(batch, device=device)[..., None]++ # account for stereo++ x = stft_repr[batch_arange, self.freq_indices]++ # fold the complex (real and imag) into the frequencies dimension++ x = rearrange(x, 'b f t c -> b t (f c)')++ if self.use_torch_checkpoint:+ x = checkpoint(self.band_split, x, use_reentrant=False)+ else:+ x = self.band_split(x)++ # band_split and the stft run in fp32 (fp16 accumulation overflows on+ # loud material); the attention stack runs in the model dtype+ x = x.to(model_dtype)++ # axial / hierarchical attention++ store = [None] * len(self.layers)+ for i, transformer_block in enumerate(self.layers):++ if len(transformer_block) == 3:+ linear_transformer, time_transformer, freq_transformer = transformer_block++ x, ft_ps = pack([x], 'b * d')+ if self.use_torch_checkpoint:+ x = checkpoint(linear_transformer, x, use_reentrant=False)+ else:+ x = linear_transformer(x)+ x, = unpack(x, ft_ps, 'b * d')+ else:+ time_transformer, freq_transformer = transformer_block++ if self.skip_connection:+ # Sum all previous+ for j in range(i):+ x = x + store[j]++ x = rearrange(x, 'b t f d -> b f t d')+ x, ps = pack([x], '* t d')++ if self.use_torch_checkpoint:+ x = checkpoint(time_transformer, x, use_reentrant=False)+ else:+ x = time_transformer(x)++ x, = unpack(x, ps, '* t d')+ x = rearrange(x, 'b f t d -> b t f d')+ x, ps = pack([x], '* f d')++ if self.use_torch_checkpoint:+ x = checkpoint(freq_transformer, x, use_reentrant=False)+ else:+ x = freq_transformer(x)++ x, = unpack(x, ps, '* f d')++ if self.skip_connection:+ store[i] = x++ if active_stem_ids is None:+ heads = self.mask_estimators+ stem_ids = list(range(len(self.mask_estimators)))+ else:+ heads = [self.mask_estimators[i] for i in active_stem_ids]+ stem_ids = active_stem_ids++ num_stems = len(heads)++ if self.use_torch_checkpoint:+ masks = torch.stack([checkpoint(fn, x, use_reentrant=False) for fn in heads], dim=1)+ else:+ masks = torch.stack([fn(x) for fn in heads], dim=1)+ masks = rearrange(masks, 'b n t (f c) -> b n f t c', c=2)++ # modulate frequency representation++ stft_repr = rearrange(stft_repr, 'b f t c -> b 1 f t c')++ # complex math is done in real/imag components because MPS does not+ # support scatter_add_ (or reliable complex mul) on complex tensors;+ # results are identical to the complex-tensor path on CUDA/CPU++ # need to average the estimated mask for the overlapped frequencies++ scatter_indices = repeat(self.freq_indices, 'f -> b n f t 2', b=batch, n=num_stems, t=stft_repr.shape[-2])++ stft_repr_expanded_stems = repeat(stft_repr, 'b 1 ... -> b n ...', n=num_stems)+ masks_summed = torch.zeros_like(stft_repr_expanded_stems).scatter_add_(2, scatter_indices, masks.float())++ denom = repeat(self.num_bands_per_freq, 'f -> (f r) 1', r=channels)++ # MPS materializes a huge intermediate buffer when broadcasting a+ # division against 5d (F, 1, 1, 1), so divide in 3d: (b*n, F, t*2) / (F, 1)+ summed_shape = masks_summed.shape+ masks_averaged = (+ masks_summed.reshape(summed_shape[0] * summed_shape[1], summed_shape[2], -1)+ / denom.clamp(min=1e-8)+ ).reshape(summed_shape)++ # modulate stft repr with estimated mask: (a + bi) * (c + di)++ ar, ai = stft_repr_expanded_stems[..., 0], stft_repr_expanded_stems[..., 1]+ br, bi = masks_averaged[..., 0], masks_averaged[..., 1]+ masked = torch.stack([ar * br - ai * bi, ar * bi + ai * br], dim=-1).float()++ # istft++ stft_repr = rearrange(masked, 'b n (f s) t c -> (b n s) f t c', s=self.audio_channels)++ if self.zero_dc:+ # whether to dc filter+ stft_repr[:, 0] = 0.++ stft_repr = torch.view_as_complex(stft_repr.contiguous())++ # manual istft: torch.istft relies on aten::unfold_backward, which is+ # not implemented on MPS. overlap-add is done with ceil(win/hop)+ # slice-adds instead, which is mathematically identical+ n_fft = self.stft_kwargs['n_fft']+ hop = self.stft_kwargs['hop_length']+ win_len = self.stft_kwargs['win_length']+ frames = torch.fft.irfft(stft_repr, n=n_fft, dim=-2) # (B, win, T)+ frames = frames * stft_window.view(1, -1, 1)+ batch_istft, _, num_frames = frames.shape+ out_len = num_frames * hop + win_len+ out = torch.zeros((batch_istft, out_len), device=frames.device, dtype=frames.dtype)+ wsum = torch.zeros(out_len, device=frames.device, dtype=frames.dtype)+ win_sq = stft_window * stft_window+ for offset in range(0, win_len, hop):+ hb = min(hop, win_len - offset)+ seg = frames[:, offset:offset + hb, :].transpose(1, 2) # (B, T, hb)+ if hb < hop:+ seg = torch.nn.functional.pad(seg, (0, hop - hb))+ out[:, offset:offset + num_frames * hop] += seg.reshape(batch_istft, num_frames * hop)+ wseg = torch.nn.functional.pad(win_sq[offset:offset + hb], (0, hop - hb))+ wsum[offset:offset + num_frames * hop] += wseg.repeat(num_frames)+ out = out / wsum.clamp(min=1e-11)+ half = n_fft // 2+ if istft_length is not None:+ out = out[:, half:half + istft_length]+ else:+ out = out[:, half:-half]+ recon_audio = out++ recon_audio = rearrange(recon_audio, '(b n s) t -> b n s t', b=batch, s=self.audio_channels, n=num_stems)++ if num_stems == 1:+ recon_audio = rearrange(recon_audio, 'b 1 s t -> b s t')++ # if a target is passed in, calculate loss for learning++ if not exists(target):+ return recon_audio++ if self.num_stems > 1:+ assert target.ndim == 4 and target.shape[1] == self.num_stems++ if target.ndim == 2:+ target = rearrange(target, '... t -> ... 1 t')++ target = target[..., :recon_audio.shape[-1]] # protect against lost length on istft++ target_sel = target[:, stem_ids]++ loss = F.l1_loss(recon_audio, target_sel)++ multi_stft_resolution_loss = 0.++ for window_size in self.multi_stft_resolutions_window_sizes:+ res_stft_kwargs = dict(+ n_fft=max(window_size, self.multi_stft_n_fft), # not sure what n_fft is across multi resolution stft+ win_length=window_size,+ return_complex=True,+ window=self.multi_stft_window_fn(window_size, device=device),+ **self.multi_stft_kwargs,+ )++ recon_Y = torch.stft(+ rearrange(recon_audio, 'b n s t -> (b n s) t'),+ **res_stft_kwargs+ )+ target_Y = torch.stft(+ rearrange(target_sel, 'b n s t -> (b n s) t'),+ **res_stft_kwargs+ )++ multi_stft_resolution_loss = multi_stft_resolution_loss + F.l1_loss(recon_Y, target_Y)++ weighted_multi_resolution_loss = multi_stft_resolution_loss * self.multi_stft_resolution_loss_weight++ total_loss = loss + weighted_multi_resolution_loss++ if not return_loss_breakdown:+ return total_loss++ return total_loss, (loss, multi_stft_resolution_loss)