ckpt / code /infer_bg2fg_variable.py
AE-W's picture
archive loose scripts/configs
219f052 verified
Raw
History Blame Contribute Delete
18.3 kB
"""Variable-length bg→fg inference for SA + Frieren.
Short bg (< window): repeat-pad to window, infer, truncate to original length.
Long bg (> window): 50% overlap windows + linear-crossfade overlap-add.
Same wrapper for both models; per-model imports are lazy so a missing env on
one side doesn't break the other.
Mixture audio is generated alongside fg_pred:
bg_norm = LUFS-normalize(bg, -30)
mix_raw = bg_norm + fg_pred
mix_norm = LUFS-normalize(mix_raw, -23)
Usage:
conda activate stable-audio
python infer_bg2fg_variable.py --model sa --ckpt <last.ckpt> \
--bg-dir /home/dingqy/inference_demo/youtube \
--out /home/dingqy/inference_demo/youtube_out/sa
conda activate V2A
python infer_bg2fg_variable.py --model frieren --ckpt <last.ckpt> \
--bg-dir /home/dingqy/inference_demo/youtube \
--out /home/dingqy/inference_demo/youtube_out/frieren
"""
import argparse, os, sys, json
from pathlib import Path
import numpy as np
import torch
import torchaudio
# ------------------------- variable-length glue -------------------------
def repeat_pad(bg_1d_np: np.ndarray, target_len: int) -> np.ndarray:
"""Tile bg until length >= target_len, then truncate."""
L = len(bg_1d_np)
if L >= target_len:
return bg_1d_np[:target_len]
n = (target_len + L - 1) // L
return np.tile(bg_1d_np, n)[:target_len]
def overlap_stitch(bg_1d_np: np.ndarray, infer_one,
window_len: int, hop: int) -> np.ndarray:
"""Sliding 50%-overlap windows, infer each, weighted overlap-add.
Triangular window for crossfade; weight normalization at the end so edges
(covered by fewer windows) don't get attenuated.
`infer_one` takes a 1-D float32 ndarray of length `window_len`,
returns a 1-D float32 ndarray of the same length.
"""
L = len(bg_1d_np)
assert L > window_len, "use repeat_pad for short bg"
# triangular window peaking at window_len // 2
half = window_len // 2
ramp_up = np.linspace(0.0, 1.0, half, endpoint=False, dtype=np.float32)
ramp_dn = np.linspace(1.0, 0.0, window_len - half, endpoint=False, dtype=np.float32)
win = np.concatenate([ramp_up, ramp_dn])
starts = list(range(0, L - window_len + 1, hop))
if starts[-1] + window_len < L:
starts.append(L - window_len) # last window flush to end
fg_acc = np.zeros(L, dtype=np.float32)
w_acc = np.zeros(L, dtype=np.float32)
for k, s in enumerate(starts):
bg_chunk = bg_1d_np[s:s + window_len].astype(np.float32)
fg_chunk = infer_one(bg_chunk).astype(np.float32)
fg_acc[s:s + window_len] += fg_chunk * win
w_acc [s:s + window_len] += win
print(f" window {k+1}/{len(starts)} start={s/16000:.2f}s", flush=True)
w_acc = np.maximum(w_acc, 1e-6)
return fg_acc / w_acc
def render_3panel_spec(bg_1d, fg_1d, mix_1d, sr, title, out_path,
n_fft=2048, hop_length=512, n_mels=128, fmax=None):
"""3-panel mel spec (bg / fg_pred / mixture) using librosa.display.specshow."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import librosa.display as ld
from librosa.filters import mel as librosa_mel_fn
if fmax is None:
fmax = sr // 2
mb = torch.from_numpy(librosa_mel_fn(sr=sr, n_fft=n_fft, n_mels=n_mels,
fmin=0, fmax=fmax)).float()
win = torch.hann_window(n_fft)
def to_mel(x):
x_t = torch.from_numpy(x.astype(np.float32)).unsqueeze(0)
spec = torch.stft(x_t, n_fft=n_fft, hop_length=hop_length, win_length=n_fft,
window=win, center=True, return_complex=True).abs()
return ((mb @ spec[0]).clamp(min=1e-5).log10().numpy() * 20.0)
mels = [to_mel(bg_1d), to_mel(fg_1d), to_mel(mix_1d)]
labels = ["bg", "fg_pred", "mixture"]
vmin = min(m.min() for m in mels); vmax = max(m.max() for m in mels)
fig, axes = plt.subplots(3, 1, figsize=(12, 7.5), dpi=110, sharex=True)
last_img = None
for ax, m, lab in zip(axes, mels, labels):
last_img = ld.specshow(m, x_axis="time", y_axis="mel",
sr=sr, hop_length=hop_length, fmax=fmax,
cmap="magma", ax=ax, vmin=vmin, vmax=vmax)
ax.set_ylabel(f"{lab}\nmel (Hz)", fontsize=9)
axes[0].set_title(title, fontsize=11)
axes[-1].set_xlabel("time (s)")
fig.colorbar(last_img, ax=axes, format="%+.1f", label="log-mel (dB)",
shrink=0.9, pad=0.02)
fig.savefig(out_path, bbox_inches="tight")
plt.close(fig)
def lufs_normalize(wav_1d: np.ndarray, target_lufs: float, sr: int) -> np.ndarray:
import pyloudnorm as pyln
meter = pyln.Meter(sr)
cur = meter.integrated_loudness(wav_1d)
if not np.isfinite(cur):
return wav_1d
return pyln.normalize.loudness(wav_1d, cur, target_lufs).astype(np.float32)
def find_lufs_mixture_gains(bg_mono, fg_mono, sr,
bg_lufs=-30.0, mix_lufs=-23.0,
tol=0.05, max_iter=25):
"""Hidingsound LUFS protocol — returns (bg_gain, fg_gain) linear scalars.
- bg final LUFS in mixture = bg_lufs (FIXED, no further scaling).
- LUFS(bg_gain*bg_mono + fg_gain*fg_mono) = mix_lufs.
Caller multiplies these gains into the actual (possibly stereo) signals.
Binary search on fg gain in dB-space. LUFS is monotone in s_db, so binary
search converges robustly in ~log2(range/tol) ≈ 12-15 iterations regardless
of bg/fg power balance.
"""
import pyloudnorm as pyln
meter = pyln.Meter(sr)
L_bg = meter.integrated_loudness(bg_mono)
if not np.isfinite(L_bg):
return 1.0, 0.0
bg_gain = 10 ** ((bg_lufs - L_bg) / 20)
bg_norm_mono = bg_mono * bg_gain
L_fg = meter.integrated_loudness(fg_mono)
if not np.isfinite(L_fg):
return float(bg_gain), 0.0
e_target = 10 ** (mix_lufs / 10)
e_bg = 10 ** (bg_lufs / 10)
if e_target <= e_bg:
return float(bg_gain), 0.0 # mix target ≤ bg → no fg
def loudness_at(s_db):
mix = bg_norm_mono + (10 ** (s_db / 20)) * fg_mono
return meter.integrated_loudness(mix)
# Initial bracket centered on the analytic energy-sum estimate ± 30 dB.
s0_db = 10 * np.log10(max(e_target - e_bg, 0)) - L_fg
lo, hi = s0_db - 30.0, s0_db + 30.0
L_lo, L_hi = loudness_at(lo), loudness_at(hi)
# Expand if bracket doesn't span the target.
while np.isfinite(L_lo) and L_lo > mix_lufs and lo > -120.0:
lo -= 20.0; L_lo = loudness_at(lo)
while np.isfinite(L_hi) and L_hi < mix_lufs and hi < 60.0:
hi += 20.0; L_hi = loudness_at(hi)
if not np.isfinite(L_hi) or L_hi < mix_lufs:
return float(bg_gain), float(10 ** (hi / 20)) # un-reachable; clamp at hi
mid = 0.5 * (lo + hi)
for _ in range(max_iter):
mid = 0.5 * (lo + hi)
L_mid = loudness_at(mid)
if not np.isfinite(L_mid): break
if abs(L_mid - mix_lufs) < tol: break
if L_mid < mix_lufs:
lo = mid
else:
hi = mid
return float(bg_gain), float(10 ** (mid / 20))
def make_mixture(bg_1d, fg_1d, sr, bg_lufs=-30.0, mix_lufs=-23.0):
"""Mono convenience wrapper. Returns (bg_norm, mix)."""
bg_g, fg_g = find_lufs_mixture_gains(bg_1d, fg_1d, sr, bg_lufs, mix_lufs)
bg_norm = (bg_1d * bg_g).astype(np.float32)
mix = (bg_norm + fg_g * fg_1d).astype(np.float32)
return bg_norm, mix
# ------------------------- per-model wrappers -------------------------
def run_sa(args):
"""SA: native 44.1 kHz stereo. window=440320 samples (9.98s), hop=220160."""
SA_ROOT = Path("/nfs/turbo/coe-ahowens-nobackup/dingqy/friendly-stable-audio-tools")
sys.path.insert(0, str(SA_ROOT))
from stable_audio_tools.models import create_model_from_config
from stable_audio_tools.models.utils import load_ckpt_state_dict
from stable_audio_tools.training import create_training_wrapper_from_config
from stable_audio_tools.inference.generation import generate_diffusion_cond
model_cfg_path = SA_ROOT / "stable_audio_tools/configs/model_configs/txt2audio/stable_audio_open_1_0_bg2fg_rebalance.json"
mc = json.load(open(model_cfg_path))
print("[sa] instantiating + loading wrapper...", flush=True)
base = create_model_from_config(mc)
wrapper = create_training_wrapper_from_config(mc, base)
sd = load_ckpt_state_dict(args.ckpt)
wrapper.load_state_dict(sd, strict=False)
if getattr(wrapper, "diffusion_ema", None) is not None:
wrapper.diffusion.model = wrapper.diffusion_ema.ema_model
model = wrapper.diffusion.cuda().eval()
SR = mc["sample_rate"] # 44100
CH = mc["audio_channels"] # 2
SAMPLE_SIZE = mc["sample_size"] # 440320 = ~9.98s
def sa_infer_window(bg_2d_np):
"""bg_2d_np shape [C=2, T=SAMPLE_SIZE] float32 in [-1,1] → fg [C, T]."""
bg_t = torch.from_numpy(bg_2d_np).clamp(-1, 1)
cond = [{
"bg_audio": bg_t.unsqueeze(0), # [1, C, T]
"seconds_start": 0,
"seconds_total": 10,
}]
with torch.no_grad(), torch.cuda.amp.autocast():
fakes = generate_diffusion_cond(
model, steps=args.steps, cfg_scale=args.cfg_scale,
conditioning=cond, sample_size=SAMPLE_SIZE,
seed=args.seed, disable_tqdm=True,
)
return fakes[0].cpu().float().numpy().clip(-1, 1) # [C, T]
out_dir = Path(args.out); out_dir.mkdir(parents=True, exist_ok=True)
bg_files = sorted(Path(args.bg_dir).glob("*.wav"))
print(f"[sa] {len(bg_files)} bg files -> {out_dir}", flush=True)
for bg_path in bg_files:
tag = bg_path.stem.replace("_bg", "")
print(f"\n[sa] === {tag} ===", flush=True)
# Load + resample to 44.1k stereo
wav, sr_in = torchaudio.load(str(bg_path))
if wav.shape[0] == 1:
wav = wav.repeat(2, 1)
elif wav.shape[0] != CH:
wav = wav[:CH] if wav.shape[0] > CH else wav.mean(0, keepdim=True).repeat(CH, 1)
if sr_in != SR:
wav = torchaudio.functional.resample(wav, sr_in, SR)
bg_full = wav.numpy().astype(np.float32) # [C, T]
L = bg_full.shape[-1]
print(f" bg loaded: shape={bg_full.shape} dur={L/SR:.2f}s", flush=True)
if L <= SAMPLE_SIZE:
print(f" short → repeat-pad to {SAMPLE_SIZE/SR:.2f}s", flush=True)
bg_pad = np.stack([repeat_pad(bg_full[c], SAMPLE_SIZE) for c in range(CH)])
fg_pad = sa_infer_window(bg_pad)
fg_full = fg_pad[:, :L]
else:
print(f" long → overlap-add ({SAMPLE_SIZE//2/SR:.2f}s hop)", flush=True)
hop = SAMPLE_SIZE // 2
half = SAMPLE_SIZE // 2
ramp_up = np.linspace(0.0, 1.0, half, endpoint=False, dtype=np.float32)
ramp_dn = np.linspace(1.0, 0.0, SAMPLE_SIZE - half, endpoint=False, dtype=np.float32)
win = np.concatenate([ramp_up, ramp_dn])
starts = list(range(0, L - SAMPLE_SIZE + 1, hop))
if starts[-1] + SAMPLE_SIZE < L:
starts.append(L - SAMPLE_SIZE)
fg_acc = np.zeros((CH, L), dtype=np.float32)
w_acc = np.zeros(L, dtype=np.float32)
for k, s in enumerate(starts):
bg_chunk = bg_full[:, s:s + SAMPLE_SIZE]
fg_chunk = sa_infer_window(bg_chunk) # [C, T]
fg_acc[:, s:s + SAMPLE_SIZE] += fg_chunk * win[None, :]
w_acc [s:s + SAMPLE_SIZE] += win
print(f" window {k+1}/{len(starts)} start={s/SR:.2f}s", flush=True)
w_acc = np.maximum(w_acc, 1e-6)
fg_full = fg_acc / w_acc
# Save bg / fg_pred FIRST so a downstream mixture/spec crash doesn't
# discard the diffusion output.
torchaudio.save(str(out_dir / f"{tag}_bg.wav"),
torch.from_numpy(bg_full), SR)
torchaudio.save(str(out_dir / f"{tag}_fg_pred.wav"),
torch.from_numpy(fg_full).clamp(-1, 1), SR)
try:
# Hidingsound LUFS protocol: measure on mono channel-mean, apply
# the resulting (bg_gain, fg_gain) to the stereo signals so bg ends
# at exactly -30 LUFS and (bg+fg) at -23 LUFS in mixture.
bg_mono = bg_full.mean(0); fg_mono = fg_full.mean(0)
bg_g, fg_g = find_lufs_mixture_gains(bg_mono, fg_mono, SR)
mix_stereo = (bg_full * bg_g + fg_full * fg_g).astype(np.float32)
torchaudio.save(str(out_dir / f"{tag}_mixture.wav"),
torch.from_numpy(mix_stereo).clamp(-1, 1), SR)
render_3panel_spec(bg_full.mean(0) * bg_g, fg_full.mean(0) * fg_g,
mix_stereo.mean(0),
sr=SR, title=f"[SA] {tag}",
out_path=str(out_dir / f"{tag}_spec.png"))
print(f" wrote {tag}_{{bg,fg_pred,mixture}}.wav + spec.png", flush=True)
except Exception as e:
print(f" [warn] mixture/spec failed but bg+fg_pred saved: {e}", flush=True)
def run_frieren(args):
"""Frieren: 16 kHz mono. window=131072 samples (8.19s), hop=65536."""
FR_ROOT = Path("/nfs/turbo/coe-ahowens-nobackup/dingqy/Frieren-V2A")
sys.path.insert(0, str(FR_ROOT / "Frieren"))
from cfm.util import instantiate_from_config
from vocoder.bigvgan.models import VocoderBigVGAN
from omegaconf import OmegaConf
cfg = OmegaConf.load(FR_ROOT / "Frieren/configs/ldm_training/hidingsound_bg2fg_rebalance.yaml")
print("[frieren] instantiating model...", flush=True)
model = instantiate_from_config(cfg.model)
sd = torch.load(args.ckpt, map_location="cpu", weights_only=False)
state_dict = sd.get("state_dict", sd)
model.load_state_dict(state_dict, strict=False)
model = model.cuda().eval()
vocoder = VocoderBigVGAN(str(FR_ROOT / "checkpoints/vocoder/bigvnat"), device="cuda")
SR = 16000
WINDOW = 131072 # 8.19s @ 16k
HOP = WINDOW // 2
def fr_infer_window(bg_1d_np):
"""bg [T=131072] float32 → fg [T=131072] float32 (vocoded)."""
bg_t = torch.from_numpy(bg_1d_np).cuda().unsqueeze(0) # [1, T]
with torch.no_grad():
bg_for_cond = bg_t.unsqueeze(-1) # [1, T, 1]
cond = model.cond_stage_model(bg_for_cond)
shape = (1, model.mel_dim, model.mel_length)
z_pred, _ = model.sample_param_cfg(
cond=cond, cfg_scale=args.cfg_scale, batch_size=1,
timesteps=args.steps, solver="euler", shape=shape,
)
vae = getattr(model.first_stage_model, "vae", model.first_stage_model)
mel_pred = vae.decode(z_pred)
wav = vocoder.vocode(mel_pred[0].cpu().numpy()) # ndarray [T_wav]
wav = np.asarray(wav, dtype=np.float32)
# vocoder may emit slightly different length; trim/pad to WINDOW
if len(wav) >= WINDOW:
return wav[:WINDOW]
out = np.zeros(WINDOW, dtype=np.float32); out[:len(wav)] = wav
return out
out_dir = Path(args.out); out_dir.mkdir(parents=True, exist_ok=True)
bg_files = sorted(Path(args.bg_dir).glob("*.wav"))
print(f"[frieren] {len(bg_files)} bg files -> {out_dir}", flush=True)
for bg_path in bg_files:
tag = bg_path.stem.replace("_bg", "")
print(f"\n[frieren] === {tag} ===", flush=True)
wav, sr_in = torchaudio.load(str(bg_path))
if wav.shape[0] > 1:
wav = wav.mean(0, keepdim=True)
if sr_in != SR:
wav = torchaudio.functional.resample(wav, sr_in, SR)
bg_1d = wav.squeeze(0).numpy().astype(np.float32)
L = len(bg_1d)
print(f" bg loaded: dur={L/SR:.2f}s", flush=True)
if L <= WINDOW:
print(f" short → repeat-pad to {WINDOW/SR:.2f}s", flush=True)
bg_pad = repeat_pad(bg_1d, WINDOW)
fg_pad = fr_infer_window(bg_pad)
fg_1d = fg_pad[:L]
else:
print(f" long → overlap-add ({HOP/SR:.2f}s hop)", flush=True)
fg_1d = overlap_stitch(bg_1d, fr_infer_window, WINDOW, HOP)
# Save bg / fg_pred FIRST so a downstream crash (LUFS / spec) doesn't
# discard the diffusion output that just took ~10 min to produce.
torchaudio.save(str(out_dir / f"{tag}_bg.wav"),
torch.from_numpy(bg_1d).unsqueeze(0), SR)
torchaudio.save(str(out_dir / f"{tag}_fg_pred.wav"),
torch.from_numpy(fg_1d.astype(np.float32)).clamp(-1, 1).unsqueeze(0), SR)
try:
_, mix_norm = make_mixture(bg_1d, fg_1d, SR)
torchaudio.save(str(out_dir / f"{tag}_mixture.wav"),
torch.from_numpy(mix_norm.astype(np.float32)).clamp(-1, 1).unsqueeze(0), SR)
render_3panel_spec(bg_1d, fg_1d, mix_norm,
sr=SR, n_fft=1024, hop_length=256, n_mels=80, fmax=8000,
title=f"[Frieren] {tag}",
out_path=str(out_dir / f"{tag}_spec.png"))
print(f" wrote {tag}_{{bg,fg_pred,mixture}}.wav + spec.png", flush=True)
except Exception as e:
print(f" [warn] mixture/spec failed but bg+fg_pred saved: {e}", flush=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", choices=["sa", "frieren"], required=True)
ap.add_argument("--ckpt", required=True)
ap.add_argument("--bg-dir", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--steps", type=int, default=None,
help="default: SA=100, Frieren=26")
ap.add_argument("--cfg-scale", type=float, default=1.0)
ap.add_argument("--seed", type=int, default=42)
args = ap.parse_args()
if args.steps is None:
args.steps = 100 if args.model == "sa" else 26
if args.model == "sa":
run_sa(args)
else:
run_frieren(args)
if __name__ == "__main__":
main()