Audio-to-Audio
TensorRT
moonbox
inworld
voice-isolation
speech-enhancement
denoising
noise-suppression
48khz
full-band
Run this model with HF Jobs
Run moonbox-dev/voice-isolator-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/voice-isolator-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/voice-isolator-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/voice-isolator-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/voice-isolator-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
fp16 build of Inworld Voice Isolator
Browse filesFiles changed (5)
- .gitattributes+1
- fp16/model.engineAdded+3
- fp16/pipeline.pyAdded+92
- fp16/pipeline_trt.pyAdded+42
- fp16/trt_runner.pyAdded+98
32 unmodified lines33343532 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 -text32 unmodified lines3334353632 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 -textfp16/model.engine filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:3ad3e431070d8db395a8137adeb29f7d655be35b1a0d946b4fc3176dd8c705desize 3753333321234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Inworld Voice Isolator (offline, 48 kHz) with ONNX Runtime: numpy STFT / iSTFT and chunking around one graph.
from pipeline import VoiceIsolator iso = VoiceIsolator("fp16") # a folder holding model.onnx (+ model.onnx.data) voice = iso.isolate(audio) # float32 mono at 48 kHz -> float32 mono at 48 kHz
The graph maps the noisy spectrum to the change the network makes to it: spec [1, 1025, T, 2] real / imaginary parts of the STFT (n_fft 2048, hop 480, periodic Hann, centred) change [1, 1025, T, 2] the complex correction (mask delta x spectrum + bounded residual)and the output is the input plus the iSTFT of the change, exactly as inworld-voice-isolation'sVoiceIsolatorNetwork.forward. Clips longer than 8 s run in 8 s windows overlapping by 2 s with a linear crossfade(VoiceIsolatorNetwork.enhance). Only numpy and onnxruntime are needed."""
from __future__ import annotations
from pathlib import Path
import numpy as np
SR = 48000N_FFT = 2048HOP = 480CHUNK_SECONDS = 8.0OVERLAP_SECONDS = 2.0WINDOW = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)).astype(np.float32) # torch.hann_window
def stft(x: np.ndarray) -> np.ndarray: """torch.stft(x, 2048, 480, window, center=True, return_complex=True) of one clip: [1025, T] complex64.""" pad = N_FFT // 2 x = np.pad(x.astype(np.float32), pad, mode="reflect" if len(x) > pad else "constant") t = 1 + (len(x) - N_FFT) // HOP idx = np.arange(N_FFT)[None, :] + HOP * np.arange(t)[:, None] return np.fft.rfft(x[idx] * WINDOW, axis=-1).T.astype(np.complex64)
def istft(spec: np.ndarray, length: int) -> np.ndarray: """torch.istft(spec, 2048, 480, window, center=True, length=length): overlap-add over the squared window.""" frames = np.fft.irfft(spec.T, n=N_FFT, axis=-1).astype(np.float32) * WINDOW t = frames.shape[0] n = N_FFT + HOP * (t - 1) y = np.zeros(n, np.float32) env = np.zeros(n, np.float32) w2 = WINDOW * WINDOW for i in range(t): y[i * HOP:i * HOP + N_FFT] += frames[i] env[i * HOP:i * HOP + N_FFT] += w2 start = N_FFT // 2 y = y[start:start + length] / np.maximum(env[start:start + length], 1e-11) return np.pad(y, (0, length - len(y))) if len(y) < length else y
class VoiceIsolator: def __init__(self, model_dir: str | Path, providers=None, session_options=None): import onnxruntime as ort path = Path(model_dir) path = path / "model.onnx" if path.is_dir() else path self.session = ort.InferenceSession(str(path), session_options, providers=providers or ["CPUExecutionProvider"])
def forward(self, audio: np.ndarray) -> np.ndarray: """One window: audio [N] -> isolated voice [N].""" spec = stft(audio) ri = np.stack([spec.real, spec.imag], -1)[None].astype(np.float32) change = self.session.run(None, {"spec": ri})[0][0] return audio + istft(change[..., 0] + 1j * change[..., 1], len(audio))
def isolate(self, audio: np.ndarray) -> np.ndarray: """Any length: 8 s windows overlapping by 2 s, linear crossfades (the original's enhance).""" audio = np.asarray(audio, np.float32).reshape(-1) chunk = int(CHUNK_SECONDS * SR) overlap = min(int(OVERLAP_SECONDS * SR), chunk // 2) n = len(audio) if n <= chunk: return self.forward(audio) out = np.zeros(n, np.float32) weight = np.zeros(n, np.float32) starts = list(range(0, n - chunk, chunk - overlap)) + [n - chunk] for k, start in enumerate(starts): end = start + chunk w = np.ones(chunk, np.float32) if k > 0: fade_in = starts[k - 1] + chunk - overlap - start w[:fade_in] = 0.0 if overlap > 0: w[fade_in:fade_in + overlap] = np.linspace(0.0, 1.0, overlap, dtype=np.float32) if overlap > 0 and end < n: w[-overlap:] = np.linspace(1.0, 0.0, overlap, dtype=np.float32) out[start:end] += self.forward(audio[start:end]) * w weight[start:end] += w return out / np.maximum(weight, 1e-6)123456789101112131415161718192021222324252627282930313233343536373839404142"""Inworld Voice Isolator (offline) with a TensorRT engine: the same pipeline as pipeline.py (the STFT, the iSTFT andthe 8 s windows with 2 s crossfades in numpy), with- model.engine: spec [1, 1025, T, 2] (the window's STFT as real / imaginary; T 100 - 801 frames: 1-8 s at 48 kHz) -> change [1, 1025, T, 2] (the complex change to add to the noisy spectrum).Built from the fp16 ONNX build, whose weights are stored in fp16 and read as fp32: the engine's math is fp32. Needsnumpy, tensorrt-cu12 / tensorrt-lean-cu12 10.x and polygraphy; soundfile to read and write files.
python fp16/pipeline_trt.py noisy_48k.wav clean.wav"""
from __future__ import annotations
import sysfrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from pipeline import SR, VoiceIsolator # noqa: E402from trt_runner import OrtLike # noqa: E402
MIN_SECONDS = 1.0
class VoiceIsolatorTrt(VoiceIsolator): def __init__(self, model_dir=HERE): path = Path(model_dir) self.session = OrtLike(path / "model.engine" if path.is_dir() else path, ["change"])
def isolate(self, audio): audio = np.asarray(audio, np.float32).reshape(-1) if len(audio) < MIN_SECONDS * SR: raise ValueError(f"{len(audio) / SR:.2f} s of audio; the engine takes at least {MIN_SECONDS:.0f} s") return super().isolate(audio)
if __name__ == "__main__": import soundfile as sf x, sr = sf.read(sys.argv[1], dtype="float32", always_2d=True) assert sr == SR, "48 kHz audio" sf.write(sys.argv[2], VoiceIsolatorTrt().isolate(x.mean(1)), 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)].gitattributes+1
fp16/model.engineAdded+3
fp16/pipeline.pyAdded+92
fp16/pipeline_trt.pyAdded+42
fp16/trt_runner.pyAdded+98