Audio-to-Audio
MLX
Safetensors
moonbox
inworld
voice-isolation
speech-enhancement
denoising
noise-suppression
48khz
full-band
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.
Instructions to use moonbox-dev/voice-isolator-MLX with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use moonbox-dev/voice-isolator-MLX with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download moonbox-dev/voice-isolator-MLX --local-dir voice-isolator-MLX
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
8bit build of Inworld Voice Isolator
Browse filesFiles changed (3)
- 8bit/config.jsonAdded+795
- 8bit/mlx_model.pyAdded+481
- 8bit/model.safetensorsAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795{ "band_plan": [ [ 100, 1000 ], [ 250, 4000 ], [ 500, 8000 ], [ 1000, 16000 ], [ 2000, 24000 ] ], "block_types": [ "transformer", "mamba", "transformer", "mamba", "transformer", "mamba", "transformer" ], "causal": false, "chunk_seconds": 8.0, "correction_bound": 0.5, "dual_mode": false, "exclusive_axes": "time", "exclusive_self_attention": true, "hop_length": 480, "lookahead_frames": 0, "lookahead_frames_choices": [], "mamba_conv": 4, "mamba_expand": 2, "mamba_state": 16, "mode_film": false, "n_fft": 2048, "num_heads": 8, "overlap_seconds": 2.0, "sample_rate": 48000, "width": 512, "model_type": "inworld_voice_isolator", "precision": "8bit", "source": { "repository": "inworld/voice-isolator", "revision": "9b0285b3fe8403aa8e2f1dbb2165a80a4294c970", "file": "denoiser.safetensors", "code": "github.com/inworld-ai/voice-isolator @c73b3fa" }, "compute": "bfloat16", "quantization": { "bits": 8, "mode": "affine", "group_size": 64, "note": "group size 32 where a layer's input width is not a multiple of 64; `layers` gives each quantized layer's own group size and bits", "kept": null, "layers": { "denoise_decoder.heads.45.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.45.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.44.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.44.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.43.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.43.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.42.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.42.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.41.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.41.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.40.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.40.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.39.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.39.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.38.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.38.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.37.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.37.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.36.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.36.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.35.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.35.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.34.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.34.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.33.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.33.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.32.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.32.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.31.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.31.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.30.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.30.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.29.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.29.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.28.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.28.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.27.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.27.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.26.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.26.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.25.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.25.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.24.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.24.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.23.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.23.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.22.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.22.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.21.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.21.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.20.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.20.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.19.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.19.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.18.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.18.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.17.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.17.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.16.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.16.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.15.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.15.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.14.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.14.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.13.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.13.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.12.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.12.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.11.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.11.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.10.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.10.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.9.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.9.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.8.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.8.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.7.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.7.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.6.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.6.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.5.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.5.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.4.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.4.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.3.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.3.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.2.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.2.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.1.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.1.1": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.0.3": { "group_size": 64, "bits": 8 }, "denoise_decoder.heads.0.1": { "group_size": 64, "bits": 8 }, "blocks.6.band_transformer.linear2": { "group_size": 64, "bits": 8 }, "blocks.6.band_transformer.linear1": { "group_size": 64, "bits": 8 }, "blocks.6.band_transformer.self_attn.out_proj": { "group_size": 64, "bits": 8 }, "blocks.6.band_transformer.self_attn.in_proj": { "group_size": 64, "bits": 8 }, "blocks.6.time_transformer.ffn.3": { "group_size": 64, "bits": 8 }, "blocks.6.time_transformer.ffn.0": { "group_size": 64, "bits": 8 }, "blocks.6.time_transformer.attn.proj": { "group_size": 64, "bits": 8 }, "blocks.6.time_transformer.attn.qkv": { "group_size": 64, "bits": 8 }, "blocks.5.freq_mamba.output_proj": { "group_size": 64, "bits": 8 }, "blocks.5.freq_mamba.backward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.5.freq_mamba.backward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.5.freq_mamba.backward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.5.freq_mamba.forward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.5.freq_mamba.forward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.5.freq_mamba.forward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.5.time_mamba.output_proj": { "group_size": 64, "bits": 8 }, "blocks.5.time_mamba.backward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.5.time_mamba.backward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.5.time_mamba.backward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.5.time_mamba.forward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.5.time_mamba.forward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.5.time_mamba.forward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.4.band_transformer.linear2": { "group_size": 64, "bits": 8 }, "blocks.4.band_transformer.linear1": { "group_size": 64, "bits": 8 }, "blocks.4.band_transformer.self_attn.out_proj": { "group_size": 64, "bits": 8 }, "blocks.4.band_transformer.self_attn.in_proj": { "group_size": 64, "bits": 8 }, "blocks.4.time_transformer.ffn.3": { "group_size": 64, "bits": 8 }, "blocks.4.time_transformer.ffn.0": { "group_size": 64, "bits": 8 }, "blocks.4.time_transformer.attn.proj": { "group_size": 64, "bits": 8 }, "blocks.4.time_transformer.attn.qkv": { "group_size": 64, "bits": 8 }, "blocks.3.freq_mamba.output_proj": { "group_size": 64, "bits": 8 }, "blocks.3.freq_mamba.backward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.3.freq_mamba.backward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.3.freq_mamba.backward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.3.freq_mamba.forward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.3.freq_mamba.forward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.3.freq_mamba.forward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.3.time_mamba.output_proj": { "group_size": 64, "bits": 8 }, "blocks.3.time_mamba.backward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.3.time_mamba.backward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.3.time_mamba.backward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.3.time_mamba.forward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.3.time_mamba.forward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.3.time_mamba.forward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.2.band_transformer.linear2": { "group_size": 64, "bits": 8 }, "blocks.2.band_transformer.linear1": { "group_size": 64, "bits": 8 }, "blocks.2.band_transformer.self_attn.out_proj": { "group_size": 64, "bits": 8 }, "blocks.2.band_transformer.self_attn.in_proj": { "group_size": 64, "bits": 8 }, "blocks.2.time_transformer.ffn.3": { "group_size": 64, "bits": 8 }, "blocks.2.time_transformer.ffn.0": { "group_size": 64, "bits": 8 }, "blocks.2.time_transformer.attn.proj": { "group_size": 64, "bits": 8 }, "blocks.2.time_transformer.attn.qkv": { "group_size": 64, "bits": 8 }, "blocks.1.freq_mamba.output_proj": { "group_size": 64, "bits": 8 }, "blocks.1.freq_mamba.backward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.1.freq_mamba.backward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.1.freq_mamba.backward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.1.freq_mamba.forward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.1.freq_mamba.forward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.1.freq_mamba.forward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.1.time_mamba.output_proj": { "group_size": 64, "bits": 8 }, "blocks.1.time_mamba.backward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.1.time_mamba.backward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.1.time_mamba.backward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.1.time_mamba.forward_blocks.out_proj": { "group_size": 64, "bits": 8 }, "blocks.1.time_mamba.forward_blocks.x_proj": { "group_size": 64, "bits": 8 }, "blocks.1.time_mamba.forward_blocks.in_proj": { "group_size": 64, "bits": 8 }, "blocks.0.band_transformer.linear2": { "group_size": 64, "bits": 8 }, "blocks.0.band_transformer.linear1": { "group_size": 64, "bits": 8 }, "blocks.0.band_transformer.self_attn.out_proj": { "group_size": 64, "bits": 8 }, "blocks.0.band_transformer.self_attn.in_proj": { "group_size": 64, "bits": 8 }, "blocks.0.time_transformer.ffn.3": { "group_size": 64, "bits": 8 }, "blocks.0.time_transformer.ffn.0": { "group_size": 64, "bits": 8 }, "blocks.0.time_transformer.attn.proj": { "group_size": 64, "bits": 8 }, "blocks.0.time_transformer.attn.qkv": { "group_size": 64, "bits": 8 } }, "float_layers": [ "blocks.1.freq_mamba.backward_blocks.dt_proj", "blocks.1.freq_mamba.forward_blocks.dt_proj", "blocks.1.time_mamba.backward_blocks.dt_proj", "blocks.1.time_mamba.forward_blocks.dt_proj", "blocks.3.freq_mamba.backward_blocks.dt_proj", "blocks.3.freq_mamba.forward_blocks.dt_proj", "blocks.3.time_mamba.backward_blocks.dt_proj", "blocks.3.time_mamba.forward_blocks.dt_proj", "blocks.5.freq_mamba.backward_blocks.dt_proj", "blocks.5.freq_mamba.forward_blocks.dt_proj", "blocks.5.time_mamba.backward_blocks.dt_proj", "blocks.5.time_mamba.forward_blocks.dt_proj", "denoise_decoder.condition", "encoders.0.1", "encoders.1.1", "encoders.10.1", "encoders.11.1", "encoders.12.1", "encoders.13.1", "encoders.14.1", "encoders.15.1", "encoders.16.1", "encoders.17.1", "encoders.18.1", "encoders.19.1", "encoders.2.1", "encoders.20.1", "encoders.21.1", "encoders.22.1", "encoders.23.1", "encoders.24.1", "encoders.25.1", "encoders.26.1", "encoders.27.1", "encoders.28.1", "encoders.29.1", "encoders.3.1", "encoders.30.1", "encoders.31.1", "encoders.32.1", "encoders.33.1", "encoders.34.1", "encoders.35.1", "encoders.36.1", "encoders.37.1", "encoders.38.1", "encoders.39.1", "encoders.4.1", "encoders.40.1", "encoders.41.1", "encoders.42.1", "encoders.43.1", "encoders.44.1", "encoders.45.1", "encoders.5.1", "encoders.6.1", "encoders.7.1", "encoders.8.1", "encoders.9.1" ], "quantized_parameters": 62130176 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481"""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 samearithmetic 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, theexclusive-attention projection, the depthwise convolution, softplus, the scan and the complex correction are float32whatever the build, and so is the residual stream. `compute` in config.json is the dtype of the matrix products andattention: "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 inthe 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 jsonimport mathimport osfrom 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: E402import mlx.nn as nn # noqa: E402import 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.compiledef _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.compiledef _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)123version https://git-lfs.github.com/spec/v1oid sha256:4deeb8f096121bb32f5cb5cd0aa1b9664c24940f7724b8d9169adf6789020b80size 706884028bit/config.jsonAdded+795
8bit/mlx_model.pyAdded+481
8bit/model.safetensorsAdded+3