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
6bit build of MeanVC2
Browse filesFiles changed (7)
- 6bit/config.jsonAdded+104
- 6bit/content.safetensorsAdded+3
- 6bit/dit_120ms.safetensorsAdded+3
- 6bit/dit_40ms.safetensorsAdded+3
- 6bit/mlx_model.pyAdded+668
- 6bit/speaker.safetensorsAdded+3
- 6bit/vocoder.safetensorsAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104{ "model_type": "meanvc2", "sample_rate": 16000, "presets": { "120ms": { "content": "content", "dit": "dit_120ms", "window": 19, "stride": 16, "offset_init": 8, "offset_step": 4, "req_cache": 8, "chunk": 12, "block": 4 }, "40ms": { "content": "content", "dit": "dit_40ms", "window": 11, "stride": 8, "offset_init": 4, "offset_step": 2, "req_cache": 4, "chunk": 4, "block": 4 } }, "steps": 3, "precision": "6bit", "dtype": "float16", "sources": { "ASLP-lab/MeanVC2": { "revision": "39cdd19522fe896c227da691314d9a0e3b995486", "code": "github.com/ASLP-lab/MeanVC2 @13acf84", "files": [ "meanvc2_120ms_40ms.safetensors", "meanvc2_40ms_40ms.safetensors", "fastu2pp_160ms.pt", "fastu2pp_80ms.pt", "vocos.pt" ] }, "bezzam/wavlm_large_finetune_seed_tts_eval": { "revision": "f127f699a44abb1c6e05f03522bd1b8c48be3184", "files": [ "wavlm_large_finetune.pth" ], "sha256": "51f07e3b94d9e0262a6a675ef5a087be3dd09e8c62e9d886827f44f82fe7f94b", "note": "byte-for-byte mirror of the Google Drive file UniSpeech / MeanVC2's initialization.py link" } }, "quantization": { "group_size": 64, "bits": 6, "mode": "affine" }, "kept_float": { "content": [ "(the whole part)" ], "dit_120ms": [ "(the whole part)" ], "dit_40ms": [ "(the whole part)" ], "vocoder": [ "(the whole part)" ], "speaker": [ "layer2.se1", "layer2.se2", "layer3.se1", "layer3.se2", "layer4.se1", "layer4.se2", "layers.0.grep_linear", "layers.1.grep_linear", "layers.10.grep_linear", "layers.11.grep_linear", "layers.12.grep_linear", "layers.13.grep_linear", "layers.14.grep_linear", "layers.15.grep_linear", "layers.16.grep_linear", "layers.17.grep_linear", "layers.18.grep_linear", "layers.19.grep_linear", "layers.2.grep_linear", "layers.20.grep_linear", "layers.21.grep_linear", "layers.22.grep_linear", "layers.23.grep_linear", "layers.3.grep_linear", "layers.4.grep_linear", "layers.5.grep_linear", "layers.6.grep_linear", "layers.7.grep_linear", "layers.8.grep_linear", "layers.9.grep_linear", "linear" ] }}123version https://git-lfs.github.com/spec/v1oid sha256:616b834cf243ed748096eb3e2f0a72255a72279baf46d5aa56f0d1393cb9b2cfsize 35306448123version https://git-lfs.github.com/spec/v1oid sha256:16bcf3e4d7a079e96cd782276f75fb8f7965d0e0764d9328d64e6558aa4e9a4csize 35423513123version https://git-lfs.github.com/spec/v1oid sha256:0a68bb5057a62081ed727b8c94ec09a936e8aceabcc067ce59e812fa22261e9csize 35423513123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668"""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 kHzoutput. 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, andcontent / dit_120ms / dit_40ms / vocoder / speaker .safetensors (one content encoder for both presets: the officialfastu2pp_160ms.pt and fastu2pp_80ms.pt hold the same weights in the layers the step function runs; they differ only inthe traced window size). A quantized layer is one whoseweights 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, soa seed gives the same output every run."""
from __future__ import annotations
import jsonimport mathfrom pathlib import Path
import mlx.core as mximport mlx.nn as nnimport numpy as np
SR, N_FFT, HOP = 16000, 640, 160PRESETS = { # 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)123version https://git-lfs.github.com/spec/v1oid sha256:48c2268632485c930ec103ee782926d0b6086356e7e1be7356edaad5b0d4b2casize 288613474123version https://git-lfs.github.com/spec/v1oid sha256:a79d9138715bc94e3d203df1c1f3492d3be1b39e3b2044b614007ff7a481f2c7size 165970006bit/config.jsonAdded+104
6bit/content.safetensorsAdded+3
6bit/dit_120ms.safetensorsAdded+3
6bit/dit_40ms.safetensorsAdded+3
6bit/mlx_model.pyAdded+668
6bit/speaker.safetensorsAdded+3
6bit/vocoder.safetensorsAdded+3