Run this model with HF Jobs

Run moonbox-dev/Vevo-TensorRT on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/moonbox-dev/Vevo-TensorRT. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/moonbox-dev/Vevo-TensorRT on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Vevo-TensorRT / int8 /pipeline.py
jennyxue's picture
int8 build of Vevo
cb64540 verified
Raw History Blame Contribute Delete
7.18 kB
"""Vevo-Timbre voice conversion with ONNX Runtime: re-voice a recording into the voice of a reference recording,
keeping its words, timing and speaking style. Follows the official `VevoInferencePipeline.inference_fm`
(infer_vevotimbre.py): content-style tokens of reference and source, the flow-matching transformer with the
reference mel as prompt (32 steps, classifier-free guidance 1.0 rescaled 0.75), the Vocos vocoder. 24 kHz output.
Needs numpy, onnxruntime (or onnxruntime-gpu), soundfile and soxr.
python fp16/pipeline.py source.wav voice.wav out.wav [--cuda] [--steps 32] [--seed 0]
The flow's starting noise comes from numpy's generator (`seed`). The flow attends over reference and source together:
keep both short (the official examples use a few seconds of reference and under 30 s of source).
"""
from __future__ import annotations
import json
import math
from pathlib import Path
import numpy as np
SR, N_FFT, HOP = 24000, 1920, 480
def resample(x, orig, new, lowpass_filter_width=6, rolloff=0.99):
"""torchaudio.functional.resample(orig, new) (sinc_interp_hann), which the official load_wav uses for 16 kHz."""
g = math.gcd(int(orig), int(new))
o, n = int(orig) // g, int(new) // g
if o == n:
return np.asarray(x, np.float32)
base = min(o, n) * rolloff
width = math.ceil(lowpass_filter_width * o / base)
idx = np.arange(-width, width + o, dtype=np.float64)[None, :] / o
t = (np.arange(0, -n, -1, dtype=np.float64)[:, None] / n + idx) * base
t = np.clip(t, -lowpass_filter_width, lowpass_filter_width)
win = np.cos(t * math.pi / lowpass_filter_width / 2) ** 2
t = t * math.pi
with np.errstate(invalid="ignore", divide="ignore"):
k = np.where(t == 0, 1.0, np.sin(t) / t)
k = (k * win * base / o).astype(np.float32)
xp = np.pad(np.asarray(x, np.float32), (width, width + o))
frames = np.lib.stride_tricks.sliding_window_view(xp, k.shape[1])[::o]
y = (frames @ k.T).reshape(-1)
return y[: math.ceil(n * len(x) / o)].astype(np.float32)
def mel(wav24, basis, mean=-4.92, var=8.14):
"""melvqgan MelSpectrogram(n_fft 1920, 128 mels up to 12 kHz, hop 480, center=False): reflect padding of 720 each
side, periodic Hann, magnitude, log of the clamp at 1e-5, then (x - mean) / sqrt(var). Returns [1, T, 128]."""
x = np.pad(np.asarray(wav24, np.float32), ((N_FFT - HOP) // 2, (N_FFT - HOP) // 2), mode="reflect")
win = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)).astype(np.float32)
n = 1 + (len(x) - N_FFT) // HOP
idx = np.arange(N_FFT)[None, :] + HOP * np.arange(n)[:, None]
s = np.fft.rfft(x[idx] * win, axis=1)
mag = np.sqrt(s.real.astype(np.float64) ** 2 + s.imag.astype(np.float64) ** 2 + 1e-9).astype(np.float32)
m = np.log(np.maximum(basis @ mag.T, 1e-5)).T
return ((m - mean) / math.sqrt(var))[None].astype(np.float32)
def istft(re, im):
"""Vocos ISTFT(padding="same"): inverse real FFT of each frame, periodic Hann, overlap-add, trimmed by
(win - hop) / 2 each side, divided by the window envelope. re, im [1, 961, T] -> [T * 480]."""
spec = (re[0].astype(np.float64) + 1j * im[0].astype(np.float64))
T = spec.shape[1]
win = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)
frames = np.fft.irfft(spec, N_FFT, axis=0) * win[:, None] # [1920, T]
size = (T - 1) * HOP + N_FFT
y, env = np.zeros(size), np.zeros(size)
for i in range(T):
y[i * HOP:i * HOP + N_FFT] += frames[:, i]
env[i * HOP:i * HOP + N_FFT] += win ** 2
pad = (N_FFT - HOP) // 2
return (y[pad:-pad] / env[pad:-pad]).astype(np.float32)
class VevoTimbre:
def __init__(self, folder, provider="cpu", threads=4):
import onnxruntime as ort
folder = Path(folder)
if provider != "cpu" and hasattr(ort, "preload_dlls"):
try:
ort.preload_dlls()
except Exception:
pass
so = ort.SessionOptions()
so.intra_op_num_threads = threads
prov = ["CPUExecutionProvider"] if provider == "cpu" else [
("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}), "CPUExecutionProvider"]
self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=prov)
for n in ("content", "cond", "estimator", "vocoder")}
self.basis = np.load(folder / "mel_basis.npy")
self.cfg = json.loads((folder / "config.json").read_text())
def run(self, name, **feeds):
return self.s[name].run(None, feeds)
def tokens(self, wav16):
return self.run("content", wave=np.asarray(wav16, np.float32)[None])[0].astype(np.int64).reshape(1, -1)
def flow(self, cond, prompt, steps, rng, cfg=1.0, rescale_cfg=0.75):
"""fmt_model.reverse_diffusion: Euler steps at midpoints, CFG against the source-only unconditional pass."""
pl = prompt.shape[1]
L = cond.shape[1] - pl
xt = rng.standard_normal((1, L, 128)).astype(np.float32)
h = 1.0 / steps
for i in range(steps):
t = np.full(1, (0 + (i + 0.5) * h), np.float32)
f = self.run("estimator", x=np.concatenate([prompt, xt], 1), t=t, cond=cond)[0][:, pl:]
if cfg > 0:
u = self.run("estimator", x=xt, t=t, cond=np.zeros_like(cond[:, :L]))[0]
std = f.std(ddof=1)
fc = f + cfg * (f - u)
f = rescale_cfg * (fc * std / fc.std(ddof=1)) + (1 - rescale_cfg) * fc
xt = (xt + f * np.float32(h)).astype(np.float32)
return xt
def __call__(self, src, src_sr, ref, ref_sr, steps=32, seed=0, rng=None):
import soxr
rng = rng or np.random.default_rng(seed)
rs = lambda w, a: soxr.resample(np.asarray(w, np.float32), a, SR, quality="HQ").astype(np.float32) \
if a != SR else np.asarray(w, np.float32)
src, ref = rs(src, src_sr), rs(ref, ref_sr)
st, rt = self.tokens(resample(src, SR, 16000)), self.tokens(resample(ref, SR, 16000))
cond = self.run("cond", tokens=np.concatenate([rt, st], 1))[0]
prompt = mel(ref, self.basis, self.cfg["mel_mean"], self.cfg["mel_var"])
m = self.flow(cond, prompt, steps, rng)
re, im = self.run("vocoder", mel=np.ascontiguousarray(m.transpose(0, 2, 1)))
return istft(re, im), SR
if __name__ == "__main__":
import argparse
import soundfile as sf
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("source"); ap.add_argument("voice"); ap.add_argument("output")
ap.add_argument("--dir", default=str(Path(__file__).resolve().parent))
ap.add_argument("--cuda", action="store_true")
ap.add_argument("--steps", type=int, default=32); ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
s, ssr = sf.read(a.source, dtype="float32", always_2d=True)
r, rsr = sf.read(a.voice, dtype="float32", always_2d=True)
vc = VevoTimbre(a.dir, "cuda" if a.cuda else "cpu")
y, sr = vc(s.mean(1), ssr, r.mean(1), rsr, steps=a.steps, seed=a.seed)
sf.write(a.output, y, sr)