Run this model with HF Jobs

Run moonbox-dev/voice-isolator-realtime-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-realtime-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-realtime-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.
jennyxue's picture
8bit build of Inworld Voice Isolator (realtime)
78380f4 verified
Raw History Blame Contribute Delete
46.9 kB
"""Inworld Voice Isolator v1 realtime (causal, streaming, 48 kHz) on MLX: the network and the whole streaming
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) # a whole clip: float32 mono at 48 kHz -> float32 mono at 48 kHz
stream = iso.stream(block_frames=2) # live audio, pushed in pieces of any size
for piece in microphone: # e.g. 960 samples (20 ms) at a time
out = stream.push(piece) # the output samples that became final (63 ms behind the input)
out = stream.flush() # the rest
A build folder (made by convert_mlx.py) holds
config.json the checkpoint's architecture (width 512, 46 bands, 7 blocks, causal, attention window 1200
frames, look-aheads 0 / 2 / 4 frames, ...), 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, scan.py and
streaming.py, operation for operation. `isolate` is the original's streaming render (VoiceIsolator in mode
"streaming": the stream run over the clip), so a whole clip and a live session give the same audio:
frame analysis (n_fft 2048, hop 480, periodic Hann; a frame is computed once its 2048-sample window has arrived)
-> per-band LayerNorm + Linear encoders (46 bands) + band embedding + look-ahead embedding
-> 7 dual-path blocks over the new frames, with each lane's state carried: transformer blocks (causal time
attention with rotary positions and exclusive self attention, over a cache of the lane's past keys and values,
then a transformer across the bands) and Mamba blocks (forward-only Mamba along time with its convolution tail
and scan state carried, then bidirectional Mamba across the bands)
-> per-band decoder heads -> raw output per bin (complex mask delta, bounded residual)
-> output frame t takes the raw output of frame t + look-ahead (2 frames = 20 ms by default)
-> correction applied to the spectrum -> iSTFT frame -> overlap-add; output = input + change.
Windows (streaming.Stream's window_frames 600 / crossfade_frames 200, the session defaults): the time attention never
looks back across a 6 s window boundary. 2 s before each boundary a second lane starts with the Mamba states copied
and the attention cache empty; the two lanes' raw outputs blend linearly over those 200 frames, and the new lane
carries on from the boundary. A lane lives at most 800 frames, inside the checkpoint's 1200-frame attention window,
so each frame sees all of its lane's past and the output does not depend on how the audio is pushed or on the block
size (beyond float rounding).
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, with the carried state in and out: one thread per channel, the state in registers,
float32, precise::exp). As in the original under autocast, the frame analysis, the synthesis, the LayerNorms, the
exclusive-attention projection, the depthwise convolution, softplus, the scan and the correction are float32 whatever
the build, and so is the residual stream. `compute` in config.json is the dtype of the matrix products, attention and
the attention cache: "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
WINDOW_FRAMES, CROSSFADE_FRAMES = 600, 200 # streaming.Stream's windows as VoiceIsolator sets them (6 s, 2 s)
# ------------------------------------------------------------------------------------------------------------ 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] = h0[index * NS + n];
}
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;
}
for (uint n = 0; n < NS; ++n) {
last[index * NS + n] = h[n];
}
"""
_SCAN_KERNEL = None
def selective_scan(u, delta, a, b, c, d, z, h0=None) -> tuple[mx.array, mx.array]:
"""scan.selective_scan with a carried state: u, delta, z [B, T, C], a [C, N], b, c [B, T, N], d [C], h0 [B, C, N]
(zeros when None) -> y [B, T, C] float32 and the state after the last frame [B, C, N]:
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_rt_selective_scan",
input_names=["dims", "u", "delta", "a", "b", "c", "d", "z", "h0"],
output_names=["y", "last"], source=_SCAN_SOURCE)
batch, frames, channels = u.shape
n = a.shape[1]
f32 = mx.float32
if h0 is None:
h0 = mx.zeros((batch, channels, n), f32)
dims = mx.array([batch, frames, channels], dtype=mx.uint32)
threads = batch * channels
y, last = _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), h0.astype(f32)],
template=[("NS", n)], grid=(threads, 1, 1), threadgroup=(min(256, threads), 1, 1),
output_shapes=[u.shape, (batch, channels, n)], output_dtypes=[f32, f32])
return y, last
def selective_scan_loop(u, delta, a, b, c, d, z, h0=None) -> tuple[mx.array, 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) if h0 is None else h0
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), h
# ------------------------------------------------------------------------------------------------------------ network
class TimeAttention(nn.Module):
def __init__(self, width: int, heads: int, exclusive_attention: bool, window: int):
super().__init__()
self.heads, self.head_dim, self.exclusive, self.window = heads, width // heads, exclusive_attention, window
self.qkv = nn.Linear(width, 3 * width)
self.proj = nn.Linear(width, width)
def qkv_heads(self, x: mx.array, dt) -> tuple[mx.array, mx.array, mx.array]:
"""x [rows, F, width] -> query, key, value [rows, heads, F, dim] (before the rotary positions)."""
rows, frames, _ = x.shape
qkv = lin(self.qkv, x, dt).reshape(rows, frames, 3, self.heads, self.head_dim).transpose(2, 0, 3, 1, 4)
return qkv[0], qkv[1], qkv[2]
def attend(self, q: mx.array, k: mx.array, v: mx.array, caches: list["AttentionCache"]) -> mx.array:
"""streaming._attend_lane for each lane: q, k, v [lanes * bands, heads, F, dim] (lane-major); each lane's new
keys (rotated at their slots) and values are written to its cache, and every new frame sees its lane's past
and the block's frames up to itself, within the checkpoint's attention window. -> [rows, heads, F, dim]"""
per, frames = q.shape[0] // len(caches), q.shape[2]
outs = []
for i, cache in enumerate(caches):
sl = slice(i * per, (i + 1) * per)
first = cache.end
# model.apply_rope at the slots first.. (rope_tables: 10000^(-i / (dim / 2)), halves rotated)
qi = mx.fast.rope(q[sl], self.head_dim, traditional=False, base=10000.0, scale=1.0, offset=first)
ki = mx.fast.rope(k[sl], self.head_dim, traditional=False, base=10000.0, scale=1.0, offset=first)
keys, values = cache.write(ki, v[sl]) # slots [0, first + F)
total = first + frames
mask = None
if frames > 1 or (self.window and total > self.window):
pos = mx.arange(total)[None, :]
qpos = (first + mx.arange(frames))[:, None]
mask = pos <= qpos
if self.window:
mask = mask & (pos > qpos - self.window)
outs.append(mx.fast.scaled_dot_product_attention(qi, keys, values, scale=1.0 / math.sqrt(self.head_dim),
mask=mask))
return outs[0] if len(outs) == 1 else mx.concatenate(outs, axis=0)
def project(self, out: mx.array, v: mx.array, dt) -> mx.array:
"""The exclusive projection and the output Linear: out, v [rows, heads, F, dim] -> [rows, F, width]."""
rows, _, frames, _ = out.shape
if self.exclusive:
out = exclusive(out, v)
return lin(self.proj, out.transpose(0, 2, 1, 3).reshape(rows, frames, self.heads * self.head_dim), 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, window: int):
super().__init__()
self.norm1 = nn.LayerNorm(width)
self.attn = TimeAttention(width, heads, exclusive_attention, window)
self.norm2 = nn.LayerNorm(width)
self.ffn = [nn.Linear(width, 4 * width), nn.GELU(), nn.Identity(), nn.Linear(4 * width, width)]
def ffn_forward(self, x: mx.array, dt) -> mx.array:
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"), config.get("attention_window_frames", 0))
self.band_transformer = BandTransformer(w, h, ex and axes in ("both", "band"))
def pre(self, x: mx.array, dt):
"""x [lanes, bands, F, width] -> the time rows [lanes * bands, F, width] and their query, key, value."""
lanes, bands, frames, width = x.shape
rows = x.reshape(lanes * bands, frames, width)
return (rows,) + self.time_transformer.attn.qkv_heads(layer_norm(self.time_transformer.norm1, rows), dt)
def post(self, rows: mx.array, out: mx.array, v: mx.array, dt, bands: int) -> mx.array:
"""The rest of the block after the attention itself: -> [lanes, bands, F, width]."""
tb = self.time_transformer
rows = tb.ffn_forward(rows + tb.attn.project(out, v, dt), dt)
n, frames, width = rows.shape
lanes = n // bands
x = rows.reshape(lanes, bands, frames, width).transpose(0, 2, 1, 3).reshape(lanes * frames, bands, width)
x = self.band_transformer(x, dt)
return x.reshape(lanes, frames, bands, width).transpose(0, 2, 1, 3)
def __call__(self, x: mx.array, caches, dt, pre=None, post=None) -> mx.array: # x [lanes, bands, F, width]
"""streaming._attend: `pre` / `post` are compiled versions of self.pre / self.post (or None)."""
bands = x.shape[1]
rows, q, k, v = (pre or (lambda t: self.pre(t, dt)))(x)
out = self.time_transformer.attn.attend(q, k, v, caches)
return (post or (lambda r, o, w: self.post(r, o, w, dt, bands)))(rows, out, v)
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 _conv_silu(history: mx.array, weight: mx.array, bias: mx.array) -> mx.array:
"""silu(depthwise conv1d over history [B, K - 1 + F, C] without padding) in float32: [B, F, C]."""
w = weight.astype(mx.float32)[:, 0, :]
k = w.shape[1]
frames = history.shape[1] - (k - 1)
conv = bias.astype(mx.float32)
for j in range(k):
conv = conv + history[:, 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, self.k = state, math.ceil(width / 16), inner, conv
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, state=None):
"""model.Mamba.forward: x [B, F, width], state (convolution tail [B, K - 1, inner] float32, scan state
[B, inner, N] float32) or None (zeros: a sequence's start) -> (output, new state)."""
xz = lin(self.in_proj, x, dt)
u, z = xz[..., :self.inner], xz[..., self.inner:]
tail = (mx.zeros((x.shape[0], self.k - 1, self.inner), mx.float32) if state is None else state[0])
history = mx.concatenate([tail, u.astype(mx.float32)], axis=1)
u = _conv_silu(history, 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, last = selective_scan(u, delta, a, b, c, self.D, z, None if state is None else state[1])
return lin(self.out_proj, y, dt), (history[:, -(self.k - 1):], last)
class CausalMamba(nn.Module):
"""model.BidirectionalMamba of a causal checkpoint: the forward scan only, its state carried."""
def __init__(self, width: int, state: int, conv: int, expand: int):
super().__init__()
self.forward_blocks = Mamba(width, state, conv, expand)
self.output_proj = nn.Linear(width, width)
self.norm = nn.LayerNorm(width)
def __call__(self, x: mx.array, dt, state):
fwd, state = self.forward_blocks(x, dt, state)
return layer_norm(self.norm, lin(self.output_proj, fwd + x, dt)), state
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)
cat = mx.concatenate([fwd + x, bwd[:, ::-1] + 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 = CausalMamba(*args)
self.freq_mamba = BidirectionalMamba(*args)
def packed_state(self, x: mx.array, tails: mx.array, hs: mx.array, dt):
return self(x, (tails, hs), dt)
def __call__(self, x: mx.array, state, dt): # x [lanes, bands, F, width]
"""streaming._scan: the time Mamba with each lane's state (stacked lane-major), then Mamba across bands."""
lanes, bands, frames, width = x.shape
rows = x.reshape(lanes * bands, frames, width)
t, state = self.time_mamba(rows, dt, state)
rows = rows + t
f = rows.reshape(lanes, bands, frames, width).transpose(0, 2, 1, 3).reshape(lanes * frames, bands, width)
f = f + self.freq_mamba(f, dt)
return f.reshape(lanes, frames, bands, width).transpose(0, 2, 1, 3), state
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 [lanes, bands, F, width] -> raw [lanes, F, bins, 4] float32."""
ss = self.condition.weight.astype(mx.float32)[:, 0] + self.condition.bias.astype(mx.float32) # controls [1, 0]
lanes, _, frames, width = features.shape
features = features * (1 + ss[:width]) + ss[width:]
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(lanes, frames, e - s, 4))
return mx.concatenate(outs, axis=2)
class PackedLinear:
"""The same Linear layer of every band stacked into one batched product (zero-padded to the widest band):
weight [bands, out, in] (or its quantized form, the per-layer quantized values stacked unchanged), bias
[bands, 1, out]. x [bands, M, in] -> [bands, M, out]."""
def __init__(self, layers: list, n_out: int):
self.quantized = isinstance(layers[0], nn.QuantizedLinear)
names = ("weight", "scales", "biases") if self.quantized else ("weight",)
self.parts = []
for name in names:
cols = max(getattr(m, name).shape[1] for m in layers)
stack = mx.zeros((len(layers), n_out, cols), getattr(layers[0], name).dtype)
for i, m in enumerate(layers):
t = getattr(m, name)
stack[i, :t.shape[0], :t.shape[1]] = t
self.parts.append(stack)
if self.quantized:
self.group_size, self.bits = layers[0].group_size, layers[0].bits
bias = mx.zeros((len(layers), 1, n_out), layers[0].bias.dtype)
for i, m in enumerate(layers):
bias[i, 0, :m.bias.shape[0]] = m.bias
self.bias = bias
mx.eval(self.parts, self.bias)
def __call__(self, x: mx.array, dt) -> mx.array:
x = x.astype(dt)
if self.quantized:
y = mx.quantized_matmul(x, *self.parts, transpose=True, group_size=self.group_size, bits=self.bits)
else:
y = x @ self.parts[0].astype(dt).swapaxes(1, 2)
return y + self.bias
class PackedBands:
"""streaming._PackedBands: the 46 band encoders and decoder heads as a few batched operations (each band's
layer a separate small product otherwise; in a stream's step of a few frames those dominate). Results equal the
per-band layers' to float rounding; quantized heads keep their exact quantized weights."""
def __init__(self, net: "Network"):
edges = net.edges
widths = [e - s for s, e in edges]
self.bands, self.n_in, self.n_out = len(edges), 2 * max(widths), 4 * max(widths)
bins = edges[-1][1]
gather = np.full((self.bands, self.n_in), 2 * bins, np.int32) # 2 * bins: a zero appended to the input
valid = np.zeros((self.bands, self.n_in), np.float32)
keep = []
for b, (s, e) in enumerate(edges):
gather[b, :2 * (e - s)] = np.arange(2 * s, 2 * e)
valid[b, :2 * (e - s)] = 1.0
keep.append(b * self.n_out + np.arange(4 * (e - s)))
self.gather, self.valid = mx.array(gather), mx.array(valid)[:, None]
self.counts = mx.array([2.0 * w for w in widths], mx.float32)[:, None, None]
self.keep = mx.array(np.concatenate(keep).astype(np.int32))
encs = net.encoders
self.enc_eps = encs[0][0].eps
self.enc_norm_w = mx.zeros((self.bands, 1, self.n_in), mx.float32)
self.enc_norm_b = mx.zeros((self.bands, 1, self.n_in), mx.float32)
for b, enc in enumerate(encs):
n = enc[0].weight.shape[0]
self.enc_norm_w[b, 0, :n] = enc[0].weight.astype(mx.float32)
self.enc_norm_b[b, 0, :n] = enc[0].bias.astype(mx.float32)
width = net.config["width"]
self.encoder = PackedLinear([enc[1] for enc in encs], width)
heads = net.denoise_decoder.heads
self.head_eps = heads[0][0].eps
self.head_norm_w = mx.stack([h[0].weight.astype(mx.float32) for h in heads])[:, None]
self.head_norm_b = mx.stack([h[0].bias.astype(mx.float32) for h in heads])[:, None]
self.hidden = PackedLinear([h[1] for h in heads], width)
self.out = PackedLinear([h[3] for h in heads], self.n_out)
cond = net.denoise_decoder.condition
self.condition = cond.weight.astype(mx.float32)[:, 0] + cond.bias.astype(mx.float32) # controls [1, 0]
mx.eval([v for v in self.__dict__.values() if isinstance(v, mx.array)])
def encode(self, spec_ri: mx.array, dt) -> mx.array:
"""spec_ri [F, bins, 2] -> the encoders' outputs [bands, F, width] float32 (LayerNorm over each band's own
values: the padding is masked out of the mean and variance)."""
frames = spec_ri.shape[0]
comps = mx.concatenate([spec_ri.reshape(frames, -1), mx.zeros((frames, 1), mx.float32)], axis=1)
x = comps[:, self.gather].transpose(1, 0, 2) # [bands, F, n_in]
mean = x.sum(-1, keepdims=True) / self.counts
centered = (x - mean) * self.valid
var = (centered * centered).sum(-1, keepdims=True) / self.counts
x = centered * mx.rsqrt(var + self.enc_eps) * self.enc_norm_w + self.enc_norm_b
return self.encoder(x, dt).astype(mx.float32)
def decode(self, features: mx.array, dt) -> mx.array:
"""features [lanes, bands, F, width] -> raw [lanes, F, bins, 4] float32 (Decoder.__call__)."""
lanes, bands, frames, width = features.shape
x = features * (1 + self.condition[:width]) + self.condition[width:]
x = x.transpose(1, 0, 2, 3).reshape(bands, lanes * frames, width)
x = mx.fast.layer_norm(x, None, None, self.head_eps) * self.head_norm_w + self.head_norm_b
x = self.out(nn.gelu(self.hidden(x, dt)), dt).astype(mx.float32) # [bands, lanes * F, n_out]
x = x.transpose(1, 0, 2).reshape(lanes * frames, bands * self.n_out)[:, self.keep]
return x.reshape(lanes, frames, -1, 4)
class AttentionCache:
"""One lane's keys and values for one attention block: buffers [bands, heads, capacity, dim] in the compute
dtype, slot i = the lane's frame i (its key rotated by i when written, as streaming._attend_lane does)."""
def __init__(self, rows: int, heads: int, dim: int, capacity: int, dtype):
self.capacity, self.end = capacity, 0
self.keys = mx.zeros((rows, heads, capacity, dim), dtype)
self.values = mx.zeros((rows, heads, capacity, dim), dtype)
def write(self, k: mx.array, v: mx.array) -> tuple[mx.array, mx.array]:
first, frames = self.end, k.shape[2]
if first + frames > self.capacity:
raise RuntimeError(f"a lane outgrew its {self.capacity}-frame attention cache")
self.keys[:, :, first:first + frames] = k.astype(self.keys.dtype)
self.values[:, :, first:first + frames] = v.astype(self.values.dtype)
self.end = first + frames
return self.keys[:, :, :self.end], self.values[:, :, :self.end]
class Lane:
"""One lane's state (streaming.Stream's states): an attention cache per attention block and the time Mamba's
convolution tail [bands, K - 1, inner] and scan state [bands, inner, N] per Mamba block."""
def __init__(self, net: "Network", mamba=None):
c = net.config
heads = c["num_heads"]
self.attention = [AttentionCache(len(net.edges), heads, c["width"] // heads, net.capacity, net.compute)
for _ in range(net.n_attention)]
rows, k, n, inner = len(net.edges), c["mamba_conv"], c["mamba_state"], c["mamba_expand"] * c["width"]
# zeros: the state of a sequence's start (the original pads the convolution and starts the scan at zero)
self.mamba = (list(mamba) if mamba is not None else
[(mx.zeros((rows, k - 1, inner), mx.float32), mx.zeros((rows, inner, n), mx.float32))
for _ in range(net.n_mamba)])
def second(self, net: "Network") -> "Lane":
"""The lane started before a window boundary: the Mamba states copied (arrays are never written in place, so
sharing them copies them), the attention empty (_clone_states)."""
return Lane(net, self.mamba)
def _bind(method, *extra):
"""A maker of `lambda *args: method(*args, *extra)` with method and extra bound now."""
return lambda: (lambda *args: method(*args, *extra))
class Network(nn.Module):
"""VoiceIsolatorNetwork of a causal checkpoint between the frame analysis and the synthesis, run over new frames
with each lane's state carried (streaming.Stream._run_block / _backbone)."""
def __init__(self, config: dict):
super().__init__()
if not config.get("causal"):
raise ValueError("this port runs the causal (realtime) 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.lookahead_embedding = nn.Embedding(len(config["lookahead_frames_choices"]), w)
self.blocks = [DualPathAttention(config) if kind == "transformer" else DualPathMamba(config)
for kind in config["block_types"]]
self.denoise_decoder = Decoder(w, self.edges)
self.capacity = WINDOW_FRAMES + CROSSFADE_FRAMES # a lane's life
self.n_attention = sum(kind == "transformer" for kind in config["block_types"])
self.n_mamba = len(config["block_types"]) - self.n_attention
self.use_packed, self.packed = True, None # PackedBands, built at the first step (after the weights load)
self.compile_frames, self._compiled = 16, {} # steps of up to this many frames run compiled functions
@property
def compute(self):
return {"float32": mx.float32, "bfloat16": mx.bfloat16, "float16": mx.float16}[
self.config.get("compute", "float32")]
def encode(self, spec_ri: mx.array, lookahead_index: int) -> mx.array:
"""spec_ri [F, bins, 2] -> band tokens [bands, F, width] float32 (model.encode at the look-ahead position)."""
dt, frames = self.compute, spec_ri.shape[0]
if self.packed is not None:
x = self.packed.encode(spec_ri, dt)
else:
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)
x = x + self.band_embedding.astype(mx.float32)[:, None]
return x + self.lookahead_embedding.weight[lookahead_index].astype(mx.float32)
def decode(self, x: mx.array) -> mx.array:
return self.packed.decode(x, self.compute) if self.packed is not None else self.denoise_decoder(x, self.compute)
def _fn(self, key, make, small: bool):
"""The compiled function for `key` (mx.compile specializes it per input shape) when the step is small, where
launching a few hundred small kernels one by one dominates; the plain function otherwise."""
if not small:
return make()
if key not in self._compiled:
self._compiled[key] = mx.compile(make())
return self._compiled[key]
def step(self, spec_ri: mx.array, lanes: list[Lane], lookahead_index: int) -> mx.array:
"""The network over F new frames, spec_ri [F, bins, 2] float32 (real, imaginary), for each lane with its own
state (the lanes' features stacked into one batch, the attention lane by lane, as streaming._backbone);
the lanes' states are updated. -> raw [lanes, F, bins, 4] float32 (the decoder output)."""
dt = self.compute
frames, n = spec_ri.shape[0], len(lanes)
small = frames <= self.compile_frames
if self.packed is None and self.use_packed:
self.packed = PackedBands(self)
# each function is made by a factory that binds its block now (a cached compiled function outlives this call)
x = self._fn(("encode", lookahead_index), _bind(self.encode, lookahead_index), small)(spec_ri)
x = mx.broadcast_to(x[None], (n,) + x.shape)
ia = im = 0
for b, block in enumerate(self.blocks):
if isinstance(block, DualPathAttention):
bands = x.shape[1]
pre = self._fn((b, "pre"), _bind(block.pre, dt), small)
post = self._fn((b, "post"), _bind(block.post, dt, bands), small)
x = block(x, [lane.attention[ia] for lane in lanes], dt, pre, post)
ia += 1
else:
states = [lane.mamba[im] for lane in lanes]
tails = states[0][0] if n == 1 else mx.concatenate([st[0] for st in states], axis=0)
hs = states[0][1] if n == 1 else mx.concatenate([st[1] for st in states], axis=0)
fn = self._fn((b, "mamba"), _bind(block.packed_state, dt), small)
x, (tails, hs) = fn(x, tails, hs)
rows = tails.shape[0] // n
for i, lane in enumerate(lanes):
lane.mamba[im] = (tails[i * rows:(i + 1) * rows], hs[i * rows:(i + 1) * rows])
im += 1
raw = self._fn("decode", _bind(self.decode), small)(x)
mx.eval(raw, [(c.keys, c.values) for lane in lanes for c in lane.attention], [lane.mamba for lane in lanes])
return raw
# ------------------------------------------------------------------------------------------------- frames and stream
def hann(n: int) -> np.ndarray:
return (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n)).astype(np.float32) # torch.hann_window (periodic)
def correction(raw: np.ndarray, spec: np.ndarray, bound: float) -> np.ndarray:
"""VoiceIsolatorNetwork.correction: raw [..., bins, 4], spec [..., bins] complex -> the complex change."""
mask = 2 * np.tanh(raw[..., :2])
comps = np.tanh(raw[..., 2:])
norm = np.maximum(np.sqrt((comps * comps).sum(-1, keepdims=True)), 1)
res = comps / norm * (bound * np.abs(spec)[..., None])
return (spec * (mask[..., 0] + 1j * mask[..., 1]) + (res[..., 0] + 1j * res[..., 1])).astype(np.complex64)
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 realtime isolator of a build folder: `isolate(audio)` for a whole clip, `stream()` for live audio (mono
float at 48 kHz). `lookahead_frames` is one of the checkpoint's trained positions (0, 2, 4 frames of 10 ms)."""
def __init__(self, folder: str | Path, lookahead_frames: int | None = None):
self.net = load_network(folder)
c = self.config = self.net.config
self.sample_rate, self.n_fft, self.hop = c["sample_rate"], c["n_fft"], c["hop_length"]
self.window = hann(self.n_fft)
choices = c["lookahead_frames_choices"]
self.lookahead = c["lookahead_frames"] if lookahead_frames is None else lookahead_frames
if self.lookahead not in choices:
raise ValueError(f"look-ahead {self.lookahead} is not among the trained positions {choices}")
self.lookahead_index = choices.index(self.lookahead)
@property
def latency_samples(self) -> int:
"""The stream's algorithmic latency: the analysis window plus the look-ahead frames."""
return self.n_fft + self.hop * self.lookahead
def stream(self, block_frames: int = 4) -> "Stream":
"""A live session with the original's windows (6 s, 2 s crossfade). Up to `block_frames` frames run per
network step: a throughput knob (a frame runs as soon as its window is complete, so it adds no latency)."""
return Stream(self, block_frames)
def isolate(self, audio: np.ndarray, block_frames: int = 600) -> np.ndarray:
"""A whole clip through the stream (the original's streaming render: VoiceIsolator.isolate in mode
"streaming"). Blocks are cut at every crossfade start and window boundary anyway, so the default runs each
stretch between them in one step; the output does not depend on the block size beyond float rounding."""
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.")
s = self.stream(block_frames)
return np.concatenate([s.push(audio), s.flush()])[:len(audio)]
class Stream:
"""streaming.Stream for one clip, windowed (window 600 frames, crossfade 200): push mono 48 kHz samples of any
size, get back the output samples that became final; flush() ends the stream and returns the rest."""
def __init__(self, iso: VoiceIsolator, block_frames: int = 4,
window_frames: int = WINDOW_FRAMES, crossfade_frames: int = CROSSFADE_FRAMES):
if block_frames < 1:
raise ValueError("Process at least one frame per block.")
if not 0 < crossfade_frames < window_frames or window_frames + crossfade_frames > iso.net.capacity:
raise ValueError("windows must satisfy 0 < crossfade < window and window + crossfade <= "
f"{iso.net.capacity}")
self.iso, self.net, self.block = iso, iso.net, block_frames
self.window, self.crossfade = window_frames, crossfade_frames
self.lookahead = iso.lookahead
self.n_fft, self.hop, self.half = iso.n_fft, iso.hop, iso.n_fft // 2
self.bound = iso.config["correction_bound"]
self.lane, self.lane_b = Lane(self.net), None
self.audio, self.audio_base = np.zeros(0, np.float32), 0
self.frames = 0 # frames computed
self.emitted = 0 # frames synthesized
self.raw, self.spectra, self.pending_base = [], [], 0
self.ola, self.env, self.ola_base = np.zeros(self.n_fft, np.float32), np.zeros(self.n_fft, np.float32), 0
self.released = 0
self.closed = False
@property
def latency_samples(self) -> int:
"""Input samples that must follow an output sample before its release (to within one hop)."""
return self.n_fft + self.hop * self.lookahead
def _analyze(self, first: int, count: int) -> np.ndarray:
"""Spectra [count, bins] of frames from `first`: each frame's window of the audio, zeros where there is
none (streaming.Stream._analyze)."""
start = first * self.hop - self.half
stop = (first + count - 1) * self.hop - self.half + self.n_fft
total = self.audio_base + len(self.audio)
lo, hi = max(start, self.audio_base), min(stop, total)
seg = self.audio[lo - self.audio_base:hi - self.audio_base] if hi > lo else self.audio[:0]
if hi <= lo:
lo = hi = start
seg = np.pad(seg, (lo - start, stop - hi))
idx = np.arange(self.n_fft)[None, :] + self.hop * np.arange(count)[:, None]
return np.fft.rfft(seg[idx] * self.iso.window, axis=-1).astype(np.complex64)
def _next_cut(self) -> int:
start = self.frames - self.frames % self.window
crossfade_start = start + self.window - self.crossfade
return crossfade_start if self.frames < crossfade_start else start + self.window
def _run(self, spectra: np.ndarray) -> np.ndarray:
"""streaming.Stream._windowed: raw [F, bins, 4] of the new frames."""
frames = len(spectra)
first = self.frames % self.window
crossfade_start = self.window - self.crossfade
if first >= crossfade_start and self.lane_b is None:
self.lane_b = self.lane.second(self.net)
ri = mx.array(np.stack([spectra.real, spectra.imag], -1)) # [F, bins, 2]
if first < crossfade_start:
return np.array(self.net.step(ri, [self.lane], self.iso.lookahead_index))[0]
both = np.array(self.net.step(ri, [self.lane, self.lane_b], self.iso.lookahead_index))
w = np.clip((np.arange(first, first + frames) - crossfade_start + 1).astype(np.float32) / self.crossfade,
0.0, 1.0)[:, None, None]
raw = both[0] * (1 - w) + both[1] * w
if first + frames == self.window:
self.lane, self.lane_b = self.lane_b, None
return raw
def _synthesize(self, first: int, count: int, sources) -> None:
raw = np.stack([self.raw[s - self.pending_base] for s in sources])
spec = np.stack(self.spectra[first - self.pending_base:first - self.pending_base + count])
frames = np.fft.irfft(correction(raw, spec, self.bound), n=self.n_fft, axis=-1).astype(np.float32)
frames *= self.iso.window
start = first * self.hop - self.ola_base
needed = start + (count - 1) * self.hop + self.n_fft
if needed > len(self.ola):
self.ola = np.pad(self.ola, (0, needed - len(self.ola)))
self.env = np.pad(self.env, (0, needed - len(self.env)))
w2 = self.iso.window * self.iso.window
for k in range(count):
at = start + k * self.hop
self.ola[at:at + self.n_fft] += frames[k]
self.env[at:at + self.n_fft] += w2
self.emitted = first + count
def _advance(self, limit: int) -> None:
while self.frames < limit:
count = min(self.block, limit - self.frames, self._next_cut() - self.frames)
spectra = self._analyze(self.frames, count)
self.raw.extend(self._run(spectra))
self.spectra.extend(spectra)
self.frames += count
count = self.frames - self.lookahead - self.emitted
if count > 0: # output frame t reads the decoder output of frame t + look-ahead
self._synthesize(self.emitted, count, range(self.emitted + self.lookahead,
self.emitted + self.lookahead + count))
self._trim()
def _trim(self) -> None:
drop = self.emitted - self.pending_base
self.raw, self.spectra = self.raw[drop:], self.spectra[drop:]
self.pending_base = self.emitted
keep_from = self.released - self.ola_base
if keep_from > 0:
self.ola, self.env = self.ola[keep_from:], self.env[keep_from:]
self.ola_base = self.released
needed_from = min(self.released, max(0, self.frames * self.hop - self.half))
if needed_from > self.audio_base:
self.audio = self.audio[needed_from - self.audio_base:]
self.audio_base = needed_from
def _release(self, upto: int) -> np.ndarray:
total = self.audio_base + len(self.audio)
start, stop = self.released, min(upto, total)
if stop <= start:
return np.zeros(0, np.float32)
off = self.half - self.ola_base
delta = self.ola[start + off:stop + off] / np.maximum(self.env[start + off:stop + off], 1e-11)
self.released = stop
return self.audio[start - self.audio_base:stop - self.audio_base] + delta
def push(self, samples: np.ndarray) -> np.ndarray:
"""Feeds new samples; returns the output samples that became final."""
if self.closed:
raise RuntimeError("the stream was flushed")
self.audio = np.concatenate([self.audio, np.asarray(samples, np.float32).reshape(-1)])
total = self.audio_base + len(self.audio)
self._advance(max(0, (total - self.half) // self.hop + 1))
out = self._release(self.emitted * self.hop - self.half)
self._trim()
return out
def flush(self) -> np.ndarray:
"""Ends the stream and returns every remaining output sample."""
if self.closed:
return np.zeros(0, np.float32)
self.closed = True
total = self.audio_base + len(self.audio)
self._advance(total // self.hop + 1)
last = self.frames - 1
while self.emitted < self.frames: # the last frames read the last computed frame
i = self.emitted
self._synthesize(i, 1, [min(i + self.lookahead, last)])
return self._release(total)