feat(stems): implement stage 2 Demucs stem separation with low-VRAM chunking

This commit is contained in:
2026-11-02 10:22:25 +01:00
parent 191133b006
commit 6a01296af6
4 changed files with 869 additions and 6 deletions

View File

@ -1,30 +1,144 @@
"""Stage 2: Stem separation using Demucs."""
"""Stage 2: Stem separation using Demucs with chunking for low VRAM."""
from pathlib import Path
from typing import Any
import julius
import soundfile as sf
import torch
from songsplit.config import config
from songsplit.pipeline.runner import PipelineContext, Stage
class StemsStage(Stage):
"""Stage 2 separates mixed audio into isolated stems (vocals, instrumental, drums, bass, etc.)."""
name = "s2_stems"
version = "1.0.0"
model_name = "htdemucs_ft"
model_version = "1.0.0"
dependencies = ["s1_extract"]
def __init__(self, model_name: str = "htdemucs_ft"):
self.model_name = model_name
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "extracted.wav"]
return [ctx.cache_dir / "extracted.wav"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [
base_stems = [
ctx.stems_dir / "vocals.wav",
ctx.stems_dir / "instrumental.wav",
ctx.stems_dir / "drums.wav",
ctx.stems_dir / "bass.wav",
ctx.stems_dir / "other.wav",
]
if ctx.stems == 6:
base_stems.extend(
[
ctx.stems_dir / "guitar.wav",
ctx.stems_dir / "piano.wav",
]
)
return base_stems
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"stems": ctx.stems, "quality": ctx.quality}
return {
"stems": ctx.stems,
"quality": ctx.quality,
"segment": 7 if ctx.quality == "fast" else 10,
"shifts": 0 if ctx.quality == "fast" else 1,
}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M1
raise NotImplementedError("Stage s2_stems will be implemented in M1.")
import demucs.pretrained
from demucs.apply import apply_model
input_wav = self.get_inputs(ctx)[0]
if not input_wav.exists():
raise FileNotFoundError(f"Input WAV not found: {input_wav}")
# Target model selection based on stems count and quality
if ctx.stems == 6:
target_model = "htdemucs_6s"
else:
target_model = "htdemucs_ft" if ctx.quality == "best" else "htdemucs"
self.model_name = target_model
# Determine compute device with fallback to cpu
device_str = config.get_device(self.name)
if device_str.startswith("cuda") and not torch.cuda.is_available():
device_str = "cpu"
device = torch.device(device_str)
# Configure models directory
models_dir = config.get_models_dir()
torch.hub.set_dir(str(models_dir))
model = demucs.pretrained.get_model(target_model)
model.to(device)
model.eval()
# Load audio using soundfile
audio_data, sr = sf.read(str(input_wav), dtype="float32")
# audio_data shape: [samples] (mono) or [samples, channels] (stereo)
if audio_data.ndim == 1:
wav = torch.from_numpy(audio_data).unsqueeze(0).repeat(2, 1)
else:
wav = torch.from_numpy(audio_data.T)
if wav.shape[0] == 1:
wav = wav.repeat(2, 1)
elif wav.shape[0] > 2:
wav = wav[:2, :]
if sr != model.samplerate:
wav = julius.resample_frac(wav, sr, model.samplerate)
# Normalize audio for stable separation
ref = wav.mean(0)
wav = (wav - ref.mean()) / (ref.std() + 1e-8)
params = self.get_params(ctx)
segment = params["segment"]
shifts = params["shifts"]
# Add batch dimension: [1, 2, samples]
wav = wav.unsqueeze(0).to(device)
# Execute separation with chunking
with torch.no_grad():
sources = apply_model(
model,
wav,
shifts=shifts,
split=True,
overlap=0.25,
segment=segment,
device=device,
progress=False,
)
# Rescale back to original loudness
sources = sources * (ref.std() + 1e-8) + ref.mean()
# [num_sources, channels, samples]
sources = sources.squeeze(0).cpu()
ctx.stems_dir.mkdir(parents=True, exist_ok=True)
stem_dict: dict[str, torch.Tensor] = {}
for idx, src_name in enumerate(model.sources):
stem_dict[src_name] = sources[idx]
# Save each stem WAV file using soundfile (16-bit PCM)
for src_name, tensor in stem_dict.items():
out_path = ctx.stems_dir / f"{src_name}.wav"
# tensor is [channels, samples] -> transpose to [samples, channels]
data_out = tensor.clamp(-1.0, 1.0).numpy().T
sf.write(str(out_path), data_out, model.samplerate, subtype="PCM_16")
# Create instrumental stem: sum of all non-vocals stems
non_vocals = [tensor for name, tensor in stem_dict.items() if name != "vocals"]
if non_vocals:
instrumental = torch.stack(non_vocals).sum(dim=0)
data_inst = instrumental.clamp(-1.0, 1.0).numpy().T
sf.write(str(ctx.stems_dir / "instrumental.wav"), data_inst, model.samplerate, subtype="PCM_16")