Run this model with HF Jobs

Run moonbox-dev/Seed-VC-v2-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/Seed-VC-v2-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/Seed-VC-v2-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.
File size: 34,115 Bytes
1b76cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
"""Seed-VC v2 on MLX: zero-shot voice conversion in one file (mlx, numpy, soxr; no PyTorch at run time).

Re-voices a recording into the voice of a reference recording, keeping its words and timing; 22.05 kHz output.
Follows the official default v2 path (github.com/Plachtaa/seed-vc @51383ef, inference_v2.py defaults:
`VoiceConversionWrapper.convert_voice_with_streaming`, convert_style off, so the AR model is not used):

    content     ASTRAL-quantization "bsq2048" content tokenizer: HuBERT-large (facebook/hubert-large-ll60k, its
                first 18 layers, no final layer norm) on the normalised 16 kHz wave -> 12 ConvNeXt-V2 blocks ->
                binary spherical quantizer, 11 bits -> 2048 content tokens at 50 Hz
    style       CAM++ (funasr/campplus campplus_cn_common.bin) on the mean-removed Kaldi fbank of the reference
                -> 192-value style vector
    regulator   token embedding, nearest-neighbour stretch to the mel length, 4 x (conv, GroupNorm, Mish) -> the
                DiT condition [L, 512]
    dit         the 13-layer DiT (512 wide, 8 heads, adaptive RMSNorm on the time embedding, time and style as
                tokens, rotary positions): a flow-matching velocity; 30 Euler steps on a cosine schedule with
                two-condition classifier-free guidance (intelligibility 0.7, similarity 0.7) and the reference mel
                as prompt
    vocoder     BigVGAN v2 (nvidia/bigvgan_v2_22khz_80band_256x): mel [80, T] -> 256 T samples

Sources longer than the 30 s context are converted in chunks with the official 16-frame crossfade; the reference is
cut to 25 s; content tokens are taken in 30 s windows with 5 s of overlap, as the official code does.

A build folder (made by convert_mlx.py) holds config.json (precision, quantization, sources), this file, and
content / style / regulator / dit / vocoder .safetensors. 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 SeedVC2
    vc = SeedVC2("8bit")
    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=30, seed=0)        # numpy float32, 22.05 kHz

    python mlx_model.py source.wav voice.wav out.wav [--steps 30] [--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.

License: GPL-3.0 (a derivative of Seed-VC, github.com/Plachtaa/seed-vc, GPL-3.0). The CAM++ layers follow 3D-Speaker
(Apache-2.0), BigVGAN follows NVIDIA's BigVGAN (MIT), HuBERT follows transformers (Apache-2.0).
"""

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, HOP, N_FFT = 22050, 256, 1024
CONTEXT_S, OVERLAP = 30, 16
DTYPES = {"float32": mx.float32, "bfloat16": mx.bfloat16, "float16": mx.float16}


# ---------------------------------------------------------------------------------------------------------- front end
def mel(wav22, basis):
    """modules.audio.mel_spectrogram(n_fft 1024, 80 mels, hop 256, win 1024, center=False): reflect padding of 384
    each side, periodic Hann, magnitude, log of the clamp at 1e-5. Returns [80, T] (numpy)."""
    x = np.pad(np.asarray(wav22, np.float32), ((N_FFT - HOP) // 2, (N_FFT - HOP) // 2), mode="reflect")
    win = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)).astype(np.float32)
    n = 1 + (len(x) - N_FFT) // HOP
    idx = np.arange(N_FFT)[None, :] + HOP * np.arange(n)[:, None]
    s = np.fft.rfft(x[idx] * win, axis=1)
    mag = np.sqrt(s.real.astype(np.float64) ** 2 + s.imag.astype(np.float64) ** 2 + 1e-9).astype(np.float32)
    return np.log(np.maximum(basis @ mag.T, 1e-5)).astype(np.float32)


def mel_basis(sr=SR, n_fft=N_FFT, n_mels=80):
    """librosa.filters.mel(sr=22050, n_fft=1024, n_mels=80, fmin=0, fmax=None): Slaney mel scale, Slaney area
    normalisation. [80, 513] float32 (convert_mlx.py checks it against librosa)."""
    def hz_to_mel(f):
        f = np.asarray(f, np.float64)
        lin = f / (200.0 / 3)
        log = 15.0 + np.log(np.maximum(f, 1e-10) / 1000.0) / (np.log(6.4) / 27.0)
        return np.where(f >= 1000.0, log, lin)

    def mel_to_hz(m):
        m = np.asarray(m, np.float64)
        lin = m * (200.0 / 3)
        log = 1000.0 * np.exp((np.log(6.4) / 27.0) * (m - 15.0))
        return np.where(m >= 15.0, log, lin)
    fft_f = np.linspace(0, sr / 2, 1 + n_fft // 2)
    mel_f = mel_to_hz(np.linspace(hz_to_mel(0.0), hz_to_mel(sr / 2), n_mels + 2))
    fdiff = np.diff(mel_f)
    ramps = mel_f[:, None] - fft_f[None, :]
    lower = -ramps[:-2] / fdiff[:-1, None]
    upper = ramps[2:] / fdiff[1:, None]
    w = np.maximum(0, np.minimum(lower, upper)).astype(np.float32)
    w *= (2.0 / (mel_f[2:n_mels + 2] - mel_f[:n_mels]))[:, None]
    return w


def kaldi_fbank(wav16):
    """torchaudio.compliance.kaldi.fbank(num_mel_bins=80, dither=0, sample_frequency=16000) with its defaults: 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(wav16, np.float64)
    fl, fs, nfft = 400, 160, 512
    n = 1 + (len(x) - fl) // fs
    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 nearest(tokens, n):
    """F.interpolate(mode='nearest') of a token sequence [T] to length n."""
    t = tokens.shape[0]
    scale = np.float32(t) / np.float32(n)
    src = np.minimum(np.floor(np.arange(n, dtype=np.float32) * scale).astype(np.int64), t - 1)
    return tokens[src]


def crossfade(a, b, overlap):
    fade_out = np.cos(np.linspace(0, np.pi / 2, overlap)) ** 2
    fade_in = np.cos(np.linspace(np.pi / 2, 0, overlap)) ** 2
    b = b.copy()
    if len(b) < overlap:
        b[:overlap] = b[:overlap] * fade_in[:len(b)] + (a[-overlap:] * fade_out)[:len(b)]
    else:
        b[:overlap] = b[:overlap] * fade_in + a[-overlap:] * fade_out
    return b


def resample(w, a, b):
    w = np.asarray(w, np.float32)
    if w.ndim > 1:
        w = w.mean(1)
    if a == b:
        return w
    import soxr
    y = soxr.resample(w, a, b, quality="HQ").astype(np.float32)
    n = int(np.ceil(len(w) * b / a))                 # librosa.resample's fix_length: zero-pad / trim to ceil(n b / a)
    return np.pad(y, (0, max(0, n - len(y))))[:n]


# ---------------------------------------------------------------------------------------------------- content: HuBERT
class HubertLayer(nn.Module):
    """transformers' HubertEncoderLayerStableLayerNorm (pre-LN), eval."""

    def __init__(self, d=1024, heads=16, ff=4096):
        super().__init__()
        self.heads = heads
        self.layer_norm = nn.LayerNorm(d)
        self.q_proj, self.k_proj, self.v_proj = nn.Linear(d, d), nn.Linear(d, d), nn.Linear(d, d)
        self.out_proj = nn.Linear(d, d)
        self.final_layer_norm = nn.LayerNorm(d)
        self.fc1, self.fc2 = nn.Linear(d, ff), nn.Linear(ff, d)

    def __call__(self, x):
        B, T, D = x.shape
        h = self.layer_norm(x)
        q, k, v = (p(h).reshape(B, T, self.heads, -1).transpose(0, 2, 1, 3) for p in (self.q_proj, self.k_proj, self.v_proj))
        a = mx.fast.scaled_dot_product_attention(q, k, v, scale=(D // self.heads) ** -0.5)
        x = x + self.out_proj(a.transpose(0, 2, 1, 3).reshape(B, T, D))
        return x + self.fc2(nn.gelu(self.fc1(self.final_layer_norm(x))))


class Hubert(nn.Module):
    """facebook/hubert-large-ll60k as AstralQuantizer runs it: layer-norm conv feature extractor, feature projection,
    weight-normalised positional convolution (folded at conversion), the first 18 of 24 layers, no final layer norm
    (ssl_output_layer 18, encoder.layer_norm = Identity)."""
    KERNELS, STRIDES = (10, 3, 3, 3, 3, 2, 2), (5, 2, 2, 2, 2, 2, 2)

    def __init__(self, n_layers=18):
        super().__init__()
        self.conv_layers = [nn.Conv1d(1 if i == 0 else 512, 512, k, s) for i, (k, s) in enumerate(zip(self.KERNELS, self.STRIDES))]
        self.conv_norms = [nn.LayerNorm(512) for _ in self.KERNELS]
        self.fp_norm = nn.LayerNorm(512)
        self.fp_proj = nn.Linear(512, 1024)
        self.pos_conv_weight = mx.zeros((1024, 128, 64))
        self.pos_conv_bias = mx.zeros((1024,))
        self.layers = [HubertLayer() for _ in range(n_layers)]

    def __call__(self, wave):                          # [B, N] normalised -> [B, T, 1024]
        x = wave[..., None]
        for conv, norm in zip(self.conv_layers, self.conv_norms):
            x = nn.gelu(norm(conv(x)))
        x = self.fp_proj(self.fp_norm(x))
        p = mx.conv1d(x, self.pos_conv_weight, padding=64, groups=16) + self.pos_conv_bias
        x = x + nn.gelu(p[:, :-1])
        for layer in self.layers:
            x = layer(x)
        return x


# ------------------------------------------------------------------------------------- content: ConvNeXt + quantizer
class ConvNeXtBlock(nn.Module):
    def __init__(self, dim=512, inter=1536):
        super().__init__()
        self.dwconv = nn.Conv1d(dim, dim, 7, padding=3, groups=dim)
        self.norm = nn.LayerNorm(dim, eps=1e-6)
        self.pwconv1 = nn.Linear(dim, inter)
        self.grn_gamma = mx.zeros((inter,))
        self.grn_beta = mx.zeros((inter,))
        self.pwconv2 = nn.Linear(inter, dim)

    def __call__(self, x):                             # [B, T, C]
        h = self.pwconv1(self.norm(self.dwconv(x)))
        h = nn.gelu(h)
        g = mx.sqrt(mx.sum(mx.square(h.astype(mx.float32)), axis=1, keepdims=True))      # GRN: L2 over time
        n = (g / (mx.mean(g, axis=-1, keepdims=True) + 1e-6)).astype(h.dtype)
        h = self.grn_gamma * (h * n) + self.grn_beta + h
        return x + self.pwconv2(h)


class ContentEncoder(nn.Module):
    """AstralQuantizer (bsq2048): HuBERT -> ConvNeXtV2Stage (1024 -> 512, 12 blocks) -> BSQ project_in (512 -> 11)
    -> sign bits -> token = sum of bit_i 2^(10 - i)."""

    def __init__(self):
        super().__init__()
        self.hubert = Hubert()
        self.input_projection = nn.Linear(1024, 512)
        self.blocks = [ConvNeXtBlock() for _ in range(12)]
        self.project_in = nn.Linear(512, 11)

    def features(self, wave):
        n = wave.shape[1] // 320
        h = self.hubert(wave)[:, :n]
        x = self.input_projection(h)
        for b in self.blocks:
            x = b(x)
        return x

    def __call__(self, wave):                          # [1, N] normalised -> int tokens [T]
        p = self.project_in(self.features(wave)).astype(mx.float32)
        bits = (p > 0).astype(mx.int32)
        return mx.sum(bits * (2 ** mx.arange(10, -1, -1, dtype=mx.int32)), axis=-1)[0]


# ------------------------------------------------------------------------------------------------- style: CAM++
class BN(nn.Module):
    """BatchNorm in inference form: y = x * scale + shift (folded at conversion), channels last."""

    def __init__(self, c):
        super().__init__()
        self.scale = mx.ones((c,))
        self.shift = mx.zeros((c,))

    def __call__(self, x):
        return x * self.scale + self.shift


class ResBlock2d(nn.Module):
    def __init__(self, cin, c, stride):
        super().__init__()
        self.conv1 = nn.Conv2d(cin, c, 3, stride=(stride, 1), padding=1, bias=False)
        self.bn1 = BN(c)
        self.conv2 = nn.Conv2d(c, c, 3, stride=1, padding=1, bias=False)
        self.bn2 = BN(c)
        self.has_shortcut = stride != 1 or cin != c
        if self.has_shortcut:
            self.sc_conv = nn.Conv2d(cin, c, 1, stride=(stride, 1), bias=False)
            self.sc_bn = BN(c)

    def __call__(self, x):
        o = nn.relu(self.bn1(self.conv1(x)))
        o = self.bn2(self.conv2(o))
        return nn.relu(o + (self.sc_bn(self.sc_conv(x)) if self.has_shortcut else x))


class CAMDenseLayer(nn.Module):
    def __init__(self, cin, out=32, bn=128, k=3, dil=1):
        super().__init__()
        self.bn1 = BN(cin)
        self.linear1 = nn.Conv1d(cin, bn, 1, bias=False)
        self.bn2 = BN(bn)
        self.local = nn.Conv1d(bn, out, k, padding=(k - 1) // 2 * dil, dilation=dil, bias=False)
        self.cam1 = nn.Conv1d(bn, bn // 2, 1)
        self.cam2 = nn.Conv1d(bn // 2, out, 1)

    def __call__(self, x):                             # [B, T, C]
        x = nn.relu(self.bn2(self.linear1(nn.relu(self.bn1(x)))))
        y = self.local(x)
        T = x.shape[1]
        nseg = -(-T // 100)                            # avg_pool1d(100, 100, ceil_mode=True): mean of each segment
        pad = nseg * 100 - T
        xs = mx.pad(x, [(0, 0), (0, pad), (0, 0)]).reshape(x.shape[0], nseg, 100, x.shape[2]).sum(2)
        cnt = mx.array([100.0] * (nseg - 1) + [float(100 - pad)], dtype=x.dtype)[None, :, None]
        seg = mx.repeat(xs / cnt, 100, axis=1)[:, :T]
        ctx = mx.mean(x, axis=1, keepdims=True) + seg
        m = mx.sigmoid(self.cam2(nn.relu(self.cam1(ctx))))
        return y * m


class Transit(nn.Module):
    def __init__(self, cin, cout):
        super().__init__()
        self.bn = BN(cin)
        self.linear = nn.Conv1d(cin, cout, 1, bias=False)

    def __call__(self, x):
        return self.linear(nn.relu(self.bn(x)))


class CAMPPlus(nn.Module):
    """3D-Speaker's CAM++ (feat 80, embedding 192), modules/campplus/DTDNN.py, eval; statistics pooling over the
    first T // 2 frames as VoiceConversionWrapper.compute_style asks."""

    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, padding=1, bias=False)
        self.bn1 = BN(32)
        self.layer1 = [ResBlock2d(32, 32, 2), ResBlock2d(32, 32, 1)]
        self.layer2 = [ResBlock2d(32, 32, 2), ResBlock2d(32, 32, 1)]
        self.conv2 = nn.Conv2d(32, 32, 3, stride=(2, 1), padding=1, bias=False)
        self.bn2 = BN(32)
        self.tdnn = nn.Conv1d(320, 128, 5, stride=2, padding=2, bias=False)
        self.tdnn_bn = BN(128)
        c = 128
        self.blocks, self.transits = [], []
        for n, dil in zip((12, 24, 16), (1, 2, 2)):
            self.blocks.append([CAMDenseLayer(c + i * 32, dil=dil) for i in range(n)])
            c += n * 32
            self.transits.append(Transit(c, c // 2))
            c //= 2
        self.out_bn = BN(c)
        self.dense = nn.Conv1d(c * 2, 192, 1, bias=False)
        self.dense_bn = BN(192)

    def __call__(self, feat):                          # [B, T, 80] mean-removed fbank -> [B, 192]
        n_keep = feat.shape[1] // 2
        x = feat.transpose(0, 2, 1)[..., None]         # NHWC: H = mel bins, W = frames
        x = nn.relu(self.bn1(self.conv1(x)))
        for blk in self.layer1 + self.layer2:
            x = blk(x)
        x = nn.relu(self.bn2(self.conv2(x)))           # [B, 10, T, 32]
        B, H, T, C = x.shape
        x = x.transpose(0, 2, 3, 1).reshape(B, T, C * H)
        x = nn.relu(self.tdnn_bn(self.tdnn(x)))
        for layers, tr in zip(self.blocks, self.transits):
            for l in layers:
                x = mx.concatenate([x, l(x)], axis=-1)
            x = tr(x)
        x = nn.relu(self.out_bn(x))[:, :n_keep].astype(mx.float32)
        mean = mx.mean(x, axis=1)
        std = mx.sqrt(mx.sum(mx.square(x - mean[:, None]), axis=1) / (n_keep - 1))
        s = mx.concatenate([mean, std], axis=-1)[:, None].astype(self.dense.weight.dtype)
        return self.dense_bn(self.dense(s))[:, 0]


# ----------------------------------------------------------------------------------------------------- regulator
class Regulator(nn.Module):
    """InterpolateRegulator (discrete, sampling ratios [1, 1, 1, 1]): embedding, nearest stretch (done by the caller
    on the token ids), 4 x (Conv1d k3, GroupNorm(1), Mish)."""

    def __init__(self, c=512, codebook=2048):
        super().__init__()
        self.embedding = nn.Embedding(codebook, c)
        self.convs = [nn.Conv1d(c, c, 3, padding=1) for _ in range(4)]
        self.norm_w = [mx.ones((c,)) for _ in range(4)]
        self.norm_b = [mx.zeros((c,)) for _ in range(4)]

    def __call__(self, ids):                           # int [B, L] -> [B, L, 512]
        x = self.embedding(ids)
        for conv, w, b in zip(self.convs, self.norm_w, self.norm_b):
            x = conv(x)
            xf = x.astype(mx.float32)
            mu = mx.mean(xf, axis=(1, 2), keepdims=True)
            var = mx.var(xf, axis=(1, 2), keepdims=True)
            x = ((xf - mu) * mx.rsqrt(var + 1e-5)).astype(x.dtype) * w + b
            x = x * mx.tanh(mx.logaddexp(x, mx.zeros_like(x)))        # Mish
        return x


# ------------------------------------------------------------------------------------------------------------ DiT
def rope(x, cos, sin):
    """dit_model.apply_rotary_emb: interleaved pairs (x0, x1) -> (x0 c - x1 s, x1 c + x0 s), in float32, with the
    checkpoint's bfloat16 cos / sin table. x [B, H, L, D]; cos, sin [L, D/2]."""
    B, H, L, D = x.shape
    xf = x.astype(mx.float32).reshape(B, H, L, D // 2, 2)
    a, b = xf[..., 0], xf[..., 1]
    out = mx.stack([a * cos - b * sin, b * cos + a * sin], axis=-1)
    return out.reshape(B, H, L, D).astype(x.dtype)


class DiTBlock(nn.Module):
    def __init__(self, d=512, heads=8, inter=1536):
        super().__init__()
        self.heads = heads
        self.ada = nn.Linear(d, 6 * d)                 # attention_norm.linear
        self.attn_norm = mx.ones((d,))
        self.wqkv = nn.Linear(d, 3 * d, bias=False)
        self.wo = nn.Linear(d, d, bias=False)
        self.ffn_norm = mx.ones((d,))
        self.w1 = nn.Linear(d, inter, bias=False)
        self.w3 = nn.Linear(d, inter, bias=False)
        self.w2 = nn.Linear(inter, d, bias=False)

    def __call__(self, x, c, cos, sin):                # x [B, L, D], c [B, 1, D] (SiLU of the time embedding)
        B, L, D = x.shape
        sh_a, sc_a, g_a, sh_m, sc_m, g_m = mx.split(self.ada(c), 6, axis=-1)
        h = mx.fast.rms_norm(x, self.attn_norm, 1e-5) * (1 + sc_a) + sh_a
        q, k, v = mx.split(self.wqkv(h), 3, axis=-1)
        q, k, v = (t.reshape(B, L, self.heads, -1).transpose(0, 2, 1, 3) for t in (q, k, v))
        q, k = rope(q, cos, sin), rope(k, cos, sin)
        a = mx.fast.scaled_dot_product_attention(q, k, v, scale=(D // self.heads) ** -0.5)
        x = x + g_a * self.wo(a.transpose(0, 2, 1, 3).reshape(B, L, D))
        h = mx.fast.rms_norm(x, self.ffn_norm, 1e-5) * (1 + sc_m) + sh_m
        return x + g_m * self.w2(nn.silu(self.w1(h)) * self.w3(h))


class DiT(nn.Module):
    """modules/v2/dit_wrapper.DiT (time_as_token, style_as_token, no U-ViT skips, 13 layers, 512 wide) as the CFM
    estimator: velocity of x [B, L, 80] given the prompt mel, t, style [B, 192] and the condition [B, L, 512]."""

    def __init__(self, d=512, depth=13, rope_len=8192):
        super().__init__()
        self.t_mlp0 = nn.Linear(256, d)
        self.t_mlp2 = nn.Linear(d, d)
        self.cond_projection = nn.Linear(512, d)
        self.cond_x_merge_linear = nn.Linear(d + 160, d)
        self.style_in = nn.Linear(192, d)
        self.layers = [DiTBlock(d) for _ in range(depth)]
        self.norm_ada = nn.Linear(d, 2 * d)            # transformer.norm.linear
        self.norm_w = mx.ones((d,))
        self.final_mlp0 = nn.Linear(d, d)
        self.final_mlp2 = nn.Linear(d, 80)
        self.rope_cos = mx.ones((rope_len, 32))        # transformer.freqs_cis (bfloat16 in the checkpoint), float32 here
        self.rope_sin = mx.zeros((rope_len, 32))
        self.dtype_ = mx.float32                       # compute dtype (the build's float dtype; set by the loader)

    def time_embed(self, t):                           # [B] -> [B, D]
        half = 128
        freqs = mx.exp(-math.log(10000) * mx.arange(half, dtype=mx.float32) / half)
        args = 1000 * t[:, None].astype(mx.float32) * freqs[None]
        e = mx.concatenate([mx.cos(args), mx.sin(args)], axis=-1).astype(self.dtype_)
        return self.t_mlp2(nn.silu(self.t_mlp0(e)))

    def __call__(self, x, prompt_x, t, style, cond):
        dt = self.dtype_
        t1 = self.time_embed(t)
        h = self.cond_x_merge_linear(mx.concatenate([x.astype(dt), prompt_x.astype(dt), self.cond_projection(cond)], -1))
        h = mx.concatenate([t1[:, None], self.style_in(style.astype(dt))[:, None], h], axis=1)
        L = h.shape[1]
        cos, sin = self.rope_cos[:L], self.rope_sin[:L]
        c = nn.silu(t1)[:, None]
        for layer in self.layers:
            h = layer(h, c, cos, sin)
        scale, shift = mx.split(self.norm_ada(c), 2, axis=-1)
        h = mx.fast.rms_norm(h, self.norm_w, 1e-5) * (1 + scale) + shift
        return self.final_mlp2(nn.silu(self.final_mlp0(h[:, 2:])))


# ------------------------------------------------------------------------------------------------------- BigVGAN
def _taps():
    """kaiser_sinc_filter1d(cutoff 0.25, half_width 0.3, kernel 12): the filter of every Activation1d's 2x upsampler
    and downsampler (the checkpoint's buffers; checked equal at conversion)."""
    k, half = 12, 6
    delta_f = 4 * 0.3
    A = 2.285 * (half - 1) * math.pi * delta_f + 7.95
    beta = 0.1102 * (A - 8.7) if A > 50 else (0.5842 * (A - 21) ** 0.4 + 0.07886 * (A - 21.0) if A >= 21 else 0.0)
    win = np.kaiser(k, beta)
    t = np.arange(-half, half) + 0.5
    f = 2 * 0.25 * win * np.sinc(2 * 0.25 * t)
    return (f / f.sum()).tolist()


_KERNEL_SRC = """
    uint gid = thread_position_in_grid.x;
    int C = x_shape[2]; int T = x_shape[1]; int B = x_shape[0];
    int nt = (T + R - 1) / R;
    if (int(gid) >= B * nt * C) return;
    int c = gid % C; int bt = gid / C; int i0 = (bt % nt) * R; int b = bt / nt;
    const device InT* xb = x + size_t(b) * T * C + c;
    device InT* ob = out + size_t(b) * T * C + c;
    float a = alpha[c]; float ib = ibeta[c];
    float su[2 * R + 10];
    for (int m = 0; m < 2 * R + 10; m++) {
        int n = clamp(2 * i0 - 5 + m, 0, 2 * T - 1);
        int p = n >> 1;
        float u = 0.0f;
        if ((n & 1) == 0) {
            for (int j = 0; j < 6; j++) u += FU_O[j] * float(xb[size_t(clamp(p + 2 - j, 0, T - 1)) * C]);
        } else {
            for (int j = 0; j < 6; j++) u += FU_E[j] * float(xb[size_t(clamp(p + 3 - j, 0, T - 1)) * C]);
        }
        float s = metal::precise::sin(u * a);
        su[m] = u + ib * s * s;
    }
    for (int r = 0; r < R && i0 + r < T; r++) {
        float acc = 0.0f;
        for (int k = 0; k < 12; k++) acc += FD[k] * su[2 * r + k];
        ob[size_t(i0 + r) * C] = InT(acc);
    }
"""


def _activation_reference(x, a, inv_b, f):
    """The same as the Metal kernel in MLX ops (used when Metal is not available)."""
    dtype = x.dtype
    x = x.astype(mx.float32)
    B, T, C = x.shape
    xp = mx.concatenate([mx.repeat(x[:, :1], 5, 1), x, mx.repeat(x[:, -1:], 5, 1)], axis=1)          # T + 10
    even = sum(2 * f[2 * j + 1] * xp[:, 7 - j: 7 - j + T] for j in range(6))
    odd = sum(2 * f[2 * j] * xp[:, 8 - j: 8 - j + T] for j in range(6))
    u = mx.stack([even, odd], axis=2).reshape(B, 2 * T, C)
    u = u + inv_b * mx.square(mx.sin(u * a))
    up = mx.concatenate([mx.repeat(u[:, :1], 5, 1), u, mx.repeat(u[:, -1:], 7, 1)], axis=1)       # 2T + 12
    up = up.reshape(B, T + 6, 2, C)
    ev, od = up[:, :, 0], up[:, :, 1]
    return sum(f[2 * j] * ev[:, j: j + T] + f[2 * j + 1] * od[:, j: j + T] for j in range(6)).astype(dtype)


class Activation1d(nn.Module):
    """alias_free_activation Activation1d(SnakeBeta, logscale): 2x upsample (kaiser-sinc transposed convolution,
    replicate padding), SnakeBeta x + sin^2(x e^alpha) / (e^beta + 1e-9), 2x downsample (kaiser-sinc, stride 2,
    replicate padding). One Metal kernel (polyphase form, float32 math, 8 output samples per thread), like BigVGAN's
    fused CUDA activation."""
    F = None
    KERNEL = None

    def __init__(self, c):
        super().__init__()
        self.alpha = mx.zeros((c,))
        self.beta = mx.zeros((c,))

    @classmethod
    def kernel(cls):
        if cls.KERNEL is None:
            f = cls.F
            lit = lambda v: ", ".join(f"{x!r}f" for x in v)
            head = (f"    const float FU_E[6] = {{{lit([2 * f[2 * j] for j in range(6)])}}};\n"
                    f"    const float FU_O[6] = {{{lit([2 * f[2 * j + 1] for j in range(6)])}}};\n"
                    f"    const float FD[12] = {{{lit(f)}}};\n")
            cls.KERNEL = mx.fast.metal_kernel(name="bigvgan_snakebeta_aa", input_names=["x", "alpha", "ibeta"],
                                              output_names=["out"], source=head + _KERNEL_SRC)
        return cls.KERNEL

    def __call__(self, x):                             # [B, T, C]
        a = mx.exp(self.alpha.astype(mx.float32))
        inv_b = 1.0 / (mx.exp(self.beta.astype(mx.float32)) + 1e-9)
        if not mx.metal.is_available() or mx.default_device() != mx.gpu:
            return _activation_reference(x, a, inv_b, Activation1d.F)
        R = 8
        n = x.shape[0] * ((x.shape[1] + R - 1) // R) * x.shape[2]
        return self.kernel()(inputs=[x, a, inv_b], template=[("InT", x.dtype), ("R", R)], grid=(n, 1, 1),
                             threadgroup=(256, 1, 1), output_shapes=[x.shape], output_dtypes=[x.dtype])[0]


class AMPBlock1(nn.Module):
    def __init__(self, c, k, dil=(1, 3, 5)):
        super().__init__()
        self.convs1 = [nn.Conv1d(c, c, k, padding=(k * d - d) // 2, dilation=d) for d in dil]
        self.convs2 = [nn.Conv1d(c, c, k, padding=(k - 1) // 2) for _ in dil]
        self.acts = [Activation1d(c) for _ in range(2 * len(dil))]

    def __call__(self, x):
        for i, (c1, c2) in enumerate(zip(self.convs1, self.convs2)):
            x = x + c2(self.acts[2 * i + 1](c1(self.acts[2 * i](x))))
        return x


class BigVGAN(nn.Module):
    """BigVGAN v2 (22 kHz, 80 bands, 256x; resblock 1, snakebeta, no final tanh / bias), weight norm folded."""
    RATES, KERNELS, CH = (4, 4, 2, 2, 2, 2), (8, 8, 4, 4, 4, 4), 1536

    def __init__(self):
        super().__init__()
        self.conv_pre = nn.Conv1d(80, self.CH, 7, padding=3)
        self.ups, self.resblocks = [], []
        for i, (u, k) in enumerate(zip(self.RATES, self.KERNELS)):
            cin, cout = self.CH // 2 ** i, self.CH // 2 ** (i + 1)
            self.ups.append(nn.ConvTranspose1d(cin, cout, k, stride=u, padding=(k - u) // 2))
            self.resblocks.extend(AMPBlock1(cout, rk) for rk in (3, 7, 11))
        self.activation_post = Activation1d(self.CH // 64)
        self.conv_post = nn.Conv1d(self.CH // 64, 1, 7, padding=3, bias=False)

    def __call__(self, mel):                           # [B, T, 80] -> [B, 256 T]
        x = self.conv_pre(mel)
        for i, up in enumerate(self.ups):
            x = up(x)
            xs = self.resblocks[3 * i](x) + self.resblocks[3 * i + 1](x) + self.resblocks[3 * i + 2](x)
            x = xs / 3
        x = self.conv_post(self.activation_post(x))
        return mx.clip(x[..., 0].astype(mx.float32), -1.0, 1.0)


Activation1d.F = _taps()

PARTS = {"content": ContentEncoder, "style": CAMPPlus, "regulator": Regulator, "dit": DiT, "vocoder": BigVGAN}


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 SeedVC2:
    def __init__(self, folder):
        self.folder = Path(folder)
        self.config = json.loads((self.folder / "config.json").read_text())
        self.dtype = DTYPES[self.config["dtype"]]
        self.content_model = load_part(self.folder, "content", self.config)
        self.style_model = load_part(self.folder, "style", self.config)
        self.regulator = load_part(self.folder, "regulator", self.config)
        self.dit = load_part(self.folder, "dit", self.config)
        self.dit.dtype_ = self.dtype
        self.vocoder = load_part(self.folder, "vocoder", self.config)
        self.basis = mel_basis()
        self._dit = mx.compile(self.dit)

    # parts ---------------------------------------------------------------------------------------------------
    def _tokens1(self, w):
        w = np.asarray(w, np.float32)
        x = ((w - w.mean()) / np.sqrt(w.var() + 1e-7)).astype(np.float32)[None]
        return np.array(self.content_model(mx.array(x).astype(self.dtype)))

    def tokens(self, wav16):
        """ASTRAL tokens (50 Hz); audio over 30 s in 30 s windows with 5 s of overlap, as the official code does."""
        if len(wav16) <= 16000 * 30:
            return self._tokens1(wav16)
        out, buf, pos = [], None, 0
        while pos < len(wav16):
            chunk = wav16[pos:pos + 16000 * 30] if buf is None else np.concatenate([buf, wav16[pos:pos + 16000 * 25]])
            t = self._tokens1(chunk)
            out.append(t if pos == 0 else t[50 * 5:])
            buf = chunk[-16000 * 5:]
            pos += 30 * 16000 if pos == 0 else len(chunk) - 16000 * 5
        return np.concatenate(out)

    def style(self, wav16):
        f = kaldi_fbank(wav16)
        f = f - f.mean(0, keepdims=True)
        return self.style_model(mx.array(f[None]).astype(self.dtype))

    def condition(self, tokens, n):
        return self.regulator(mx.array(nearest(tokens, n)[None]))

    def cfm(self, cond, prompt, style, steps, cfg, rng):
        """CFM.inference + solve_euler: cosine-scheduled Euler, three-way batch (both conditions, text only, none)."""
        L, pl = cond.shape[1], prompt.shape[1]
        x = mx.array(rng.standard_normal((1, 80, L)).astype(np.float32)).transpose(0, 2, 1)   # [1, L, 80]
        ts = np.linspace(0, 1, steps + 1, dtype=np.float32)
        ts = (ts + (-1) * (np.cos(np.float32(np.pi / 2) * ts) - 1 + ts)).astype(np.float32)
        t, dt = ts[0], ts[1] - ts[0]
        px = mx.concatenate([prompt, mx.zeros((1, L - pl, 80))], 1)
        keep = mx.concatenate([mx.zeros((1, pl, 1)), mx.ones((1, L - pl, 1))], 1)
        x = x * keep
        z = mx.zeros_like
        c0, c1 = cfg
        px3 = mx.concatenate([px, z(px), z(px)])
        style3 = mx.concatenate([style, z(style), z(style)])
        cond3 = mx.concatenate([cond, cond, z(cond)])
        for step in range(1, len(ts)):
            v = self._dit(mx.concatenate([x, x, x]), px3, mx.full((3,), t, mx.float32), style3, cond3).astype(mx.float32)
            d = (1.0 + c0 + c1) * v[0:1] - c0 * v[2:3] - c1 * v[1:2]
            x = (x + float(dt) * d) * keep
            t = np.float32(t + dt)
            if step < len(ts) - 1:
                dt = ts[step + 1] - t
            mx.async_eval(x)
        return x

    def __call__(self, src, src_sr, ref, ref_sr, steps=30, cfg=(0.7, 0.7), seed=0, rng=None):
        rng = rng or np.random.default_rng(seed)
        src, ref = resample(src, src_sr, SR), resample(ref, ref_sr, SR)[: SR * (CONTEXT_S - 5)]
        src16, ref16 = resample(src, SR, 16000), resample(ref, SR, 16000)
        smel, tmel = mel(src, self.basis), mel(ref, self.basis)
        tl = tmel.shape[1]
        st, tt = self.tokens(src16), self.tokens(ref16)
        style = self.style(ref16).astype(mx.float32)
        prompt_cond = self.condition(tt, tl)
        cond = self.condition(st, smel.shape[1])
        prompt = mx.array(tmel.T[None])
        window = SR // HOP * CONTEXT_S - tl
        ov = OVERLAP * HOP
        chunks, prev, done = [], None, 0
        while done < cond.shape[1]:
            cc = cond[:, done:done + window]
            last = done + window >= cond.shape[1]
            m = self.cfm(mx.concatenate([prompt_cond, cc], 1), prompt, style, steps, cfg, rng)[:, tl:]
            wav = np.array(self.vocoder(m.astype(self.dtype))).reshape(-1)
            if done == 0 and last:
                chunks.append(wav)
                break
            if done == 0:
                chunks.append(wav[:-ov]); prev = wav[-ov:]
            elif last:
                chunks.append(crossfade(prev, wav, ov))
                break
            else:
                chunks.append(crossfade(prev, wav[:-ov], ov)); prev = wav[-ov:]
            done += m.shape[1] - OVERLAP
        return np.concatenate(chunks).astype(np.float32), 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("--steps", type=int, default=30); 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 = SeedVC2(a.dir)
    wav, sr = vc(s.mean(1), ssr, r.mean(1), rsr, steps=a.steps, seed=a.seed)
    sf.write(a.output, wav, sr)