Spaces:
Running on Zero
Running on Zero
Download stemdeck/pipeline/mega.py from AnjaneyaTurai/stemdeck-gpu: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/AnjaneyaTurai/stemdeck-gpu/resolve/main/stemdeck/pipeline/mega.py
- Command line
-
hf download hf://spaces/AnjaneyaTurai/stemdeck-gpu/stemdeck/pipeline/mega.py
-
curl -L -o mega.py https://huggingface.co/spaces/AnjaneyaTurai/stemdeck-gpu/resolve/main/stemdeck/pipeline/mega.py
11.9 kB
| """MVSep "Mega" 53-stem BS-RoFormer (ZFTurbo/MVSep, Music-Source-Separation-Training release v1.0.21), run as a | |
| small subset model. | |
| The released checkpoint is one shared BS-RoFormer backbone plus one mask-estimator head per instrument (53 heads, | |
| 1.37 GB; its authors suggest 16 GB of VRAM for all of them at once). Every head reads the same backbone output, so | |
| a model with only the heads we want gives exactly the same result for those instruments while needing a fraction | |
| of the memory: the backbone runs once and each chosen instrument costs one small head. The subset is built once | |
| from the big checkpoint and cached next to it. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import logging | |
| import os | |
| import urllib.error | |
| import urllib.request | |
| from collections.abc import Callable, Sequence | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import yaml | |
| log = logging.getLogger(__name__) | |
| CHECKPOINT = "mvsep_mega_model_bs_roformer_53_stems_v1.ckpt" | |
| CONFIG = "mvsep_mega_model_bs_roformer_53_stems.yaml" | |
| RELEASE_URL = "https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.21" | |
| HEAD_PREFIX = "mask_estimators." | |
| DEFAULT_CHUNK_SEC = 8.0 | |
| DEFAULT_OVERLAP = 2 | |
| FADE_FRACTION = 0.1 | |
| SAMPLE_RATE = 44100 | |
| STFT_HOP = 512 # stft_hop_length in the model config | |
| STFT_SIZE = 2048 | |
| CONSISTENCY_CHUNK_SEC = 20.0 | |
| DOWNLOAD_BLOCK = 1 << 20 | |
| USER_AGENT = "StemDeck (local stem splitter)" | |
| class _TupleLoader(yaml.SafeLoader): | |
| """Safe YAML loader that also understands the `!!python/tuple` tags MSST configs use.""" | |
| _TupleLoader.add_constructor("tag:yaml.org,2002:python/tuple", | |
| lambda loader, node: tuple(loader.construct_sequence(node))) | |
| class MegaConfig: | |
| model: dict[str, Any] | |
| instruments: tuple[str, ...] | |
| def read_config(path: Path) -> MegaConfig: | |
| with open(path, encoding="utf-8") as fh: | |
| raw = yaml.load(fh, Loader=_TupleLoader) # noqa: S506 - SafeLoader subclass, only adds tuples | |
| return MegaConfig(model=dict(raw["model"]), instruments=tuple(raw["training"]["instruments"])) | |
| def subset_state_dict(full: dict[str, Any], all_instruments: Sequence[str], | |
| wanted: Sequence[str]) -> dict[str, Any]: | |
| """Backbone weights plus the heads of `wanted`, renumbered 0..n-1 in the order given.""" | |
| missing = [name for name in wanted if name not in all_instruments] | |
| if missing: | |
| raise ValueError(f"unknown instruments for this model: {missing}") | |
| index_of = {name: i for i, name in enumerate(all_instruments)} | |
| out: dict[str, Any] = {} | |
| for key, value in full.items(): | |
| if not key.startswith(HEAD_PREFIX): | |
| out[key] = value | |
| for new_index, name in enumerate(wanted): | |
| old = f"{HEAD_PREFIX}{index_of[name]}." | |
| for key, value in full.items(): | |
| if key.startswith(old): | |
| out[f"{HEAD_PREFIX}{new_index}.{key[len(old):]}"] = value | |
| return out | |
| def needs_download(model_dir: Path, wanted: Sequence[str]) -> bool: | |
| """True when the config, or both the cached subset and the full checkpoint, are missing.""" | |
| if not (model_dir / CONFIG).exists(): | |
| return True | |
| return not _subset_cache_path(model_dir, wanted).exists() and not (model_dir / CHECKPOINT).exists() | |
| def ensure_files(model_dir: Path, wanted: Sequence[str], on_progress: Callable[[float], None]) -> None: | |
| """Downloads the config and, unless the subset is cached, the 1.37 GB checkpoint (resumable).""" | |
| model_dir.mkdir(parents=True, exist_ok=True) | |
| if not (model_dir / CONFIG).exists(): | |
| _download(f"{RELEASE_URL}/{CONFIG}", model_dir / CONFIG, None) | |
| if not _subset_cache_path(model_dir, wanted).exists() and not (model_dir / CHECKPOINT).exists(): | |
| _download(f"{RELEASE_URL}/{CHECKPOINT}", model_dir / CHECKPOINT, on_progress) | |
| def _download(url: str, target: Path, on_progress: Callable[[float], None] | None) -> None: | |
| """Resumable download into `<target>.partial`; only a complete file (Content-Length checked) is promoted.""" | |
| partial = target.with_name(target.name + ".partial") | |
| done = partial.stat().st_size if partial.exists() else 0 | |
| headers = {"User-Agent": USER_AGENT, **({"Range": f"bytes={done}-"} if done else {})} | |
| try: | |
| response = urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=60) | |
| except urllib.error.HTTPError as exc: | |
| if exc.code == 416 and done > 0: # the partial already holds every byte (died before the rename) | |
| os.replace(partial, target) | |
| return | |
| raise | |
| with response: | |
| if done and response.status != 206: # server ignored the range: start over | |
| done = 0 | |
| length = response.headers.get("Content-Length") | |
| total = done + int(length) if length else None | |
| with open(partial, "ab" if done else "wb") as out: | |
| while block := response.read(DOWNLOAD_BLOCK): | |
| out.write(block) | |
| done += len(block) | |
| if on_progress is not None and total: | |
| on_progress(done / total) | |
| if total is not None and done != total: | |
| raise OSError(f"download of {target.name} stopped early ({done} of {total} bytes); retry to resume") | |
| os.replace(partial, target) | |
| log.info("downloaded %s (%.1f MB)", target.name, done / 1e6) | |
| def _subset_cache_path(model_dir: Path, wanted: Sequence[str]) -> Path: | |
| digest = hashlib.sha1(",".join(wanted).encode()).hexdigest()[:10] | |
| return model_dir / f"stemdeck_subset_{digest}.pt" | |
| def load_model(model_dir: Path, wanted: Sequence[str], device: str) -> Any: | |
| """A BS-RoFormer with only the `wanted` heads, on `device`, in eval mode (fp16 on CUDA).""" | |
| import torch | |
| from audio_separator.separator.uvr_lib_v5.roformer.bs_roformer import BSRoformer | |
| config = read_config(model_dir / CONFIG) | |
| cache = _subset_cache_path(model_dir, wanted) | |
| state = None | |
| if cache.exists(): | |
| try: | |
| state = torch.load(cache, map_location="cpu", weights_only=True) | |
| except Exception: # noqa: BLE001 - a damaged cache is rebuilt from the checkpoint below | |
| log.warning("subset cache %s is unreadable; rebuilding it", cache.name, exc_info=True) | |
| cache.unlink(missing_ok=True) | |
| if state is None: | |
| checkpoint = model_dir / CHECKPOINT | |
| if not checkpoint.exists(): | |
| raise FileNotFoundError(f"{checkpoint} is missing; download it from {RELEASE_URL}") | |
| full = torch.load(checkpoint, map_location="cpu", weights_only=True) | |
| full = full.get("state_dict", full) if isinstance(full, dict) else full | |
| state = subset_state_dict(full, config.instruments, wanted) | |
| del full | |
| tmp = cache.with_suffix(".tmp") | |
| torch.save(state, tmp) | |
| os.replace(tmp, cache) | |
| log.info("built mega subset model %s for %s", cache.name, list(wanted)) | |
| params = {**config.model, "num_stems": len(wanted)} | |
| model = BSRoformer(**params) | |
| model.load_state_dict(state, strict=True) | |
| model.eval() | |
| if device == "cuda": | |
| model = model.half() | |
| return model.to(device) | |
| def _window(size: int) -> np.ndarray: | |
| fade = max(1, int(size * FADE_FRACTION)) | |
| window = np.ones(size, dtype=np.float32) | |
| window[:fade] = np.linspace(0.0, 1.0, fade, dtype=np.float32) | |
| window[-fade:] = np.linspace(1.0, 0.0, fade, dtype=np.float32) | |
| return window | |
| def separate(model: Any, audio: np.ndarray, device: str, num_stems: int, | |
| on_progress: Callable[[float], None] | None = None, | |
| chunk_sec: float = DEFAULT_CHUNK_SEC, overlap: int = DEFAULT_OVERLAP) -> np.ndarray: | |
| """Overlap-add inference. `audio` is (n, 2) float32 at 44.1 kHz; returns (num_stems, n, 2) float32.""" | |
| import torch | |
| # A multiple of the STFT hop: the model returns (frames - 1) * hop samples, so other lengths come back short. | |
| chunk = int(chunk_sec * SAMPLE_RATE) // STFT_HOP * STFT_HOP | |
| step = chunk // overlap | |
| n = len(audio) | |
| mix = audio.T.astype(np.float32) # (2, n) | |
| pad = chunk - step | |
| padded = np.pad(mix, ((0, 0), (pad, pad + chunk)), mode="constant") | |
| total = padded.shape[1] | |
| result = np.zeros((num_stems, total, 2), dtype=np.float32) | |
| weight = np.zeros(total, dtype=np.float32) | |
| window = _window(chunk) | |
| starts = list(range(0, n + pad, step)) | |
| dtype = torch.float16 if device == "cuda" else torch.float32 | |
| with torch.inference_mode(): | |
| for i, start in enumerate(starts): | |
| part = torch.from_numpy(padded[:, start:start + chunk]).to(device=device, dtype=dtype)[None] | |
| out = model(part).reshape(num_stems, 2, -1).float().cpu().numpy() | |
| if out.shape[-1] != chunk: # defensive: pad/trim to the chunk length | |
| out = np.pad(out, ((0, 0), (0, 0), (0, max(0, chunk - out.shape[-1]))))[..., :chunk] | |
| result[:, start:start + chunk, :] += out.transpose(0, 2, 1) * window[:, None] | |
| weight[start:start + chunk] += window | |
| if on_progress is not None: | |
| on_progress((i + 1) / len(starts)) | |
| weight[weight == 0] = 1.0 | |
| stems = result[:, pad:pad + n] # a view: no second copy of every stem | |
| stems /= weight[pad:pad + n, None] | |
| return stems | |
| def consistent_with_mixture(stems: np.ndarray, mixture: np.ndarray) -> np.ndarray: | |
| """Scale the stems down wherever, together, they claim more than the mixture holds. | |
| Heads of a multi-instrument model can overlap (an organ-like synth lands in both 'organ' and 'synth'). | |
| Subtracting both from the source would remove that sound twice and leave an inverted copy behind. In the | |
| STFT domain each bin's stem magnitudes are scaled so their sum never exceeds the mixture's magnitude. | |
| Works in chunks (hop-aligned, padded by one FFT size) so memory stays small for long songs. | |
| `stems` is (k, n, 2), `mixture` (n, 2); returns (k, n, 2). | |
| """ | |
| import torch | |
| k, n, channels = stems.shape | |
| if k == 0: | |
| return stems | |
| window = torch.hann_window(STFT_SIZE) | |
| chunk = int(CONSISTENCY_CHUNK_SEC * SAMPLE_RATE) // STFT_HOP * STFT_HOP | |
| pad = STFT_SIZE | |
| out = np.zeros_like(stems) | |
| for start in range(0, n, chunk): | |
| end = min(n, start + chunk) | |
| lo, hi = start - pad, end + pad | |
| seg = np.zeros((k + 1, hi - lo, channels), dtype=np.float32) | |
| src_lo, src_hi = max(0, lo), min(n, hi) | |
| seg[0, src_lo - lo:src_hi - lo] = mixture[src_lo:src_hi] | |
| seg[1:, src_lo - lo:src_hi - lo] = stems[:, src_lo:src_hi] | |
| x = torch.from_numpy(seg).permute(0, 2, 1).reshape(-1, hi - lo) # ((k+1)*channels, t) | |
| spec = torch.stft(x, STFT_SIZE, STFT_HOP, window=window, return_complex=True) | |
| spec = spec.reshape(k + 1, channels, *spec.shape[-2:]) | |
| total = spec[1:].abs().sum(dim=0) | |
| scale = torch.clamp(spec[0].abs() / (total + 1e-8), max=1.0) | |
| fixed = (spec[1:] * scale).reshape(k * channels, *spec.shape[-2:]) | |
| audio = torch.istft(fixed, STFT_SIZE, STFT_HOP, window=window, length=hi - lo) | |
| audio = audio.reshape(k, channels, hi - lo).permute(0, 2, 1).numpy() | |
| out[:, start:end] = audio[:, start - lo:end - lo] | |
| return out | |
| def presence(stem: np.ndarray, source: np.ndarray) -> tuple[float, float]: | |
| """(share of the source's energy, RMS in dBFS) of an extracted stem.""" | |
| energy = float(np.sum(np.square(stem, dtype=np.float64))) | |
| share = energy / (float(np.sum(np.square(source, dtype=np.float64))) + 1e-12) | |
| rms = float(np.sqrt(energy / max(1, stem.size))) | |
| return share, 20 * float(np.log10(rms + 1e-12)) | |