int8 build of MeanVC
Browse filesFiles changed (6)
- int8/content.onnxAdded+3
- int8/dit.onnxAdded+3
- int8/mel_basis.npyAdded+3
- int8/pipeline.pyAdded+181
- int8/speaker.onnxAdded+3
- int8/vocoder.onnxAdded+3
123version https://git-lfs.github.com/spec/v1oid sha256:cc73300066f3442077b10e55aa09ce50595da80cf01abc3aae8621b6debf8ac7size 25976459123version https://git-lfs.github.com/spec/v1oid sha256:15f2c6c1fba1066e250961a61c127065d086966b9908e479ec67a83a3017d018size 14704431123version https://git-lfs.github.com/spec/v1oid sha256:50f72dcd637c02334f1f41110b5ec017091c2213763fcc00cbbaf7a02f1d136esize 164288123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""MeanVC voice conversion with ONNX Runtime: re-voice a recording into the voice of a reference recording, keeping itswords and timing. Follows the official offline script (src/infer/infer_ref.py, as scripts/infer_ref.sh runs it): FastU2++content features of the source in streaming steps, a WavLM-Large + ECAPA-TDNN speaker embedding and the mel spectrogramof the reference, the chunked mean-flow DiT (200 ms chunks, 2 steps each, the previous chunk and a KV cache ascontext), the Vocos vocoder. 16 kHz output. Needs numpy, onnxruntime (or onnxruntime-gpu), soundfile and soxr.
python fp16/pipeline.py source.wav voice.wav out.wav [--cuda] [--steps 2] [--seed 0]
The flow's starting noise comes from numpy's generator (`seed`), so a seed gives the same output every run (not thesame as PyTorch with that seed)."""
from __future__ import annotations
from pathlib import Path
import numpy as np
SR, N_FFT, HOP = 16000, 640, 160CHUNK, KV_MAX = 20, 100
def kaldi_fbank(wav): """torchaudio.compliance.kaldi.fbank(num_mel_bins=80, dither=0, energy_floor=0, sample_frequency=16000) of the wave scaled to 16-bit range: 25 / 10 ms povey frames (snip_edges), DC removal, pre-emphasis 0.97, 512-point power spectrum, 80 Kaldi mel bins from 20 Hz to Nyquist, natural log (floored at float eps). Returns [T, 80].""" x = np.asarray(wav, np.float64) * 32768.0 fl, fs, nfft = 400, 160, 512 n = 1 + (len(x) - fl) // fs if n < 1: return np.zeros((0, 80), np.float32) idx = np.arange(fl)[None, :] + fs * np.arange(n)[:, None] f = x[idx] f = f - f.mean(1, keepdims=True) f = np.concatenate([f[:, :1] - 0.97 * f[:, :1], f[:, 1:] - 0.97 * f[:, :-1]], 1) win = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(fl) / (fl - 1))) ** 0.85 p = np.abs(np.fft.rfft(f * win, nfft, axis=1)) ** 2 melf = lambda hz: 1127.0 * np.log(1.0 + hz / 700.0) centers = np.linspace(melf(20.0), melf(8000.0), 82) fft_mel = melf(np.arange(nfft // 2) * 16000.0 / nfft) bank = np.zeros((80, nfft // 2 + 1)) for m in range(80): l, c, r = centers[m], centers[m + 1], centers[m + 2] bank[m, : nfft // 2] = np.maximum(0, np.minimum((fft_mel - l) / (c - l), (r - fft_mel) / (r - c))) return np.log(np.maximum(p @ bank.T, np.finfo(np.float32).eps)).astype(np.float32)
def prompt_mel(wav, basis): """infer_ref.MelSpectrogramFeatures: torch.stft(n_fft 1024, hop 160, 640-point periodic Hann centred in the frame, center=True with reflect padding), magnitude sqrt(|S|^2 + 1e-6), the librosa mel basis (80 bins, 0-8 kHz), 20 log10 floored at -115 dB, minus 20, then mapped to [-1, 1]. Returns [1, T, 80].""" nfft = 1024 x = np.pad(np.asarray(wav, np.float64), (nfft // 2, nfft // 2), mode="reflect") win = np.zeros(nfft) win[(nfft - N_FFT) // 2:(nfft - N_FFT) // 2 + N_FFT] = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT) n = 1 + (len(x) - nfft) // HOP idx = np.arange(nfft)[None, :] + HOP * np.arange(n)[:, None] s = np.fft.rfft(x[idx] * win, axis=1) mag = np.sqrt(s.real ** 2 + s.imag ** 2 + 1e-6) m = mag @ basis.astype(np.float64).T db = 20 * np.log10(np.maximum(m, 10 ** (-115 / 20))) - 20 return np.clip(2 * (db + 115) / 115 - 1, -1, 1)[None].astype(np.float32)
def upsample4(bn): """F.interpolate(size=4 T, mode='linear', align_corners=True) along time: [T, C] -> [4 T, C].""" t = bn.shape[0] if t == 1: return np.repeat(bn, 4, 0) pos = np.arange(4 * t, dtype=np.float64) * (t - 1) / (4 * t - 1) i0 = np.minimum(np.floor(pos).astype(np.int64), t - 2) w = (pos - i0)[:, None] return ((1 - w) * bn[i0] + w * bn[i0 + 1]).astype(np.float32)
def istft(re, im): """Vocos ISTFT(padding="center") = torch.istft(n_fft 640, hop 160, periodic Hann, center=True): inverse real FFT of each frame, windowed overlap-add divided by the window envelope, n_fft / 2 trimmed each side. re, im [1, 321, T] -> [160 (T - 1)].""" 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] 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 s, e = N_FFT // 2, size - N_FFT // 2 return (y[s:e] / env[s:e]).astype(np.float32)
class MeanVC: 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", "speaker", "dit", "vocoder")} self.basis = np.load(folder / "mel_basis.npy")
def run(self, name, **feeds): return self.s[name].run(None, feeds)
def content(self, wav16): """infer_ref's encoder loop: 23 fbank frames every 20 (a short last window zero-padded to 10), from empty caches (keeping the last 10 frames of attention cache).""" fb = kaldi_fbank(wav16) att = np.zeros((7, 4, 0, 128), np.float32) cnn = np.zeros((7, 1, 256, 8), np.float32) out, off = [], 0 for i in range(0, fb.shape[0], 20): ch = fb[i:i + 23] if ch.shape[0] < 10: ch = np.pad(ch, ((0, 10 - ch.shape[0]), (0, 0))) bn, att, cnn = self.run("content", fbank=ch[None], offset=np.array(off, np.int64), att_cache=att, cnn_cache=cnn) out.append(bn[0]) off += bn.shape[1] return np.concatenate(out, 0)
def convert(self, bn, spk, prompt, steps, rng): """infer_ref.inference: 20-frame chunks, each from fresh noise in `steps` mean-flow steps, with the previous chunk's output and the KV cache (its last 100 frames) as context.""" cond = upsample4(bn)[None] L = cond.shape[1] ts = {1: [1.0, 0.0], 2: [1.0, 0.8, 0.0]}.get(steps) ts = np.array(ts if ts else np.linspace(1.0, 0.0, steps + 1), np.float32) k = v = np.zeros((4, 1, 2, 0, 64), np.float32) cache = np.zeros((1, 0, 80), np.float32) out, offset = [], 0 for start in range(0, L, CHUNK): c = np.ascontiguousarray(cond[:, start:start + CHUNK]) x = rng.standard_normal((1, c.shape[1], 80)).astype(np.float32) for i in range(steps): u, nk, nv = self.run("dit", x=x, t=ts[i:i + 1], r=ts[i + 1:i + 2], cache=cache, cond=c, spk=spk, prompt=prompt, offset=np.array(offset, np.int64), k_cache=k, v_cache=v) x = (x - (ts[i] - ts[i + 1]) * u).astype(np.float32) k, v = nk, nv offset += x.shape[1] cache = x out.append(x) if offset > 40 and k.shape[3] > KV_MAX: k, v = np.ascontiguousarray(k[:, :, :, -KV_MAX:]), np.ascontiguousarray(v[:, :, :, -KV_MAX:]) return np.concatenate(out, 1)
def __call__(self, src, src_sr, ref, ref_sr, steps=2, 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) spk = self.run("speaker", wave=ref[None])[0] x = self.convert(self.content(src), spk, prompt_mel(ref, self.basis), steps, rng) mel = np.ascontiguousarray(((x + 1) / 2).transpose(0, 2, 1)) re, im = self.run("vocoder", mel=mel) 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=2); 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 = MeanVC(a.dir, "cuda" if a.cuda else "cpu") wav, sr = vc(s.mean(1), ssr, r.mean(1), rsr, steps=a.steps, seed=a.seed) sf.write(a.output, wav, sr)123version https://git-lfs.github.com/spec/v1oid sha256:24764e4095c917db72078cf8490947a0d623a61e078b72dbfb8efbc8d76f2b46size 352627179123version https://git-lfs.github.com/spec/v1oid sha256:8f1153cee321abc3e684744390f0f1c41848c9fa0038af34fc9be2ef0f4fc0f2size 8498430int8/content.onnxAdded+3
int8/dit.onnxAdded+3
int8/mel_basis.npyAdded+3
int8/pipeline.pyAdded+181
int8/speaker.onnxAdded+3
int8/vocoder.onnxAdded+3