[Model] add soulx-singer support (#3862)
Signed-off-by: Mr.Dong <1042542469@qq.com> Signed-off-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: Mr.Dong <1042542469@qq.com> Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com> Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
50 files changed
+9533
-13
No files matched your search
@@ -0,0 +1,7 @@
|
||||
"""Preprocess neural network modules for SoulX-Singer."""
|
||||
|
||||
from .pipeline import SoulXPreprocessPipeline
|
||||
|
||||
__all__ = [
|
||||
"SoulXPreprocessPipeline",
|
||||
]
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Lyric transcription (Paraformer + Parakeet) for SoulX preprocess."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from omegaconf import open_dict
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .utils import get_audio_duration
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _import_funasr_automodel():
|
||||
"""Import FunASR without shelling out to ffmpeg at module import time."""
|
||||
import subprocess
|
||||
from functools import wraps
|
||||
|
||||
real_check_output = subprocess.check_output
|
||||
|
||||
@wraps(real_check_output)
|
||||
def _safe_check_output(cmd, *args, **kwargs):
|
||||
if cmd and Path(str(cmd[0])).name == "ffmpeg":
|
||||
raise FileNotFoundError("ffmpeg unavailable for FunASR import probe")
|
||||
return real_check_output(cmd, *args, **kwargs)
|
||||
|
||||
subprocess.check_output = _safe_check_output
|
||||
try:
|
||||
from funasr import AutoModel
|
||||
finally:
|
||||
subprocess.check_output = real_check_output
|
||||
return AutoModel
|
||||
|
||||
|
||||
def build_words_with_gaps(raw_words, raw_timestamps, audio_duration: float):
|
||||
words, word_durs = [], []
|
||||
prev = 0.0
|
||||
for w, t in zip(raw_words, raw_timestamps):
|
||||
s, e = float(t[0]), float(t[1])
|
||||
if s > prev:
|
||||
words.append("<SP>")
|
||||
word_durs.append(s - prev)
|
||||
words.append(w)
|
||||
word_durs.append(e - s)
|
||||
prev = e
|
||||
|
||||
if audio_duration > prev:
|
||||
if not words:
|
||||
words.append("<SP>")
|
||||
word_durs.append(audio_duration)
|
||||
elif words[-1] != "<SP>":
|
||||
words.append("<SP>")
|
||||
word_durs.append(audio_duration - prev)
|
||||
else:
|
||||
word_durs[-1] += audio_duration - prev
|
||||
return words, word_durs
|
||||
|
||||
|
||||
class ParaformerASR(nn.Module):
|
||||
"""Mandarin/Cantonese ASR via FunASR Paraformer."""
|
||||
|
||||
def __init__(self, model_path: str, device: str):
|
||||
super().__init__()
|
||||
from vllm_omni.diffusion.models.soulx_singer.utils import _patch_torchaudio_load
|
||||
|
||||
_patch_torchaudio_load()
|
||||
AutoModel = _import_funasr_automodel()
|
||||
self.asr = AutoModel(model=model_path, disable_update=True, device=device)
|
||||
logger.info("Loaded Paraformer ASR from %s", model_path)
|
||||
|
||||
def _generate(self, source: str) -> tuple[list[str], list[float], float]:
|
||||
out = self.asr.generate(source, output_timestamp=True)[0]
|
||||
raw_words = out["text"].replace("@", "").split(" ")
|
||||
raw_timestamps = [[t[0] / 1000, t[1] / 1000] for t in out["timestamp"]]
|
||||
duration = float(raw_timestamps[-1][1]) if raw_timestamps else 0.0
|
||||
return raw_words, raw_timestamps, duration
|
||||
|
||||
def _maybe_refine_with_sidecar_f0(
|
||||
self,
|
||||
wav_path: str,
|
||||
words: list[str],
|
||||
word_durs: list[float],
|
||||
*,
|
||||
sample_rate: int,
|
||||
hop_size: int,
|
||||
) -> tuple[list[str], list[float]]:
|
||||
"""Match upstream ``_ASRZhModel.process``: refine using ``{wav}_f0.npy`` if present."""
|
||||
f0_path = os.path.splitext(wav_path)[0] + "_f0.npy"
|
||||
if not os.path.isfile(f0_path):
|
||||
return words, word_durs
|
||||
f0 = np.load(f0_path)
|
||||
if f0.size == 0:
|
||||
return words, word_durs
|
||||
return refine_word_durs_with_f0(
|
||||
words,
|
||||
word_durs,
|
||||
f0,
|
||||
sample_rate=sample_rate,
|
||||
hop_size=hop_size,
|
||||
)
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, audio: str | np.ndarray, sample_rate: int = 16000) -> tuple[list[str], list[float]]:
|
||||
if isinstance(audio, str):
|
||||
raw_words, raw_timestamps, _ = self._generate(audio)
|
||||
audio_duration = get_audio_duration(audio)
|
||||
words, word_durs = build_words_with_gaps(raw_words, raw_timestamps, audio_duration)
|
||||
return self._maybe_refine_with_sidecar_f0(
|
||||
audio,
|
||||
words,
|
||||
word_durs,
|
||||
sample_rate=24000,
|
||||
hop_size=480,
|
||||
)
|
||||
|
||||
waveform = np.asarray(audio, dtype=np.float32).squeeze()
|
||||
audio_duration = len(waveform) / float(sample_rate)
|
||||
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
|
||||
tmp_path = tmp.name
|
||||
try:
|
||||
sf.write(tmp_path, waveform, sample_rate)
|
||||
raw_words, raw_timestamps, _ = self._generate(tmp_path)
|
||||
words, word_durs = build_words_with_gaps(raw_words, raw_timestamps, audio_duration)
|
||||
return self._maybe_refine_with_sidecar_f0(
|
||||
tmp_path,
|
||||
words,
|
||||
word_durs,
|
||||
sample_rate=24000,
|
||||
hop_size=480,
|
||||
)
|
||||
finally:
|
||||
Path(tmp_path).unlink(missing_ok=True)
|
||||
Path(os.path.splitext(tmp_path)[0] + "_f0.npy").unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _disable_nemo_cuda_graphs(model) -> None:
|
||||
decoding_cfg = model.cfg.decoding
|
||||
with open_dict(decoding_cfg):
|
||||
if hasattr(decoding_cfg, "greedy") and decoding_cfg.greedy is not None:
|
||||
decoding_cfg.greedy.use_cuda_graph_decoder = False
|
||||
if hasattr(decoding_cfg, "beam") and decoding_cfg.beam is not None:
|
||||
decoding_cfg.beam.allow_cuda_graphs = False
|
||||
model.change_decoding_strategy(decoding_cfg)
|
||||
|
||||
|
||||
class ParakeetASR(nn.Module):
|
||||
"""English ASR via NeMo Parakeet-TDT."""
|
||||
|
||||
def __init__(self, model_path: str, device: str):
|
||||
super().__init__()
|
||||
try:
|
||||
import nemo.collections.asr as nemo_asr # type: ignore
|
||||
except Exception as e: # pragma: no cover
|
||||
raise ImportError(
|
||||
"NeMo (nemo_toolkit) is required for ASR English but is not available in this Python env."
|
||||
) from e
|
||||
|
||||
self.asr = nemo_asr.models.ASRModel.restore_from(
|
||||
restore_path=model_path,
|
||||
map_location=device,
|
||||
)
|
||||
self.asr.eval()
|
||||
_disable_nemo_cuda_graphs(self.asr)
|
||||
logger.info("Loaded Parakeet ASR from %s", model_path)
|
||||
|
||||
@staticmethod
|
||||
def _clean_word(word: str) -> str:
|
||||
return re.sub(r"[\?\.,:]", "", word).strip()
|
||||
|
||||
@staticmethod
|
||||
def _extract_word_segments(output: Any) -> list[dict[str, Any]]:
|
||||
ts = getattr(output, "timestamp", None)
|
||||
if not ts or not isinstance(ts, dict):
|
||||
return []
|
||||
word_ts = ts.get("word")
|
||||
return word_ts if isinstance(word_ts, list) else []
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, audio: str | np.ndarray, sample_rate: int = 16000) -> tuple[list[str], list[float]]:
|
||||
if isinstance(audio, str):
|
||||
sources = [audio]
|
||||
duration = 0.0
|
||||
else:
|
||||
waveform = np.asarray(audio, dtype=np.float32).squeeze()
|
||||
duration = len(waveform) / float(sample_rate)
|
||||
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
|
||||
tmp_path = tmp.name
|
||||
sf.write(tmp_path, waveform, sample_rate)
|
||||
sources = [tmp_path]
|
||||
|
||||
try:
|
||||
outputs = self.asr.transcribe(
|
||||
sources,
|
||||
timestamps=True,
|
||||
batch_size=1,
|
||||
num_workers=0,
|
||||
)
|
||||
finally:
|
||||
if not isinstance(audio, str):
|
||||
Path(sources[0]).unlink(missing_ok=True)
|
||||
|
||||
output = outputs[0] if outputs else None
|
||||
raw_words: list[str] = []
|
||||
raw_timestamps: list[list[float]] = []
|
||||
if output is not None:
|
||||
for w in self._extract_word_segments(output):
|
||||
s, e = float(w.get("start", 0.0)), float(w.get("end", 0.0))
|
||||
word = self._clean_word(str(w.get("word", "")))
|
||||
if word:
|
||||
raw_words.append(word)
|
||||
raw_timestamps.append([s, e])
|
||||
|
||||
if raw_timestamps:
|
||||
duration = max(duration, float(raw_timestamps[-1][1]))
|
||||
return build_words_with_gaps(raw_words, raw_timestamps, duration)
|
||||
|
||||
|
||||
def refine_word_durs_with_f0(
|
||||
words: list[str],
|
||||
word_durs: list[float],
|
||||
f0: np.ndarray,
|
||||
*,
|
||||
sample_rate: int = 24000,
|
||||
hop_size: int = 480,
|
||||
) -> tuple[list[str], list[float]]:
|
||||
boundaries = np.cumsum([0, *[int(dur * sample_rate / hop_size) for dur in word_durs]]).tolist()
|
||||
sil_tolerance = 5
|
||||
ext_tolerance = 5
|
||||
new_words: list[str] = []
|
||||
new_word_durs: list[float] = []
|
||||
if words:
|
||||
new_words.append(words[0])
|
||||
new_word_durs.append(word_durs[0])
|
||||
|
||||
for i in range(1, len(words)):
|
||||
word = words[i]
|
||||
if word == "<SP>":
|
||||
start_frame = boundaries[i]
|
||||
end_frame = boundaries[i + 1]
|
||||
num_frames = end_frame - start_frame
|
||||
frame_idx = start_frame
|
||||
unvoiced_count = 0
|
||||
while frame_idx < end_frame:
|
||||
if f0[frame_idx] <= 1:
|
||||
unvoiced_count += 1
|
||||
if unvoiced_count >= sil_tolerance:
|
||||
frame_idx -= sil_tolerance - 1
|
||||
break
|
||||
else:
|
||||
unvoiced_count = 0
|
||||
frame_idx += 1
|
||||
|
||||
voice_frames = frame_idx - start_frame
|
||||
if voice_frames >= int(num_frames * 0.9):
|
||||
new_word_durs[-1] += word_durs[i]
|
||||
elif voice_frames >= ext_tolerance:
|
||||
dur = voice_frames * hop_size / sample_rate
|
||||
new_word_durs[-1] += dur
|
||||
new_words.append("<SP>")
|
||||
new_word_durs.append(word_durs[i] - dur)
|
||||
else:
|
||||
new_words.append(word)
|
||||
new_word_durs.append(word_durs[i])
|
||||
else:
|
||||
new_words.append(word)
|
||||
new_word_durs.append(word_durs[i])
|
||||
return new_words, new_word_durs
|
||||
|
||||
|
||||
class LyricModel(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
zh_model_path: str,
|
||||
en_model_path: str,
|
||||
device: str = "cuda",
|
||||
*,
|
||||
target_sr: int = 24000,
|
||||
hop_size: int = 480,
|
||||
):
|
||||
super().__init__()
|
||||
self.device_str = device
|
||||
self.en_model_path = en_model_path
|
||||
self.target_sr = target_sr
|
||||
self.hop_size = hop_size
|
||||
self.zh_asr = ParaformerASR(zh_model_path, device=device)
|
||||
self.en_asr: nn.Module | None = None
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(
|
||||
self,
|
||||
audio: str | np.ndarray,
|
||||
language: str = "Mandarin",
|
||||
*,
|
||||
sample_rate: int = 16000,
|
||||
f0: np.ndarray | None = None,
|
||||
) -> tuple[list[str], list[float]]:
|
||||
if language not in {"Mandarin", "Cantonese", "English"}:
|
||||
raise ValueError(f"Unsupported language: {language}")
|
||||
|
||||
if language.lower() == "english":
|
||||
if self.en_asr is None:
|
||||
self.en_asr = ParakeetASR(self.en_model_path, device=self.device_str)
|
||||
self.add_module("en_asr", self.en_asr)
|
||||
words, durs = self.en_asr(audio, sample_rate=sample_rate)
|
||||
else:
|
||||
# Path-based ASR loads ``{wav}_f0.npy`` inside ParaformerASR (upstream parity).
|
||||
if isinstance(audio, str):
|
||||
words, durs = self.zh_asr(audio)
|
||||
else:
|
||||
words, durs = self.zh_asr(audio, sample_rate=sample_rate)
|
||||
if f0 is not None and len(f0) > 0:
|
||||
words, durs = refine_word_durs_with_f0(
|
||||
words,
|
||||
durs,
|
||||
f0,
|
||||
sample_rate=self.target_sr,
|
||||
hop_size=self.hop_size,
|
||||
)
|
||||
return words, durs
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Resample RMVPE F0 (16 kHz hop) onto the SoulX mel frame grid."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
from scipy.interpolate import interp1d
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .rmvpe import RMVPE_SAMPLE_RATE
|
||||
from .utils import load_mono_audio
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .rmvpe import RMVPE
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
RMVPE_HOP = 160
|
||||
|
||||
|
||||
def interpolate_f0_to_mel_grid(
|
||||
f0_16k: np.ndarray,
|
||||
original_length: int,
|
||||
original_sr: int,
|
||||
*,
|
||||
target_sr: int,
|
||||
hop_size: int,
|
||||
max_duration: float = 300.0,
|
||||
) -> np.ndarray:
|
||||
batch_max_length = int(max_duration * target_sr / hop_size)
|
||||
duration_in_seconds = original_length / original_sr
|
||||
effective_target_length = int(duration_in_seconds * target_sr)
|
||||
original_frames = math.ceil(effective_target_length / hop_size)
|
||||
target_frames = min(original_frames, batch_max_length)
|
||||
|
||||
t_16k = np.arange(len(f0_16k)) * (RMVPE_HOP / float(original_sr))
|
||||
t_target = np.arange(target_frames) * (hop_size / float(target_sr))
|
||||
|
||||
if len(f0_16k) > 0:
|
||||
f_interp = interp1d(
|
||||
t_16k,
|
||||
f0_16k,
|
||||
kind="linear",
|
||||
bounds_error=False,
|
||||
fill_value=0.0,
|
||||
assume_sorted=True,
|
||||
)
|
||||
f0 = f_interp(t_target)
|
||||
else:
|
||||
f0 = np.zeros(target_frames)
|
||||
|
||||
if len(f0) != target_frames:
|
||||
f0 = f0[:target_frames] if len(f0) > target_frames else np.pad(f0, (0, target_frames - len(f0)))
|
||||
return f0.astype(np.float32, copy=False)
|
||||
|
||||
|
||||
def extract_f0_file(
|
||||
rmvpe: RMVPE,
|
||||
wav_path: str,
|
||||
*,
|
||||
target_sr: int,
|
||||
hop_size: int,
|
||||
f0_path: str | None = None,
|
||||
thread: float = 0.03,
|
||||
max_duration: float = 300.0,
|
||||
verbose: bool = False,
|
||||
) -> np.ndarray:
|
||||
if verbose:
|
||||
logger.info("[f0] extracting from %s", wav_path)
|
||||
t0 = time.perf_counter()
|
||||
|
||||
audio, _ = load_mono_audio(wav_path, target_sr=RMVPE_SAMPLE_RATE)
|
||||
f0_16k = rmvpe.infer_from_audio(audio, sample_rate=RMVPE_SAMPLE_RATE)
|
||||
f0 = interpolate_f0_to_mel_grid(
|
||||
np.asarray(f0_16k, dtype=np.float32),
|
||||
original_length=audio.shape[-1],
|
||||
original_sr=RMVPE_SAMPLE_RATE,
|
||||
target_sr=target_sr,
|
||||
hop_size=hop_size,
|
||||
max_duration=max_duration,
|
||||
)
|
||||
|
||||
if verbose:
|
||||
voiced_ratio = float(np.mean(f0 > 0)) if len(f0) else 0.0
|
||||
logger.info(
|
||||
"[f0] done: frames=%s voiced_ratio=%.3f time=%.3fs",
|
||||
len(f0),
|
||||
voiced_ratio,
|
||||
time.perf_counter() - t0,
|
||||
)
|
||||
if f0_path is not None:
|
||||
np.save(f0_path, f0)
|
||||
return f0
|
||||
@@ -0,0 +1,431 @@
|
||||
"""SoulX preprocess pipeline."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.models.interface import SupportAudioInput, SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.models.soulx_singer.modules.preprocess.stack import SoulXPreprocessStack
|
||||
from vllm_omni.diffusion.models.soulx_singer.modules.preprocess.utils import load_mono_audio, resample_mono
|
||||
from vllm_omni.diffusion.models.soulx_singer.preprocess.metadata_utils import (
|
||||
SegmentMetadata,
|
||||
_merge_group,
|
||||
convert_metadata,
|
||||
)
|
||||
from vllm_omni.diffusion.models.soulx_singer.utils import (
|
||||
load_config,
|
||||
load_wav,
|
||||
preprocess_weight_paths,
|
||||
resolve_preprocess_weights_root,
|
||||
resolve_soulx_kind,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def build_svs_prompt_meta(
|
||||
preprocess: SoulXPreprocessPipeline,
|
||||
*,
|
||||
prompt_audio: str | tuple[np.ndarray, int],
|
||||
prompt_meta_raw: dict[str, Any],
|
||||
metadata_processor,
|
||||
vocal_sep: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build SVS prompt_meta; in-memory prompt wav is trimmed to mel2note length."""
|
||||
if isinstance(prompt_audio, str):
|
||||
return metadata_processor.process(prompt_meta_raw, prompt_audio)
|
||||
prompt_meta = metadata_processor.process(prompt_meta_raw, None)
|
||||
prompt_vocal, prompt_sr = preprocess._extract_vocal(prompt_audio, vocal_sep=vocal_sep)
|
||||
if prompt_sr != metadata_processor.sample_rate:
|
||||
prompt_vocal = resample_mono(
|
||||
prompt_vocal,
|
||||
orig_sr=prompt_sr,
|
||||
target_sr=metadata_processor.sample_rate,
|
||||
)
|
||||
max_samples = prompt_meta["mel2note"].shape[1] * metadata_processor.hop_size
|
||||
segment_wav = np.asarray(prompt_vocal[:max_samples], dtype=np.float32)
|
||||
prompt_meta["wav"] = torch.from_numpy(segment_wav).unsqueeze(0).float().to(metadata_processor.device)
|
||||
return prompt_meta
|
||||
|
||||
|
||||
class SoulXPreprocessPipeline(nn.Module, SupportAudioInput, SupportsComponentDiscovery):
|
||||
"""Lazy-loaded preprocess stack integrated with vLLM-Omni diffusion lifecycle."""
|
||||
|
||||
support_audio_input: ClassVar[bool] = True
|
||||
weights_sources: ClassVar[tuple] = ()
|
||||
_dit_modules: ClassVar[list[str]] = []
|
||||
_encoder_modules: ClassVar[list[str]] = [
|
||||
"stack.vocal_sep",
|
||||
"stack.lyric",
|
||||
"stack.rosvot",
|
||||
]
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = ["stack.rmvpe"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
od_config: OmniDiffusionConfig,
|
||||
prefix: str = "",
|
||||
vocal_sep: bool = True,
|
||||
midi_transcribe: bool = True,
|
||||
max_merge_duration_ms: int = 60000,
|
||||
verbose: bool = False,
|
||||
extra_args: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
del prefix
|
||||
self.od_config = od_config
|
||||
extra_args = extra_args or {}
|
||||
self.kind = resolve_soulx_kind(od_config.model)
|
||||
hf_config = load_config(str(Path(od_config.model) / "config.yaml"))
|
||||
audio_config = hf_config.audio
|
||||
if self.kind == "svc" and midi_transcribe:
|
||||
logger.warning("SVC model (config.json): midi_transcribe is ignored; lyric/MIDI transcription is SVS-only.")
|
||||
midi_transcribe = False
|
||||
|
||||
self.vocal_sep = vocal_sep
|
||||
self.midi_transcribe = midi_transcribe
|
||||
self.max_merge_duration_ms = max_merge_duration_ms
|
||||
self.verbose = verbose
|
||||
self.target_sr = int(audio_config.sample_rate)
|
||||
self.hop_size = int(audio_config.hop_size)
|
||||
self._metadata_processor = None
|
||||
self._weights_root: Path | None = None
|
||||
self.stack: SoulXPreprocessStack | None = None
|
||||
self._ensure_stack(extra_args)
|
||||
|
||||
def _ensure_stack(self, extra_args: dict[str, Any] | None = None) -> None:
|
||||
extra_args = extra_args or {}
|
||||
weights_root = resolve_preprocess_weights_root(self.od_config)
|
||||
if self.stack is not None and self._weights_root == weights_root:
|
||||
return
|
||||
weights = preprocess_weight_paths(weights_root)
|
||||
device = str(get_local_device())
|
||||
self.stack = SoulXPreprocessStack(
|
||||
weights,
|
||||
device,
|
||||
target_sr=self.target_sr,
|
||||
hop_size=self.hop_size,
|
||||
verbose=self.verbose,
|
||||
)
|
||||
self._weights_root = weights_root
|
||||
|
||||
def forward(self, req) -> DiffusionOutput:
|
||||
from vllm_omni.diffusion.models.soulx_singer.preprocess.payload import (
|
||||
SOULX_PREPROCESSED_KEY,
|
||||
)
|
||||
from vllm_omni.diffusion.models.soulx_singer.preprocess.pre_process import (
|
||||
build_metadata_processor,
|
||||
build_preprocess_payload,
|
||||
build_warmup_payload,
|
||||
is_warmup_request,
|
||||
)
|
||||
from vllm_omni.inputs.data import OmniTextPrompt
|
||||
|
||||
extra_args = dict(getattr(req.sampling_params, "extra_args", None) or {})
|
||||
prompt = OmniTextPrompt(prompt=req.prompts[0]) if isinstance(req.prompts[0], str) else req.prompts[0]
|
||||
info = prompt.get("additional_information") or {}
|
||||
if isinstance(info, dict):
|
||||
extra_args.update(dict(info.get("extra_args") or {}))
|
||||
|
||||
self._ensure_stack(extra_args)
|
||||
if self._metadata_processor is None:
|
||||
self._metadata_processor = build_metadata_processor(self.od_config)
|
||||
|
||||
device = get_local_device()
|
||||
if is_warmup_request(req):
|
||||
payload = build_warmup_payload(
|
||||
self.kind,
|
||||
metadata_processor=self._metadata_processor,
|
||||
device=device,
|
||||
sample_rate=self.target_sr,
|
||||
)
|
||||
else:
|
||||
payload = build_preprocess_payload(
|
||||
self.kind,
|
||||
prompt=prompt,
|
||||
extra_args=extra_args,
|
||||
preprocess=self,
|
||||
metadata_processor=self._metadata_processor,
|
||||
device=device,
|
||||
sample_rate=self.target_sr,
|
||||
)
|
||||
|
||||
# Non-None placeholder so DiffusionEngine forwards custom_output to stage-1
|
||||
# (output=None triggers an early return that drops handoff).
|
||||
return DiffusionOutput(
|
||||
output=torch.zeros(0),
|
||||
custom_output={SOULX_PREPROCESSED_KEY: payload},
|
||||
to_cpu=True,
|
||||
)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
del weights
|
||||
self._ensure_stack({})
|
||||
return set()
|
||||
|
||||
def _extract_vocal(
|
||||
self,
|
||||
audio: str | tuple[np.ndarray, int],
|
||||
*,
|
||||
vocal_sep: bool | None = None,
|
||||
) -> tuple[np.ndarray, int]:
|
||||
if self.stack is None:
|
||||
self._ensure_stack({})
|
||||
use_sep = self.vocal_sep if vocal_sep is None else vocal_sep
|
||||
if use_sep:
|
||||
return self.stack.extract_vocal(audio)
|
||||
return load_mono_audio(audio)
|
||||
|
||||
def extract_f0(self, vocal: np.ndarray, sample_rate: int) -> np.ndarray:
|
||||
if self.stack is None:
|
||||
self._ensure_stack({})
|
||||
return self.stack.extract_f0(vocal, sample_rate)
|
||||
|
||||
def iter_svs_metadata(
|
||||
self,
|
||||
audio_source: str | tuple[np.ndarray, int],
|
||||
*,
|
||||
language: str = "Mandarin",
|
||||
vocal_sep: bool | None = None,
|
||||
max_merge_duration_ms: int | None = None,
|
||||
):
|
||||
"""Yield merged SVS metadata dicts one segment at a time."""
|
||||
if isinstance(audio_source, tuple):
|
||||
vocal, sample_rate = audio_source
|
||||
origin_wav_fn = ""
|
||||
else:
|
||||
vocal, sample_rate = self._extract_vocal(str(audio_source), vocal_sep=vocal_sep)
|
||||
origin_wav_fn = str(audio_source)
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="soulx_preprocess_") as work_dir:
|
||||
work = Path(work_dir)
|
||||
vocal_path = work / "vocal.wav"
|
||||
sf.write(vocal_path, vocal, sample_rate)
|
||||
|
||||
vocal_f0_path = str(vocal_path).replace(".wav", "_f0.npy")
|
||||
vocal_f0 = self.stack.extract_f0(str(vocal_path), sample_rate=sample_rate, f0_path=vocal_f0_path)
|
||||
|
||||
if not self.midi_transcribe:
|
||||
end_ms = int(len(vocal) / sample_rate * 1000)
|
||||
item = SegmentMetadata(
|
||||
item_name="full",
|
||||
wav_fn=str(vocal_path),
|
||||
language=language,
|
||||
start_time_ms=0,
|
||||
end_time_ms=end_ms,
|
||||
note_text=["<SP>"],
|
||||
note_dur=[end_ms / 1000.0],
|
||||
note_pitch=[0],
|
||||
note_type=[1],
|
||||
)
|
||||
yield convert_metadata(item)
|
||||
return
|
||||
|
||||
segments = self.stack.ensure_segmenter().forward(
|
||||
vocal,
|
||||
sample_rate,
|
||||
vocal_f0,
|
||||
base_name="vocal",
|
||||
origin_wav_fn=origin_wav_fn,
|
||||
verbose=self.verbose,
|
||||
)
|
||||
cut_dir = work / "cut_wavs"
|
||||
cut_dir.mkdir(parents=True, exist_ok=True)
|
||||
lyric = self.stack.ensure_lyric()
|
||||
rosvot = self.stack.ensure_rosvot()
|
||||
|
||||
long_cut_dir = work / "long_cut_wavs"
|
||||
max_dur = max_merge_duration_ms or self.max_merge_duration_ms
|
||||
max_gap_ms = 10000
|
||||
current_group: list[Any] = []
|
||||
current_len = 0
|
||||
prev_end = -1
|
||||
|
||||
def _flush_group() -> dict[str, Any]:
|
||||
merged_item = _merge_group(vocal, sample_rate, current_group, long_cut_dir)
|
||||
merged_f0_path = merged_item.wav_fn.replace(".wav", "_f0.npy")
|
||||
self.stack.extract_f0(merged_item.wav_fn, sample_rate=sample_rate, f0_path=merged_f0_path)
|
||||
return convert_metadata(merged_item)
|
||||
|
||||
for seg in segments:
|
||||
seg_key = seg["item_name"]
|
||||
seg_wav_path = cut_dir / f"{seg_key}.wav"
|
||||
sf.write(seg_wav_path, seg["wav"], seg["sample_rate"])
|
||||
seg_f0_path = str(seg_wav_path).replace(".wav", "_f0.npy")
|
||||
self.stack.extract_f0(str(seg_wav_path), sample_rate=seg["sample_rate"], f0_path=seg_f0_path)
|
||||
|
||||
words, durs = lyric.forward(
|
||||
str(seg_wav_path),
|
||||
language,
|
||||
sample_rate=seg["sample_rate"],
|
||||
)
|
||||
seg_item = {
|
||||
"item_name": seg_key,
|
||||
"wav_fn": str(seg_wav_path),
|
||||
"start_time_ms": seg["start_time_ms"],
|
||||
"end_time_ms": seg["end_time_ms"],
|
||||
"origin_wav_fn": origin_wav_fn or str(vocal_path),
|
||||
"words": words,
|
||||
"word_durs": durs,
|
||||
"language": language,
|
||||
}
|
||||
meta_item = rosvot.transcribe(seg_item, segment_info=seg_item, verbose=self.verbose)
|
||||
|
||||
start_time = int(meta_item.get("start_time_ms", seg["start_time_ms"]))
|
||||
end_time = int(meta_item.get("end_time_ms", seg["end_time_ms"]))
|
||||
if current_group and (
|
||||
start_time - prev_end > max_gap_ms or current_len + end_time - start_time > max_dur
|
||||
):
|
||||
yield _flush_group()
|
||||
current_group = []
|
||||
current_len = 0
|
||||
|
||||
current_group.append(meta_item)
|
||||
current_len += end_time - start_time
|
||||
prev_end = end_time
|
||||
|
||||
if current_group:
|
||||
yield _flush_group()
|
||||
|
||||
@staticmethod
|
||||
def build_svs_payload_from_paths(
|
||||
*,
|
||||
prompt_metadata_path: str,
|
||||
target_metadata_path: str,
|
||||
audio_path: str,
|
||||
metadata_processor,
|
||||
) -> dict[str, Any]:
|
||||
with open(prompt_metadata_path, encoding="utf-8") as f:
|
||||
prompt_metadata = json.load(f)
|
||||
with open(target_metadata_path, encoding="utf-8") as f:
|
||||
target_metadata = json.load(f)
|
||||
if not prompt_metadata:
|
||||
raise ValueError("prompt_metadata is empty")
|
||||
if not target_metadata:
|
||||
raise ValueError("target_metadata is empty")
|
||||
|
||||
prompt_meta = metadata_processor.process(prompt_metadata[0], audio_path)
|
||||
return {
|
||||
"kind": "svs",
|
||||
"prompt_meta": prompt_meta,
|
||||
"target_meta_list": target_metadata,
|
||||
}
|
||||
|
||||
def build_svs_payload_from_audio(
|
||||
self,
|
||||
*,
|
||||
prompt_audio: str | tuple[np.ndarray, int],
|
||||
target_audio: str | tuple[np.ndarray, int],
|
||||
metadata_processor,
|
||||
language: str = "Mandarin",
|
||||
vocal_sep: bool | None = None,
|
||||
prompt_vocal_sep: bool | None = None,
|
||||
target_vocal_sep: bool | None = None,
|
||||
prompt_max_merge_duration_ms: int | None = None,
|
||||
target_max_merge_duration_ms: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
p_sep = prompt_vocal_sep if prompt_vocal_sep is not None else vocal_sep
|
||||
t_sep = target_vocal_sep if target_vocal_sep is not None else vocal_sep
|
||||
p_merge = (
|
||||
prompt_max_merge_duration_ms if prompt_max_merge_duration_ms is not None else self.max_merge_duration_ms
|
||||
)
|
||||
t_merge = (
|
||||
target_max_merge_duration_ms if target_max_merge_duration_ms is not None else self.max_merge_duration_ms
|
||||
)
|
||||
prompt_list = list(
|
||||
self.iter_svs_metadata(
|
||||
prompt_audio,
|
||||
language=language,
|
||||
vocal_sep=p_sep,
|
||||
max_merge_duration_ms=p_merge,
|
||||
)
|
||||
)
|
||||
target_list = list(
|
||||
self.iter_svs_metadata(
|
||||
target_audio,
|
||||
language=language,
|
||||
vocal_sep=t_sep,
|
||||
max_merge_duration_ms=t_merge,
|
||||
)
|
||||
)
|
||||
if not prompt_list or not target_list:
|
||||
raise ValueError("SVS preprocess produced empty metadata")
|
||||
|
||||
# Prompt wav is trimmed to mel2note length, not the metadata time window.
|
||||
prompt_meta = build_svs_prompt_meta(
|
||||
self,
|
||||
prompt_audio=prompt_audio,
|
||||
prompt_meta_raw=prompt_list[0],
|
||||
metadata_processor=metadata_processor,
|
||||
vocal_sep=vocal_sep,
|
||||
)
|
||||
|
||||
return {
|
||||
"kind": "svs",
|
||||
"prompt_meta": prompt_meta,
|
||||
"target_meta_list": target_list,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_svc_payload_from_paths(
|
||||
*,
|
||||
prompt_wav_path: str,
|
||||
target_wav_path: str,
|
||||
prompt_f0_path: str,
|
||||
target_f0_path: str,
|
||||
sample_rate: int,
|
||||
device: torch.device | str,
|
||||
) -> dict[str, Any]:
|
||||
prompt_wav = load_wav(prompt_wav_path, sample_rate).to(device)
|
||||
target_wav = load_wav(target_wav_path, sample_rate).to(device)
|
||||
prompt_f0 = torch.from_numpy(np.load(prompt_f0_path)).unsqueeze(0).to(device)
|
||||
target_f0 = torch.from_numpy(np.load(target_f0_path)).unsqueeze(0).to(device)
|
||||
return {
|
||||
"kind": "svc",
|
||||
"prompt_wav": prompt_wav,
|
||||
"target_wav": target_wav,
|
||||
"prompt_f0": prompt_f0,
|
||||
"target_f0": target_f0,
|
||||
}
|
||||
|
||||
def build_svc_payload_from_audio(
|
||||
self,
|
||||
*,
|
||||
prompt_audio: str | tuple[np.ndarray, int],
|
||||
target_audio: str | tuple[np.ndarray, int],
|
||||
sample_rate: int,
|
||||
device: torch.device | str,
|
||||
vocal_sep: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
prompt_vocal, prompt_sr = self._extract_vocal(prompt_audio, vocal_sep=vocal_sep)
|
||||
target_vocal, target_sr = self._extract_vocal(target_audio, vocal_sep=vocal_sep)
|
||||
|
||||
if prompt_sr != sample_rate:
|
||||
prompt_vocal = resample_mono(prompt_vocal, orig_sr=prompt_sr, target_sr=sample_rate)
|
||||
if target_sr != sample_rate:
|
||||
target_vocal = resample_mono(target_vocal, orig_sr=target_sr, target_sr=sample_rate)
|
||||
|
||||
prompt_f0 = self.extract_f0(prompt_vocal, sample_rate)
|
||||
target_f0 = self.extract_f0(target_vocal, sample_rate)
|
||||
|
||||
return {
|
||||
"kind": "svc",
|
||||
"prompt_wav": torch.from_numpy(prompt_vocal).unsqueeze(0).to(device),
|
||||
"target_wav": torch.from_numpy(target_vocal).unsqueeze(0).to(device),
|
||||
"prompt_f0": torch.from_numpy(prompt_f0).unsqueeze(0).to(device),
|
||||
"target_f0": torch.from_numpy(target_f0).unsqueeze(0).to(device),
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
"""RMVPE F0 extractor.
|
||||
|
||||
All model code is inlined (originally from RickyL-2000/ROSVOT
|
||||
``modules/pe/rmvpe/``) with two minor substitutions:
|
||||
|
||||
* ``librosa.filters.mel`` → ``torchaudio.functional.melscale_fbanks``
|
||||
(already used elsewhere in vllm-omni);
|
||||
* ``librosa.sequence.viterbi`` → hand-written numpy viterbi (non-default path).
|
||||
* ``pyworld`` (deprecated) → removed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from torchaudio.functional import melscale_fbanks
|
||||
from torchaudio.transforms import Resample
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.models.interface import SupportAudioInput, SupportsComponentDiscovery
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
RMVPE_SAMPLE_RATE = 16000
|
||||
_N_CLASS = 360
|
||||
_N_MELS = 128
|
||||
_MEL_FMIN = 30
|
||||
_MEL_FMAX = 8000
|
||||
_WINDOW_LENGTH = 1024
|
||||
_CONST = 1997.3794084376191
|
||||
|
||||
|
||||
class ConvBlockRes(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int, momentum: float = 0.01):
|
||||
super().__init__()
|
||||
self.conv = nn.Sequential(
|
||||
nn.Conv2d(in_channels, out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False),
|
||||
nn.BatchNorm2d(out_channels, momentum=momentum),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(out_channels, out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False),
|
||||
nn.BatchNorm2d(out_channels, momentum=momentum),
|
||||
nn.ReLU(),
|
||||
)
|
||||
if in_channels != out_channels:
|
||||
self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
|
||||
self._has_shortcut = True
|
||||
else:
|
||||
self._has_shortcut = False
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
if self._has_shortcut:
|
||||
return self.conv(x) + self.shortcut(x)
|
||||
return self.conv(x) + x
|
||||
|
||||
|
||||
class ResEncoderBlock(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int, kernel_size, n_blocks: int = 1, momentum: float = 0.01):
|
||||
super().__init__()
|
||||
self.n_blocks = n_blocks
|
||||
self.conv = nn.ModuleList()
|
||||
self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
|
||||
for _ in range(n_blocks - 1):
|
||||
self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
|
||||
self.kernel_size = kernel_size
|
||||
if self.kernel_size is not None:
|
||||
self.pool = nn.AvgPool2d(kernel_size=kernel_size)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
for i in range(self.n_blocks):
|
||||
x = self.conv[i](x)
|
||||
if self.kernel_size is not None:
|
||||
return x, self.pool(x)
|
||||
return x
|
||||
|
||||
|
||||
class ResDecoderBlock(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int, stride, n_blocks: int = 1, momentum: float = 0.01):
|
||||
super().__init__()
|
||||
out_padding = (0, 1) if stride == (1, 2) else (1, 1)
|
||||
self.n_blocks = n_blocks
|
||||
self.conv1 = nn.Sequential(
|
||||
nn.ConvTranspose2d(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size=(3, 3),
|
||||
stride=stride,
|
||||
padding=(1, 1),
|
||||
output_padding=out_padding,
|
||||
bias=False,
|
||||
),
|
||||
nn.BatchNorm2d(out_channels, momentum=momentum),
|
||||
nn.ReLU(),
|
||||
)
|
||||
self.conv2 = nn.ModuleList()
|
||||
self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
|
||||
for _ in range(n_blocks - 1):
|
||||
self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
|
||||
|
||||
def forward(self, x: torch.Tensor, concat_tensor: torch.Tensor) -> torch.Tensor:
|
||||
x = self.conv1(x)
|
||||
x = torch.cat((x, concat_tensor), dim=1)
|
||||
for i in range(self.n_blocks):
|
||||
x = self.conv2[i](x)
|
||||
return x
|
||||
|
||||
|
||||
class Encoder(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels: int,
|
||||
in_size: int,
|
||||
n_encoders: int,
|
||||
kernel_size,
|
||||
n_blocks: int,
|
||||
out_channels: int = 16,
|
||||
momentum: float = 0.01,
|
||||
):
|
||||
super().__init__()
|
||||
self.n_encoders = n_encoders
|
||||
self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
|
||||
self.layers = nn.ModuleList()
|
||||
self.latent_channels: list[list[int]] = []
|
||||
for _ in range(self.n_encoders):
|
||||
self.layers.append(ResEncoderBlock(in_channels, out_channels, kernel_size, n_blocks, momentum=momentum))
|
||||
self.latent_channels.append([out_channels, in_size])
|
||||
in_channels = out_channels
|
||||
out_channels *= 2
|
||||
in_size //= 2
|
||||
self.out_size = in_size
|
||||
self.out_channel = out_channels
|
||||
|
||||
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, list[torch.Tensor]]:
|
||||
concat_tensors: list[torch.Tensor] = []
|
||||
x = self.bn(x)
|
||||
for i in range(self.n_encoders):
|
||||
_c, x = self.layers[i](x)
|
||||
concat_tensors.append(_c)
|
||||
return x, concat_tensors
|
||||
|
||||
|
||||
class Intermediate(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int, n_inters: int, n_blocks: int, momentum: float = 0.01):
|
||||
super().__init__()
|
||||
self.n_inters = n_inters
|
||||
self.layers = nn.ModuleList()
|
||||
self.layers.append(ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum))
|
||||
for _ in range(n_inters - 1):
|
||||
self.layers.append(ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
for i in range(self.n_inters):
|
||||
x = self.layers[i](x)
|
||||
return x
|
||||
|
||||
|
||||
class Decoder(nn.Module):
|
||||
def __init__(self, in_channels: int, n_decoders: int, stride, n_blocks: int, momentum: float = 0.01):
|
||||
super().__init__()
|
||||
self.layers = nn.ModuleList()
|
||||
self.n_decoders = n_decoders
|
||||
for _ in range(self.n_decoders):
|
||||
out_channels = in_channels // 2
|
||||
self.layers.append(ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum))
|
||||
in_channels = out_channels
|
||||
|
||||
def forward(self, x: torch.Tensor, concat_tensors: list[torch.Tensor]) -> torch.Tensor:
|
||||
for i in range(self.n_decoders):
|
||||
x = self.layers[i](x, concat_tensors[-1 - i])
|
||||
return x
|
||||
|
||||
|
||||
class TimbreFilter(nn.Module):
|
||||
def __init__(self, latent_rep_channels: list[list[int]]):
|
||||
super().__init__()
|
||||
self.layers = nn.ModuleList()
|
||||
for ch in latent_rep_channels:
|
||||
self.layers.append(ConvBlockRes(ch[0], ch[0]))
|
||||
|
||||
def forward(self, x_tensors: list[torch.Tensor]) -> list[torch.Tensor]:
|
||||
return [layer(t) for layer, t in zip(self.layers, x_tensors)]
|
||||
|
||||
|
||||
class DeepUnet0(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
kernel_size,
|
||||
n_blocks: int,
|
||||
en_de_layers: int = 5,
|
||||
inter_layers: int = 4,
|
||||
in_channels: int = 1,
|
||||
en_out_channels: int = 16,
|
||||
):
|
||||
super().__init__()
|
||||
self.encoder = Encoder(in_channels, _N_MELS, en_de_layers, kernel_size, n_blocks, en_out_channels)
|
||||
self.intermediate = Intermediate(
|
||||
self.encoder.out_channel // 2, self.encoder.out_channel, inter_layers, n_blocks
|
||||
)
|
||||
self.tf = TimbreFilter(self.encoder.latent_channels)
|
||||
self.decoder = Decoder(self.encoder.out_channel, en_de_layers, kernel_size, n_blocks)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
x, concat_tensors = self.encoder(x)
|
||||
x = self.intermediate(x)
|
||||
x = self.decoder(x, concat_tensors)
|
||||
return x
|
||||
|
||||
|
||||
class BiGRU(nn.Module):
|
||||
def __init__(self, input_features: int, hidden_features: int, num_layers: int):
|
||||
super().__init__()
|
||||
self.gru = nn.GRU(input_features, hidden_features, num_layers=num_layers, batch_first=True, bidirectional=True)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.gru(x)[0]
|
||||
|
||||
|
||||
class E2E0(nn.Module):
|
||||
"""E2E0 pitch estimator network (DeepUnet0 + CNN + BiGRU + classifier)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
n_blocks: int,
|
||||
n_gru: int,
|
||||
kernel_size,
|
||||
en_de_layers: int = 5,
|
||||
inter_layers: int = 4,
|
||||
in_channels: int = 1,
|
||||
en_out_channels: int = 16,
|
||||
):
|
||||
super().__init__()
|
||||
self.unet = DeepUnet0(kernel_size, n_blocks, en_de_layers, inter_layers, in_channels, en_out_channels)
|
||||
self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
|
||||
if n_gru:
|
||||
self.fc = nn.Sequential(
|
||||
BiGRU(3 * _N_MELS, 256, n_gru),
|
||||
nn.Linear(512, _N_CLASS),
|
||||
nn.Dropout(0.25),
|
||||
nn.Sigmoid(),
|
||||
)
|
||||
else:
|
||||
self.fc = nn.Sequential(
|
||||
nn.Linear(3 * _N_MELS, _N_CLASS),
|
||||
nn.Dropout(0.25),
|
||||
nn.Sigmoid(),
|
||||
)
|
||||
|
||||
def forward(self, mel: torch.Tensor) -> torch.Tensor:
|
||||
mel = mel.transpose(-1, -2).unsqueeze(1)
|
||||
x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
|
||||
x = self.fc(x)
|
||||
return x
|
||||
|
||||
|
||||
class MelSpectrogram(nn.Module):
|
||||
"""Mel-spectrogram extractor matching ROSVOT's MelSpectrogram.
|
||||
|
||||
Log-mel spectrogram via torch.stft + adaptive filterbank.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
n_mel_channels: int = _N_MELS,
|
||||
sampling_rate: int = RMVPE_SAMPLE_RATE,
|
||||
win_length: int = _WINDOW_LENGTH,
|
||||
hop_length: int = 160,
|
||||
n_fft: int | None = None,
|
||||
mel_fmin: float = _MEL_FMIN,
|
||||
mel_fmax: float = _MEL_FMAX,
|
||||
clamp: float = 1e-5,
|
||||
):
|
||||
super().__init__()
|
||||
n_fft = win_length if n_fft is None else n_fft
|
||||
self.hann_window: dict[str, torch.Tensor] = {}
|
||||
mel_basis = melscale_fbanks(
|
||||
n_freqs=n_fft // 2 + 1,
|
||||
f_min=float(mel_fmin),
|
||||
f_max=float(mel_fmax) if mel_fmax is not None else 8000.0,
|
||||
n_mels=n_mel_channels,
|
||||
sample_rate=int(sampling_rate),
|
||||
norm="slaney",
|
||||
mel_scale="htk",
|
||||
).T # (n_freqs, n_mels) → (n_mels, n_freqs) to match librosa/layernorm convention
|
||||
self.register_buffer("mel_basis", mel_basis) # (n_mels, n_freqs)
|
||||
self.n_fft = n_fft
|
||||
self.hop_length = hop_length
|
||||
self.win_length = win_length
|
||||
self.sampling_rate = sampling_rate
|
||||
self.n_mel_channels = n_mel_channels
|
||||
self.clamp = clamp
|
||||
|
||||
def forward(self, audio: torch.Tensor, keyshift: float = 0, speed: float = 1, center: bool = True) -> torch.Tensor:
|
||||
factor = 2 ** (keyshift / 12)
|
||||
n_fft_new = int(np.round(self.n_fft * factor))
|
||||
win_length_new = int(np.round(self.win_length * factor))
|
||||
hop_length_new = int(np.round(self.hop_length * speed))
|
||||
|
||||
key = str(keyshift) + "_" + str(audio.device)
|
||||
if key not in self.hann_window:
|
||||
self.hann_window[key] = torch.hann_window(win_length_new).to(audio.device)
|
||||
|
||||
if center:
|
||||
pad_left = win_length_new // 2
|
||||
pad_right = (win_length_new + 1) // 2
|
||||
audio = F.pad(audio, (pad_left, pad_right))
|
||||
|
||||
fft = torch.stft(
|
||||
audio,
|
||||
n_fft=n_fft_new,
|
||||
hop_length=hop_length_new,
|
||||
win_length=win_length_new,
|
||||
window=self.hann_window[key],
|
||||
center=False,
|
||||
return_complex=True,
|
||||
)
|
||||
magnitude = fft.abs()
|
||||
|
||||
if keyshift != 0:
|
||||
size = self.n_fft // 2 + 1
|
||||
if magnitude.size(1) < size:
|
||||
magnitude = F.pad(magnitude, (0, 0, 0, size - magnitude.size(1)))
|
||||
magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
|
||||
|
||||
# register_buffer confuses type checkers; cast to Tensor explicitly
|
||||
mel_basis: torch.Tensor = self.mel_basis # type: ignore[assignment]
|
||||
mel_output = torch.matmul(mel_basis, magnitude)
|
||||
log_mel = torch.log(torch.clamp(mel_output, min=self.clamp))
|
||||
return log_mel
|
||||
|
||||
|
||||
def to_local_average_f0(hidden: torch.Tensor, center: torch.Tensor | None = None, thread: float = 0.03) -> np.ndarray:
|
||||
"""Decode hidden representation to F0 via local weighted average."""
|
||||
idx = torch.arange(_N_CLASS, device=hidden.device)[None, None, :]
|
||||
idx_cents = idx * 20 + _CONST
|
||||
if center is None:
|
||||
center = torch.argmax(hidden, dim=2, keepdim=True)
|
||||
start = torch.clip(center - 4, min=0)
|
||||
end = torch.clip(center + 5, max=_N_CLASS)
|
||||
idx_mask = (idx >= start) & (idx < end)
|
||||
weights = hidden * idx_mask
|
||||
product_sum = torch.sum(weights * idx_cents, dim=2)
|
||||
weight_sum = torch.sum(weights, dim=2)
|
||||
cents = product_sum / (weight_sum + (weight_sum == 0))
|
||||
f0 = 10 * 2 ** (cents / 1200)
|
||||
uv = hidden.max(dim=2)[0] < thread
|
||||
f0 = f0 * ~uv
|
||||
return f0.cpu().numpy()
|
||||
|
||||
|
||||
def numpy_viterbi(prob: np.ndarray, transition: np.ndarray) -> np.ndarray:
|
||||
"""Viterbi decoding on log-probabilities (numpy).
|
||||
|
||||
Args:
|
||||
prob: Emission probabilities, shape (n_states, n_obs).
|
||||
transition: Transition matrix, shape (n_states, n_states), row-stochastic.
|
||||
|
||||
Returns:
|
||||
path: Most likely state sequence, shape (n_obs,).
|
||||
"""
|
||||
n_states, n_obs = prob.shape
|
||||
log_emit = np.log(prob + 1e-12)
|
||||
log_trans = np.log(transition + 1e-12)
|
||||
|
||||
delta = log_emit[:, 0] + np.zeros(n_states) # initial: log(pi) omitted (uniform)
|
||||
psi = np.zeros((n_obs, n_states), dtype=np.int64)
|
||||
|
||||
for t in range(1, n_obs):
|
||||
scores = delta[:, None] + log_trans # (n_states, n_states)
|
||||
psi[t] = np.argmax(scores, axis=0)
|
||||
delta = scores[psi[t], np.arange(n_states)] + log_emit[:, t]
|
||||
|
||||
# Backtrack
|
||||
path = np.zeros(n_obs, dtype=np.int64)
|
||||
path[-1] = np.argmax(delta)
|
||||
for t in range(n_obs - 2, -1, -1):
|
||||
path[t] = psi[t + 1, path[t + 1]]
|
||||
return path
|
||||
|
||||
|
||||
def to_viterbi_f0(hidden: torch.Tensor, thread: float = 0.03) -> np.ndarray:
|
||||
"""Decode hidden representation to F0 via Viterbi.
|
||||
|
||||
Uses a hand-written numpy Viterbi decoder (replacing
|
||||
``librosa.sequence.viterbi``) to avoid the librosa dependency.
|
||||
"""
|
||||
if not hasattr(to_viterbi_f0, "_transition"):
|
||||
xx, yy = np.meshgrid(range(_N_CLASS), range(_N_CLASS))
|
||||
transition = np.maximum(30 - abs(xx - yy), 0)
|
||||
transition = transition / transition.sum(axis=1, keepdims=True)
|
||||
to_viterbi_f0._transition = transition # type: ignore[attr-defined]
|
||||
|
||||
prob = hidden.squeeze(0).cpu().numpy()
|
||||
prob = prob.T
|
||||
prob = prob / prob.sum(axis=0, keepdims=True)
|
||||
|
||||
path = numpy_viterbi(prob, to_viterbi_f0._transition) # type: ignore[attr-defined]
|
||||
center = torch.from_numpy(path).unsqueeze(0).unsqueeze(-1).to(hidden.device)
|
||||
return to_local_average_f0(hidden, center=center, thread=thread)
|
||||
|
||||
|
||||
def resample_align_curve(
|
||||
points: np.ndarray, original_timestep: float, target_timestep: float, align_length: int = -1
|
||||
) -> np.ndarray:
|
||||
"""Align a curve from one time grid to another via linear interpolation."""
|
||||
t_max = (len(points) - 1) * original_timestep
|
||||
curve_interp = np.interp(
|
||||
np.arange(0, t_max, target_timestep),
|
||||
original_timestep * np.arange(len(points)),
|
||||
points,
|
||||
).astype(points.dtype)
|
||||
if align_length > 0:
|
||||
if len(curve_interp) > align_length:
|
||||
curve_interp = curve_interp[:align_length]
|
||||
elif len(curve_interp) < align_length:
|
||||
curve_interp = np.concatenate(
|
||||
[curve_interp, np.full(align_length - len(curve_interp), fill_value=curve_interp[-1])],
|
||||
axis=0,
|
||||
)
|
||||
return curve_interp
|
||||
|
||||
|
||||
class RMVPE(nn.Module, SupportAudioInput, SupportsComponentDiscovery):
|
||||
"""RMVPE F0 extractor (SoulX-Singer).
|
||||
|
||||
Wraps the E2E0 model with mel-spectrogram front-end and decoding
|
||||
post-processing.
|
||||
"""
|
||||
|
||||
support_audio_input: ClassVar[bool] = True
|
||||
_dit_modules: ClassVar[list[str]] = []
|
||||
_encoder_modules: ClassVar[list[str]] = []
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = ["."]
|
||||
_layerwise_offload_blocks_attrs: ClassVar[list[str]] = []
|
||||
|
||||
def __init__(self, model_path: str | None = None, hop_length: int = 160, device: str | None = None):
|
||||
super().__init__()
|
||||
self.resample_kernel: dict[str, Resample] = {}
|
||||
if device is None:
|
||||
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
else:
|
||||
self.device = torch.device(device)
|
||||
|
||||
self.model = E2E0(4, 1, (2, 2)).eval()
|
||||
if model_path is not None:
|
||||
ckpt = torch.load(model_path, map_location=self.device)
|
||||
state_dict = ckpt if not isinstance(ckpt, dict) else ckpt.get("model", ckpt)
|
||||
self.model.load_state_dict(state_dict, strict=False)
|
||||
logger.info("Loaded RMVPE weights from %s", model_path)
|
||||
self.model = self.model.to(self.device)
|
||||
|
||||
self.mel_extractor = MelSpectrogram(
|
||||
_N_MELS,
|
||||
RMVPE_SAMPLE_RATE,
|
||||
_WINDOW_LENGTH,
|
||||
hop_length,
|
||||
None,
|
||||
_MEL_FMIN,
|
||||
_MEL_FMAX,
|
||||
).to(self.device)
|
||||
self.hop_length = hop_length
|
||||
|
||||
# ---- internal helpers ----
|
||||
|
||||
@torch.no_grad()
|
||||
def mel2hidden(self, mel: torch.Tensor) -> torch.Tensor:
|
||||
n_frames = mel.shape[-1]
|
||||
pad_len = 32 * ((n_frames - 1) // 32 + 1) - n_frames
|
||||
mel = F.pad(mel, (0, pad_len), mode="constant")
|
||||
hidden = self.model(mel)
|
||||
return hidden[:, :n_frames]
|
||||
|
||||
def decode(self, hidden: torch.Tensor, thread: float = 0.03, use_viterbi: bool = False) -> np.ndarray:
|
||||
if use_viterbi:
|
||||
return to_viterbi_f0(hidden, thread=thread)
|
||||
return to_local_average_f0(hidden, thread=thread)
|
||||
|
||||
def postprocess(self, f0: np.ndarray, fmin: float = 50, fmax: float = 1000, min_gap: int = 2) -> np.ndarray:
|
||||
f0[f0 < fmin] = 0
|
||||
f0[f0 > fmax] = 0
|
||||
# Eliminate glitch: if positive f0 values span fewer than min_gap frames
|
||||
# between zeros, zero them out.
|
||||
for idx in range(f0.shape[0] - min_gap - 1):
|
||||
if f0[idx] == 0 and f0[idx + min_gap + 1] == 0 and np.sum(f0[idx : idx + min_gap + 2]) > 0:
|
||||
f0[idx : idx + min_gap + 2] = 0
|
||||
return f0
|
||||
|
||||
# ---- single audio inference ----
|
||||
|
||||
def infer_from_audio(
|
||||
self, audio: np.ndarray, sample_rate: int = 16000, thread: float = 0.03, use_viterbi: bool = False
|
||||
) -> np.ndarray:
|
||||
audio_t = torch.from_numpy(audio).float().unsqueeze(0).to(self.device)
|
||||
if sample_rate == RMVPE_SAMPLE_RATE:
|
||||
audio_res = audio_t
|
||||
else:
|
||||
key_str = str(sample_rate)
|
||||
if key_str not in self.resample_kernel:
|
||||
self.resample_kernel[key_str] = Resample(sample_rate, RMVPE_SAMPLE_RATE, lowpass_filter_width=128)
|
||||
self.resample_kernel[key_str] = self.resample_kernel[key_str].to(self.device)
|
||||
audio_res = self.resample_kernel[key_str](audio_t)
|
||||
mel = self.mel_extractor(audio_res, center=True)
|
||||
hidden = self.mel2hidden(mel)
|
||||
f0 = self.decode(hidden, thread=thread, use_viterbi=use_viterbi).squeeze(0)
|
||||
return f0
|
||||
|
||||
def get_pitch(
|
||||
self,
|
||||
waveform,
|
||||
sample_rate: int,
|
||||
hop_size: int,
|
||||
length: int,
|
||||
interp_uv: bool = False,
|
||||
fmin: float = 50,
|
||||
fmax: float = 1000,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
f0 = self.infer_from_audio(waveform, sample_rate=sample_rate)
|
||||
f0 = self.postprocess(f0, fmin, fmax)
|
||||
uv = f0 == 0
|
||||
time_step = hop_size / sample_rate
|
||||
f0_res = resample_align_curve(f0, 0.01, time_step, length)
|
||||
uv_res = resample_align_curve(uv.astype(np.float32), 0.01, time_step, length) > 0.5
|
||||
if not interp_uv:
|
||||
f0_res[uv_res] = 0
|
||||
return f0_res, uv_res
|
||||
|
||||
# ---- batch audio inference ----
|
||||
|
||||
def infer_from_audio_batch(
|
||||
self, audios, sample_rate: int = 16000, thread: float = 0.03, use_viterbi: bool = False
|
||||
) -> list[np.ndarray]:
|
||||
sizes: list[int] | None = None
|
||||
if isinstance(audios, list):
|
||||
audios = [torch.from_numpy(a).float() for a in audios]
|
||||
sizes = [math.ceil((a.shape[0] + 1) / self.hop_length) for a in audios]
|
||||
audios = nn.utils.rnn.pad_sequence(audios, batch_first=True, padding_value=0.0).to(self.device)
|
||||
elif isinstance(audios, torch.Tensor):
|
||||
if audios.device != self.device:
|
||||
audios = audios.to(self.device)
|
||||
else:
|
||||
raise NotImplementedError(f"Unsupported audio type: {type(audios)}")
|
||||
|
||||
if sample_rate == RMVPE_SAMPLE_RATE:
|
||||
audios_res = audios
|
||||
else:
|
||||
key_str = str(sample_rate)
|
||||
if key_str not in self.resample_kernel:
|
||||
self.resample_kernel[key_str] = Resample(sample_rate, RMVPE_SAMPLE_RATE, lowpass_filter_width=128)
|
||||
self.resample_kernel[key_str] = self.resample_kernel[key_str].to(self.device)
|
||||
audios_res = self.resample_kernel[key_str](audios)
|
||||
|
||||
mels = self.mel_extractor(audios_res, center=True)
|
||||
hiddens = self.mel2hidden(mels)
|
||||
f0 = self.decode(hiddens, thread=thread, use_viterbi=use_viterbi)
|
||||
|
||||
f0s: list[np.ndarray] = []
|
||||
for i in range(f0.shape[0]):
|
||||
f0s.append(f0[i, : sizes[i]] if sizes is not None else f0[i, :])
|
||||
return f0s
|
||||
|
||||
def get_pitch_batch(
|
||||
self,
|
||||
waveforms,
|
||||
sample_rate: int,
|
||||
hop_size: int,
|
||||
lengths: list[int],
|
||||
interp_uv: bool = False,
|
||||
fmin: float = 50,
|
||||
fmax: float = 1000,
|
||||
) -> tuple[list[np.ndarray], list[np.ndarray]]:
|
||||
f0s = self.infer_from_audio_batch(waveforms, sample_rate=sample_rate)
|
||||
f0s_res: list[np.ndarray] = []
|
||||
uvs_res: list[np.ndarray] = []
|
||||
for idx, f0 in enumerate(f0s):
|
||||
f0 = self.postprocess(f0, fmin, fmax, min_gap=6)
|
||||
uv = f0 == 0
|
||||
length = lengths[idx]
|
||||
time_step = hop_size / sample_rate
|
||||
f0_res = resample_align_curve(f0, 0.01, time_step, length)
|
||||
uv_res = resample_align_curve(uv.astype(np.float32), 0.01, time_step, length) > 0.5
|
||||
if not interp_uv:
|
||||
f0_res[uv_res] = 0
|
||||
f0s_res.append(f0_res)
|
||||
uvs_res.append(uv_res)
|
||||
return f0s_res, uvs_res
|
||||
|
||||
def release_cuda(self):
|
||||
self.model = self.model.cpu()
|
||||
self.mel_extractor = self.mel_extractor.cpu()
|
||||
@@ -0,0 +1,619 @@
|
||||
"""ROSVOT note transcription."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.models.interface import SupportAudioInput, SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.models.soulx_singer.modules.mel_transform import spectral_normalize_torch
|
||||
from vllm_omni.diffusion.models.soulx_singer.modules.note_transcription import (
|
||||
BackboneNet,
|
||||
ConvBlocks,
|
||||
Embedding,
|
||||
)
|
||||
from vllm_omni.diffusion.models.soulx_singer.modules.preprocess.utils import (
|
||||
boundary2Interval,
|
||||
denorm_f0,
|
||||
f0_to_coarse,
|
||||
load_model_ckpt,
|
||||
load_mono_audio,
|
||||
load_rosvot_config,
|
||||
norm_interp_f0,
|
||||
pad_or_cut_xd,
|
||||
resample_mono,
|
||||
)
|
||||
from vllm_omni.utils.audio import mel_filter_bank as librosa_mel_fn
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def regulate_real_note_itv(
|
||||
note_itv: np.ndarray,
|
||||
note_bd: np.ndarray,
|
||||
word_bd: np.ndarray,
|
||||
word_durs: np.ndarray,
|
||||
hop_size: int,
|
||||
audio_sample_rate: int,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
assert note_itv.shape[0] == np.sum(note_bd) + 1
|
||||
assert np.sum(word_bd) <= np.sum(note_bd)
|
||||
assert word_durs.shape[0] == np.sum(word_bd) + 1, f"{word_durs.shape[0]} {np.sum(word_bd) + 1}"
|
||||
word_bd = np.cumsum(word_bd) * word_bd
|
||||
word_itv = np.zeros((word_durs.shape[0], 2))
|
||||
word_offsets = np.cumsum(word_durs)
|
||||
note2words = np.zeros(note_itv.shape[0], dtype=int)
|
||||
for idx in range(len(word_offsets) - 1):
|
||||
word_itv[idx, 1] = word_itv[idx + 1, 0] = word_offsets[idx]
|
||||
word_itv[-1, 1] = word_offsets[-1]
|
||||
note_itv_secs = note_itv * hop_size / audio_sample_rate
|
||||
for idx, itv in enumerate(note_itv):
|
||||
start_idx, end_idx = itv
|
||||
if word_bd[start_idx] > 0:
|
||||
word_dur_idx = word_bd[start_idx]
|
||||
note_itv_secs[idx, 0] = word_itv[word_dur_idx, 0]
|
||||
note2words[idx] = word_dur_idx
|
||||
if word_bd[end_idx] > 0:
|
||||
word_dur_idx = word_bd[end_idx] - 1
|
||||
note_itv_secs[idx, 1] = word_itv[word_dur_idx, 1]
|
||||
note2words[idx] = word_dur_idx
|
||||
note2words += 1
|
||||
return note_itv_secs, note2words
|
||||
|
||||
|
||||
def regulate_ill_slur(
|
||||
notes: np.ndarray, note_itv: np.ndarray, note2words: np.ndarray
|
||||
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
res_note2words: list[int] = []
|
||||
res_note_itv: list[list[float]] = []
|
||||
res_notes: list[int] = []
|
||||
note_idx = 0
|
||||
note_idx_end = 0
|
||||
while note_idx <= len(notes) - 1:
|
||||
while note_idx <= note_idx_end < len(notes) and note2words[note_idx] == note2words[note_idx_end]:
|
||||
note_idx_end += 1
|
||||
res_note2words.append(note2words[note_idx])
|
||||
res_note_itv.append(note_itv[note_idx].tolist())
|
||||
res_notes.append(notes[note_idx])
|
||||
for idx in range(note_idx + 1, note_idx_end):
|
||||
if notes[idx] == notes[idx - 1]:
|
||||
res_note_itv[-1][1] = note_itv[idx][1]
|
||||
else:
|
||||
res_note_itv.append(note_itv[idx].tolist())
|
||||
res_note2words.append(note2words[idx])
|
||||
res_notes.append(notes[idx])
|
||||
note_idx = note_idx_end
|
||||
return (
|
||||
np.array(res_notes, dtype=notes.dtype),
|
||||
np.array(res_note_itv, dtype=note_itv.dtype),
|
||||
np.array(res_note2words, dtype=note2words.dtype),
|
||||
)
|
||||
|
||||
|
||||
def regulate_boundary(bd_logits, threshold, min_gap=18, ref_bd=None, ref_bd_min_gap=8, non_padding=None):
|
||||
# this doesn't preserve gradient
|
||||
device = bd_logits.device
|
||||
bd_logits = torch.sigmoid(bd_logits).data.cpu()
|
||||
# bd_logits[0] = bd_logits[-1] = 1e-5 # avoid itv invalid problem
|
||||
bd = (bd_logits > threshold).long()
|
||||
bd_res = torch.zeros_like(bd).long()
|
||||
for i in range(bd.shape[0]):
|
||||
bd_i = bd[i]
|
||||
last_bd_idx = -1
|
||||
start = -1
|
||||
for j in range(bd_i.shape[0]):
|
||||
if bd_i[j] == 1:
|
||||
if 0 <= start < j:
|
||||
continue
|
||||
elif start < 0:
|
||||
start = j
|
||||
else:
|
||||
if 0 <= start < j:
|
||||
if j - 1 > start:
|
||||
bd_idx = start + int(torch.argmax(bd_logits[i, start:j]).item())
|
||||
else:
|
||||
bd_idx = start
|
||||
if bd_idx - last_bd_idx < min_gap and last_bd_idx > 0:
|
||||
bd_idx = round((bd_idx + last_bd_idx) / 2)
|
||||
bd_res[i, last_bd_idx] = 0
|
||||
bd_res[i, bd_idx] = 1
|
||||
last_bd_idx = bd_idx
|
||||
start = -1
|
||||
|
||||
# assert ref_bd_min_gap <= min_gap // 2
|
||||
if ref_bd is not None and ref_bd_min_gap > 0:
|
||||
ref = ref_bd.data.cpu()
|
||||
for i in range(bd_res.shape[0]):
|
||||
ref_bd_i = ref[i]
|
||||
ref_bd_i_js = []
|
||||
for j in range(ref_bd_i.shape[0]):
|
||||
if ref_bd_i[j] == 1:
|
||||
ref_bd_i_js.append(j)
|
||||
seg_sum = torch.sum(bd_res[i, max(0, j - ref_bd_min_gap) : j + ref_bd_min_gap])
|
||||
if seg_sum == 0:
|
||||
bd_res[i, j] = 1
|
||||
elif seg_sum == 1 and bd_res[i, j] != 1:
|
||||
bd_res[i, max(0, j - ref_bd_min_gap) : j + ref_bd_min_gap] = ref_bd_i[
|
||||
max(0, j - ref_bd_min_gap) : j + ref_bd_min_gap
|
||||
]
|
||||
elif seg_sum > 1:
|
||||
for k in range(1, ref_bd_min_gap + 1):
|
||||
if bd_res[i, max(0, j - k)] == 1 and ref_bd_i[max(0, j - k)] != 1:
|
||||
bd_res[i, max(0, j - k)] = 0
|
||||
break
|
||||
if (
|
||||
bd_res[i, min(bd_res.shape[1] - 1, j + k)] == 1
|
||||
and ref_bd_i[min(bd_res.shape[1] - 1, j + k)] != 1
|
||||
):
|
||||
bd_res[i, min(bd_res.shape[1] - 1, j + k)] = 0
|
||||
break
|
||||
bd_res[i, j] = 1
|
||||
# final check
|
||||
assert torch.sum(bd_res[i, ref_bd_i_js]) == len(ref_bd_i_js), (
|
||||
f"{torch.sum(bd_res[i, ref_bd_i_js])} {len(ref_bd_i_js)}"
|
||||
)
|
||||
|
||||
bd_res = bd_res.to(device)
|
||||
|
||||
# force valid begin and end
|
||||
bd_res[:, 0] = 0
|
||||
if non_padding is not None:
|
||||
for i in range(bd_res.shape[0]):
|
||||
bd_res[i, sum(non_padding[i]) - 1 :] = 0
|
||||
else:
|
||||
bd_res[:, -1] = 0
|
||||
|
||||
return bd_res
|
||||
|
||||
|
||||
def _align_word(word_durs: list[float], mel_len: int, hop_size: int, audio_sample_rate: int) -> np.ndarray:
|
||||
mel2word = np.zeros([mel_len], int)
|
||||
start_time = 0.0
|
||||
for i_word, wd in enumerate(word_durs):
|
||||
start_frame = int(start_time * audio_sample_rate / hop_size + 0.5)
|
||||
end_frame = int((start_time + wd) * audio_sample_rate / hop_size + 0.5)
|
||||
mel2word[start_frame:end_frame] = i_word + 1
|
||||
start_time += wd
|
||||
return mel2word
|
||||
|
||||
|
||||
class PitchDecoder(nn.Module):
|
||||
def __init__(self, hparams):
|
||||
super().__init__()
|
||||
self.hidden_size = hidden_size = hparams["hidden_size"]
|
||||
self.dropout = hparams.get("dropout", 0.0)
|
||||
self.note_bd_out = nn.Linear(hidden_size, 1)
|
||||
self.note_bd_temperature = max(1e-7, hparams.get("note_bd_temperature", 1.0))
|
||||
|
||||
# note prediction
|
||||
self.pitch_attn_num_head = hparams.get("pitch_attn_num_head", 1)
|
||||
self.multihead_dot_attn = nn.Linear(hidden_size, self.pitch_attn_num_head)
|
||||
self.post = ConvBlocks(
|
||||
hidden_size,
|
||||
out_dims=hidden_size,
|
||||
dilations=None,
|
||||
kernel_size=3,
|
||||
layers_in_block=1,
|
||||
c_multiple=1,
|
||||
post_net_kernel=3,
|
||||
)
|
||||
self.pitch_out = nn.Linear(hidden_size, hparams.get("note_num", 100) + 4)
|
||||
self.note_num = hparams.get("note_num", 100)
|
||||
self.note_start = hparams.get("note_start", 30)
|
||||
self.pitch_temperature = max(1e-7, hparams.get("note_pitch_temperature", 1.0))
|
||||
|
||||
def forward(self, feat, note_bd, train=True):
|
||||
bsz, T, _ = feat.shape
|
||||
|
||||
attn = torch.sigmoid(self.multihead_dot_attn(feat)) # [B, T, C] -> [B, T, num_head]
|
||||
attn_feat = feat.unsqueeze(3) * attn.unsqueeze(2) # [B, T, C, 1] x [B, T, 1, num_head] -> [B, T, C, num_head]
|
||||
attn_feat = torch.mean(attn_feat, dim=-1) # [B, T, C, num_head] -> [B, T, C]
|
||||
mel2note = torch.cumsum(note_bd, 1)
|
||||
note_length = torch.max(torch.sum(note_bd, dim=1)).item() + 1 # max length
|
||||
note_lengths = torch.sum(note_bd, dim=1) + 1 # [B]
|
||||
|
||||
attn = torch.mean(attn, dim=-1, keepdim=True) # [B, T, num_head] -> [B, T, 1]
|
||||
denom = mel2note.new_zeros(bsz, note_length, dtype=attn.dtype).scatter_add_(
|
||||
dim=1, index=mel2note, src=attn.squeeze(-1)
|
||||
) # [B, T] -> [B, note_length] count the note frames of each note (with padding excluded)
|
||||
frame2note = mel2note.unsqueeze(-1).repeat(1, 1, self.hidden_size) # [B, T] -> [B, T, C], with padding included
|
||||
note_aggregate = frame2note.new_zeros(bsz, note_length, self.hidden_size, dtype=attn_feat.dtype).scatter_add_(
|
||||
dim=1, index=frame2note, src=attn_feat
|
||||
) # [B, T, C] -> [B, note_length, C]
|
||||
note_aggregate = note_aggregate / (denom.unsqueeze(-1) + 1e-5)
|
||||
note_logits = self.post(note_aggregate)
|
||||
note_logits = self.pitch_out(note_logits) / self.pitch_temperature
|
||||
# note_logits = torch.clamp(note_logits, min=-16., max=16.) # don't know need it or not
|
||||
|
||||
note_pred = torch.softmax(note_logits, dim=-1) # [B, note_length, note_num]
|
||||
note_pred = torch.argmax(note_pred, dim=-1) # [B, note_length]
|
||||
# for some reason, note idx maybe 130 (why?)
|
||||
note_pred[note_pred > self.note_num] = 0
|
||||
note_pred[note_pred < self.note_start] = 0
|
||||
|
||||
return note_lengths, note_logits, note_pred
|
||||
|
||||
|
||||
class MidiExtractor(nn.Module):
|
||||
def __init__(self, hparams):
|
||||
super().__init__()
|
||||
self.hparams = hparams.copy()
|
||||
self.hidden_size = hidden_size = hparams["hidden_size"]
|
||||
self.note_bd_threshold = hparams.get("note_bd_threshold", 0.5)
|
||||
self.note_bd_min_gap = round(
|
||||
hparams.get("note_bd_min_gap", 100) * hparams["audio_sample_rate"] / 1000 / hparams["hop_size"]
|
||||
)
|
||||
self.note_bd_ref_min_gap = round(
|
||||
hparams.get("note_bd_ref_min_gap", 50) * hparams["audio_sample_rate"] / 1000 / hparams["hop_size"]
|
||||
)
|
||||
|
||||
self.mel_proj = nn.Conv1d(hparams["use_mel_bins"], hidden_size, kernel_size=3, padding=1)
|
||||
self.mel_encoder = ConvBlocks(
|
||||
hidden_size,
|
||||
out_dims=hidden_size,
|
||||
dilations=None,
|
||||
kernel_size=3,
|
||||
layers_in_block=2,
|
||||
c_multiple=1,
|
||||
post_net_kernel=3,
|
||||
)
|
||||
self.use_pitch = hparams.get("use_pitch_embed", True)
|
||||
if self.use_pitch:
|
||||
self.pitch_embed = Embedding(300, hidden_size, 0, "kaiming")
|
||||
self.uv_embed = Embedding(3, hidden_size, 0, "kaiming")
|
||||
self.use_wbd = hparams.get("use_wbd", True)
|
||||
if self.use_wbd:
|
||||
self.word_bd_embed = Embedding(3, hidden_size, 0, "kaiming")
|
||||
self.cond_encoder = ConvBlocks(
|
||||
hidden_size,
|
||||
out_dims=hidden_size,
|
||||
dilations=None,
|
||||
kernel_size=3,
|
||||
layers_in_block=1,
|
||||
c_multiple=1,
|
||||
post_net_kernel=3,
|
||||
)
|
||||
|
||||
# backbone
|
||||
self.net = BackboneNet(hparams)
|
||||
|
||||
# note bd prediction
|
||||
self.note_bd_out = nn.Linear(hidden_size, 1)
|
||||
self.note_bd_temperature = max(1e-7, hparams.get("note_bd_temperature", 1.0))
|
||||
|
||||
# note prediction
|
||||
self.pitch_decoder = PitchDecoder(hparams)
|
||||
|
||||
def run_encoder(self, mel, word_bd=None, pitch=None, uv=None):
|
||||
mel_embed = self.mel_proj(mel.transpose(1, 2)).transpose(1, 2)
|
||||
mel_embed = self.mel_encoder(mel_embed)
|
||||
pitch_embed = word_bd_embed = 0
|
||||
if self.use_pitch and pitch is not None and uv is not None:
|
||||
pitch_embed = self.pitch_embed(pitch) + self.uv_embed(uv) # [B, T, C]
|
||||
if self.use_wbd and word_bd is not None:
|
||||
word_bd_embed = self.word_bd_embed(word_bd)
|
||||
feat = self.cond_encoder(mel_embed + pitch_embed + word_bd_embed)
|
||||
return feat
|
||||
|
||||
def forward(self, mel, word_bd=None, note_bd=None, pitch=None, uv=None, non_padding=None, train=True):
|
||||
ret = {}
|
||||
bsz, T, _ = mel.shape
|
||||
|
||||
feat = self.run_encoder(mel, word_bd, pitch, uv)
|
||||
feat = self.net(feat) # [B, T, C]
|
||||
|
||||
# note bd prediction
|
||||
# dropout has been dropped (inference mode)
|
||||
note_bd_logits = self.note_bd_out(feat).squeeze(-1) / self.note_bd_temperature
|
||||
note_bd_logits = torch.clamp(note_bd_logits, min=-16.0, max=16.0)
|
||||
ret["note_bd_logits"] = note_bd_logits # [B, T]
|
||||
if note_bd is None or not train:
|
||||
note_bd = regulate_boundary(
|
||||
note_bd_logits,
|
||||
self.note_bd_threshold,
|
||||
self.note_bd_min_gap,
|
||||
word_bd,
|
||||
self.note_bd_ref_min_gap,
|
||||
non_padding,
|
||||
)
|
||||
ret["note_bd_pred"] = note_bd # [B, T]
|
||||
|
||||
# note pitch prediction
|
||||
note_lengths, note_logits, note_pred = self.pitch_decoder(feat, note_bd, train)
|
||||
ret["note_lengths"], ret["note_logits"], ret["note_pred"] = note_lengths, note_logits, note_pred
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
class MelNet(nn.Module):
|
||||
def __init__(self, hparams, device="cpu") -> None:
|
||||
super().__init__()
|
||||
self.n_fft = hparams["fft_size"]
|
||||
self.num_mels = hparams["audio_num_mel_bins"]
|
||||
self.sampling_rate = hparams["audio_sample_rate"]
|
||||
self.hop_size = hparams["hop_size"]
|
||||
self.win_size = hparams["win_size"]
|
||||
self.fmin = hparams["fmin"]
|
||||
self.fmax = hparams["fmax"]
|
||||
self.device = device
|
||||
|
||||
mel = librosa_mel_fn(
|
||||
sr=self.sampling_rate,
|
||||
n_fft=self.n_fft,
|
||||
n_mels=self.num_mels,
|
||||
fmin=self.fmin,
|
||||
fmax=self.fmax,
|
||||
)
|
||||
self.mel_basis = mel.float().to(self.device)
|
||||
self.hann_window = torch.hann_window(self.win_size).to(self.device)
|
||||
|
||||
def to(self, device, **kwagrs):
|
||||
super().to(device=device, **kwagrs)
|
||||
self.mel_basis = self.mel_basis.to(device)
|
||||
self.hann_window = self.hann_window.to(device)
|
||||
self.device = device
|
||||
|
||||
def forward(self, y, center=False, complex=False):
|
||||
if isinstance(y, np.ndarray):
|
||||
y = torch.FloatTensor(y)
|
||||
if len(y.shape) == 1:
|
||||
y = y.unsqueeze(0)
|
||||
y = y.clamp(min=-1.0, max=1.0).to(self.device)
|
||||
|
||||
pad_length = math.ceil(y.shape[1] / self.hop_size) * self.hop_size - y.shape[1]
|
||||
y = torch.nn.functional.pad(
|
||||
y.unsqueeze(1),
|
||||
[int((self.n_fft - self.hop_size) / 2), int((self.n_fft - self.hop_size) / 2 + pad_length)],
|
||||
mode="reflect",
|
||||
)
|
||||
y = y.squeeze(1)
|
||||
|
||||
spec = torch.stft(
|
||||
y,
|
||||
self.n_fft,
|
||||
hop_length=self.hop_size,
|
||||
win_length=self.win_size,
|
||||
window=self.hann_window,
|
||||
center=center,
|
||||
pad_mode="reflect",
|
||||
normalized=False,
|
||||
onesided=True,
|
||||
return_complex=True,
|
||||
)
|
||||
if not complex:
|
||||
spec = torch.view_as_real(spec)
|
||||
spec = torch.sqrt(spec.pow(2).sum(-1) + (1e-9)) # [B, n_fft, T]
|
||||
spec = torch.matmul(self.mel_basis, spec)
|
||||
spec = spectral_normalize_torch(spec)
|
||||
spec = spec.transpose(1, 2) # [B, T, n_fft]
|
||||
else:
|
||||
B, C, T, _ = spec.shape
|
||||
spec = spec.transpose(1, 2) # [B, T, n_fft, 2]
|
||||
return spec
|
||||
|
||||
|
||||
class RosvotModel(nn.Module, SupportAudioInput, SupportsComponentDiscovery):
|
||||
support_audio_input: ClassVar[bool] = True
|
||||
_dit_modules: ClassVar[list[str]] = []
|
||||
_encoder_modules: ClassVar[list[str]] = ["."]
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
_layerwise_offload_blocks_attrs: ClassVar[list[str]] = ["midi.net", "midi.pitch_decoder", "midi.cond_encoder"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rosvot_ckpt: str | Path,
|
||||
*,
|
||||
config_path: str | Path = "",
|
||||
pe: nn.Module | None = None,
|
||||
the: float = 0.85,
|
||||
verbose: bool = False,
|
||||
rosvot_source_dir: str | Path | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.verbose = verbose
|
||||
ckpt = Path(rosvot_ckpt)
|
||||
resolved_config = Path(config_path) if config_path else ckpt.with_name("config.yaml")
|
||||
self.hparams = load_rosvot_config(resolved_config, hparams_str=f"note_bd_threshold={the}")
|
||||
if verbose:
|
||||
logger.info("ROSVOT config: %s", resolved_config)
|
||||
|
||||
self.midi = MidiExtractor(self.hparams)
|
||||
self.mel_net = MelNet(self.hparams)
|
||||
self.pe = pe if pe is not None and self.hparams.get("use_pitch_embed", False) else None
|
||||
self._checkpoint_path = str(ckpt)
|
||||
self.load_checkpoint(str(ckpt), verbose=verbose)
|
||||
self.eval()
|
||||
|
||||
def load_checkpoint(self, checkpoint_path: str | None = None, *, verbose: bool = False) -> None:
|
||||
load_model_ckpt(self.midi, checkpoint_path or self._checkpoint_path, verbose=verbose)
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, wav: torch.Tensor, word_durs: list[float]) -> dict[str, Any]:
|
||||
hparams = self.hparams
|
||||
if wav.ndim == 1:
|
||||
wav = wav.unsqueeze(0)
|
||||
|
||||
mel_len = (wav.shape[-1] + hparams["hop_size"] - 1) // hparams["hop_size"]
|
||||
min_word_dur = hparams.get("min_word_dur", 20) / 1000
|
||||
wd_raw = list(word_durs)
|
||||
word_durs_filtered: list[float] = []
|
||||
for i, wd in enumerate(wd_raw):
|
||||
if wd < min_word_dur:
|
||||
if i == 0 and len(wd_raw) > 1:
|
||||
wd_raw[i + 1] += wd
|
||||
elif word_durs_filtered:
|
||||
word_durs_filtered[-1] += wd
|
||||
else:
|
||||
word_durs_filtered.append(wd)
|
||||
|
||||
mel2word = _align_word(word_durs_filtered, mel_len, hparams["hop_size"], hparams["audio_sample_rate"])
|
||||
if mel2word.size > 0 and mel2word[0] == 0:
|
||||
mel2word = mel2word + 1
|
||||
|
||||
real_len = min(mel_len, int(np.sum(mel2word > 0)))
|
||||
T = math.ceil(min(real_len, hparams["max_frames"]) / hparams["frames_multiple"]) * hparams["frames_multiple"]
|
||||
device = wav.device
|
||||
self.mel_net.to(device)
|
||||
wav_t = pad_or_cut_xd(wav.float(), T * hparams["hop_size"], 1)
|
||||
|
||||
pitch_coarse = uv_t = None
|
||||
if self.pe is not None:
|
||||
f0s, uvs = self.pe.get_pitch_batch(
|
||||
wav_t,
|
||||
sample_rate=hparams["audio_sample_rate"],
|
||||
hop_size=hparams["hop_size"],
|
||||
lengths=[real_len],
|
||||
fmax=hparams["f0_max"],
|
||||
fmin=hparams["f0_min"],
|
||||
)
|
||||
f0_1d, uv_1d = norm_interp_f0(f0s[0][:T])
|
||||
f0_t = pad_or_cut_xd(torch.as_tensor(f0_1d, device=device, dtype=torch.float32), T, 0).unsqueeze(0)
|
||||
uv_t = pad_or_cut_xd(torch.as_tensor(uv_1d, device=device, dtype=torch.float32), T, 0).long().unsqueeze(0)
|
||||
pitch_coarse = f0_to_coarse(denorm_f0(f0_t, uv_t)).to(device)
|
||||
|
||||
mel = pad_or_cut_xd(self.mel_net(wav_t)[0], T, dim=0).unsqueeze(0)
|
||||
mel_nonpadding_mask = torch.zeros(1, T, device=device)
|
||||
mel_nonpadding_mask[:, :real_len] = 1.0
|
||||
mel = (mel.transpose(1, 2) * mel_nonpadding_mask.unsqueeze(1)).transpose(1, 2)
|
||||
mel_nonpadding = mel.abs().sum(-1) > 0
|
||||
|
||||
mel2word_t = pad_or_cut_xd(torch.as_tensor(mel2word, device=device, dtype=torch.long), T, 0)
|
||||
word_bd = torch.zeros_like(mel2word_t)
|
||||
word_bd[1:] = (mel2word_t[1:] != mel2word_t[:-1]).long()
|
||||
word_bd[real_len:] = 0
|
||||
word_bd = word_bd.unsqueeze(0)
|
||||
|
||||
outputs = self.midi(
|
||||
mel=mel[:, :, : hparams.get("use_mel_bins", 80)],
|
||||
word_bd=word_bd,
|
||||
pitch=pitch_coarse,
|
||||
uv=uv_t,
|
||||
non_padding=mel_nonpadding,
|
||||
)
|
||||
outputs["word_durs_filtered"] = word_durs_filtered
|
||||
outputs["real_len"] = real_len
|
||||
outputs["word_bd"] = word_bd
|
||||
return outputs
|
||||
|
||||
@staticmethod
|
||||
def _load_wav(wav_src: str | np.ndarray, sample_rate: int, *, src_sample_rate: int | None = None) -> np.ndarray:
|
||||
if isinstance(wav_src, str):
|
||||
wav, _ = load_mono_audio(wav_src, target_sr=sample_rate)
|
||||
return wav
|
||||
wav = np.asarray(wav_src, dtype=np.float32)
|
||||
if src_sample_rate is not None and src_sample_rate != sample_rate:
|
||||
wav = resample_mono(wav, orig_sr=src_sample_rate, target_sr=sample_rate)
|
||||
return wav
|
||||
|
||||
@staticmethod
|
||||
def _normalize_note2words(note2words: list[int]) -> list[int]:
|
||||
if not note2words:
|
||||
return []
|
||||
out = [note2words[0]]
|
||||
for idx in range(1, len(note2words)):
|
||||
out.append(max(note2words[idx], out[-1]))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _build_ep_types(note2words: list[int], align_words: list[str]) -> list[int]:
|
||||
ep_types: list[int] = []
|
||||
prev = -1
|
||||
for i, w in zip(note2words, align_words):
|
||||
ep_types.append(1 if w == "<SP>" else (2 if i != prev else 3))
|
||||
prev = i
|
||||
return ep_types
|
||||
|
||||
@torch.no_grad()
|
||||
def transcribe(
|
||||
self,
|
||||
item: dict[str, Any],
|
||||
*,
|
||||
segment_info: dict[str, Any] | None = None,
|
||||
verbose: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
if "word_durs" not in item:
|
||||
raise ValueError('item must contain "word_durs" from lyric transcription')
|
||||
|
||||
if item.get("wav_fn"):
|
||||
wav = self._load_wav(item["wav_fn"], self.hparams["audio_sample_rate"])
|
||||
elif item.get("wav") is not None:
|
||||
wav = self._load_wav(
|
||||
item["wav"],
|
||||
self.hparams["audio_sample_rate"],
|
||||
src_sample_rate=item.get("sample_rate"),
|
||||
)
|
||||
else:
|
||||
raise ValueError('item must contain "wav_fn" or "wav"')
|
||||
|
||||
device = next(self.parameters()).device
|
||||
outputs = self(torch.from_numpy(wav).float().to(device), list(item["word_durs"]))
|
||||
real_len = int(outputs["real_len"])
|
||||
word_durs_filtered = outputs["word_durs_filtered"]
|
||||
word_bd = outputs["word_bd"]
|
||||
item_name = item.get("item_name", "")
|
||||
|
||||
note_lengths = outputs["note_lengths"].detach().cpu().numpy()
|
||||
note_bd_pred = outputs["note_bd_pred"][0].detach().cpu().numpy()[:real_len]
|
||||
note_pred = outputs["note_pred"][0].detach().cpu().numpy()[: note_lengths[0]]
|
||||
|
||||
if note_pred.shape == (0,):
|
||||
rosvot_out = {"item_name": item_name, "pitches": [], "note_durs": [], "note2words": None}
|
||||
else:
|
||||
note_itv_pred = boundary2Interval(note_bd_pred)
|
||||
word_bd_for_reg = word_bd[0].detach().cpu().numpy()[:real_len]
|
||||
hop = self.hparams["hop_size"]
|
||||
sr = self.hparams["audio_sample_rate"]
|
||||
|
||||
if self.hparams.get("infer_regulate_real_note_itv", True):
|
||||
try:
|
||||
note_itv_pred_secs, note2words = regulate_real_note_itv(
|
||||
note_itv_pred,
|
||||
note_bd_pred,
|
||||
word_bd_for_reg,
|
||||
np.array(word_durs_filtered),
|
||||
hop,
|
||||
sr,
|
||||
)
|
||||
note_pred, note_itv_pred_secs, note2words = regulate_ill_slur(
|
||||
note_pred, note_itv_pred_secs, note2words
|
||||
)
|
||||
except Exception:
|
||||
if verbose:
|
||||
logger.exception("ROSVOT postprocess failed")
|
||||
note_itv_pred_secs = note_itv_pred * hop / sr
|
||||
note2words = None
|
||||
else:
|
||||
note_itv_pred_secs = note_itv_pred * hop / sr
|
||||
note2words = None
|
||||
|
||||
rosvot_out = {
|
||||
"item_name": item_name,
|
||||
"pitches": note_pred.tolist(),
|
||||
"note_durs": [float(itv[1] - itv[0]) for itv in note_itv_pred_secs],
|
||||
"note2words": note2words.tolist() if note2words is not None else None,
|
||||
}
|
||||
|
||||
note2words_raw = rosvot_out.get("note2words") or []
|
||||
align_words = [item["words"][idx - 1] for idx in note2words_raw if 0 < idx <= len(item["words"])]
|
||||
ep_types = self._build_ep_types(self._normalize_note2words(note2words_raw), align_words) if align_words else []
|
||||
seg = segment_info or item
|
||||
|
||||
return {
|
||||
"item_name": seg.get("item_name", item_name),
|
||||
"wav_fn": seg.get("wav_fn", item.get("wav_fn", "")),
|
||||
"origin_wav_fn": seg.get("origin_wav_fn", item.get("origin_wav_fn", "")),
|
||||
"start_time_ms": seg.get("start_time_ms", ""),
|
||||
"end_time_ms": seg.get("end_time_ms", ""),
|
||||
"language": item.get("language", ""),
|
||||
"note_text": align_words,
|
||||
"note_dur": rosvot_out.get("note_durs", []),
|
||||
"note_type": ep_types,
|
||||
"note_pitch": rosvot_out.get("pitches", []),
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
"""Rule-based vocal segmentation from F0 contour (no neural net)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.models.interface import SupportAudioInput, SupportsComponentDiscovery
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VocalSegmentConfig:
|
||||
hop_ms: int = 20
|
||||
smooth_ms: int = 200
|
||||
start_ms: int = 120
|
||||
end_ms: int = 200
|
||||
prepad_ms: int = 80
|
||||
postpad_ms: int = 120
|
||||
min_len_ms: int = 1000
|
||||
max_len_ms: int = 20000
|
||||
short_seg_merge_gap_ms: int = 8000
|
||||
small_gap_ms: int = 500
|
||||
lookback_ms: int = 200
|
||||
lookahead_ms: int = 100
|
||||
|
||||
|
||||
def _moving_average(x: np.ndarray, win: int) -> np.ndarray:
|
||||
if win <= 1:
|
||||
return x
|
||||
kernel = np.ones(win, dtype=np.float32) / float(win)
|
||||
return np.convolve(x, kernel, mode="same")
|
||||
|
||||
|
||||
def _merge_short_segments(
|
||||
segments_ms: list[list[int]],
|
||||
*,
|
||||
min_len_ms: int,
|
||||
max_len_ms: int,
|
||||
short_seg_merge_gap_ms: int,
|
||||
small_gap_ms: int,
|
||||
) -> list[list[int]]:
|
||||
if not segments_ms:
|
||||
return []
|
||||
|
||||
merged: list[list[int]] = []
|
||||
cur_start, cur_end = segments_ms[0]
|
||||
for next_start, next_end in segments_ms[1:]:
|
||||
cur_len = cur_end - cur_start
|
||||
gap_ms = next_start - cur_end
|
||||
merged_len = next_end - cur_start
|
||||
should_merge = (cur_len < min_len_ms and gap_ms < short_seg_merge_gap_ms) or (
|
||||
gap_ms < small_gap_ms and merged_len < max_len_ms
|
||||
)
|
||||
if should_merge:
|
||||
cur_end = next_end
|
||||
continue
|
||||
if (cur_end - cur_start) >= min_len_ms:
|
||||
merged.append([cur_start, cur_end])
|
||||
cur_start, cur_end = next_start, next_end
|
||||
|
||||
if (cur_end - cur_start) >= min_len_ms:
|
||||
merged.append([cur_start, cur_end])
|
||||
|
||||
if not merged:
|
||||
return segments_ms
|
||||
|
||||
return merged
|
||||
|
||||
|
||||
def _voiced_to_segments(
|
||||
voiced: np.ndarray,
|
||||
*,
|
||||
hop_ms: int,
|
||||
smooth_ms: int,
|
||||
start_ms: int,
|
||||
end_ms: int,
|
||||
prepad_ms: int,
|
||||
postpad_ms: int,
|
||||
max_len_ms: int,
|
||||
) -> list[list[int]]:
|
||||
smooth_frames = max(1, int(round(smooth_ms / hop_ms)))
|
||||
active = _moving_average(voiced.astype(np.float32), smooth_frames) >= 0.5
|
||||
|
||||
segments: list[list[int]] = []
|
||||
start_idx = None
|
||||
start_frames = max(1, int(round(start_ms / hop_ms)))
|
||||
end_frames = max(1, int(round(end_ms / hop_ms)))
|
||||
prepad_frames = max(0, int(round(prepad_ms / hop_ms)))
|
||||
postpad_frames = max(0, int(round(postpad_ms / hop_ms)))
|
||||
active_count = 0
|
||||
inactive_count = 0
|
||||
|
||||
for i, flag in enumerate(active):
|
||||
if flag:
|
||||
active_count += 1
|
||||
inactive_count = 0
|
||||
else:
|
||||
inactive_count += 1
|
||||
active_count = 0
|
||||
|
||||
if start_idx is None:
|
||||
if active_count >= start_frames:
|
||||
start_idx = max(0, i - start_frames + 1 - prepad_frames)
|
||||
else:
|
||||
if inactive_count >= end_frames:
|
||||
end_idx = min(len(active) - 1, i - end_frames + 1 + postpad_frames)
|
||||
start_ms_val = start_idx * hop_ms
|
||||
end_ms_val = end_idx * hop_ms + hop_ms
|
||||
if end_ms_val > start_ms_val:
|
||||
segments.append([int(start_ms_val), int(end_ms_val)])
|
||||
start_idx = None
|
||||
|
||||
if start_idx is not None:
|
||||
start_ms_val = start_idx * hop_ms
|
||||
end_idx = min(len(active) - 1, len(active) - 1 + postpad_frames)
|
||||
end_ms_val = end_idx * hop_ms + hop_ms
|
||||
if end_ms_val > start_ms_val:
|
||||
segments.append([int(start_ms_val), int(end_ms_val)])
|
||||
|
||||
def _split_segment(seg: list[int]) -> list[list[int]]:
|
||||
start_ms_val, end_ms_val = seg
|
||||
start_frame = int(start_ms_val // hop_ms)
|
||||
end_frame = int((end_ms_val - 1) // hop_ms)
|
||||
end_frame = max(start_frame, min(end_frame, len(active) - 1))
|
||||
|
||||
best_start = None
|
||||
best_len = 0
|
||||
cur_start = None
|
||||
cur_len = 0
|
||||
for idx in range(start_frame, end_frame + 1):
|
||||
if not active[idx]:
|
||||
if cur_start is None:
|
||||
cur_start = idx
|
||||
cur_len = 1
|
||||
else:
|
||||
cur_len += 1
|
||||
else:
|
||||
if cur_start is not None and cur_len > best_len:
|
||||
best_start, best_len = cur_start, cur_len
|
||||
cur_start = None
|
||||
cur_len = 0
|
||||
if cur_start is not None and cur_len > best_len:
|
||||
best_start, best_len = cur_start, cur_len
|
||||
|
||||
if best_start is None:
|
||||
split_frame = (start_frame + end_frame) // 2
|
||||
else:
|
||||
split_frame = best_start + best_len // 2
|
||||
|
||||
split_ms = split_frame * hop_ms
|
||||
if split_ms <= start_ms_val:
|
||||
split_ms = start_ms_val + hop_ms
|
||||
if split_ms >= end_ms_val:
|
||||
split_ms = end_ms_val - hop_ms
|
||||
if split_ms <= start_ms_val or split_ms >= end_ms_val:
|
||||
return [seg]
|
||||
return [[start_ms_val, int(split_ms)], [int(split_ms), end_ms_val]]
|
||||
|
||||
queue = segments[:]
|
||||
segments = []
|
||||
while queue:
|
||||
seg = queue.pop(0)
|
||||
if (seg[1] - seg[0]) <= max_len_ms:
|
||||
segments.append(seg)
|
||||
continue
|
||||
parts = _split_segment(seg)
|
||||
if len(parts) == 1:
|
||||
segments.append(seg)
|
||||
else:
|
||||
queue = parts + queue
|
||||
return segments
|
||||
|
||||
|
||||
class VocalSegmenter(nn.Module, SupportAudioInput, SupportsComponentDiscovery):
|
||||
support_audio_input: ClassVar[bool] = True
|
||||
_dit_modules: ClassVar[list[str]] = []
|
||||
_encoder_modules: ClassVar[list[str]] = []
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = ["."]
|
||||
_layerwise_offload_blocks_attrs: ClassVar[list[str]] = []
|
||||
|
||||
def __init__(self, config: VocalSegmentConfig | None = None, *, verbose: bool = False):
|
||||
super().__init__()
|
||||
self.config = config or VocalSegmentConfig()
|
||||
self.verbose = verbose
|
||||
|
||||
def forward(
|
||||
self,
|
||||
audio: np.ndarray,
|
||||
sample_rate: int,
|
||||
f0: np.ndarray,
|
||||
*,
|
||||
base_name: str = "vocal",
|
||||
origin_wav_fn: str = "",
|
||||
verbose: bool | None = None,
|
||||
) -> list[dict]:
|
||||
verbose = self.verbose if verbose is None else verbose
|
||||
if verbose:
|
||||
logger.info("[vocal detection] segmenting %s", base_name)
|
||||
t0 = time.time()
|
||||
|
||||
cfg = self.config
|
||||
y = np.asarray(audio, dtype=np.float32).squeeze()
|
||||
sr = int(sample_rate)
|
||||
|
||||
segments_ms = _voiced_to_segments(
|
||||
f0 > 0,
|
||||
hop_ms=cfg.hop_ms,
|
||||
smooth_ms=cfg.smooth_ms,
|
||||
start_ms=cfg.start_ms,
|
||||
end_ms=cfg.end_ms,
|
||||
prepad_ms=cfg.prepad_ms,
|
||||
postpad_ms=cfg.postpad_ms,
|
||||
max_len_ms=cfg.max_len_ms,
|
||||
)
|
||||
segments_ms = _merge_short_segments(
|
||||
segments_ms,
|
||||
min_len_ms=cfg.min_len_ms,
|
||||
max_len_ms=cfg.max_len_ms,
|
||||
short_seg_merge_gap_ms=cfg.short_seg_merge_gap_ms,
|
||||
small_gap_ms=cfg.small_gap_ms,
|
||||
)
|
||||
|
||||
adjusted_segments: list[list[int]] = []
|
||||
prev_end = 0
|
||||
for start_ms, end_ms in segments_ms:
|
||||
start_ms = max(0, start_ms - cfg.lookback_ms)
|
||||
end_ms = min(end_ms + cfg.lookahead_ms, int(y.shape[0] / sr * 1000))
|
||||
if start_ms < prev_end and adjusted_segments:
|
||||
adjusted_segments[-1][1] = start_ms
|
||||
adjusted_segments.append([start_ms, end_ms])
|
||||
prev_end = end_ms
|
||||
|
||||
segment_infos = []
|
||||
for idx, (start_ms, end_ms) in enumerate(adjusted_segments):
|
||||
if end_ms - start_ms > cfg.max_len_ms:
|
||||
start_ms = end_ms - cfg.max_len_ms
|
||||
key = f"{base_name}_{idx}"
|
||||
start_sample = int(start_ms * sr / 1000)
|
||||
end_sample = int(end_ms * sr / 1000)
|
||||
segment_infos.append(
|
||||
{
|
||||
"item_name": key,
|
||||
"wav": y[start_sample:end_sample],
|
||||
"sample_rate": sr,
|
||||
"wav_fn": key,
|
||||
"start_time_ms": int(start_sample * 1000 / sr),
|
||||
"end_time_ms": int(end_sample * 1000 / sr),
|
||||
"origin_wav_fn": origin_wav_fn,
|
||||
"duration": int((end_sample - start_sample) * 1000 / sr),
|
||||
}
|
||||
)
|
||||
|
||||
if verbose:
|
||||
logger.info(
|
||||
"[vocal detection] done n_segments=%s time=%.3fs",
|
||||
len(segment_infos),
|
||||
time.time() - t0,
|
||||
)
|
||||
return segment_infos
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Lazy-loaded SoulX preprocess model tree."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import ClassVar
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
|
||||
|
||||
from .asr import LyricModel
|
||||
from .mel_grid_f0 import extract_f0_file
|
||||
from .rmvpe import RMVPE
|
||||
from .rosvot import RosvotModel
|
||||
from .segmenter import VocalSegmenter
|
||||
from .utils import resample_mono
|
||||
from .vocal_sep import MelBandRoformerSeparator
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SoulXPreprocessStack(nn.Module, SupportsComponentDiscovery):
|
||||
"""Unified nn.Module tree for SoulX-Singer audio preprocess."""
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = []
|
||||
_encoder_modules: ClassVar[list[str]] = ["vocal_sep", "lyric", "rosvot"]
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = ["rmvpe"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
weights: dict[str, str],
|
||||
device: str,
|
||||
*,
|
||||
target_sr: int = 24000,
|
||||
hop_size: int = 480,
|
||||
verbose: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.weights = weights
|
||||
self.device_str = device
|
||||
self.target_sr = target_sr
|
||||
self.hop_size = hop_size
|
||||
self.verbose = verbose
|
||||
self._rmvpe: nn.Module | None = None
|
||||
self._vocal_sep: nn.Module | None = None
|
||||
self._segmenter: nn.Module | None = None
|
||||
self._lyric: nn.Module | None = None
|
||||
self._rosvot: nn.Module | None = None
|
||||
|
||||
@property
|
||||
def device(self) -> torch.device:
|
||||
return torch.device(self.device_str)
|
||||
|
||||
def ensure_rmvpe(self):
|
||||
if self._rmvpe is None:
|
||||
if self.verbose:
|
||||
logger.info("[rmvpe] loading shared pitch model")
|
||||
self._rmvpe = RMVPE(self.weights["rmvpe"], device=self.device_str)
|
||||
self.add_module("rmvpe", self._rmvpe)
|
||||
return self._rmvpe
|
||||
|
||||
def ensure_vocal_sep(self):
|
||||
if self._vocal_sep is None:
|
||||
if self.verbose:
|
||||
logger.info("[vocal extraction] loading model")
|
||||
self._vocal_sep = MelBandRoformerSeparator(
|
||||
self.weights["sep_config"],
|
||||
self.weights["sep_ckpt"],
|
||||
use_half=False,
|
||||
).to(self.device)
|
||||
self.add_module("vocal_sep", self._vocal_sep)
|
||||
if self.verbose:
|
||||
logger.info("[vocal extraction] ready on %s, sr=%s", self.device_str, self._vocal_sep.sample_rate)
|
||||
return self._vocal_sep
|
||||
|
||||
def ensure_segmenter(self):
|
||||
if self._segmenter is None:
|
||||
self._segmenter = VocalSegmenter(verbose=self.verbose)
|
||||
self.add_module("segmenter", self._segmenter)
|
||||
return self._segmenter
|
||||
|
||||
def ensure_lyric(self):
|
||||
if self._lyric is None:
|
||||
if self.verbose:
|
||||
logger.info("[lyric transcription] loading ASR")
|
||||
self._lyric = LyricModel(
|
||||
self.weights["asr_zh"],
|
||||
self.weights["asr_en"],
|
||||
device=self.device_str,
|
||||
target_sr=self.target_sr,
|
||||
hop_size=self.hop_size,
|
||||
)
|
||||
self.add_module("lyric", self._lyric)
|
||||
return self._lyric
|
||||
|
||||
def ensure_rosvot(self):
|
||||
if self._rosvot is None:
|
||||
if self.verbose:
|
||||
logger.info("[note transcription] loading ROSVOT")
|
||||
rosvot_src = os.environ.get("ROSVOT_SOURCE_DIR")
|
||||
self._rosvot = RosvotModel(
|
||||
self.weights["rosvot"],
|
||||
pe=self.ensure_rmvpe(),
|
||||
verbose=self.verbose,
|
||||
rosvot_source_dir=rosvot_src,
|
||||
).to(self.device)
|
||||
self.add_module("rosvot", self._rosvot)
|
||||
return self._rosvot
|
||||
|
||||
def extract_f0(self, vocal, sample_rate: int, *, f0_path: str | None = None) -> np.ndarray:
|
||||
"""Extract F0 on the mel grid; ndarray inputs are spooled to a temp wav."""
|
||||
rmvpe = self.ensure_rmvpe()
|
||||
kwargs = dict(
|
||||
target_sr=self.target_sr,
|
||||
hop_size=self.hop_size,
|
||||
f0_path=f0_path,
|
||||
verbose=self.verbose,
|
||||
)
|
||||
if isinstance(vocal, str):
|
||||
return extract_f0_file(rmvpe, vocal, **kwargs)
|
||||
tmp_path: str | None = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
|
||||
tmp_path = tmp.name
|
||||
sf.write(tmp_path, np.asarray(vocal, dtype=np.float32).squeeze(), int(sample_rate))
|
||||
return extract_f0_file(rmvpe, tmp_path, **kwargs)
|
||||
finally:
|
||||
if tmp_path is not None:
|
||||
Path(tmp_path).unlink(missing_ok=True)
|
||||
|
||||
def extract_vocal(self, audio: str | tuple[np.ndarray, int]) -> tuple[np.ndarray, int]:
|
||||
sep = self.ensure_vocal_sep()
|
||||
if isinstance(audio, tuple):
|
||||
mix, sr = audio
|
||||
mix = np.asarray(mix, dtype=np.float32).squeeze()
|
||||
if sr != sep.sample_rate:
|
||||
mix = resample_mono(mix, orig_sr=sr, target_sr=sep.sample_rate)
|
||||
return sep.separate_mono(mix, self.device), sep.sample_rate
|
||||
return sep.separate_path(str(audio), self.device)
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Shared helpers for SoulX preprocess (I/O, config, checkpoints, pitch)."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from omegaconf import OmegaConf
|
||||
from vllm.logger import init_logger
|
||||
from vllm.multimodal.audio import AudioResampler
|
||||
from vllm.multimodal.media.audio import load_audio
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
# --- audio I/O ---
|
||||
|
||||
|
||||
def resample_mono(
|
||||
audio: np.ndarray,
|
||||
*,
|
||||
orig_sr: int,
|
||||
target_sr: int,
|
||||
) -> np.ndarray:
|
||||
"""Resample mono float waveform to ``target_sr``."""
|
||||
audio = np.asarray(audio, dtype=np.float32).squeeze()
|
||||
if orig_sr == target_sr:
|
||||
return audio
|
||||
resampler = AudioResampler(target_sr=float(target_sr))
|
||||
return np.asarray(
|
||||
resampler.resample(audio, orig_sr=float(orig_sr)),
|
||||
dtype=np.float32,
|
||||
)
|
||||
|
||||
|
||||
def get_audio_duration(path: str) -> float:
|
||||
"""Return audio duration in seconds for a file on disk."""
|
||||
return float(sf.info(path).duration)
|
||||
|
||||
|
||||
def load_mono_audio(
|
||||
source: str | tuple[np.ndarray, int],
|
||||
*,
|
||||
target_sr: int | None = None,
|
||||
) -> tuple[np.ndarray, int]:
|
||||
if isinstance(source, tuple):
|
||||
audio, sr = source
|
||||
audio = np.asarray(audio, dtype=np.float32).squeeze()
|
||||
if target_sr is not None and sr != target_sr:
|
||||
audio = resample_mono(audio, orig_sr=sr, target_sr=target_sr)
|
||||
sr = target_sr
|
||||
return audio, sr
|
||||
|
||||
if target_sr is None:
|
||||
audio, sr = load_audio(str(source), sr=None, mono=True)
|
||||
else:
|
||||
audio, sr = load_audio(str(source), sr=target_sr, mono=True)
|
||||
return np.asarray(audio, dtype=np.float32).squeeze(), int(sr)
|
||||
|
||||
|
||||
# --- tensor padding ---
|
||||
|
||||
|
||||
def pad_or_cut_xd(values: torch.Tensor, tgt_len: int, dim: int = -1, pad_value=0) -> torch.Tensor:
|
||||
ndim = values.ndim
|
||||
if ndim == 1:
|
||||
if values.shape[0] < tgt_len:
|
||||
return F.pad(values, [0, tgt_len - values.shape[0]], value=pad_value)
|
||||
return values[:tgt_len]
|
||||
if ndim == 2:
|
||||
if dim in (0, -2):
|
||||
src_len = values.shape[0]
|
||||
if src_len < tgt_len:
|
||||
return F.pad(values, [0, 0, 0, tgt_len - src_len], value=pad_value)
|
||||
return values[:tgt_len]
|
||||
src_len = values.shape[1]
|
||||
if src_len < tgt_len:
|
||||
return F.pad(values, [0, tgt_len - src_len], value=pad_value)
|
||||
return values[:, :tgt_len]
|
||||
raise NotImplementedError(f"pad_or_cut_xd supports 1D/2D tensors, got ndim={ndim}")
|
||||
|
||||
|
||||
# --- YAML config (OmegaConf) ---
|
||||
|
||||
|
||||
def _apply_hparams_str(config: dict[str, Any], hparams_str: str) -> None:
|
||||
if not hparams_str:
|
||||
return
|
||||
for item in hparams_str.split(","):
|
||||
key, raw_value = item.split("=", maxsplit=1)
|
||||
raw_value = raw_value.strip().strip("'\"")
|
||||
node: dict[str, Any] = config
|
||||
parts = key.split(".")
|
||||
for part in parts[:-1]:
|
||||
node = node.setdefault(part, {})
|
||||
leaf = parts[-1]
|
||||
current = node.get(leaf)
|
||||
if raw_value in {"True", "False"}:
|
||||
node[leaf] = raw_value == "True"
|
||||
elif isinstance(current, bool):
|
||||
node[leaf] = raw_value.lower() == "true"
|
||||
elif isinstance(current, int):
|
||||
node[leaf] = int(raw_value)
|
||||
elif isinstance(current, float):
|
||||
node[leaf] = float(raw_value)
|
||||
else:
|
||||
node[leaf] = type(current)(raw_value) if current is not None else raw_value
|
||||
|
||||
|
||||
def load_yaml_config(
|
||||
config: str | Path,
|
||||
*,
|
||||
hparams_str: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""Load YAML with optional ``base_config`` chain; returns a plain dict."""
|
||||
config_path = Path(config).expanduser()
|
||||
if not config_path.is_file():
|
||||
raise FileNotFoundError(f"Config not found: {config_path}")
|
||||
|
||||
merged = OmegaConf.create({})
|
||||
pending = [config_path.resolve()]
|
||||
loaded: set[str] = set()
|
||||
|
||||
while pending:
|
||||
path = pending.pop(0)
|
||||
path_key = str(path)
|
||||
if path_key in loaded:
|
||||
continue
|
||||
loaded.add(path_key)
|
||||
|
||||
current = OmegaConf.load(path_key)
|
||||
base_configs = current.get("base_config")
|
||||
if base_configs is not None:
|
||||
entries = base_configs if OmegaConf.is_list(base_configs) else [base_configs]
|
||||
for entry in entries:
|
||||
base_path = Path(entry)
|
||||
if not base_path.is_absolute():
|
||||
base_path = (path.parent / entry).resolve()
|
||||
if not base_path.is_file():
|
||||
logger.warning("Skipping missing base config: %s", base_path)
|
||||
continue
|
||||
pending.insert(0, base_path)
|
||||
merged = OmegaConf.merge(current, merged)
|
||||
|
||||
result = OmegaConf.to_container(merged, resolve=True)
|
||||
if not isinstance(result, dict):
|
||||
raise TypeError(f"Expected dict config, got {type(result)}")
|
||||
_apply_hparams_str(result, hparams_str)
|
||||
return result
|
||||
|
||||
|
||||
def load_rosvot_config(config: str | Path, *, hparams_str: str = "") -> dict[str, Any]:
|
||||
return load_yaml_config(config, hparams_str=hparams_str)
|
||||
|
||||
|
||||
# --- checkpoint loading ---
|
||||
|
||||
|
||||
def load_model_ckpt(
|
||||
model: nn.Module,
|
||||
checkpoint_path: str,
|
||||
*,
|
||||
model_name: str = "model",
|
||||
verbose: bool = True,
|
||||
) -> None:
|
||||
checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
|
||||
if not isinstance(checkpoint, dict) or "state_dict" not in checkpoint:
|
||||
raise ValueError(f"Unexpected ROSVOT checkpoint format: {checkpoint_path}")
|
||||
|
||||
state_dict = checkpoint["state_dict"]
|
||||
if state_dict and "." in next(iter(state_dict)):
|
||||
prefix = f"{model_name}."
|
||||
state_dict = {k[len(prefix) :]: v for k, v in state_dict.items() if k.startswith(prefix)}
|
||||
elif model_name in state_dict and isinstance(state_dict[model_name], dict):
|
||||
state_dict = state_dict[model_name]
|
||||
|
||||
model.load_state_dict(state_dict, strict=True)
|
||||
if verbose:
|
||||
logger.info("Loaded ROSVOT weights from %s", checkpoint_path)
|
||||
|
||||
|
||||
# --- pitch helpers (ROSVOT / RMVPE) ---
|
||||
|
||||
|
||||
def f0_to_coarse(f0, f0_bin=256, f0_max=900.0, f0_min=50.0):
|
||||
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
||||
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
||||
is_torch = isinstance(f0, torch.Tensor)
|
||||
f0_mel = 1127 * (1 + f0 / 700).log() if is_torch else 1127 * np.log(1 + f0 / 700)
|
||||
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * (f0_bin - 2) / (f0_mel_max - f0_mel_min) + 1
|
||||
f0_mel[f0_mel <= 1] = 1
|
||||
f0_mel[f0_mel > f0_bin - 1] = f0_bin - 1
|
||||
return (f0_mel + 0.5).long() if is_torch else np.rint(f0_mel).astype(int)
|
||||
|
||||
|
||||
def norm_f0(f0, uv, pitch_norm="log", f0_mean=400, f0_std=100):
|
||||
is_torch = isinstance(f0, torch.Tensor)
|
||||
if pitch_norm == "standard":
|
||||
f0 = (f0 - f0_mean) / f0_std
|
||||
if pitch_norm == "log":
|
||||
f0 = torch.log2(f0 + 1e-8) if is_torch else np.log2(f0 + 1e-8)
|
||||
if uv is not None:
|
||||
f0[uv > 0] = 0
|
||||
return f0
|
||||
|
||||
|
||||
def norm_interp_f0(f0, pitch_norm="log", f0_mean=None, f0_std=None):
|
||||
is_torch = isinstance(f0, torch.Tensor)
|
||||
if is_torch:
|
||||
device = f0.device
|
||||
f0 = f0.detach().cpu().numpy()
|
||||
uv = f0 == 0
|
||||
f0 = norm_f0(f0, uv, pitch_norm, f0_mean, f0_std)
|
||||
if sum(uv) == len(f0):
|
||||
f0[uv] = 0
|
||||
elif sum(uv) > 0:
|
||||
f0[uv] = np.interp(np.where(uv)[0], np.where(~uv)[0], f0[~uv])
|
||||
if is_torch:
|
||||
uv_t = torch.FloatTensor(uv)
|
||||
f0_t = torch.FloatTensor(f0)
|
||||
return f0_t.to(device), uv_t.to(device)
|
||||
return f0, uv
|
||||
|
||||
|
||||
def denorm_f0(f0, uv, pitch_norm="log", f0_mean=400, f0_std=100, pitch_padding=None, min=50, max=900):
|
||||
is_torch = isinstance(f0, torch.Tensor)
|
||||
if pitch_norm == "standard":
|
||||
f0 = f0 * f0_std + f0_mean
|
||||
if pitch_norm == "log":
|
||||
f0 = 2**f0
|
||||
f0 = f0.clamp(min=min, max=max) if is_torch else np.clip(f0, a_min=min, a_max=max)
|
||||
if uv is not None:
|
||||
f0[uv > 0] = 0
|
||||
if pitch_padding is not None:
|
||||
f0[pitch_padding] = 0
|
||||
return f0
|
||||
|
||||
|
||||
def boundary2Interval(bd):
|
||||
is_torch = isinstance(bd, torch.Tensor)
|
||||
if is_torch:
|
||||
device = bd.device
|
||||
bd = bd.detach().cpu().numpy()
|
||||
ret = np.zeros(shape=(bd.sum() + 1, 2), dtype=int)
|
||||
ret_idx = 0
|
||||
ret[0, 0] = 0
|
||||
for i, u in enumerate(bd):
|
||||
if i == 0:
|
||||
continue
|
||||
if u == 1:
|
||||
ret[ret_idx, 1] = i
|
||||
ret[ret_idx + 1, 0] = i
|
||||
ret_idx += 1
|
||||
ret[-1, 1] = bd.shape[0] - 1
|
||||
if is_torch:
|
||||
return torch.LongTensor(ret).to(device)
|
||||
return ret
|
||||
@@ -0,0 +1,207 @@
|
||||
"""BS-RoFormer vocal separation adapter (external pip package + SoulX chunking)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import yaml
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
from vllm.logger import init_logger
|
||||
from vllm.multimodal.media.audio import load_audio
|
||||
|
||||
from vllm_omni.diffusion.models.interface import SupportAudioInput, SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.offloader.layerwise_backend import LayerWiseOffloadBackend
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class MelBandRoformerSeparator(nn.Module, SupportAudioInput, SupportsComponentDiscovery):
|
||||
support_audio_input: ClassVar[bool] = True
|
||||
_dit_modules: ClassVar[list[str]] = []
|
||||
_encoder_modules: ClassVar[list[str]] = ["roformer"]
|
||||
_vae_modules: ClassVar[list[str]] = []
|
||||
_resident_modules: ClassVar[list[str]] = []
|
||||
_layerwise_offload_blocks_attrs: ClassVar[list[str]] = ["roformer.layers"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config_path: str | Path,
|
||||
checkpoint_path: str | Path | None = None,
|
||||
*,
|
||||
chunk_length_sec: float = 5,
|
||||
use_half: bool = True,
|
||||
):
|
||||
super().__init__()
|
||||
try:
|
||||
from bs_roformer import MelBandRoformer as ExtModel
|
||||
except ImportError as e:
|
||||
raise ImportError(
|
||||
'Install BS-RoFormer: pip install "vllm-omni[soulx-preprocess]" or pip install BS-RoFormer'
|
||||
) from e
|
||||
|
||||
cfg = self._load_config(Path(config_path))
|
||||
model_cfg = self._normalize_cfg(OmegaConf.to_container(cfg.model, resolve=True))
|
||||
self.roformer = ExtModel(**model_cfg)
|
||||
self.config = cfg
|
||||
self.sample_rate = int(cfg.audio.sample_rate)
|
||||
|
||||
LayerWiseOffloadBackend.set_blocks_attr_names(self.roformer, ["layers"])
|
||||
dtype = torch.float16 if use_half else torch.float32
|
||||
self.roformer = self.roformer.to(dtype=dtype)
|
||||
|
||||
chunk = int(chunk_length_sec * self.sample_rate)
|
||||
self.config.inference = getattr(self.config, "inference", {})
|
||||
inf = self.config.inference
|
||||
inf.chunk_size = chunk
|
||||
inf.num_overlap = inf.get("num_overlap", 4)
|
||||
inf.use_amp = False
|
||||
inf.normalize = inf.get("normalize", True)
|
||||
|
||||
fade = chunk // 10
|
||||
w = torch.ones(chunk)
|
||||
w[:fade] = torch.linspace(0, 1, fade)
|
||||
w[-fade:] = torch.linspace(1, 0, fade)
|
||||
self.register_buffer("_window", w.to(dtype=dtype), persistent=False)
|
||||
|
||||
if checkpoint_path:
|
||||
self.load_checkpoint(str(checkpoint_path), use_half=use_half)
|
||||
else:
|
||||
self.roformer.eval()
|
||||
|
||||
@staticmethod
|
||||
def _normalize_cfg(cfg: dict) -> dict:
|
||||
tuple_keys = {"multi_stft_resolutions_window_sizes", "freqs_per_bands", "multi_stft_window_sizes"}
|
||||
|
||||
def _fix(v):
|
||||
if isinstance(v, list):
|
||||
return tuple(_fix(x) for x in v)
|
||||
if isinstance(v, dict):
|
||||
return {k: _fix(val) for k, val in v.items()}
|
||||
return v
|
||||
|
||||
for k in tuple_keys:
|
||||
if k in cfg:
|
||||
cfg[k] = _fix(cfg[k])
|
||||
return cfg
|
||||
|
||||
@staticmethod
|
||||
def _load_config(path: Path) -> DictConfig:
|
||||
class Loader(yaml.SafeLoader):
|
||||
pass
|
||||
|
||||
Loader.add_constructor(
|
||||
"tag:yaml.org,2002:python/tuple",
|
||||
lambda loader, node: tuple(loader.construct_sequence(node)),
|
||||
)
|
||||
with open(path) as f:
|
||||
return OmegaConf.create(yaml.load(f, Loader=Loader))
|
||||
|
||||
def load_checkpoint(self, path: str, *, use_half: bool = True) -> None:
|
||||
self.roformer.load_state_dict(torch.load(path, map_location="cpu"), strict=False)
|
||||
if use_half:
|
||||
self.roformer.half()
|
||||
self.roformer.eval()
|
||||
|
||||
@property
|
||||
def chunk_size(self) -> int:
|
||||
return int(self.config.inference.chunk_size)
|
||||
|
||||
@property
|
||||
def num_overlap(self) -> int:
|
||||
return int(self.config.inference.num_overlap)
|
||||
|
||||
@property
|
||||
def use_amp(self) -> bool:
|
||||
return bool(self.config.inference.use_amp)
|
||||
|
||||
@property
|
||||
def normalize_input(self) -> bool:
|
||||
return bool(self.config.inference.normalize)
|
||||
|
||||
@property
|
||||
def num_channels(self) -> int:
|
||||
return int(self.config.audio.get("num_channels", 1))
|
||||
|
||||
def _prepare_mix(self, mix: np.ndarray) -> tuple[np.ndarray, tuple[float, float] | None]:
|
||||
if mix.ndim == 1:
|
||||
mix = mix[np.newaxis, :]
|
||||
if self.num_channels == 2 and mix.shape[0] == 1:
|
||||
mix = np.repeat(mix, 2, axis=0)
|
||||
if not self.normalize_input:
|
||||
return mix, None
|
||||
mono = mix.mean(0)
|
||||
return (mix - mono.mean()) / mono.std(), (float(mono.mean()), float(mono.std()))
|
||||
|
||||
@staticmethod
|
||||
def _select_vocal(recon: torch.Tensor) -> torch.Tensor:
|
||||
if recon.ndim == 4:
|
||||
return recon[0, 0]
|
||||
if recon.ndim == 3:
|
||||
return recon[0]
|
||||
if recon.ndim == 2:
|
||||
return recon
|
||||
raise ValueError(recon.shape)
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, mix: torch.Tensor) -> torch.Tensor:
|
||||
if mix.ndim == 1:
|
||||
mix = mix.unsqueeze(0)
|
||||
if self.num_channels == 2 and mix.shape[0] == 1:
|
||||
mix = mix.repeat(2, 1)
|
||||
|
||||
model_dtype = next(self.roformer.parameters()).dtype
|
||||
compute_dtype = torch.float32 if model_dtype == torch.float16 else model_dtype
|
||||
if mix.dtype != compute_dtype:
|
||||
mix = mix.to(dtype=compute_dtype)
|
||||
|
||||
chunk_size = self.chunk_size
|
||||
step = chunk_size // self.num_overlap
|
||||
fade = chunk_size // 10
|
||||
border = chunk_size - step
|
||||
n_samples = mix.shape[-1]
|
||||
window = self._window.to(mix.device)
|
||||
|
||||
if n_samples > 2 * border and border > 0:
|
||||
mix = nn.functional.pad(mix, (border, border), mode="reflect")
|
||||
|
||||
out = torch.zeros_like(mix)
|
||||
weight = torch.zeros(mix.shape[-1], device=mix.device, dtype=mix.dtype)
|
||||
pos = 0
|
||||
with torch.cuda.amp.autocast(enabled=self.use_amp):
|
||||
while pos < mix.shape[-1]:
|
||||
part = mix[:, pos : pos + chunk_size]
|
||||
seg_len = part.shape[-1]
|
||||
pad_mode = "reflect" if seg_len > chunk_size // 2 else "constant"
|
||||
part = nn.functional.pad(part, (0, chunk_size - seg_len), mode=pad_mode, value=0)
|
||||
stem = self._select_vocal(self.roformer(part.unsqueeze(0)))
|
||||
win = window.clone()
|
||||
if pos == 0:
|
||||
win[:fade] = 1
|
||||
elif pos + step >= n_samples:
|
||||
win[-fade:] = 1
|
||||
out[:, pos : pos + seg_len] += stem[:, :seg_len] * win[:seg_len]
|
||||
weight[pos : pos + seg_len] += win[:seg_len]
|
||||
pos += step
|
||||
|
||||
out = out / weight
|
||||
if n_samples > 2 * border and border > 0:
|
||||
out = out[..., border:-border]
|
||||
return out
|
||||
|
||||
@torch.inference_mode()
|
||||
def separate_mono(self, mix: np.ndarray, device: torch.device) -> np.ndarray:
|
||||
m, norm = self._prepare_mix(mix)
|
||||
target_dtype = next(self.roformer.parameters()).dtype
|
||||
v = self.forward(torch.as_tensor(m, dtype=target_dtype, device=device))
|
||||
if norm:
|
||||
v = v * norm[1] + norm[0]
|
||||
v = v.mean(0) if v.ndim == 2 else v
|
||||
return v.float().cpu().numpy().astype(np.float32)
|
||||
|
||||
def separate_path(self, path: str, device: torch.device) -> tuple[np.ndarray, int]:
|
||||
mix, _ = load_audio(path, sr=self.sample_rate, mono=False)
|
||||
return self.separate_mono(np.asarray(mix, dtype=np.float32), device), self.sample_rate
|
||||
Reference in new issue
Block a user