File size: 12,326 Bytes
a2b7d48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""FRCRN SE 16K in MLX: speech enhancement (denoising) at 16 kHz, a port of ClearerVoice-Studio's FRCRN
(clearvoice/models/frcrn_se: DCCRN-style complex UNet x2 with complex FSMN memories and SE layers on a 640-point
STFT). Parameter names are the original's; convolutions are channels-last.

    import mlx_model
    model = mlx_model.load("fp16")                 # a folder: config.json + model.safetensors
    clean = mlx_model.enhance(model, "noisy.wav")  # float32 numpy, 16 kHz (input resampled to 16 kHz)

Tensors are pairs (re, im) of [B, F, T, C] arrays (the original's [B, C, F, T, 2]). Everything computes in float32
(the 16-bit and quantized folders only store the weights smaller; load() upcasts them): in 16-bit the network drifts
far from the original. Like ClearerVoice, enhance() first normalizes the input's loudness (two RMS stages to
-25 dBFS) and scales the output back. Set MLX_ENABLE_TF32=0 for float32 matmuls (MLX uses TF32 otherwise).
"""
from __future__ import annotations

import json
from pathlib import Path

import mlx.core as mx
import mlx.nn as nn
import numpy as np
from mlx.utils import tree_unflatten

SAMPLE_RATE = 16000
ENC_K = [(5, 2)] * 6 + [(2, 2)]
DEC_K = [(2, 2), (5, 2), (5, 2), (5, 2), (6, 2), (5, 2), (5, 2)]
ENC_C = [1, 128, 128, 128, 128, 128, 128, 128]
DEC_C = [64, 128, 128, 128, 128, 128, 128, 1]
DEPTH = 7


def leaky(x):
    return mx.where(x >= 0, x, 0.01 * x)


class BN(nn.Module):
    def __init__(self, c):
        super().__init__()
        self.weight, self.bias = mx.ones((c,)), mx.zeros((c,))
        self.running_mean, self.running_var = mx.zeros((c,)), mx.ones((c,))

    def __call__(self, x):
        return (x - self.running_mean) * mx.rsqrt(self.running_var + 1e-5) * self.weight + self.bias


class CBN(nn.Module):
    def __init__(self, c):
        super().__init__()
        self.bn_re, self.bn_im = BN(c), BN(c)

    def __call__(self, z):
        return self.bn_re(z[0]), self.bn_im(z[1])


class CConv(nn.Module):
    def __init__(self, i, o, k, s=(1, 1), p=(0, 0)):
        super().__init__()
        self.conv_re = nn.Conv2d(i, o, k, stride=s, padding=p)
        self.conv_im = nn.Conv2d(i, o, k, stride=s, padding=p)

    def __call__(self, z):
        re, im = z
        return self.conv_re(re) - self.conv_im(im), self.conv_re(im) + self.conv_im(re)


class CConvT(nn.Module):
    def __init__(self, i, o, k, s, p):
        super().__init__()
        self.tconv_re = nn.ConvTranspose2d(i, o, k, stride=s, padding=p)
        self.tconv_im = nn.ConvTranspose2d(i, o, k, stride=s, padding=p)

    def __call__(self, z):
        re, im = z
        return self.tconv_re(re) - self.tconv_im(im), self.tconv_re(im) + self.tconv_im(re)


class Encoder(nn.Module):
    def __init__(self, i, o, k):
        super().__init__()
        self.conv, self.bn = CConv(i, o, k, (2, 1), (0, 1)), CBN(o)

    def __call__(self, z):
        return tuple(leaky(a) for a in self.bn(self.conv(z)))


class Decoder(nn.Module):
    def __init__(self, i, o, k):
        super().__init__()
        self.transconv, self.bn = CConvT(i, o, k, (2, 1), (0, 1)), CBN(o)

    def __call__(self, z):
        return tuple(leaky(a) for a in self.bn(self.transconv(z)))


class Fsmn(nn.Module):
    """UniDeepFsmn: x + project(relu(linear(x))) + causal depthwise memory (order 20) along the sequence axis."""

    def __init__(self, d=128, order=20):
        super().__init__()
        self.order = order
        self.linear = nn.Linear(d, d)
        self.project = nn.Linear(d, d, bias=False)
        self.conv1 = {"weight": mx.zeros((d, order, 1))}     # depthwise, [C, order, 1]

    def __call__(self, x):                                  # [N, L, C]
        p = self.project(nn.relu(self.linear(x)))
        y = mx.pad(p, [(0, 0), (self.order - 1, 0), (0, 0)])
        return x + p + mx.conv1d(y, self.conv1["weight"].astype(p.dtype), groups=p.shape[-1])


class CFsmnL1(nn.Module):
    """ComplexUniDeepFsmn_L1: memory along frequency, per frame."""

    def __init__(self):
        super().__init__()
        self.fsmn_re_L1, self.fsmn_im_L1 = Fsmn(), Fsmn()

    def __call__(self, z):
        B, F, T, C = z[0].shape
        re, im = (mx.transpose(a, (0, 2, 1, 3)).reshape(B * T, F, C) for a in z)
        r = self.fsmn_re_L1(re) - self.fsmn_im_L1(im)
        i = self.fsmn_re_L1(im) + self.fsmn_im_L1(re)
        return tuple(mx.transpose(a.reshape(B, T, F, C), (0, 2, 1, 3)) for a in (r, i))


class CFsmn(nn.Module):
    """ComplexUniDeepFsmn (the bottleneck): two complex layers, memory along time over C*F features."""

    def __init__(self):
        super().__init__()
        self.fsmn_re_L1, self.fsmn_im_L1 = Fsmn(), Fsmn()
        self.fsmn_re_L2, self.fsmn_im_L2 = Fsmn(), Fsmn()

    def __call__(self, z):
        B, F, T, C = z[0].shape
        re, im = (mx.transpose(a, (0, 2, 3, 1)).reshape(B, T, C * F) for a in z)
        r1 = self.fsmn_re_L1(re) - self.fsmn_im_L1(im)
        i1 = self.fsmn_re_L1(im) + self.fsmn_im_L1(re)
        r = self.fsmn_re_L2(r1) - self.fsmn_im_L2(i1)
        i = self.fsmn_re_L2(i1) + self.fsmn_im_L2(r1)
        return tuple(mx.transpose(a.reshape(B, T, C, F), (0, 3, 1, 2)) for a in (r, i))


class SE(nn.Module):
    def __init__(self, c=128, r=8):
        super().__init__()
        self.fc_r = [nn.Linear(c, c // r), nn.ReLU(), nn.Linear(c // r, c), nn.Sigmoid()]
        self.fc_i = [nn.Linear(c, c // r), nn.ReLU(), nn.Linear(c // r, c), nn.Sigmoid()]

    @staticmethod
    def _seq(layers, x):
        for l in layers:
            x = l(x)
        return x

    def __call__(self, z):
        re, im = z
        xr = mx.mean(re.astype(mx.float32), axis=(1, 2)).astype(re.dtype)
        xi = mx.mean(im.astype(mx.float32), axis=(1, 2)).astype(im.dtype)
        yr = self._seq(self.fc_r, xr) - self._seq(self.fc_i, xi)
        yi = self._seq(self.fc_r, xi) + self._seq(self.fc_i, xr)
        return re * yr[:, None, None, :], im * yi[:, None, None, :]


class UNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fsmn = CFsmn()
        for i in range(DEPTH):
            setattr(self, f"fsmn_enc{i}", CFsmnL1())
            setattr(self, f"encoder{i}", Encoder(ENC_C[i], ENC_C[i + 1], ENC_K[i]))
            setattr(self, f"se_layer_enc{i}", SE(ENC_C[i + 1]))
            setattr(self, f"fsmn_dec{i}", CFsmnL1())
            setattr(self, f"decoder{i}", Decoder(DEC_C[i] * 2, DEC_C[i + 1], DEC_K[i]))
            if i < DEPTH - 1:
                setattr(self, f"se_layer_dec{i}", SE(DEC_C[i + 1]))
        self.linear = CConv(DEC_C[-1], 1, (1, 1))

    def __call__(self, z):
        xs_se = [z]
        x = z
        for i in range(DEPTH):
            if i > 0:
                x = getattr(self, f"fsmn_enc{i}")(x)
            x = getattr(self, f"encoder{i}")(x)
            xs_se.append(getattr(self, f"se_layer_enc{i}")(x))
        p = self.fsmn(x)
        for i in range(DEPTH):
            p = getattr(self, f"decoder{i}")(p)
            if i < DEPTH - 1:
                p = getattr(self, f"fsmn_dec{i}")(p)
            if i == DEPTH - 1:
                break
            if i < DEPTH - 2:
                p = getattr(self, f"se_layer_dec{i}")(p)
            s = xs_se[DEPTH - 1 - i]
            p = tuple(mx.concatenate([a, b], axis=-1) for a, b in zip(p, s))
        return self.linear(p)


class FRCRN(nn.Module):
    def __init__(self, win_len=640, win_inc=320, fft_len=640):
        super().__init__()
        self.win_len, self.win_inc, self.dim = win_len, win_inc, fft_len // 2 + 1
        self.unet, self.unet2 = UNet(), UNet()
        self.stft = {"weight": mx.zeros((2 * self.dim, 1, win_len))}
        self.istft = {"weight": mx.zeros((2 * self.dim, 1, win_len)), "window": mx.zeros((1, win_len, 1))}

    def _frames(self, x):                                   # [L] -> [T, win]
        n = 1 + (x.shape[0] - self.win_len) // self.win_inc
        idx = mx.arange(n)[:, None] * self.win_inc + mx.arange(self.win_len)[None, :]
        return x[idx]

    def __call__(self, x: mx.array) -> mx.array:            # [L] float32 -> [L'] float32
        w = self.stft["weight"][:, 0, :].astype(mx.float32)
        spec = self._frames(x.astype(mx.float32)) @ w.T     # [T, 2D]
        re, im = spec[:, : self.dim].T, spec[:, self.dim:].T  # [D, T]
        z = (re[None, :, :, None], im[None, :, :, None])
        u1 = self.unet(z)
        m1 = tuple(mx.tanh(a) for a in u1)
        u2 = self.unet2(u1)
        mr, mi = (mx.tanh(a).astype(mx.float32) + b.astype(mx.float32) for a, b in zip(u2, m1))
        mr, mi = mr[0, :, :, 0], mi[0, :, :, 0]
        er, ei = re * mr - im * mi, re * mi + im * mr
        est = mx.concatenate([er, ei], axis=0).T            # [T, 2D]
        iw = self.istft["weight"][:, 0, :].astype(mx.float32)
        frames = est @ iw                                   # [T, win]
        win2 = self.istft["window"][0, :, 0].astype(mx.float32) ** 2
        T = frames.shape[0]
        L = (T - 1) * self.win_inc + self.win_len
        out = mx.zeros((L,)); coff = mx.zeros((L,))
        idx = mx.arange(T)[:, None] * self.win_inc + mx.arange(self.win_len)[None, :]
        out = out.at[idx.reshape(-1)].add(frames.reshape(-1))
        coff = coff.at[idx.reshape(-1)].add(mx.broadcast_to(win2, (T, self.win_len)).reshape(-1))
        return out / (coff + 1e-8)


def quantizable(path: str, module) -> bool:
    return isinstance(module, nn.Linear) and module.weight.shape[1] % 64 == 0


def load(folder) -> FRCRN:
    folder = Path(folder)
    conf = json.loads((folder / "config.json").read_text())
    model = FRCRN(conf.get("win_len", 640), conf.get("win_inc", 320), conf.get("fft_len", 640))
    q = conf.get("quantization")
    if q:
        nn.quantize(model, group_size=q["group_size"], bits=q["bits"], class_predicate=quantizable)
    w = mx.load(str(folder / "model.safetensors"))
    model.update(tree_unflatten([(k, v.astype(mx.float32) if mx.issubdtype(v.dtype, mx.floating) else v)
                                 for k, v in w.items()]))
    mx.eval(model.parameters())
    return model


def audio_norm(x: np.ndarray, eps: float = 1e-6):
    """ClearerVoice's dataloader.audio_norm: scale to -25 dBFS RMS, then again on the louder-than-average samples."""
    x = x.astype(np.float64)
    s1 = 10 ** (-25 / 20) / (np.sqrt((x ** 2).mean()) + eps)
    x = x * s1
    p = x ** 2
    s2 = 10 ** (-25 / 20) / (np.sqrt(p[p > p.mean()].mean()) + eps)
    return (x * s2).astype(np.float32), 1 / (s1 * s2 + eps)


def enhance(model: FRCRN, audio, sr: int | None = None, one_time_decode_length: float = 120.0,
            decode_window: float = 1.0, normalize: bool = True) -> np.ndarray:
    """Denoise `audio` (a path or a float waveform at `sr`); float32 at 16 kHz, the input's length. Pads and segments
    exactly as ClearerVoice's decode_one_audio_frcrn_se_16k (inputs over 120 s go through 1 s windows, 0.75 s
    stride)."""
    if isinstance(audio, (str, Path)):
        import soundfile as sf
        audio, sr = sf.read(str(audio), dtype="float32")
    audio = np.asarray(audio, dtype=np.float32)
    audio = audio.mean(1) if audio.ndim > 1 else audio
    if sr and sr != SAMPLE_RATE:
        import librosa
        audio = librosa.resample(audio, orig_sr=sr, target_sr=SAMPLE_RATE)
    scale = 1.0
    if normalize:
        audio, scale = audio_norm(audio)
    n = len(audio)
    window = int(SAMPLE_RATE * decode_window)
    stride = int(window * 0.75)
    x = audio
    if n < window:
        x = np.concatenate([x, np.zeros(window - n, np.float32)])
    elif n < window + stride:
        x = np.concatenate([x, np.zeros(window + stride - n, np.float32)])
    elif (n - window) % stride:
        x = np.concatenate([x, np.zeros(n - (n - window) // stride * stride, np.float32)])
    if n <= SAMPLE_RATE * one_time_decode_length:
        y = np.array(model(mx.array(x)))
    else:
        y = np.zeros(len(x), np.float32)
        give = (window - stride) // 2
        i = 0
        while i + window <= len(x):
            seg = np.array(model(mx.array(x[i:i + window])))
            if i == 0:
                y[:window - give] = seg[:window - give]
            else:
                y[i + give:i + window - give] = seg[give:window - give]
            i += stride
    return (np.pad(y, (0, max(0, n - len(y))))[:n] * scale).astype(np.float32)