int8 build of MeanVC2
Browse filesFiles changed (7)
- int8/content_160ms.onnxAdded+3
- int8/content_80ms.onnxAdded+3
- int8/dit_120ms.onnxAdded+3
- int8/dit_40ms.onnxAdded+3
- int8/pipeline.pyAdded+175
- int8/speaker.onnxAdded+3
- int8/vocoder.onnxAdded+3
123version https://git-lfs.github.com/spec/v1oid sha256:b0fbc32e871eb5fc8d2d5919ca0e53f7ee2840065e0990316bcc181e27203af4size 75781949123version https://git-lfs.github.com/spec/v1oid sha256:74466705219e625223b0584b5aced1fd0bdf1188149c4c09b5a9b1a029d9ff3csize 75781949123version https://git-lfs.github.com/spec/v1oid sha256:1d2bb292220ac718efba40cf4fdf8175d330efd6273970774038b46a35682deasize 18410812123version https://git-lfs.github.com/spec/v1oid sha256:ae5ecb1c244f2e667385a139860dfeea4b87c1abc17c3599b5cfd3b8ad8022fesize 18410812123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"""MeanVC2 voice conversion with ONNX Runtime: re-voice a recording into the voice of a reference recording, keepingits words and timing. Follows the official end-to-end script (src/infer/infer_e2e.py): FastU2++ content features ofthe source in streaming steps, a WavLM-Large + ECAPA-TDNN speaker embedding of the reference, the chunked mean-flowDiT (3 steps per chunk, KV cache across chunks), the Vocos vocoder. 16 kHz output. Two presets: "120ms" (120 mschunks + 40 ms look-ahead, the official recommendation for quality) and "40ms" (40 ms chunks + 40 ms look-ahead).Needs numpy, onnxruntime (or onnxruntime-gpu), soundfile and soxr.
python fp16/pipeline.py source.wav voice.wav out.wav [--preset 120ms] [--cuda] [--steps 3] [--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, 160PRESETS = { "120ms": dict(content="content_160ms", dit="dit_120ms", window=19, stride=16, offset_init=8, offset_step=4, req_cache=8, chunk=12, block=4), "40ms": dict(content="content_80ms", dit="dit_40ms", window=11, stride=8, offset_init=4, offset_step=2, req_cache=4, chunk=4, block=4),}
def int16_scale(x): """The official scripts read 16-bit files as int16 and divide by 32767 (soundfile's float read divides by 32768).""" return np.asarray(x, np.float32) * np.float32(32768 / 32767)
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 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] # [640, 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 s, e = N_FFT // 2, size - N_FFT // 2 return (y[s:e] / env[s:e]).astype(np.float32)
class MeanVC2: def __init__(self, folder, preset="120ms", provider="cpu", threads=4): import onnxruntime as ort folder = Path(folder) self.c = PRESETS[preset] 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"{self.c[k]}.onnx" if k else folder / f"{n}.onnx"), so, providers=prov) for n, k in (("content", "content"), ("speaker", None), ("dit", "dit"), ("vocoder", None))}
def run(self, name, **feeds): return self.s[name].run(None, feeds)
def content(self, wav16): """infer_e2e.extract_bn: the streaming encoder over 19 (11) fbank frames every 16 (8), from zero caches.""" c = self.c fb = kaldi_fbank(int16_scale(wav16)) att = np.zeros((6, 4, c["req_cache"], 128), np.float32) cnn = np.zeros((6, 1, 256, 8), np.float32) out, off, i = [], c["offset_init"], 0 while i + c["window"] <= fb.shape[0]: bn, att, cnn = self.run("content", fbank=fb[None, i:i + c["window"]], offset=np.array(off, np.int64), att_cache=att, cnn_cache=cnn) out.append(bn[0]) off += c["offset_step"] i += c["stride"] return np.concatenate(out, 0)
def speaker(self, wav16): return self.run("speaker", wave=int16_scale(wav16)[None])[0]
def convert(self, bn, spk, steps, rng): """infer_e2e.vc_inference: chunks of `chunk` frames plus `block` frames of look-ahead, `steps` mean-flow steps from t = 1 to 0 each, the KV cache of the last step carried to the next chunk.""" c = self.c cond = upsample4(bn)[None] L = cond.shape[1] noise = rng.standard_normal((1, L, 80)).astype(np.float32) ts = np.linspace(1.0, 0.0, steps + 1, dtype=np.float32) k = v = np.zeros((4, 1, 2, 0, 64), np.float32) out, offset = [], 0 for start in range(0, L, c["chunk"]): mid = min(start + c["chunk"], L) end = min(mid + c["block"], L) x = noise[:, start:end] for i in range(steps): u, nk, nv = self.run("dit", x=x, t=ts[i:i + 1], r=ts[i + 1:i + 2], cond=np.ascontiguousarray(cond[:, start:end]), spk=spk, 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 out.append(x[:, :mid - start]) offset += mid - start return np.concatenate(out, 1)
def __call__(self, src, src_sr, ref, ref_sr, steps=3, 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) x = self.convert(self.content(src), self.speaker(ref), 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("--preset", default="120ms", choices=list(PRESETS)) ap.add_argument("--cuda", action="store_true") ap.add_argument("--steps", type=int, default=3); 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 = MeanVC2(a.dir, a.preset, "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_160ms.onnxAdded+3
int8/content_80ms.onnxAdded+3
int8/dit_120ms.onnxAdded+3
int8/dit_40ms.onnxAdded+3
int8/pipeline.pyAdded+175
int8/speaker.onnxAdded+3
int8/vocoder.onnxAdded+3