Audio-to-Audio
MLX
moonbox
meanvc2
voice-conversion
zero-shot
streaming
wavlm
multilingual
apple-silicon
Run this model with HF Jobs
Run moonbox-dev/MeanVC2-MLX 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/MeanVC2-MLX. 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/MeanVC2-MLX 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/MeanVC2-MLX with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use moonbox-dev/MeanVC2-MLX with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download moonbox-dev/MeanVC2-MLX --local-dir MeanVC2-MLX
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
Download fp16/mlx_model.py from moonbox-dev/MeanVC2-MLX: direct link, hf CLI and curl.
- Browser
- Download file 32.6 kB
-
https://huggingface.co/moonbox-dev/MeanVC2-MLX/resolve/main/fp16/mlx_model.py
- Command line
-
hf download hf://moonbox-dev/MeanVC2-MLX/fp16/mlx_model.py
-
curl -L -o mlx_model.py https://huggingface.co/moonbox-dev/MeanVC2-MLX/resolve/main/fp16/mlx_model.py
32.6 kB
| """MeanVC2 on MLX: streaming zero-shot voice conversion in one file (mlx, numpy, soxr; no PyTorch at run time). | |
| Re-voices a recording into the voice of a few seconds of reference audio, keeping its words and timing; 16 kHz | |
| output. Follows the official end-to-end script (github.com/ASLP-lab/MeanVC2 @13acf84, src/infer/infer_e2e.py): | |
| content FastU2++ streaming encoder (the first 6 conformer layers of the official TorchScript ASR model, the | |
| ones its traced step function runs): Kaldi fbank windows of 19 (11) frames every 16 (8) -> 4 (2) | |
| content vectors per step, attention and convolution caches carried between steps | |
| speaker WavLM-Large + ECAPA-TDNN (Microsoft UniSpeech's speaker-verification model): reference wave -> | |
| speaker embedding [256] | |
| dit the chunked mean-flow DiT (18M parameters, with its global timbre memory): 3 flow steps per chunk | |
| of 12 (4) mel frames plus 4 frames of look-ahead, a KV cache carried between chunks | |
| vocoder Vocos (8 ConvNeXt blocks + ISTFT head), inverse STFT n_fft 640 / hop 160 | |
| Two presets: "120ms" (120 ms chunks + 40 ms look-ahead, FastU2++ 160 ms; the official recommendation for quality) | |
| and "40ms" (40 ms chunks + 40 ms look-ahead, FastU2++ 80 ms; lower latency). | |
| A build folder (made by convert_mlx.py) holds config.json (sizes, precision, quantization, sources), this file, and | |
| content / dit_120ms / dit_40ms / vocoder / speaker .safetensors (one content encoder for both presets: the official | |
| fastu2pp_160ms.pt and fastu2pp_80ms.pt hold the same weights in the layers the step function runs; they differ only in | |
| the traced window size). A quantized layer is one whose | |
| weights come with `.scales` (MLX affine quantization); everything else is stored in the build's float dtype. | |
| import sys, soundfile as sf | |
| sys.path.insert(0, "8bit") | |
| from mlx_model import MeanVC2 | |
| vc = MeanVC2("8bit", preset="120ms") | |
| src, sr = sf.read("source.wav", dtype="float32") | |
| ref, ref_sr = sf.read("voice.wav", dtype="float32") | |
| wav, out_sr = vc(src, sr, ref, ref_sr, steps=3, seed=0) # numpy float32, 16 kHz | |
| python mlx_model.py source.wav voice.wav out.wav [--preset 120ms] [--steps 3] [--seed 0] | |
| The flow's starting noise comes from numpy's generator (`seed`, or `rng`), the same draw as the ONNX pipeline.py, so | |
| a seed gives the same output every run. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| from pathlib import Path | |
| import mlx.core as mx | |
| import mlx.nn as nn | |
| import numpy as np | |
| SR, N_FFT, HOP = 16000, 640, 160 | |
| PRESETS = { # infer_e2e.MODEL_PRESETS | |
| "120ms": dict(content="content", dit="dit_120ms", window=19, stride=16, offset_init=8, offset_step=4, | |
| req_cache=8, chunk=12, block=4), | |
| "40ms": dict(content="content", dit="dit_40ms", window=11, stride=8, offset_init=4, offset_step=2, | |
| req_cache=4, chunk=4, block=4), | |
| } | |
| DTYPES = {"float32": mx.float32, "bfloat16": mx.bfloat16, "float16": mx.float16} | |
| def gelu(x): | |
| return nn.gelu(x) # exact (erf) GELU, torch's default | |
| def gelu_tanh(x): | |
| return 0.5 * x * (1 + mx.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x ** 3))) | |
| class LayerNorm(nn.Module): | |
| def __init__(self, dim, eps=1e-5, affine=True): | |
| super().__init__() | |
| self.eps = eps | |
| if affine: | |
| self.weight = mx.ones((dim,)) | |
| self.bias = mx.zeros((dim,)) | |
| def __call__(self, x): | |
| return mx.fast.layer_norm(x, self.get("weight"), self.get("bias"), self.eps) | |
| # ---------------------------------------------------------------------------------------------------- numpy front end | |
| 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 rel_pos_table(start, n, dim=256): | |
| """WeNet's RelPositionalEncoding table (interleaved sin / cos, float32) for positions start .. start + n - 1.""" | |
| pos = np.arange(start, start + n, dtype=np.float32)[:, None] | |
| div = np.exp(np.arange(0, dim, 2, dtype=np.float32) * np.float32(-(math.log(10000.0) / dim))) | |
| pe = np.zeros((n, dim), np.float32) | |
| pe[:, 0::2] = np.sin(pos * div) | |
| pe[:, 1::2] = np.cos(pos * div) | |
| return pe | |
| # ---------------------------------------------------------------------------------------------------- content encoder | |
| class ConformerLayer(nn.Module): | |
| """WeNet ConformerEncoderLayer (macaron FFN, relative-position self-attention without rel_shift, causal | |
| convolution module with LayerNorm), the traced streaming step: attention over [cache, chunk], depthwise | |
| convolution over [cache, chunk] with no padding.""" | |
| def __init__(self, d=256, heads=4, ffn=2048, kernel=9): | |
| super().__init__() | |
| self.heads, self.dk, self.lorder = heads, d // heads, kernel - 1 | |
| self.norm_ff_macaron, self.norm_mha, self.norm_conv, self.norm_ff, self.norm_final = (LayerNorm(d) for _ in range(5)) | |
| self.ff_macaron_w1, self.ff_macaron_w2 = nn.Linear(d, ffn), nn.Linear(ffn, d) | |
| self.ff_w1, self.ff_w2 = nn.Linear(d, ffn), nn.Linear(ffn, d) | |
| self.linear_q, self.linear_k, self.linear_v, self.linear_out = (nn.Linear(d, d) for _ in range(4)) | |
| self.linear_pos = nn.Linear(d, d, bias=False) | |
| self.pos_bias_u = mx.zeros((heads, self.dk)) | |
| self.pos_bias_v = mx.zeros((heads, self.dk)) | |
| self.pointwise_conv1 = nn.Linear(d, 2 * d) | |
| self.depthwise_conv = nn.Conv1d(d, d, kernel, groups=d) | |
| self.conv_norm = LayerNorm(d) | |
| self.pointwise_conv2 = nn.Linear(d, d) | |
| def heads_of(self, x): | |
| b, n, _ = x.shape | |
| return x.reshape(b, n, self.heads, self.dk).transpose(0, 2, 1, 3) | |
| def __call__(self, x, pos, k_cache, v_cache, cnn_cache): | |
| x = x + 0.5 * self.ff_macaron_w2(nn.silu(self.ff_macaron_w1(self.norm_ff_macaron(x)))) | |
| h = self.norm_mha(x) | |
| b, n, _ = h.shape | |
| q = self.linear_q(h).reshape(b, n, self.heads, self.dk) # [b, n, h, dk] | |
| k = mx.concatenate([k_cache, self.heads_of(self.linear_k(h))], 2) | |
| v = mx.concatenate([v_cache, self.heads_of(self.linear_v(h))], 2) | |
| p = self.heads_of(self.linear_pos(pos)) # [1, h, cache + n, dk] | |
| qu = (q + self.pos_bias_u).transpose(0, 2, 1, 3) | |
| qv = (q + self.pos_bias_v).transpose(0, 2, 1, 3) | |
| scores = (qu @ k.transpose(0, 1, 3, 2) + qv @ p.transpose(0, 1, 3, 2)) / math.sqrt(self.dk) | |
| a = mx.softmax(scores.astype(mx.float32), axis=-1).astype(v.dtype) @ v | |
| x = x + self.linear_out(a.transpose(0, 2, 1, 3).reshape(b, n, -1)) | |
| c = mx.concatenate([cnn_cache, self.norm_conv(x)], 1) # [b, lorder + n, d] (time-major) | |
| new_cnn = c[:, -self.lorder:] | |
| y = self.pointwise_conv1(c) | |
| y = y[..., : y.shape[-1] // 2] * mx.sigmoid(y[..., y.shape[-1] // 2:]) | |
| y = nn.silu(self.conv_norm(self.depthwise_conv(y))) | |
| x = x + self.pointwise_conv2(y) | |
| x = x + 0.5 * self.ff_w2(nn.silu(self.ff_w1(self.norm_ff(x)))) | |
| return self.norm_final(x), k, v, new_cnn | |
| class ContentEncoder(nn.Module): | |
| """FastU2++: Conv2dSubsampling4 (two 3x3 stride-2 convolutions, linear to 256, x16) + 6 conformer layers + | |
| after_norm, run one streaming step at a time.""" | |
| def __init__(self, d=256, layers=6, heads=4): | |
| super().__init__() | |
| self.conv0 = nn.Conv2d(1, d, 3, stride=2) | |
| self.conv2 = nn.Conv2d(d, d, 3, stride=2) | |
| self.embed_out = nn.Linear(d * 19, d) | |
| self.layers = [ConformerLayer(d, heads) for _ in range(layers)] | |
| self.after_norm = LayerNorm(d) | |
| self.d, self.heads = d, heads | |
| def step(self, fbank, pos, ks, vs, cnns): | |
| """fbank [1, W, 80], pos [1, R + n, 256] -> content [1, n, 256] and the next caches (lists per layer).""" | |
| x = nn.relu(self.conv2(nn.relu(self.conv0(fbank[..., None])))) # [1, t, f, c] | |
| b, t, f, c = x.shape | |
| x = self.embed_out(x.transpose(0, 1, 3, 2).reshape(b, t, c * f)) * 16.0 | |
| nk, nv, nc = [], [], [] | |
| for layer, k, v, cc in zip(self.layers, ks, vs, cnns): | |
| x, k2, v2, c2 = layer(x, pos, k, v, cc) | |
| r = k.shape[2] | |
| nk.append(k2[:, :, -r:]); nv.append(v2[:, :, -r:]); nc.append(c2) | |
| return self.after_norm(x), nk, nv, nc | |
| # ---------------------------------------------------------------------------------------------------- converter (DiT) | |
| def timestep_features(t, dim=256, scale=1000.0): | |
| half = dim // 2 | |
| f = mx.exp(mx.arange(half, dtype=mx.float32) * -(math.log(10000) / (half - 1))) | |
| e = scale * t[:, None].astype(mx.float32) * f[None] | |
| return mx.concatenate([mx.sin(e), mx.cos(e)], -1) | |
| class TimestepEmbedding(nn.Module): | |
| def __init__(self, dim): | |
| super().__init__() | |
| self.mlp0, self.mlp2 = nn.Linear(256, dim), nn.Linear(dim, dim) | |
| def __call__(self, t, dtype): | |
| return self.mlp2(nn.silu(self.mlp0(timestep_features(t).astype(dtype)))) | |
| class GlobalTimbreMemory(nn.Module): | |
| def __init__(self, spk=256, slots=32, hidden=256): | |
| super().__init__() | |
| self.slots, self.hidden = slots, hidden | |
| self.mlp_k0, self.mlp_k2 = nn.Linear(spk, spk), nn.Linear(spk, slots * hidden) | |
| self.mlp_v0, self.mlp_v2 = nn.Linear(spk, spk), nn.Linear(spk, slots * hidden) | |
| self.k_prior = mx.zeros((slots, hidden)) | |
| self.v_prior = mx.zeros((slots, hidden)) | |
| self.norm_k, self.norm_v = LayerNorm(hidden), LayerNorm(hidden) | |
| def __call__(self, spk): | |
| b = spk.shape[0] | |
| k = self.mlp_k2(nn.silu(self.mlp_k0(spk))).reshape(b, self.slots, self.hidden) | |
| v = self.mlp_v2(nn.silu(self.mlp_v0(spk))).reshape(b, self.slots, self.hidden) | |
| return self.norm_k(k + mx.tanh(self.k_prior)[None]), self.norm_v(v + mx.tanh(self.v_prior)[None]) | |
| class TemporalTimbre(nn.Module): | |
| """Content frames (queries) x timbre memory (keys / values), 4 heads of 32: frame-level timbre condition.""" | |
| def __init__(self, content=256, hidden=256, attn=128, heads=4): | |
| super().__init__() | |
| self.heads, self.hd = heads, attn // heads | |
| self.q_proj, self.k_proj, self.v_proj = nn.Linear(content, attn), nn.Linear(hidden, attn), nn.Linear(hidden, attn) | |
| self.out_proj = nn.Linear(attn, content) | |
| self.attn_norm = LayerNorm(content) | |
| def __call__(self, bn, k_mem, v_mem): | |
| b, t, _ = bn.shape | |
| sp = lambda x: x.reshape(b, x.shape[1], self.heads, self.hd).transpose(0, 2, 1, 3) | |
| q, k, v = sp(self.q_proj(bn)), sp(self.k_proj(k_mem)), sp(self.v_proj(v_mem)) | |
| a = mx.softmax((q @ k.transpose(0, 1, 3, 2)).astype(mx.float32) * self.hd ** -0.5, -1).astype(v.dtype) @ v | |
| return self.attn_norm(self.out_proj(a.transpose(0, 2, 1, 3).reshape(b, t, -1))) | |
| def block_mask(n, chunk, block, t_p, t_f): | |
| """BlockAttnProcessor.try_cached_mask over the n positions of [cache, new]: same chunk, the t_p chunks before it, | |
| the first t_f blocks of the next one.""" | |
| idx = np.arange(n) | |
| ci = idx // chunk | |
| qi, kj = ci[:, None], ci[None, :] | |
| nxt = (kj == qi + 1) & ((idx % chunk)[None, :] < block * t_f) | |
| return (qi == kj) | ((kj >= qi - t_p) & (kj < qi)) | nxt | |
| class DiTBlock(nn.Module): | |
| def __init__(self, dim, heads, dim_head, ff_mult, t_p, t_f): | |
| super().__init__() | |
| self.heads, self.dh, self.t_p, self.t_f = heads, dim_head, t_p, t_f | |
| inner = heads * dim_head | |
| self.attn_norm = nn.Linear(dim, dim * 6) | |
| self.to_q, self.to_k, self.to_v = nn.Linear(dim, inner), nn.Linear(dim, inner), nn.Linear(dim, inner) | |
| self.q_norm = mx.ones((dim_head,)) | |
| self.k_norm = mx.ones((dim_head,)) | |
| self.to_out = nn.Linear(inner, dim) | |
| self.ff0, self.ff2 = nn.Linear(dim, int(dim * ff_mult)), nn.Linear(int(dim * ff_mult), dim) | |
| def __call__(self, x, mod, cache, n_pos, chunk, block): | |
| """mod: this block's 6 modulation vectors [b, 6 dim]; cache: (k, v) before rope or None; n_pos: the | |
| positions so far (offset + len). Returns the block output and the new (k, v) without the look-ahead.""" | |
| shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mx.split(mod, 6, -1) | |
| h = mx.fast.layer_norm(x, None, None, 1e-6) * (1 + scale_msa[:, None]) + shift_msa[:, None] | |
| b, n, _ = h.shape | |
| sp = lambda y: y.reshape(b, n, self.heads, self.dh).transpose(0, 2, 1, 3) | |
| q = mx.fast.rms_norm(sp(self.to_q(h)), self.q_norm, 1e-6) | |
| k = mx.fast.rms_norm(sp(self.to_k(h)), self.k_norm, 1e-6) | |
| v = sp(self.to_v(h)) | |
| if cache is not None: | |
| k = mx.concatenate([cache[0], k], 2) | |
| v = mx.concatenate([cache[1], v], 2) | |
| new_cache = (k[:, :, :-block], v[:, :, :-block]) | |
| s = k.shape[2] | |
| # x-transformers' interleaved rotary embedding, positions aligned to the end of 0 .. n_pos - 1 | |
| qr = mx.fast.rope(q, self.dh, traditional=True, base=10000.0, scale=1.0, offset=n_pos - n) | |
| kr = mx.fast.rope(k, self.dh, traditional=True, base=10000.0, scale=1.0, offset=n_pos - s) | |
| mask = mx.array(block_mask(s, chunk, block, self.t_p, self.t_f)[-n:]) | |
| a = mx.fast.scaled_dot_product_attention(qr, kr, v, scale=self.dh ** -0.5, mask=mask) | |
| x = x + gate_msa[:, None] * self.to_out(a.transpose(0, 2, 1, 3).reshape(b, n, -1)) | |
| h = mx.fast.layer_norm(x, None, None, 1e-6) * (1 + scale_mlp[:, None]) + shift_mlp[:, None] | |
| x = x + gate_mlp[:, None] * self.ff2(gelu_tanh(self.ff0(h))) | |
| return x, new_cache | |
| class DiT(nn.Module): | |
| def __init__(self, dim=512, depth=4, heads=2, dim_head=64, ff_mult=2, mel_dim=80, bn_dim=256, | |
| t_p=(2, 2, 1, 1), t_f=(1, 0, 0, 0)): | |
| super().__init__() | |
| self.dim = dim | |
| self.t_time_embed, self.r_time_embed = TimestepEmbedding(dim), TimestepEmbedding(dim) | |
| self.gtm = GlobalTimbreMemory(bn_dim, 32, bn_dim) | |
| self.temporal_timbre = TemporalTimbre(bn_dim, bn_dim, 128, 4) | |
| self.input_proj = nn.Linear(mel_dim + 2 * bn_dim, dim) | |
| self.blocks = [DiTBlock(dim, heads, dim_head, ff_mult, t_p[i], t_f[i]) for i in range(depth)] | |
| self.norm_out = nn.Linear(dim, dim * 2) | |
| self.proj_out = nn.Linear(dim, mel_dim) | |
| def conditions(self, cond, spk): | |
| """Per conversion: the frame-level condition [timbre_cond, spk] (frame-wise, so computed once for the whole | |
| sequence instead of per chunk: the same numbers).""" | |
| k_mem, v_mem = self.gtm(spk) | |
| tc = self.temporal_timbre(cond, k_mem, v_mem) | |
| return mx.concatenate([tc, mx.broadcast_to(spk[:, None], (1, cond.shape[1], spk.shape[-1]))], -1) | |
| def time(self, t, r, dtype): | |
| """Per step: the time embedding and every block's modulation vectors.""" | |
| e = self.t_time_embed(t, dtype) + self.r_time_embed(r, dtype) | |
| s = nn.silu(e) | |
| return [blk.attn_norm(s) for blk in self.blocks], self.norm_out(s) | |
| def __call__(self, x, cond, mods, final, cache, n_pos, chunk, block): | |
| h = self.input_proj(mx.concatenate([x, cond], -1)) | |
| new = [] | |
| for blk, mod, c in zip(self.blocks, mods, cache or [None] * len(self.blocks)): | |
| h, nc = blk(h, mod, c, n_pos, chunk, block) | |
| new.append(nc) | |
| scale, shift = mx.split(final, 2, -1) | |
| h = mx.fast.layer_norm(h, None, None, 1e-6) * (1 + scale[:, None]) + shift[:, None] | |
| return self.proj_out(h), new | |
| # ---------------------------------------------------------------------------------------------------- vocoder | |
| class ConvNeXtBlock(nn.Module): | |
| def __init__(self, dim=320, inner=1536): | |
| super().__init__() | |
| self.dwconv = nn.Conv1d(dim, dim, 7, padding=3, groups=dim) | |
| self.norm = LayerNorm(dim, 1e-6) | |
| self.pwconv1, self.pwconv2 = nn.Linear(dim, inner), nn.Linear(inner, dim) | |
| self.gamma = mx.zeros((dim,)) | |
| def __call__(self, x): | |
| return x + self.gamma * self.pwconv2(gelu(self.pwconv1(self.norm(self.dwconv(x))))) | |
| class Vocos(nn.Module): | |
| def __init__(self, n_mels=80, dim=320, inner=1536, layers=8): | |
| super().__init__() | |
| self.embed = nn.Conv1d(n_mels, dim, 7, padding=3) | |
| self.norm = LayerNorm(dim, 1e-6) | |
| self.convnext = [ConvNeXtBlock(dim, inner) for _ in range(layers)] | |
| self.final_layer_norm = LayerNorm(dim, 1e-6) | |
| self.out = nn.Linear(dim, N_FFT + 2) | |
| self.window = mx.zeros((N_FFT,)) | |
| def spectrum(self, mel): | |
| """mel [1, T, 80] (time-major) -> magnitude-clamped complex spectrum as (real, imag) [T, 321], float32.""" | |
| x = self.norm(self.embed(mel)) | |
| for b in self.convnext: | |
| x = b(x) | |
| x = self.out(self.final_layer_norm(x)).astype(mx.float32)[0] | |
| mag, ph = x[:, : N_FFT // 2 + 1], x[:, N_FFT // 2 + 1:] | |
| mag = mx.minimum(mx.exp(mag), 100.0) | |
| return mag * mx.cos(ph), mag * mx.sin(ph) | |
| def __call__(self, mel): | |
| re, im = self.spectrum(mel) | |
| return istft(re, im, self.window.astype(mx.float32)) | |
| def istft(re, im, win): | |
| """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. [T, 321] -> [160 (T - 1)].""" | |
| T = re.shape[0] | |
| frames = mx.fft.irfft(re + 1j * im, n=N_FFT, axis=-1) * win # [T, 640] | |
| r = N_FFT // HOP | |
| fr = frames.reshape(T, r, HOP) | |
| w2 = (win * win).reshape(r, HOP) | |
| y = mx.zeros((T + r - 1, HOP)) | |
| env = mx.zeros((T + r - 1, HOP)) | |
| for j in range(r): | |
| y = y + mx.pad(fr[:, j], [(j, r - 1 - j), (0, 0)]) | |
| env = env + mx.pad(mx.broadcast_to(w2[j], (T, HOP)), [(j, r - 1 - j), (0, 0)]) | |
| y, env = y.reshape(-1), env.reshape(-1) | |
| s = N_FFT // 2 | |
| return y[s:y.shape[0] - s] / env[s:env.shape[0] - s] | |
| # ---------------------------------------------------------------------------------------------------- speaker encoder | |
| class WavLMLayer(nn.Module): | |
| def __init__(self, d=1024, heads=16, ffn=4096, rel_bias=False, buckets=320): | |
| super().__init__() | |
| self.heads, self.hd = heads, d // heads | |
| self.self_attn_layer_norm, self.final_layer_norm = LayerNorm(d), LayerNorm(d) | |
| self.q_proj, self.k_proj, self.v_proj, self.out_proj = (nn.Linear(d, d) for _ in range(4)) | |
| self.grep_linear = nn.Linear(self.hd, 8) | |
| self.grep_a = mx.ones((1, heads, 1, 1)) | |
| if rel_bias: | |
| self.relative_attention_bias = nn.Embedding(buckets, heads) | |
| self.fc1, self.fc2 = nn.Linear(d, ffn), nn.Linear(ffn, d) | |
| def __call__(self, x, pos_bias): | |
| b, n, d = x.shape | |
| h = self.self_attn_layer_norm(x) | |
| sp = lambda y: y.reshape(b, n, self.heads, self.hd).transpose(0, 2, 1, 3) | |
| # gated relative position bias (gru_rel_pos): gates from the layer's normalised input, per head | |
| g = mx.sigmoid(self.grep_linear(sp(h)).reshape(b, self.heads, n, 2, 4).sum(-1).astype(mx.float32)) | |
| gate = g[..., :1] * (g[..., 1:] * self.grep_a.astype(mx.float32) - 1.0) + 2.0 # [b, H, n, 1] | |
| mask = (gate * pos_bias).astype(h.dtype) | |
| a = mx.fast.scaled_dot_product_attention(sp(self.q_proj(h)), sp(self.k_proj(h)), sp(self.v_proj(h)), | |
| scale=self.hd ** -0.5, mask=mask) | |
| x = x + self.out_proj(a.transpose(0, 2, 1, 3).reshape(b, n, d)) | |
| return x + self.fc2(gelu(self.fc1(self.final_layer_norm(x)))) | |
| def relative_buckets(n, num_buckets=320, max_distance=800): | |
| """WavLM's bidirectional T5-style buckets of key - query position, [n, n].""" | |
| rel = np.arange(n)[None, :] - np.arange(n)[:, None] | |
| nb = num_buckets // 2 | |
| out = (rel > 0).astype(np.int64) * nb | |
| rel = np.abs(rel) | |
| max_exact = nb // 2 | |
| large = max_exact + (np.log(np.maximum(rel, 1).astype(np.float32) / max_exact) / math.log(max_distance / max_exact) | |
| * (nb - max_exact)).astype(np.int64) # used only where rel >= max_exact | |
| large = np.minimum(large, nb - 1) | |
| return out + np.where(rel < max_exact, rel, large) | |
| class BatchNorm(nn.Module): | |
| """Inference BatchNorm1d over the last axis.""" | |
| def __init__(self, c): | |
| super().__init__() | |
| self.weight, self.bias = mx.ones((c,)), mx.zeros((c,)) | |
| self.running_mean, self.running_var = mx.zeros((c,)), mx.ones((c,)) | |
| def __call__(self, x): | |
| return (x - self.running_mean) * mx.rsqrt(self.running_var + 1e-5) * self.weight + self.bias | |
| class ConvReluBn(nn.Module): | |
| def __init__(self, cin, cout, k=1, pad=0, dil=1): | |
| super().__init__() | |
| self.conv = nn.Conv1d(cin, cout, k, padding=pad, dilation=dil) | |
| self.bn = BatchNorm(cout) | |
| def __call__(self, x): | |
| return self.bn(nn.relu(self.conv(x))) | |
| class SERes2Block(nn.Module): | |
| def __init__(self, c=512, k=3, dil=2, scale=8, se=128): | |
| super().__init__() | |
| self.width, self.nums = c // scale, scale - 1 | |
| self.cb1 = ConvReluBn(c, c) | |
| self.res2 = [ConvReluBn(self.width, self.width, k, dil, dil) for _ in range(self.nums)] | |
| self.cb2 = ConvReluBn(c, c) | |
| self.se1, self.se2 = nn.Linear(c, se), nn.Linear(se, c) | |
| def __call__(self, x): | |
| r = x | |
| x = self.cb1(x) | |
| spx = mx.split(x, self.nums + 1, -1) | |
| out, sp = [], None | |
| for i in range(self.nums): | |
| sp = spx[i] if i == 0 else sp + spx[i] | |
| sp = self.res2[i](sp) | |
| out.append(sp) | |
| x = self.cb2(mx.concatenate(out + [spx[self.nums]], -1)) | |
| s = mx.sigmoid(self.se2(nn.relu(self.se1(x.mean(1))))) | |
| return x * s[:, None] + r | |
| class SpeakerEncoder(nn.Module): | |
| """WavLM-Large (s3prl's UpstreamExpert: whole-wave layer norm, the 25 hidden states: each layer's input and the | |
| encoder output) + UniSpeech's ECAPA-TDNN (softmax-weighted hidden states, instance norm, 3 SE-Res2Blocks, | |
| attentive statistics pooling, 256-d embedding).""" | |
| def __init__(self, d=1024, layers=24, heads=16, ffn=4096, conv_pos=128, conv_groups=16, c=512, emb=256): | |
| super().__init__() | |
| self.conv_layers = [nn.Conv1d(1 if i == 0 else 512, 512, k, stride=s, bias=False) | |
| for i, (k, s) in enumerate([(10, 5)] + [(3, 2)] * 4 + [(2, 2)] * 2)] | |
| self.conv_norms = [LayerNorm(512) for _ in range(7)] | |
| self.layer_norm = LayerNorm(512) | |
| self.post_extract_proj = nn.Linear(512, d) | |
| self.pos_conv = nn.Conv1d(d, d, conv_pos, padding=conv_pos // 2, groups=conv_groups) | |
| self.layers = [WavLMLayer(d, heads, ffn, rel_bias=i == 0) for i in range(layers)] | |
| self.encoder_layer_norm = LayerNorm(d) | |
| self.feature_weight = mx.zeros((layers + 1,)) | |
| self.layer1 = ConvReluBn(d, c, 5, 2) | |
| self.layer2, self.layer3, self.layer4 = SERes2Block(c, 3, 2), SERes2Block(c, 3, 3), SERes2Block(c, 3, 4) | |
| self.conv = nn.Conv1d(3 * c, 1536, 1) | |
| self.pool1, self.pool2 = nn.Conv1d(1536, 128, 1), nn.Conv1d(128, 1536, 1) | |
| self.bn = BatchNorm(3072) | |
| self.linear = nn.Linear(3072, emb) | |
| def hidden_states(self, wave): | |
| x = wave[None, :, None] | |
| for conv, norm in zip(self.conv_layers, self.conv_norms): | |
| x = gelu(norm(conv(x))) | |
| x = self.post_extract_proj(self.layer_norm(x)) | |
| c = self.pos_conv(x)[:, :-1] # SamePad: even kernel, drop the last | |
| x = x + gelu(c) | |
| n = x.shape[1] | |
| rb = self.layers[0].relative_attention_bias(mx.array(relative_buckets(n))) # [n, n, H] | |
| pos_bias = rb.transpose(2, 0, 1)[None].astype(mx.float32) | |
| hs = [] | |
| for layer in self.layers: | |
| hs.append(x) | |
| x = layer(x, pos_bias) | |
| hs.append(self.encoder_layer_norm(x)) | |
| return hs | |
| def __call__(self, wave): | |
| """wave: mx.array [N] at 16 kHz (int16-scaled) -> embedding [1, 256].""" | |
| w = wave.astype(mx.float32) | |
| w = (w - w.mean()) * mx.rsqrt(((w - w.mean()) ** 2).mean() + 1e-5) | |
| hs = self.hidden_states(w.astype(self.post_extract_proj.bias.dtype)) | |
| nw = mx.softmax(self.feature_weight.astype(mx.float32), -1) | |
| x = sum(nw[i] * h.astype(mx.float32) for i, h in enumerate(hs)) + 1e-6 # [1, T, 1024] | |
| mu = x.mean(1, keepdims=True) | |
| x = (x - mu) * mx.rsqrt(((x - mu) ** 2).mean(1, keepdims=True) + 1e-5) # InstanceNorm1d | |
| x = x.astype(hs[0].dtype) | |
| o1 = self.layer1(x) | |
| o2 = self.layer2(o1); o3 = self.layer3(o2); o4 = self.layer4(o3) | |
| o = nn.relu(self.conv(mx.concatenate([o2, o3, o4], -1))).astype(mx.float32) | |
| alpha = mx.softmax(self.pool2(mx.tanh(self.pool1(o.astype(x.dtype)))).astype(mx.float32), axis=1) | |
| mean = (alpha * o).sum(1) | |
| std = mx.sqrt(mx.maximum((alpha * o * o).sum(1) - mean ** 2, 1e-9)) | |
| return self.linear(self.bn(mx.concatenate([mean, std], -1).astype(x.dtype))).astype(mx.float32) | |
| # ---------------------------------------------------------------------------------------------------- loading | |
| PARTS = {"content": ContentEncoder, "dit_120ms": DiT, "dit_40ms": DiT, | |
| "vocoder": Vocos, "speaker": SpeakerEncoder} | |
| def load_part(folder, name, config): | |
| """Build a part, turn the layers stored with `.scales` into quantized layers, load the weights.""" | |
| folder = Path(folder) | |
| m = PARTS[name]() | |
| w = mx.load(str(folder / f"{name}.safetensors")) | |
| q = config.get("quantization") | |
| if q: | |
| nn.quantize(m, group_size=q["group_size"], bits=q["bits"], mode=q.get("mode", "affine"), | |
| class_predicate=lambda p, mod: f"{p}.scales" in w) | |
| m.load_weights(list(w.items()), strict=True) | |
| m.eval() | |
| mx.eval(m.parameters()) | |
| return m | |
| class MeanVC2: | |
| def __init__(self, folder, preset="120ms"): | |
| self.folder = Path(folder) | |
| self.config = json.loads((self.folder / "config.json").read_text()) | |
| self.dtype = DTYPES[self.config["dtype"]] | |
| self.c = PRESETS[preset] | |
| self.content_model = load_part(self.folder, self.c["content"], self.config) | |
| self.dit = load_part(self.folder, self.c["dit"], self.config) | |
| self.vocoder = load_part(self.folder, "vocoder", self.config) | |
| self.speaker_model = load_part(self.folder, "speaker", self.config) | |
| self._step = mx.compile(self.content_model.step) | |
| def content(self, wav16): | |
| """infer_e2e.extract_bn: the streaming encoder over 19 (11) fbank frames every 16 (8), from zero caches.""" | |
| return self.content_fbank(kaldi_fbank(int16_scale(wav16))) | |
| def content_fbank(self, fb): | |
| c, dt = self.c, self.dtype | |
| R, n_out = c["req_cache"], c["offset_step"] | |
| L = len(self.content_model.layers) | |
| ks = [mx.zeros((1, 4, R, 64), dt) for _ in range(L)] | |
| vs = [mx.zeros((1, 4, R, 64), dt) for _ in range(L)] | |
| cn = [mx.zeros((1, 8, 256), dt) for _ in range(L)] | |
| out, off, i = [], c["offset_init"], 0 | |
| while i + c["window"] <= fb.shape[0]: | |
| pos = mx.array(rel_pos_table(off - R, R + n_out)[None]).astype(dt) | |
| bn, ks, vs, cn = self._step(mx.array(fb[None, i:i + c["window"]]).astype(dt), pos, ks, vs, cn) | |
| mx.async_eval(bn, ks, vs, cn) | |
| out.append(bn[0]) | |
| off += c["offset_step"] | |
| i += c["stride"] | |
| return np.array(mx.concatenate(out, 0).astype(mx.float32)) | |
| def speaker(self, wav16): | |
| e = self.speaker_model(mx.array(int16_scale(wav16))) | |
| return np.array(e) | |
| 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. Keys and values older than | |
| the 3 chunks the attention can still reach (t_p <= 2) are dropped, whole chunks at a time.""" | |
| c, dt, dit = self.c, self.dtype, self.dit | |
| chunk, block = c["chunk"], c["block"] | |
| cond = mx.array(upsample4(bn)[None]).astype(dt) | |
| 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) | |
| full = dit.conditions(cond, mx.array(spk).reshape(1, -1).astype(dt)) | |
| times = [dit.time(mx.array(ts[i:i + 1]), mx.array(ts[i + 1:i + 2]), dt) for i in range(steps)] | |
| keep = 3 * chunk | |
| cache, out, offset = None, [], 0 | |
| for start in range(0, L, chunk): | |
| mid = min(start + chunk, L) | |
| end = min(mid + block, L) | |
| x = mx.array(noise[:, start:end]).astype(dt) | |
| cnd = full[:, start:end] | |
| for i in range(steps): | |
| u, new = dit(x, cnd, times[i][0], times[i][1], cache, offset + (end - start), chunk, block) | |
| x = x - float(ts[i] - ts[i + 1]) * u | |
| cache = new | |
| p = cache[0][0].shape[2] | |
| if p > keep: | |
| drop = (p - keep) // chunk * chunk | |
| cache = [(k[:, :, drop:], v[:, :, drop:]) for k, v in cache] | |
| mx.async_eval(x, cache) | |
| out.append(x[:, :mid - start]) | |
| offset += mid - start | |
| return mx.concatenate(out, 1) | |
| def __call__(self, src, src_sr, ref, ref_sr, steps=3, seed=0, rng=None): | |
| rng = rng or np.random.default_rng(seed) | |
| src, ref = resample16(src, src_sr), resample16(ref, ref_sr) | |
| x = self.convert(self.content(src), self.speaker(ref), steps, rng) | |
| mel = (x.astype(mx.float32) + 1) / 2 | |
| wav = self.vocoder(mel.astype(self.dtype)) | |
| return np.array(wav), SR | |
| def resample16(w, sr): | |
| w = np.asarray(w, np.float32) | |
| if w.ndim > 1: | |
| w = w.mean(1) | |
| if sr == SR: | |
| return w | |
| import soxr | |
| return soxr.resample(w, sr, SR, quality="HQ").astype(np.float32) | |
| 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("--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) | |
| wav, sr = vc(s.mean(1), ssr, r.mean(1), rsr, steps=a.steps, seed=a.seed) | |
| sf.write(a.output, wav, sr) | |