Run this model with HF Jobs

Run moonbox-dev/voice-isolator-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/voice-isolator-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/voice-isolator-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: 23,180 Bytes
e6d9dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Inworld Voice Isolator v1 (offline, 48 kHz) on MLX: the network and the whole pipeline in one file (mlx, numpy).

    from mlx_model import VoiceIsolator
    iso = VoiceIsolator("out/mlx/8bit")           # a build folder: config.json + model.safetensors (+ this file)
    voice = iso.isolate(audio)                    # float32 mono at 48 kHz -> float32 mono at 48 kHz

A build folder (made by convert_mlx.py) holds

    config.json         the checkpoint's architecture (width 512, 46 bands, 7 blocks, ...), the build's precision,
                        its compute dtype and, for 8 / 6 / 4 bit builds, which Linear layers are quantized
    model.safetensors   the weights under the original's names (two renamed: see below)

The port follows inworld-voice-isolation @c73b3fa (Apache-2.0, Copyright 2026 Inworld AI), model.py and scan.py,
operation for operation:

    STFT (n_fft 2048, hop 480, periodic Hann, centred) -> per-band LayerNorm + Linear encoders (46 bands) + band
    embedding -> 7 dual-path blocks (transformer: time attention with rotary positions and exclusive self attention,
    then a transformer across the bands; Mamba: bidirectional Mamba along time, then across the bands) -> per-band
    decoder heads -> complex mask delta and bounded residual -> output = input + iSTFT(change).

Clips longer than 8 s run in 8 s windows overlapping by 2 s with linear crossfades (VoiceIsolatorNetwork.enhance).

Precision. The selective scan runs as one Metal kernel (the original's own MPS kernel, scan.py `_METAL_SOURCE`,
ported to mx.fast.metal_kernel: one thread per channel, the state in registers, float32, precise::exp), with the same
arithmetic as the original's float32 frame loop: decay = exp(delta * a), h = decay * h + (delta * u) * b,
y = sum(h * c) + d * u, times silu(z). As in the original under autocast, the STFT, the iSTFT, the LayerNorms, the
exclusive-attention projection, the depthwise convolution, softplus, the scan and the complex correction are float32
whatever the build, and so is the residual stream. `compute` in config.json is the dtype of the matrix products and
attention: "float32" (half-precision storage: the weights are cast up where they are read) or "bfloat16".

Names: the band transformer's `self_attn.in_proj_weight` / `in_proj_bias` (a fused nn.MultiheadAttention parameter in
the original) are `self_attn.in_proj.weight` / `.bias` here so the layer is an ordinary Linear (and quantizable).
Everything else keeps the original's name.
"""

from __future__ import annotations

import json
import math
import os
from pathlib import Path

# MLX runs float32 matrix products on the M5's GPU in TF32 by default (MLX_ENABLE_TF32, read once, at the process's
# first matmul): about 62 dB from float32 per product, which this deep network turns into an output tens of dB from
# the original's. Full float32 unless the caller has set the variable (it must happen before any MLX matmul runs).
os.environ.setdefault("MLX_ENABLE_TF32", "0")

import mlx.core as mx  # noqa: E402
import mlx.nn as nn  # noqa: E402
import numpy as np  # noqa: E402

# ------------------------------------------------------------------------------------------------------------ helpers


def band_edges(config: dict) -> list[tuple[int, int]]:
    """Bin ranges [start, end) of the bands (model.band_edges)."""
    n_bins = config["n_fft"] // 2 + 1
    hz_per_bin = config["sample_rate"] / config["n_fft"]
    edges, start = [], 0
    for width_hz, upto_hz in config["band_plan"]:
        width = max(1, round(width_hz / hz_per_bin))
        upto = min(n_bins, round(upto_hz / hz_per_bin))
        while start < upto:
            end = min(start + width, upto)
            edges.append((start, end))
            start = end
    if start < n_bins:
        edges.append((start, n_bins))
    return edges


def layer_norm(m: nn.LayerNorm, x: mx.array) -> mx.array:
    """LayerNorm in float32 (autocast keeps layer_norm in float32 too)."""
    return mx.fast.layer_norm(x.astype(mx.float32), m.weight.astype(mx.float32), m.bias.astype(mx.float32), m.eps)


def lin(m: nn.Module, x: mx.array, dt) -> mx.array:
    """A Linear layer on x cast to the compute dtype (weights stored in half precision are promoted when dt is
    float32)."""
    return m(x.astype(dt))


def exclusive(output: mx.array, value: mx.array) -> mx.array:
    """Removes each token's component along its own value, in float32 (model.exclusive)."""
    o, v = output.astype(mx.float32), value.astype(mx.float32)
    coef = (o * v).sum(-1, keepdims=True) / mx.maximum((v * v).sum(-1, keepdims=True), 1e-6)
    return (o - coef * v).astype(output.dtype)


# ----------------------------------------------------------------------------------------------------- selective scan

_SCAN_SOURCE = """
    const uint index = thread_position_in_grid.x;
    const uint batch = dims[0];
    const uint frames = dims[1];
    const uint channels = dims[2];
    if (index >= batch * channels) {
        return;
    }
    const uint row = index / channels;
    const uint channel = index % channels;
    float h[NS];
    float rate[NS];
    for (uint n = 0; n < NS; ++n) {
        rate[n] = a[channel * NS + n];
        h[n] = 0.0f;
    }
    const float skip = d[channel];
    for (uint t = 0; t < frames; ++t) {
        const uint at = (row * frames + t) * channels + channel;
        const uint bt = (row * frames + t) * NS;
        const float step = delta[at];
        const float x = u[at];
        const float drive = step * x;
        float out = 0.0f;
        for (uint n = 0; n < NS; ++n) {
            h[n] = metal::precise::exp(step * rate[n]) * h[n] + drive * b[bt + n];
            out += h[n] * c[bt + n];
        }
        out += x * skip;
        const float g = z[at];
        out *= metal::precise::divide(g, 1.0f + metal::precise::exp(-g));
        y[at] = out;
    }
"""
_SCAN_KERNEL = None


def selective_scan(u, delta, a, b, c, d, z) -> mx.array:
    """y [B, T, C] float32 of u, delta, z [B, T, C], a [C, N], b, c [B, T, N], d [C] (scan.selective_scan without a
    carried state): h_t = exp(delta_t a) h_{t-1} + (delta_t u_t) b_t, y_t = (c_t . h_t + d u_t) silu(z_t)."""
    global _SCAN_KERNEL
    if _SCAN_KERNEL is None:
        _SCAN_KERNEL = mx.fast.metal_kernel(name="vi_selective_scan",
                                            input_names=["dims", "u", "delta", "a", "b", "c", "d", "z"],
                                            output_names=["y"], source=_SCAN_SOURCE)
    batch, frames, channels = u.shape
    f32 = mx.float32
    dims = mx.array([batch, frames, channels], dtype=mx.uint32)
    threads = batch * channels
    return _SCAN_KERNEL(inputs=[dims, u.astype(f32), delta.astype(f32), a.astype(f32), b.astype(f32),
                                c.astype(f32), d.astype(f32), z.astype(f32)],
                        template=[("NS", a.shape[1])], grid=(threads, 1, 1), threadgroup=(min(256, threads), 1, 1),
                        output_shapes=[u.shape], output_dtypes=[f32])[0]


def selective_scan_loop(u, delta, a, b, c, d, z) -> mx.array:
    """The same scan as plain MLX operations frame by frame (a check on the kernel; slow)."""
    f = mx.float32
    u, delta, b, c, z = (t.astype(f) for t in (u, delta, b, c, z))
    h = mx.zeros((u.shape[0], u.shape[2], a.shape[1]), f)
    ys = []
    for t in range(u.shape[1]):
        h = mx.exp(delta[:, t, :, None] * a) * h + (delta[:, t] * u[:, t])[..., None] * b[:, t, None, :]
        ys.append((h * c[:, t, None, :]).sum(-1))
    return (mx.stack(ys, 1) + u * d) * nn.silu(z)


# ------------------------------------------------------------------------------------------------------------ network


class TimeAttention(nn.Module):
    def __init__(self, width: int, heads: int, exclusive_attention: bool):
        super().__init__()
        self.heads, self.head_dim, self.exclusive = heads, width // heads, exclusive_attention
        self.qkv = nn.Linear(width, 3 * width)
        self.proj = nn.Linear(width, width)

    def __call__(self, x: mx.array, dt) -> mx.array:
        batch, frames, width = x.shape
        qkv = lin(self.qkv, x, dt).reshape(batch, frames, 3, self.heads, self.head_dim).transpose(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]
        # model.apply_rope: halves rotated by 10000^(-i / (head_dim / 2)), position = frame index
        q = mx.fast.rope(q, self.head_dim, traditional=False, base=10000.0, scale=1.0, offset=0)
        k = mx.fast.rope(k, self.head_dim, traditional=False, base=10000.0, scale=1.0, offset=0)
        out = mx.fast.scaled_dot_product_attention(q, k, v, scale=1.0 / math.sqrt(self.head_dim))
        if self.exclusive:
            out = exclusive(out, v)
        return lin(self.proj, out.transpose(0, 2, 1, 3).reshape(batch, frames, width), dt)


class TimeBlock(nn.Module):
    """A pre-norm transformer layer along time (model._TimeBlock); ffn.0 / ffn.3 as in the original."""

    def __init__(self, width: int, heads: int, exclusive_attention: bool):
        super().__init__()
        self.norm1 = nn.LayerNorm(width)
        self.attn = TimeAttention(width, heads, exclusive_attention)
        self.norm2 = nn.LayerNorm(width)
        self.ffn = [nn.Linear(width, 4 * width), nn.GELU(), nn.Identity(), nn.Linear(4 * width, width)]

    def __call__(self, x: mx.array, dt) -> mx.array:
        x = x + self.attn(layer_norm(self.norm1, x), dt)
        return x + lin(self.ffn[3], nn.gelu(lin(self.ffn[0], layer_norm(self.norm2, x), dt)), dt)


class BandSelfAttention(nn.Module):
    def __init__(self, width: int):
        super().__init__()
        self.in_proj = nn.Linear(width, 3 * width)
        self.out_proj = nn.Linear(width, width)


class BandTransformer(nn.Module):
    """A pre-norm transformer layer across the bands of one frame (model._BandTransformer)."""

    def __init__(self, width: int, heads: int, exclusive_attention: bool):
        super().__init__()
        self.heads, self.exclusive = heads, exclusive_attention
        self.self_attn = BandSelfAttention(width)
        self.linear1 = nn.Linear(width, 4 * width)
        self.linear2 = nn.Linear(4 * width, width)
        self.norm1 = nn.LayerNorm(width)
        self.norm2 = nn.LayerNorm(width)

    def __call__(self, x: mx.array, dt) -> mx.array:
        batch, bands, width = x.shape
        hd = width // self.heads
        qkv = lin(self.self_attn.in_proj, layer_norm(self.norm1, x), dt)
        qkv = qkv.reshape(batch, bands, 3, self.heads, hd).transpose(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]
        out = mx.fast.scaled_dot_product_attention(q, k, v, scale=1.0 / math.sqrt(hd))
        if self.exclusive:
            out = exclusive(out, v)
        x = x + lin(self.self_attn.out_proj, out.transpose(0, 2, 1, 3).reshape(batch, bands, width), dt)
        return x + lin(self.linear2, nn.gelu(lin(self.linear1, layer_norm(self.norm2, x), dt)), dt)


class DualPathAttention(nn.Module):
    def __init__(self, config: dict):
        super().__init__()
        w, h = config["width"], config["num_heads"]
        ex = config.get("exclusive_self_attention", True)
        axes = config.get("exclusive_axes", "time")
        self.time_transformer = TimeBlock(w, h, ex and axes in ("both", "time"))
        self.band_transformer = BandTransformer(w, h, ex and axes in ("both", "band"))

    def __call__(self, x: mx.array, dt) -> mx.array:              # one clip: [bands, frames, width]
        x = self.time_transformer(x, dt)
        return self.band_transformer(x.transpose(1, 0, 2), dt).transpose(1, 0, 2)


class Conv(nn.Module):
    """The depthwise convolution's parameters in torch's layout: weight [C, 1, K], bias [C]."""

    def __init__(self, channels: int, kernel: int):
        super().__init__()
        self.weight = mx.zeros((channels, 1, kernel))
        self.bias = mx.zeros((channels,))


@mx.compile
def _causal_conv_silu(u: mx.array, weight: mx.array, bias: mx.array) -> mx.array:
    """silu(depthwise conv1d(u) with padding K - 1, first `frames` outputs) in float32; weight [C, 1, K]."""
    w = weight.astype(mx.float32)[:, 0, :]
    k, frames = w.shape[1], u.shape[1]
    padded = mx.pad(u.astype(mx.float32), [(0, 0), (k - 1, 0), (0, 0)])
    conv = bias.astype(mx.float32)
    for j in range(k):
        conv = conv + padded[:, j:j + frames] * w[:, j]
    return nn.silu(conv)


@mx.compile
def _softplus_bias(pre: mx.array, bias: mx.array) -> mx.array:
    return nn.softplus(pre.astype(mx.float32) + bias.astype(mx.float32))


class Mamba(nn.Module):
    def __init__(self, width: int, state: int, conv: int, expand: int):
        super().__init__()
        inner = expand * width
        self.d_state, self.dt_rank, self.inner = state, math.ceil(width / 16), inner
        self.in_proj = nn.Linear(width, 2 * inner, bias=False)
        self.conv1d = Conv(inner, conv)
        self.x_proj = nn.Linear(inner, self.dt_rank + 2 * state, bias=False)
        self.dt_proj = nn.Linear(self.dt_rank, inner)
        self.A_log = mx.zeros((inner, state))
        self.D = mx.ones((inner,))
        self.out_proj = nn.Linear(inner, width, bias=False)

    def __call__(self, x: mx.array, dt) -> mx.array:
        xz = lin(self.in_proj, x, dt)
        u, z = xz[..., :self.inner], xz[..., self.inner:]
        u = _causal_conv_silu(u, self.conv1d.weight, self.conv1d.bias)
        proj = lin(self.x_proj, u, dt)
        r, s = self.dt_rank, self.d_state
        dtv, b, c = proj[..., :r], proj[..., r:r + s], proj[..., r + s:]
        # softplus(linear(dt, W).float() + bias.float()); dt_proj is never quantized
        delta = _softplus_bias(dtv.astype(dt) @ self.dt_proj.weight.astype(dt).T, self.dt_proj.bias)
        a = -mx.exp(self.A_log.astype(mx.float32))
        y = selective_scan(u, delta, a, b, c, self.D, z)
        return lin(self.out_proj, y, dt)


class BidirectionalMamba(nn.Module):
    def __init__(self, width: int, state: int, conv: int, expand: int):
        super().__init__()
        self.forward_blocks = Mamba(width, state, conv, expand)
        self.backward_blocks = Mamba(width, state, conv, expand)
        self.output_proj = nn.Linear(2 * width, width)
        self.norm = nn.LayerNorm(width)

    def __call__(self, x: mx.array, dt) -> mx.array:
        fwd = self.forward_blocks(x, dt)
        bwd = self.backward_blocks(x[:, ::-1], dt)[:, ::-1]
        cat = mx.concatenate([fwd + x, bwd + x], axis=-1)
        return layer_norm(self.norm, lin(self.output_proj, cat, dt))


class DualPathMamba(nn.Module):
    def __init__(self, config: dict):
        super().__init__()
        args = (config["width"], config["mamba_state"], config["mamba_conv"], config["mamba_expand"])
        self.time_mamba = BidirectionalMamba(*args)
        self.freq_mamba = BidirectionalMamba(*args)

    def __call__(self, x: mx.array, dt) -> mx.array:              # [bands, frames, width]
        x = x + self.time_mamba(x, dt)
        f = x.transpose(1, 0, 2)                                    # [frames, bands, width]
        f = f + self.freq_mamba(f, dt)
        return f.transpose(1, 0, 2)


class Decoder(nn.Module):
    """Per-band heads [LayerNorm, Linear, GELU, Linear]: a complex mask delta and a residual for every bin."""

    def __init__(self, width: int, edges):
        super().__init__()
        self.edges = edges
        self.condition = nn.Linear(2, 2 * width)
        self.heads = [[nn.LayerNorm(width), nn.Linear(width, width), nn.GELU(), nn.Linear(width, 4 * (e - s))]
                      for s, e in edges]

    def __call__(self, features: mx.array, dt) -> mx.array:
        """features [bands, frames, width] -> raw [frames, bins, 4] float32."""
        ss = self.condition.weight.astype(mx.float32)[:, 0] + self.condition.bias.astype(mx.float32)  # controls [1, 0]
        width = features.shape[-1]
        features = features * (1 + ss[:width]) + ss[width:]
        frames = features.shape[1]
        outs = []
        for i, ((s, e), head) in enumerate(zip(self.edges, self.heads)):
            h = nn.gelu(lin(head[1], layer_norm(head[0], features[i]), dt))
            outs.append(lin(head[3], h, dt).astype(mx.float32).reshape(frames, e - s, 4))
        return mx.concatenate(outs, axis=1)


class Network(nn.Module):
    """VoiceIsolatorNetwork between the STFT and the iSTFT, for one clip (offline, two-sided)."""

    def __init__(self, config: dict):
        super().__init__()
        if config.get("causal") or config.get("dual_mode") or config.get("lookahead_frames_choices"):
            raise ValueError("this port runs the offline (two-sided) checkpoint only")
        self.config = config
        self.edges = band_edges(config)
        w = config["width"]
        self.encoders = [[nn.LayerNorm(2 * (e - s)), nn.Linear(2 * (e - s), w)] for s, e in self.edges]
        self.band_embedding = mx.zeros((len(self.edges), w))
        self.blocks = [DualPathAttention(config) if kind == "transformer" else DualPathMamba(config)
                       for kind in config["block_types"]]
        self.denoise_decoder = Decoder(w, self.edges)

    @property
    def compute(self):
        return {"float32": mx.float32, "bfloat16": mx.bfloat16, "float16": mx.float16}[
            self.config.get("compute", "float32")]

    def change(self, spec_ri: mx.array) -> mx.array:
        """spec_ri [frames, bins, 2] float32 (real, imaginary) -> the complex change [frames, bins, 2] float32
        (the decoder's mask delta times the spectrum plus the bounded residual: VoiceIsolatorNetwork.correction)."""
        dt = self.compute
        frames = spec_ri.shape[0]
        feats = [lin(enc[1], layer_norm(enc[0], spec_ri[:, s:e].reshape(frames, 2 * (e - s))), dt)
                 for (s, e), enc in zip(self.edges, self.encoders)]
        x = mx.stack(feats, 0).astype(mx.float32) + self.band_embedding.astype(mx.float32)[:, None]
        for block in self.blocks:
            x = block(x, dt)
            mx.eval(x)                                              # one block's working set at a time
        raw = self.denoise_decoder(x, dt)                           # [frames, bins, 4]
        sr, si = spec_ri[..., 0], spec_ri[..., 1]
        mr, mi = 2 * mx.tanh(raw[..., 0]), 2 * mx.tanh(raw[..., 1])
        comps = mx.tanh(raw[..., 2:])
        norm = mx.maximum(mx.sqrt((comps * comps).sum(-1, keepdims=True)), 1.0)
        mag = mx.sqrt(sr * sr + si * si)
        res = comps / norm * (self.config["correction_bound"] * mag[..., None])
        return mx.stack([sr * mr - si * mi + res[..., 0], sr * mi + si * mr + res[..., 1]], axis=-1)


# ---------------------------------------------------------------------------------------------------- STFT and iSTFT


def hann(n: int) -> np.ndarray:
    return 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n)       # torch.hann_window (periodic)


def stft(x: np.ndarray, n_fft: int, hop: int) -> np.ndarray:
    """torch.stft(x, n_fft, hop, hann, center=True; reflect padding) of one clip: [frames, bins] complex64."""
    pad = n_fft // 2
    x = np.pad(x.astype(np.float32), pad, mode="reflect" if len(x) > pad else "constant")
    t = 1 + (len(x) - n_fft) // hop
    idx = np.arange(n_fft)[None, :] + hop * np.arange(t)[:, None]
    return np.fft.rfft(x[idx].astype(np.float64) * hann(n_fft), axis=-1).astype(np.complex64)


def istft(spec: np.ndarray, length: int, n_fft: int, hop: int) -> np.ndarray:
    """torch.istft(spec [frames, bins], n_fft, hop, hann, center=True, length): overlap-add over the squared window."""
    win = hann(n_fft)
    frames = np.fft.irfft(spec.astype(np.complex128), n=n_fft, axis=-1) * win
    t = frames.shape[0]
    n = n_fft + hop * (t - 1)
    idx = (np.arange(n_fft)[None, :] + hop * np.arange(t)[:, None]).reshape(-1)
    y = np.bincount(idx, weights=frames.reshape(-1), minlength=n)
    env = np.bincount(idx, weights=np.tile(win * win, t), minlength=n)
    start = n_fft // 2
    y = (y[start:start + length] / np.maximum(env[start:start + length], 1e-11)).astype(np.float32)
    return np.pad(y, (0, length - len(y))) if len(y) < length else y


# ---------------------------------------------------------------------------------------------------------- pipeline


def load_network(folder: str | Path) -> Network:
    """The network of a build folder; layers listed in config.json's `quantization.layers` are QuantizedLinear."""
    folder = Path(folder)
    config = json.loads((folder / "config.json").read_text())
    net = Network(config)
    q = config.get("quantization")
    if q:
        layers = q["layers"]                                        # {module path: {group_size, bits}}
        nn.quantize(net, class_predicate=lambda p, m: (
            {**layers[p], "mode": q.get("mode", "affine")} if p in layers else False))
    net.load_weights(str(folder / "model.safetensors"), strict=True)
    mx.eval(net.parameters())
    return net


class VoiceIsolator:
    """The offline isolator of a build folder: `isolate(audio)` for mono float audio at 48 kHz, any length."""

    def __init__(self, folder: str | Path):
        self.net = load_network(folder)
        c = self.config = self.net.config
        self.sample_rate = c["sample_rate"]
        self.n_fft, self.hop = c["n_fft"], c["hop_length"]
        self.chunk = int(c["chunk_seconds"] * self.sample_rate)
        self.overlap = min(int(c["overlap_seconds"] * self.sample_rate), self.chunk // 2)

    def forward(self, audio: np.ndarray) -> np.ndarray:
        """One window: audio [N] -> isolated voice [N] (VoiceIsolatorNetwork.forward)."""
        spec = stft(audio, self.n_fft, self.hop)
        ri = mx.array(np.stack([spec.real, spec.imag], -1).astype(np.float32))
        change = np.array(self.net.change(ri))
        return audio + istft(change[..., 0] + 1j * change[..., 1], len(audio), self.n_fft, self.hop)

    def isolate(self, audio: np.ndarray) -> np.ndarray:
        """Any length: 8 s windows overlapping by 2 s with linear crossfades (VoiceIsolatorNetwork.enhance)."""
        audio = np.asarray(audio, np.float32).reshape(-1)
        if not audio.size:
            raise ValueError("The audio is empty: there is nothing to isolate.")
        if not np.isfinite(audio).all():
            raise ValueError("The audio contains NaN or infinite samples.")
        chunk, overlap, n = self.chunk, self.overlap, len(audio)
        if n <= chunk:
            return self.forward(audio)
        out = np.zeros(n, np.float32)
        weight = np.zeros(n, np.float32)
        starts = list(range(0, n - chunk, chunk - overlap)) + [n - chunk]
        for k, start in enumerate(starts):
            end = start + chunk
            w = np.ones(chunk, np.float32)
            if k > 0:
                fade_in = starts[k - 1] + chunk - overlap - start
                w[:fade_in] = 0.0
                if overlap > 0:
                    w[fade_in:fade_in + overlap] = np.linspace(0.0, 1.0, overlap, dtype=np.float32)
            if overlap > 0 and end < n:
                w[-overlap:] = np.linspace(1.0, 0.0, overlap, dtype=np.float32)
            out[start:end] += self.forward(audio[start:end]) * w
            weight[start:end] += w
        return out / np.maximum(weight, 1e-6)