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.
Instructions to use moonbox-dev/Vevo-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/Vevo-TensorRT with TensorRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
int8 build of Vevo
Browse filesFiles changed (10)
- .gitattributes+4
- int8/cond.engineAdded+3
- int8/config.jsonAdded+1
- int8/content.engineAdded+3
- int8/estimator.engineAdded+3
- int8/mel_basis.npyAdded+3
- int8/pipeline.pyAdded+143
- int8/pipeline_trt.pyAdded+56
- int8/trt_runner.pyAdded+98
- int8/vocoder.engineAdded+3
32 unmodified lines3334353637383932 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textint8/cond.engine filter=lfs diff=lfs merge=lfs -textint8/content.engine filter=lfs diff=lfs merge=lfs -textint8/estimator.engine filter=lfs diff=lfs merge=lfs -textint8/vocoder.engine filter=lfs diff=lfs merge=lfs -text123version https://git-lfs.github.com/spec/v1oid sha256:de0a76c5980ec4b0ce73442369cbbea503af9406ff578d4d75876b5a82bccb7dsize 779185801{"mel_mean": -4.92, "mel_var": 8.14}123version https://git-lfs.github.com/spec/v1oid sha256:ad5aa23c835e89710f9f57c5359efc3e32ef376d3fcc8556fc5963d5c23f2855size 1136352348123version https://git-lfs.github.com/spec/v1oid sha256:d309838a44ec2778ff03ec928b35f5086c57a56d7cb15c1a34fae02cbfe72241size 1367466628123version https://git-lfs.github.com/spec/v1oid sha256:7bb7e7de4592bd36a29d212f62877f9095d8f476a9bbb10ae013d29e94aebbc4size 492160123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""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 thereference 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 jsonimport mathfrom 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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""Vevo-Timbre (zero-shot voice conversion) with TensorRT engines: the same pipeline as pipeline.py (the officialinference_fm: content tokens of the source and the reference, the condition, 32 flow-matching steps with thereference's mel as the prompt, the vocoder; resampling, mel and iSTFT in numpy), with each graph run as an engine:- content.engine: wave [1, N] (16 kHz, up to 30 s) -> tokens;- cond.engine: tokens [1, 50 - 2500] (reference + source) -> cond [1, L, 1024];- estimator.engine: x [1, 50 - 2500, 128], t [1], cond [1, 50 - 2500, 1024] -> flow;- vocoder.engine: mel [1, 128, 50 - 1500] -> real, imag.Built from the int8 ONNX build (int8 weights, fp32 math). Limits: a source of up to 30 s, a voice reference of up to20 s. Needs numpy, soundfile, soxr, tensorrt-cu12 / tensorrt-lean-cu12 10.x and polygraphy. Non-commercial licence(CC BY-NC 4.0).
python int8/pipeline_trt.py source.wav voice.wav out.wav [--steps 32] [--seed 0]"""
from __future__ import annotations
import jsonimport sysfrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from pipeline import VevoTimbre # noqa: E402from trt_runner import OrtLike # noqa: E402
OUTS = {"content": ["tokens"], "cond": ["cond"], "estimator": ["flow"], "vocoder": ["real", "imag"]}SOURCE_SECONDS, REF_SECONDS = 30, 20
class VevoTimbreTrt(VevoTimbre): def __init__(self, folder=HERE): folder = Path(folder) self.s = {n: OrtLike(folder / f"{n}.engine", o) for n, o in OUTS.items()} self.basis = np.load(folder / "mel_basis.npy") self.cfg = json.loads((folder / "config.json").read_text())
def __call__(self, src, src_sr, ref, ref_sr, steps=32, seed=0, rng=None): if len(src) / src_sr > SOURCE_SECONDS or len(ref) / ref_sr > REF_SECONDS: raise ValueError(f"the engines take a source of up to {SOURCE_SECONDS} s and a reference of up to " f"{REF_SECONDS} s") return super().__call__(src, src_sr, ref, ref_sr, steps, seed, rng)
if __name__ == "__main__": import argparse import soundfile as sf ap = argparse.ArgumentParser() ap.add_argument("source"); ap.add_argument("voice"); ap.add_argument("output") 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) v, vsr = sf.read(a.voice, dtype="float32", always_2d=True) y, sr = VevoTimbreTrt()(s.mean(1), ssr, v.mean(1), vsr, a.steps, a.seed) sf.write(a.output, y, sr)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""A minimal TensorRT engine runner: numpy in, numpy out (tensorrt-cu12 10.x and polygraphy; no torch).
from trt_runner import Engine e = Engine("model.engine") out = e({"input": x}) # dict of output name -> numpy array"""from __future__ import annotations
from pathlib import Path
import numpy as np
def lean_dlls(): """Version-compatible engines are built against and run on TensorRT's lean runtime (pip tensorrt-lean-cu12): put its DLL folder on the search path (Windows).""" import importlib.util import os spec = importlib.util.find_spec("tensorrt_lean_libs") if spec and spec.submodule_search_locations: d = list(spec.submodule_search_locations)[0] os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "") if hasattr(os, "add_dll_directory"): os.add_dll_directory(d)
class Engine: """allocation: "static" (memory for the profiles' largest shapes, reserved once) or "runtime" (sized to each call's shapes: for pipelines of many engines with wide profiles, which would otherwise reserve every engine's maximum)."""
def __init__(self, path, allocation="static"): lean_dlls() import tensorrt as trt from polygraphy.backend.trt import TrtRunner self.trt = trt logger = trt.Logger(trt.Logger.WARNING) runtime = trt.Runtime(logger) runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime engine = runtime.deserialize_cuda_engine(Path(path).read_bytes()) if engine is None: raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x " "and an RTX 30-series or newer GPU)") self.engine = engine self.runner = TrtRunner(engine, allocation_strategy=allocation) self.runner.activate() self.inputs = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors) if engine.get_tensor_mode(engine.get_tensor_name(i)) == trt.TensorIOMode.INPUT]
def __call__(self, feed: dict) -> dict: feed = {k: np.ascontiguousarray(v) for k, v in feed.items() if k in self.inputs} out = self.runner.infer(feed, check_inputs=True) return {k: np.array(v) for k, v in out.items()}
def close(self): """Release the engine's device memory and weights now (deactivating the runner alone keeps the weights on the GPU until the engine object is collected).""" runner = getattr(self, "runner", None) if runner is not None and runner.is_active: runner.deactivate() self.runner = self.engine = None
def __del__(self): try: self.close() except Exception: pass
class OrtLike: """An engine behind onnxruntime's InferenceSession calls (run / get_inputs / get_outputs / get_providers), so a pipeline.py written for ONNX Runtime runs its graphs on TensorRT unchanged. Outputs come back in the order the ONNX graph listed them (pass `outputs`), else in the engine's order."""
def __init__(self, path, outputs=None, allocation="static"): self.e = Engine(path, allocation) eng = self.e.engine names = [eng.get_tensor_name(i) for i in range(eng.num_io_tensors)] self.outs = list(outputs) if outputs else [n for n in names if n not in self.e.inputs]
def get_inputs(self): """name, type ("tensor(float16)" etc., as onnxruntime spells it) and shape (-1 for dynamic dimensions).""" from types import SimpleNamespace eng, trt = self.e.engine, self.e.trt names = {trt.float16: "float16", trt.float32: "float", trt.int64: "int64", trt.int32: "int32", trt.bool: "bool", trt.int8: "int8", trt.bfloat16: "bfloat16"} return [SimpleNamespace(name=n, type=f"tensor({names.get(eng.get_tensor_dtype(n), 'float')})", shape=list(eng.get_tensor_shape(n))) for n in self.e.inputs]
def get_outputs(self): from types import SimpleNamespace return [SimpleNamespace(name=n) for n in self.outs]
def get_providers(self): return ["TensorRT"]
def run(self, names, feed, run_options=None): out = self.e(feed) return [out[n] for n in (names or self.outs)]123version https://git-lfs.github.com/spec/v1oid sha256:070b600b6336da9a10a3995b69d3af88faf86ce016cf0eb8df226697f3fde70asize 1116870644.gitattributes+4
int8/cond.engineAdded+3
int8/config.jsonAdded+1
int8/content.engineAdded+3
int8/estimator.engineAdded+3
int8/mel_basis.npyAdded+3
int8/pipeline.pyAdded+143
int8/pipeline_trt.pyAdded+56
int8/trt_runner.pyAdded+98
int8/vocoder.engineAdded+3