Publish validated pretrained RNNoise float32 Core AI assets
Browse filesFiles changed (29)
- .gitattributes+2
- LICENSEAdded+32
- README.mdAdded+104
- SHA256SUMSAdded+27
- THIRD_PARTY_NOTICES.mdAdded+11
- convert.pyAdded+167
- docs/rnnoise10Ga_12_float32_validation.jsonAdded+16
- docs/rnnoise10Gb_15_float32_validation.jsonAdded+16
- enhance.pyAdded+61
- exports/rnnoise10Ga_12_float32_streaming.aimodel/main.hashAdded
- exports/rnnoise10Ga_12_float32_streaming.aimodel/main.mlirbAdded+3
- exports/rnnoise10Ga_12_float32_streaming.aimodel/metadata.jsonAdded+8
- exports/rnnoise10Gb_15_float32_streaming.aimodel/main.hashAdded+1
- exports/rnnoise10Gb_15_float32_streaming.aimodel/main.mlirbAdded+3
- exports/rnnoise10Gb_15_float32_streaming.aimodel/metadata.jsonAdded+8
- models.pyAdded+92
- provenance.jsonAdded+28
- pyproject.tomlAdded+7
- uv.lockAdded
- vendor/rnnoise/LICENSEAdded+32
- vendor/rnnoise/rnnoise.pyAdded+109
- vendor/rnnoise/sparsification/__init__.pyAdded+2
- vendor/rnnoise/sparsification/common.pyAdded+121
- vendor/rnnoise/sparsification/gru_sparsifier.pyAdded+187
- vendor/ulunas/LICENSEAdded+21
- vendor/ulunas/stream.pyAdded+280
- vendor/ulunas/ulunas.pyAdded+561
- weights/rnnoise10Ga_12.pthAdded+3
- weights/rnnoise10Gb_15.pthAdded+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexports/rnnoise10Ga_12_float32_streaming.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -textexports/rnnoise10Gb_15_float32_streaming.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132Copyright (c) 2007-2017, 2024 Jean-Marc ValinCopyright (c) 2023 AmazonCopyright (c) 2017, MozillaCopyright (c) 2005-2017, Xiph.Org FoundationCopyright (c) 2003-2004, Mark Borgerding
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditionsare met:
- Redistributions of source code must retain the above copyrightnotice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyrightnotice, this list of conditions and the following disclaimer in thedocumentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.Org Foundation nor the names of itscontributors may be used to endorse or promote products derived fromthis software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATIONOR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOTLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104---license: bsd-3-clausepipeline_tag: audio-to-audiotags:- coreai- aimodel- speech-enhancement- streaming- apple-silicon---
# rnnoise-coreai
Pretrained float32 Core AI assets for RNNoise (10Ga and 10Gb). CPU parity validated on macOS 27.0.1.
This Hub repository includes the named model assets and original checkpoint(s). Clone [the complete source project](https://github.com/maxffarrell/speech-enhancement-coreai) for all model variants and the full documented workflow. Model-specific licenses are in LICENSE and vendor; new conversion code is MIT as recorded in the source project.
# Speech enhancement models for Apple Core AI
Pretrained **RNNoise** and **UL-UNAS** streaming neural networks exported as self-contained `.aimodel` directories. Conversion and validation by Max Farrell; original models and weights by the upstream authors linked below. This is an independent community conversion project.
| Model | Checkpoint | Asset | License || --- | --- | --- | --- || RNNoise | official `rnnoise10Ga_12.pth` | `exports/rnnoise10Ga_12_float32_streaming.aimodel` | upstream BSD-style notices || RNNoise | official `rnnoise10Gb_15.pth` | `exports/rnnoise10Gb_15_float32_streaming.aimodel` | upstream BSD-style notices || UL-UNAS | DNS3 `model_trained_on_dns3.tar` | `exports/ulunas_dns3_float32_streaming.aimodel` | MIT |
Download complete model directories from this repository, the [GitHub release](https://github.com/maxffarrell/speech-enhancement-coreai/releases/tag/v0.1.0), or the dedicated model repositories on Hugging Face: [RNNoise Core AI](https://huggingface.co/maxffarrell/rnnoise-coreai) and [UL-UNAS Core AI](https://huggingface.co/maxffarrell/ul-unas-coreai). Integrity hashes are in `SHA256SUMS`; upstream revisions and checkpoint hashes are in `provenance.json`.
## Reproduce
An Apple Silicon Mac with the Core AI runtime is required to run parity checks. Validated on macOS 27.0.1 (26A434), with CPU specialization. Export uses PyTorch 2.11.0, coreai-torch 0.4.3 and coreai-core 1.0.0b3. GPU, Neural Engine, iOS, and earlier OS releases have **not** been validated. No accelerator latency or energy-efficiency claim is made.
```shgit clone https://github.com/maxffarrell/speech-enhancement-coreai.gitcd speech-enhancement-coreaiuv sync --frozen# Check the published assets:uv run python convert.py rnnoise10Ga_12 --validate-onlyuv run python convert.py rnnoise10Gb_15 --validate-onlyuv run python convert.py ulunas_dns3 --validate-only# Optional real-audio check, using your own 16 kHz mono file:uv run python convert.py ulunas_dns3 --validate-only --wav noisy.wav# To regenerate, move the matching exports/*.aimodel directory elsewhere first:uv run python convert.py ulunas_dns3 --dtype float32```
The exporter refuses to overwrite existing assets. It loads checkpoint dictionaries using `weights_only=True` and strict state-dict matching, exports with `torch.export.export`, runs Apple's decomposition table, then saves the Core AI AIProgram with provenance/license metadata. No retraining, checkpoint edits, quantization, or third-party Metal kernels are involved.
## UL-UNAS audio integration
[Upstream code, checkpoints and paper](https://github.com/Xiaobin-Rong/ul-unas). The checkpoint is trained on DNS3. The upstream frame-streaming implementation is used, with input caches cloned at the export boundary to preserve functional state semantics.
Audio is **16 kHz mono**, with a 512-point periodic Hann-window STFT, 256-sample hop (16 ms), centered reflect padding as in upstream PyTorch, and matching inverse STFT. The exported graph accepts one real/imaginary STFT frame, rather than raw audio.
| Input | float32 shape | Output || --- | --- | --- || `mix` | `[1,257,1,2]` | `enh` (same shape) || `conv_cache` | `[1,5358]` | `conv_cache_out` || `tfa_cache` | `[1,402]` | `tfa_cache_out` || `inter_cache` | `[1,1056]` | `inter_cache_out` |
Initialize caches to zero per stream. Feed each returned cache into the matching input for the next frame. Reset all caches when starting a new stream. Centered STFT requires buffering; the 16 ms hop is not a claim of zero-lookahead end-to-end latency.
```shuv run python enhance.py noisy.wav enhanced.wav```
This complete WAV example runs the neural network in Core AI on CPU; PyTorch is used only for STFT/ISTFT. It preserves upstream handling of the trailing audio samples. It does not resample or downmix automatically.
## RNNoise integration
[Upstream RNNoise](https://github.com/xiph/rnnoise) ([canonical repository](https://gitlab.xiph.org/xiph/rnnoise)). Both checkpoints come from the exact official model archive in `provenance.json`; its SHA-256 matches upstream `model_version`. They use the current 65-feature, 32-gain architecture, with 128 convolution conditioning channels and 384 recurrent units. No claim is made that either checkpoint exactly matches upstream's quantized default C model.
RNNoise operates on **48 kHz mono**, 480-sample (10 ms) audio frames. Its native DSP produces **65 normalized features**. The Core AI graph converts these to **32 band gains** and a voice-activity score. Native pitch analysis/filtering, feature extraction, gain smoothing/application, and waveform synthesis remain external. This asset alone does not accept PCM or generate cleaned audio. Preserve upstream feature conventions and DSP when integrating; do not pass raw PCM, GTCRN features, or arbitrary STFT bins as `features`.
| Input | float32 shape | Output || --- | --- | --- || `features` | `[1,1,65]` | `gains` `[1,1,32]`, `vad` `[1,1,1]` || `conv1_cache` | `[1,65,2]` | `conv1_cache_out` || `conv2_cache` | `[1,128,2]` | `conv2_cache_out` || `gru1_state` | `[1,1,384]` | `gru1_state_out` || `gru2_state` | `[1,1,384]` | `gru2_state_out` || `gru3_state` | `[1,1,384]` | `gru3_state_out` |
Initialize all five states to zero and carry all outputs forward on every frame. The convolution caches make the valid-convolution training graph causal for frame-wise inference. Cold-start caches match the native streaming convention. The source check compares against upstream PyTorch sliding five-frame windows after the four-frame warmup, with identical incoming GRU states.
## Validation and limits
Every output is compared over 32 consecutive frames with independent PyTorch and Core AI state trajectories, including convolution caches and GRU states. Reports are in `docs/`.
- RNNoise 10Ga float32: minimum 104.44 dB across all outputs; source graph agreement 119.08 dB.- RNNoise 10Gb float32: minimum 108.11 dB; source graph agreement 115.74 dB.- UL-UNAS float32 on upstream real-audio frames: minimum 127.83 dB; streaming versus upstream offline spectral graph 160.58 dB. A separate deterministic synthetic-input report is also included.- Full 10-second UL-UNAS WAV example versus upstream waveform output: 144.11 dB PSNR, 160,000 output samples, all finite.- RNNoise float16 was rejected: VAD minimum PSNR was 35.13 dB, below the 40 dB gate. UL-UNAS upstream float16 export hits a recurrent input/weight dtype mismatch. Only validated float32 assets are distributed.
These are conversion-parity checks, not speech-quality benchmark scores. RNNoise testing uses synthetic normalized-feature-shaped inputs and does not establish parity with native quantized C/DSP, end-to-end audio quality, or latency. UL-UNAS real-audio testing uses the upstream `audio/noisy/0174.wav` sample locally; that recording is not redistributed. A conversion can reproduce upstream outputs without establishing quality on your microphone or noise environment.
## Licensing and attribution
New conversion/example code: [MIT](LICENSE). UL-UNAS source and weights retain [upstream MIT](vendor/ulunas/LICENSE). RNNoise source and weights retain [upstream BSD-style license](vendor/rnnoise/LICENSE) and individual source-file notices. The root license does not replace those terms. See [third-party notices](THIRD_PARTY_NOTICES.md) for authors, exact revisions, modifications, and citations. Model weights use the upstream repository licenses; no separate checkpoint-specific license was supplied upstream.
Related: [GTCRN Core AI](https://github.com/maxffarrell/gtcrn-coreai), including DNS3 and VCTK streaming assets. GTCRN is maintained separately and is not redistributed by this project.12345678910111213141516171819202122232425262745d37ca1cdb278c088e1aa85e0e65ca3a534ed86a28dcc96ca16810248a61d35 LICENSE8a7085bdff985e0648f88b39dc2d17173b3cb83c976a3c19f9a9d357b95f1bf2 README.md693e13c1d65219a71c9a999d284b33266d0edd22eb040ad90be8b743d8d12cd9 THIRD_PARTY_NOTICES.md31181ae43bbbe2fdfd9127cf51b822861f9c6b3511314473c807cbf150bf89b4 convert.py9f59eb702aaff1426c66040b296907ab46aa3a8c2ff22773997a800453557158 docs/rnnoise10Ga_12_float32_validation.jsonc9b863e5afa1485b63762c6bad630e7ebc4f1575379e5dbbebb3495210876691 docs/rnnoise10Gb_15_float32_validation.json3a8e5874334ce8bb3b29d3e3bec1fa0e0ae493d2140af340766066cab01c52ae enhance.py8ed447656dd434a4c1f75e79e692e4a9c2b12deaef34fcfccd13233f38f6b89f exports/rnnoise10Ga_12_float32_streaming.aimodel/main.hash7d86836c3e86a7ef4260b58643a0e3c5d52d554baaa38f9e0098fb5c35736732 exports/rnnoise10Ga_12_float32_streaming.aimodel/main.mlirb9c2b703cec50ee3c1e704d05da54d8b1628c2d3bd4864d0f008b1bcb8a29ec98 exports/rnnoise10Ga_12_float32_streaming.aimodel/metadata.jsonc9d498085204336da2df613bd160f53caefda17b2e56c3781a2b61931a5c170c exports/rnnoise10Gb_15_float32_streaming.aimodel/main.hashd908dff07992686a72bb4b910212217e271151e2b5b37a69a9da1f14d26f2cbd exports/rnnoise10Gb_15_float32_streaming.aimodel/main.mlirb336fb91ef9661b5c6f669710d4ec2677aeec67e3a0309cebc5b40bdfbc9a899b exports/rnnoise10Gb_15_float32_streaming.aimodel/metadata.json710a0fca670e89b7e25194d963fd36c0fb07a6754b8058162ca22793dc91d86c models.pybf75018bc383bb72de518954055b8079d1a4bbad80bbb0184007423e02fc6228 provenance.json34a71fbdbfb8cd6363e2bd51f9fa2bfbebc33778439f936faee6551b895db7e8 pyproject.toml9e4705acee0103ab11bcfb2af4a740c7ce6fa5c2eec71c9664356d9e70473e0c uv.lock45d37ca1cdb278c088e1aa85e0e65ca3a534ed86a28dcc96ca16810248a61d35 vendor/rnnoise/LICENSE9cc8a07df55f6e4afd5fe5346eb2a776f152cbb22b966ee590a9e980ba213f52 vendor/rnnoise/rnnoise.pyed4ae70623fa9df13b1d60ae5c160790fb5d3c1bf429f4b0b1b74cccf64392e3 vendor/rnnoise/sparsification/__init__.pyc7b7c4ea807e5fd99a972167410fb35c1062703024d9f737619902f402055c5b vendor/rnnoise/sparsification/common.py6e78371d3c2327bf76f570ae6c5c51005ad1166e79def18ee975e0241926d2d4 vendor/rnnoise/sparsification/gru_sparsifier.py94daad6ad643a2f79d4a111015c3415fe20c6f630b908e884edf466923724184 vendor/ulunas/LICENSE0328ec624ea01f8732d47da8124c87f3d0ba292fd34b780d93899f4a2d3807fb vendor/ulunas/stream.pye53f7550d9698cb0aee0fc517b3f4caeb679d9e3f4c00fa47a0f3a975c228adf vendor/ulunas/ulunas.py1f495605b553ce1f64643e3732249ede58a72c062f42c53e9f929bbd1b1ff31c weights/rnnoise10Ga_12.pthff1f6b2a63dcf3b74eff95a77d4deb1b75e26a3a7fa6e4921210086313f412ba weights/rnnoise10Gb_15.pth1234567891011# Third-party notices
The root MIT license covers new conversion and validation code only.
- UL-UNAS implementation, streaming implementation, and DNS3 checkpoint: Xiaobin Rong and contributors, https://github.com/Xiaobin-Rong/ul-unas, revision `00f7c700da43d38347f30a6ccebd86fcbc798e07`. Repository MIT license reproduced at `vendor/ulunas/LICENSE`. Streaming implementation is credited upstream to Kailai Shen. `stream.py` is extracted before the demo block; unused ONNX imports were removed. The functional adapter clones input caches; architecture and pretrained weights are retained.- RNNoise implementation, sparsification helpers, and official pretrained checkpoints: Jean-Marc Valin and RNNoise contributors, https://github.com/xiph/rnnoise, revision `70f1d256acd4b34a572f999a05c87bf00b67730d`. Repository BSD-3-Clause-style COPYING reproduced at `vendor/rnnoise/LICENSE`; individual files also carry BSD-style notices, retained verbatim. Checkpoints came from the exact official archive identified by upstream `model_version` and `download_model.sh`; its SHA-256 was verified. No training or dataset redistribution is performed.- Converted weights retain their respective upstream license and attribution. Exporting does not create a new license for pretrained parameters. Upstream repositories do not supply separate checkpoint license files; distribution follows their repository licenses, with all corresponding notices included.- Apple's Core AI libraries are dependencies, not redistributed here; their own license and platform terms apply.
UL-UNAS paper: Rong et al., “UL-UNAS: Ultra-Lightweight U-Nets for Real-Time Speech Enhancement via Network Architecture Search,” IEEE TASLP 34, 1085–1096 (2026), https://doi.org/10.1109/TASLPRO.2026.3661271.RNNoise: Jean-Marc Valin, “A Hybrid DSP/Deep Learning Approach to Real-Time Full-Band Speech Enhancement,” https://arxiv.org/abs/1709.08243. These checkpoints use the current architecture; they are not the original 2017 network.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167"""Reproduce Core AI export and validate every output over independent state trajectories."""
import argparseimport asyncioimport jsonimport osfrom pathlib import Path
import numpy as npimport torch
os.environ.setdefault("USE_OS_COREAI", "1")from coreai.runtime import AIModel, AIModelAssetMetadata, NDArray, SpecializationOptionsfrom coreai_torch import TorchConverter, get_decomp_tablefrom models import ROOT, load_model
def psnr(ref, actual): a, b = np.asarray(ref, dtype=np.float64), np.asarray(actual, dtype=np.float64) mse = np.mean((a - b) ** 2) if mse == 0: return 300.0 return float(10 * np.log10(max(np.max(np.abs(a)), 1e-12) ** 2 / mse))
def export(variant, dtype): model, args, ins, outs, _checkpoint, _ = load_model(variant, dtype) ep = torch.export.export(model, args=args, strict=False).run_decompositions( get_decomp_table() ) program = ( TorchConverter() .add_exported_program(ep, input_names=ins, output_names=outs) .to_coreai() ) path = ROOT / "exports" / f"{variant}_{str(dtype).split('.')[-1]}_streaming.aimodel" if path.exists(): raise FileExistsError(path) meta = AIModelAssetMetadata() meta.author = ( "Xiaobin Rong and contributors" if variant == "ulunas_dns3" else "Jean-Marc Valin and RNNoise contributors" ) meta.license = ( "MIT" if variant == "ulunas_dns3" else "BSD-3-Clause; see vendor/rnnoise/LICENSE and source-file notices" ) meta.model_description = f"{variant} pretrained streaming neural network; Core AI conversion by Max Farrell. Audio DSP is external. See README and provenance.json." program.save_asset(path, meta) return path
async def validate(variant, dtype, path, count=32, wav=None): model, args, ins, outs, _, source = load_model(variant, dtype) runtime = await AIModel.load(path, SpecializationOptions.cpu_only()) fn = runtime.load_function("main") assert list(fn.desc.input_names) == ins assert list(fn.desc.output_names) == outs ts, cs = args[1:], args[1:] gen = torch.Generator().manual_seed(1234) frames = torch.randn( (1, 257, count, 2) if variant == "ulunas_dns3" else (1, count, 65), generator=gen, ).to(dtype) if variant == "ulunas_dns3": import soundfile as sf
if wav: audio, sr = sf.read(wav, dtype="float32") else: sr = 16000 t = np.arange(16000, dtype=np.float32) / sr audio = ( 0.15 * np.sin(2 * np.pi * 180 * t) + 0.05 * np.random.default_rng(1234).standard_normal(16000) ).astype(np.float32) assert sr == 16000 and audio.ndim == 1 z = torch.stft( torch.tensor(audio)[None], 512, 256, 512, torch.hann_window(512), return_complex=True, ) frames = torch.view_as_real(z)[:, :, :count].to(dtype) with torch.no_grad(): spec = frames.permute(0, 3, 2, 1) feat = source.erb.bm( torch.log10(torch.norm(spec, dim=1, keepdim=True).clamp(1e-12)) ) feat, skips = source.encoder(feat) mask = source.erb.bs(source.decoder(source.dpgrnn(feat), skips)) offline = (spec * mask).permute(0, 3, 2, 1) scores = {name: [] for name in outs} streaming = [] ref_scores = [] with torch.no_grad(): for i in range(count): x = ( frames[:, :, i : i + 1, :] if variant == "ulunas_dns3" else frames[:, i : i + 1, :] ) pre_state = ts ref = model(x, *ts) runtime_out = await fn( { name: NDArray(data=t.contiguous()) for name, t in zip(ins, (x, *cs), strict=True) } ) values = [runtime_out[name].numpy() for name in outs] ts = tuple(t.detach() for t in ref[-len(ts) :]) cs = tuple(torch.from_numpy(t.copy()) for t in values[-len(cs) :]) for name, r, v in zip(outs, ref, values, strict=True): assert np.isfinite(v).all(), name scores[name].append(psnr(r.numpy(), v)) if variant == "ulunas_dns3": streaming.append(ref[0]) elif i >= 4: direct = source(frames[:, i - 4 : i + 1, :], list(pre_state[2:])) ref_scores.append( min( psnr(direct[0].numpy(), ref[0].numpy()), psnr(direct[1].numpy(), ref[1].numpy()), ) ) if streaming: ref_scores = [psnr(offline.numpy(), torch.cat(streaming, dim=2).numpy())] result = { "variant": variant, "precision": str(dtype), "device": "CPU", "frames": count, "input_fixture": str(wav) if wav else "deterministic synthetic input", "minimum_psnr_db": {k: min(v) for k, v in scores.items()}, "source_graph_psnr_db": min(ref_scores), } print(json.dumps(result, indent=2)) assert min(ref_scores) >= 70, "Streaming wrapper differs from upstream graph" assert min(min(v) for v in scores.values()) >= 40, "Core AI parity failed" ( ROOT / "docs" / f"{variant}_{str(dtype).split('.')[-1]}_validation.json" ).write_text(json.dumps(result, indent=2) + "\n")
if __name__ == "__main__": p = argparse.ArgumentParser(description=__doc__) p.add_argument( "variant", choices=["ulunas_dns3", "rnnoise10Ga_12", "rnnoise10Gb_15"] ) p.add_argument("--dtype", choices=["float16", "float32"], default="float32") p.add_argument("--validate-only", action="store_true") p.add_argument( "--wav", type=Path, help="Optional 16 kHz mono WAV for UL-UNAS parity" ) a = p.parse_args() dtype = getattr(torch, a.dtype) path = ( ROOT / "exports" / f"{a.variant}_{a.dtype}_streaming.aimodel" if a.validate_only else export(a.variant, dtype) ) asyncio.run(validate(a.variant, dtype, path, wav=a.wav))12345678910111213141516{ "variant": "rnnoise10Ga_12", "precision": "torch.float32", "device": "CPU", "frames": 32, "minimum_psnr_db": { "gains": 119.10070676150029, "vad": 104.44268920843534, "conv1_cache_out": 300.0, "conv2_cache_out": 137.32548370006597, "gru1_state_out": 128.28476630705796, "gru2_state_out": 126.78875604393187, "gru3_state_out": 126.94951284008144 }, "source_graph_psnr_db": 119.08488718416358}12345678910111213141516{ "variant": "rnnoise10Gb_15", "precision": "torch.float32", "device": "CPU", "frames": 32, "minimum_psnr_db": { "gains": 119.31544934170611, "vad": 108.10847246728939, "conv1_cache_out": 300.0, "conv2_cache_out": 136.9386904353855, "gru1_state_out": 130.72275286716928, "gru2_state_out": 129.75496730030014, "gru3_state_out": 129.36344555317814 }, "source_graph_psnr_db": 115.73556538082136}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Enhance 16 kHz mono audio with the exported UL-UNAS neural network."""
import argparseimport asyncioimport osfrom pathlib import Path
import numpy as npimport soundfile as sfimport torch
os.environ.setdefault("USE_OS_COREAI", "1")from coreai.runtime import AIModel, NDArray, SpecializationOptions
async def enhance(asset, infile, outfile): audio, sr = sf.read(infile, dtype="float32") if sr != 16000 or audio.ndim != 1: raise ValueError("Expected 16 kHz mono WAV") window = torch.hann_window(512) spec = torch.view_as_real( torch.stft( torch.tensor(audio)[None], 512, 256, 512, window, return_complex=True ) ) model = await AIModel.load(asset, SpecializationOptions.cpu_only()) fn = model.load_function("main") state = { "conv_cache": np.zeros((1, 5358), np.float32), "tfa_cache": np.zeros((1, 402), np.float32), "inter_cache": np.zeros((1, 1056), np.float32), } frames = [] for i in range(spec.shape[2]): output = await fn( { "mix": NDArray(data=spec[:, :, i : i + 1].contiguous()), **{k: NDArray(data=v) for k, v in state.items()}, } ) frames.append(output["enh"].numpy().copy()) state = {k: output[k + "_out"].numpy().copy() for k in state} enhanced = torch.view_as_complex( torch.from_numpy(np.concatenate(frames, axis=2)).contiguous() ) wav = torch.istft(enhanced, 512, 256, 512, window).numpy()[0] wav = np.pad(wav, (0, len(audio) - len(wav))) sf.write(outfile, wav, 16000, subtype="FLOAT")
if __name__ == "__main__": p = argparse.ArgumentParser(description=__doc__) p.add_argument("input", type=Path) p.add_argument("output", type=Path) p.add_argument( "--asset", type=Path, default=Path(__file__).parent / "exports/ulunas_dns3_float32_streaming.aimodel", ) a = p.parse_args() asyncio.run(enhance(a.asset, a.input, a.output))123version https://git-lfs.github.com/spec/v1oid sha256:7d86836c3e86a7ef4260b58643a0e3c5d52d554baaa38f9e0098fb5c35736732size 1156206312345678{ "creationDate" : "20261005T034351Z", "author" : "Jean-Marc Valin and RNNoise contributors", "license" : "BSD-3-Clause; see vendor\/rnnoise\/LICENSE and source-file notices", "assetVersion" : "2.0", "description" : "rnnoise10Ga_12 pretrained streaming neural network; Core AI conversion by Max Farrell. Audio DSP is external. See README and provenance.json.", "producer" : "coreai-core 1.0.0b3"}1���y�hjr�K�!~'Qzi���o,�123version https://git-lfs.github.com/spec/v1oid sha256:d908dff07992686a72bb4b910212217e271151e2b5b37a69a9da1f14d26f2cbdsize 1156206612345678{ "author" : "Jean-Marc Valin and RNNoise contributors", "producer" : "coreai-core 1.0.0b3", "creationDate" : "20261005T034432Z", "assetVersion" : "2.0", "license" : "BSD-3-Clause; see vendor\/rnnoise\/LICENSE and source-file notices", "description" : "rnnoise10Gb_15 pretrained streaming neural network; Core AI conversion by Max Farrell. Audio DSP is external. See README and provenance.json."}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Pretrained model loaders and explicit streaming boundaries. MIT; see vendor licenses."""
import sysfrom pathlib import Path
import torchfrom torch import nn
ROOT = Path(__file__).resolve().parentsys.path.insert(0, str(ROOT / "vendor" / "ulunas"))sys.path.insert(0, str(ROOT / "vendor" / "rnnoise"))from rnnoise import RNNoisefrom stream import StreamULUNASfrom ulunas import ULUNAS
class FunctionalULUNAS(StreamULUNAS): def forward(self, mix, conv_cache, tfa_cache, inter_cache): return super().forward( mix, conv_cache.clone(), tfa_cache.clone(), inter_cache.clone() )
class StreamingRNNoise(nn.Module): def __init__(self, source): super().__init__() self.source = source
def forward( self, features, conv1_cache, conv2_cache, gru1_state, gru2_state, gru3_state ): m = self.source c1 = torch.cat((conv1_cache.clone(), features.transpose(1, 2)), dim=2) x = torch.tanh(m.conv1(c1)) c2 = torch.cat((conv2_cache.clone(), x), dim=2) x = torch.tanh(m.conv2(c2)).transpose(1, 2) y1, h1 = m.gru1(x, gru1_state.clone()) y2, h2 = m.gru2(y1, gru2_state.clone()) y3, h3 = m.gru3(y2, gru3_state.clone()) cat = torch.cat((x, y1, y2, y3), dim=-1) return ( torch.sigmoid(m.dense_out(cat)), torch.sigmoid(m.vad_dense(cat)), c1[:, :, 1:], c2[:, :, 1:], h1, h2, h3, )
def load_model(variant, dtype=torch.float16): if variant == "ulunas_dns3": checkpoint = ROOT / "weights" / "ulunas_dns3.tar" source = ULUNAS().eval() source.load_state_dict( torch.load(checkpoint, map_location="cpu", weights_only=True)["model"] ) model = FunctionalULUNAS().eval() model.load_state_dict(source.state_dict(), strict=True) args = (torch.randn(1, 257, 1, 2), *model.init_caches()) ins = ["mix", "conv_cache", "tfa_cache", "inter_cache"] outs = ["enh", "conv_cache_out", "tfa_cache_out", "inter_cache_out"] else: checkpoint = ROOT / "weights" / f"{variant}.pth" saved = torch.load(checkpoint, map_location="cpu", weights_only=True) source = RNNoise(**saved["model_kwargs"]).eval() source.load_state_dict(saved["state_dict"], strict=True) model = StreamingRNNoise(source).eval() args = ( torch.randn(1, 1, source.input_dim), torch.zeros(1, source.input_dim, 2), torch.zeros(1, source.cond_size, 2), *(torch.zeros(1, 1, source.gru_size) for _ in range(3)), ) ins = [ "features", "conv1_cache", "conv2_cache", "gru1_state", "gru2_state", "gru3_state", ] outs = ["gains", "vad", *[f"{x}_out" for x in ins[1:]]] return ( model.to(dtype), tuple(x.to(dtype) for x in args), ins, outs, checkpoint, source.to(dtype), )12345678910111213141516171819202122232425262728{ "toolchain": { "torch": "2.11.0", "coreai-torch": "0.4.3", "coreai-core": "1.0.0b3" }, "validation_os": "macOS 27.0.1 (26A434)", "compute_unit": "CPU", "upstream": { "ulunas": { "repository": "https://github.com/Xiaobin-Rong/ul-unas", "commit": "00f7c700da43d38347f30a6ccebd86fcbc798e07", "license": "MIT" }, "rnnoise": { "repository": "https://github.com/xiph/rnnoise", "commit": "70f1d256acd4b34a572f999a05c87bf00b67730d", "license": "BSD-style; see retained notices", "archive": "https://media.xiph.org/rnnoise/models/rnnoise_data-0a8755f8e2d834eff6a54714ecc7d75f9932e845df35f8b59bc52a7cfe6e8b37.tar.gz", "archive_sha256": "0a8755f8e2d834eff6a54714ecc7d75f9932e845df35f8b59bc52a7cfe6e8b37" } }, "checkpoints": { "rnnoise10Ga_12.pth": "1f495605b553ce1f64643e3732249ede58a72c062f42c53e9f929bbd1b1ff31c", "rnnoise10Gb_15.pth": "ff1f6b2a63dcf3b74eff95a77d4deb1b75e26a3a7fa6e4921210086313f412ba", "ulunas_dns3.tar": "9a0656bf8e88d36865792d3065fed9bc33d5ab85e11ae3a1ae085b928fdb49a8" }}1234567[project]name = "speech-enhancement-coreai"version = "0.1.0"description = "Reproducible pretrained RNNoise and UL-UNAS Core AI streaming exports"requires-python = ">=3.11,<3.14"license = "MIT"dependencies = ["torch==2.11.0", "coreai-core==1.0.0b3", "coreai-torch==0.4.3", "numpy==2.4.6", "einops==0.8.2", "soundfile==0.14.0", "tqdm==4.70.1"]1234567891011121314151617181920212223242526272829303132Copyright (c) 2007-2017, 2024 Jean-Marc ValinCopyright (c) 2023 AmazonCopyright (c) 2017, MozillaCopyright (c) 2005-2017, Xiph.Org FoundationCopyright (c) 2003-2004, Mark Borgerding
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditionsare met:
- Redistributions of source code must retain the above copyrightnotice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyrightnotice, this list of conditions and the following disclaimer in thedocumentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.Org Foundation nor the names of itscontributors may be used to endorse or promote products derived fromthis software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATIONOR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOTLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""/* Copyright (c) 2024 Jean-Marc Valin *//* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/"""
import torchfrom torch import nnimport torch.nn.functional as Fimport sysimport os
sys.path.append(os.path.join(os.path.split(__file__)[0], '..'))from sparsification import GRUSparsifier
sparsify_start = 6000sparsify_stop = 20000sparsify_interval = 100sparsify_exponent = 3
sparse_params1 = { 'W_hr' : (0.3, [8, 4], True), 'W_hz' : (0.2, [8, 4], True), 'W_hn' : (0.5, [8, 4], True), 'W_ir' : (0.3, [8, 4], False), 'W_iz' : (0.2, [8, 4], False), 'W_in' : (0.5, [8, 4], False) }
def init_weights(module): if isinstance(module, nn.GRU): for p in module.named_parameters(): if p[0].startswith('weight_hh_'): nn.init.orthogonal_(p[1])
class RNNoise(nn.Module): def __init__(self, input_dim=65, output_dim=32, cond_size=128, gru_size=256): super(RNNoise, self).__init__()
self.input_dim = input_dim self.output_dim = output_dim self.cond_size = cond_size self.gru_size = gru_size self.conv1 = nn.Conv1d(input_dim, cond_size, kernel_size=3, padding='valid') self.conv2 = nn.Conv1d(cond_size, gru_size, kernel_size=3, padding='valid') self.gru1 = nn.GRU(self.gru_size, self.gru_size, batch_first=True) self.gru2 = nn.GRU(self.gru_size, self.gru_size, batch_first=True) self.gru3 = nn.GRU(self.gru_size, self.gru_size, batch_first=True) self.dense_out = nn.Linear(4*self.gru_size, self.output_dim) self.vad_dense = nn.Linear(4*self.gru_size, 1) nb_params = sum(p.numel() for p in self.parameters()) print(f"model: {nb_params} weights") self.apply(init_weights) self.sparsifier = [] self.sparsifier.append(GRUSparsifier([(self.gru1, sparse_params1)], sparsify_start, sparsify_stop, sparsify_interval, sparsify_exponent)) self.sparsifier.append(GRUSparsifier([(self.gru2, sparse_params1)], sparsify_start, sparsify_stop, sparsify_interval, sparsify_exponent)) self.sparsifier.append(GRUSparsifier([(self.gru3, sparse_params1)], sparsify_start, sparsify_stop, sparsify_interval, sparsify_exponent))
def sparsify(self): for sparsifier in self.sparsifier: sparsifier.step()
def forward(self, features, states=None): #print(states) device = features.device batch_size = features.size(0) if states is None: gru1_state = torch.zeros((1, batch_size, self.gru_size), device=device) gru2_state = torch.zeros((1, batch_size, self.gru_size), device=device) gru3_state = torch.zeros((1, batch_size, self.gru_size), device=device) else: gru1_state = states[0] gru2_state = states[1] gru3_state = states[2] tmp = features.permute(0, 2, 1) tmp = torch.tanh(self.conv1(tmp)) tmp = torch.tanh(self.conv2(tmp)) tmp = tmp.permute(0, 2, 1)
gru1_out, gru1_state = self.gru1(tmp, gru1_state) gru2_out, gru2_state = self.gru2(gru1_out, gru2_state) gru3_out, gru3_state = self.gru3(gru2_out, gru3_state) out_cat = torch.cat([tmp, gru1_out, gru2_out, gru3_out], dim=-1) gain = torch.sigmoid(self.dense_out(out_cat)) vad = torch.sigmoid(self.vad_dense(out_cat)) return gain, vad, [gru1_state, gru2_state, gru3_state]12from .gru_sparsifier import GRUSparsifierfrom .common import sparsify_matrix, calculate_gru_flops_per_step123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"""/* Copyright (c) 2023 Amazon Written by Jan Buethe *//* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/"""
import torch
def sparsify_matrix(matrix : torch.tensor, density : float, block_size, keep_diagonal : bool=False, return_mask : bool=False): """ sparsifies matrix with specified block size
Parameters: ----------- matrix : torch.tensor matrix to sparsify density : int target density block_size : [int, int] block size dimensions keep_diagonal : bool If true, the diagonal will be kept. This option requires block_size[0] == block_size[1] and defaults to False """
m, n = matrix.shape m1, n1 = block_size
if m % m1 or n % n1: raise ValueError(f"block size {(m1, n1)} does not divide matrix size {(m, n)}")
# extract diagonal if keep_diagonal = True if keep_diagonal: if m != n: raise ValueError("Attempting to sparsify non-square matrix with keep_diagonal=True")
to_spare = torch.diag(torch.diag(matrix)) matrix = matrix - to_spare else: to_spare = torch.zeros_like(matrix)
# calculate energy in sub-blocks x = torch.reshape(matrix, (m // m1, m1, n // n1, n1)) x = x ** 2 block_energies = torch.sum(torch.sum(x, dim=3), dim=1)
number_of_blocks = (m * n) // (m1 * n1) number_of_survivors = round(number_of_blocks * density)
# masking threshold if number_of_survivors == 0: threshold = 0 else: threshold = torch.sort(torch.flatten(block_energies)).values[-number_of_survivors]
# create mask mask = torch.ones_like(block_energies) mask[block_energies < threshold] = 0 mask = torch.repeat_interleave(mask, m1, dim=0) mask = torch.repeat_interleave(mask, n1, dim=1)
# perform masking masked_matrix = mask * matrix + to_spare
if return_mask: return masked_matrix, mask else: return masked_matrix
def calculate_gru_flops_per_step(gru, sparsification_dict=dict(), drop_input=False): input_size = gru.input_size hidden_size = gru.hidden_size flops = 0
input_density = ( sparsification_dict.get('W_ir', [1])[0] + sparsification_dict.get('W_in', [1])[0] + sparsification_dict.get('W_iz', [1])[0] ) / 3
recurrent_density = ( sparsification_dict.get('W_hr', [1])[0] + sparsification_dict.get('W_hn', [1])[0] + sparsification_dict.get('W_hz', [1])[0] ) / 3
# input matrix vector multiplications if not drop_input: flops += 2 * 3 * input_size * hidden_size * input_density
# recurrent matrix vector multiplications flops += 2 * 3 * hidden_size * hidden_size * recurrent_density
# biases flops += 6 * hidden_size
# activations estimated by 10 flops per activation flops += 30 * hidden_size
return flops123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""/* Copyright (c) 2023 Amazon Written by Jan Buethe *//* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/"""
import torch
from .common import sparsify_matrix
class GRUSparsifier: def __init__(self, task_list, start, stop, interval, exponent=3): """ Sparsifier for torch.nn.GRUs
Parameters: ----------- task_list : list task_list contains a list of tuples (gru, sparsify_dict), where gru is an instance of torch.nn.GRU and sparsify_dic is a dictionary with keys in {'W_ir', 'W_iz', 'W_in', 'W_hr', 'W_hz', 'W_hn'} corresponding to the input and recurrent weights for the reset, update, and new gate. The values of sparsify_dict are tuples (density, [m, n], keep_diagonal), where density is the target density in [0, 1], [m, n] is the shape sub-blocks to which sparsification is applied and keep_diagonal is a bool variable indicating whether the diagonal should be kept.
start : int training step after which sparsification will be started.
stop : int training step after which sparsification will be completed.
interval : int sparsification interval for steps between start and stop. After stop sparsification will be carried out after every call to GRUSparsifier.step()
exponent : float Interpolation exponent for sparsification interval. In step i sparsification will be carried out with density (alpha + target_density * (1 * alpha)), where alpha = ((stop - i) / (start - stop)) ** exponent
Example: -------- >>> import torch >>> gru = torch.nn.GRU(10, 20) >>> sparsify_dict = { ... 'W_ir' : (0.5, [2, 2], False), ... 'W_iz' : (0.6, [2, 2], False), ... 'W_in' : (0.7, [2, 2], False), ... 'W_hr' : (0.1, [4, 4], True), ... 'W_hz' : (0.2, [4, 4], True), ... 'W_hn' : (0.3, [4, 4], True), ... } >>> sparsifier = GRUSparsifier([(gru, sparsify_dict)], 0, 100, 50) >>> for i in range(100): ... sparsifier.step() """ # just copying parameters... self.start = start self.stop = stop self.interval = interval self.exponent = exponent self.task_list = task_list
# ... and setting counter to 0 self.step_counter = 0
self.last_masks = {key : None for key in ['W_ir', 'W_in', 'W_iz', 'W_hr', 'W_hn', 'W_hz']}
def step(self, verbose=False): """ carries out sparsification step
Call this function after optimizer.step in your training loop.
Parameters: ---------- verbose : bool if true, densities are printed out
Returns: -------- None
""" # compute current interpolation factor self.step_counter += 1
if self.step_counter < self.start: return elif self.step_counter < self.stop: # update only every self.interval-th interval if self.step_counter % self.interval: return
alpha = ((self.stop - self.step_counter) / (self.stop - self.start)) ** self.exponent else: alpha = 0
with torch.no_grad(): for gru, params in self.task_list: hidden_size = gru.hidden_size
# input weights for i, key in enumerate(['W_ir', 'W_iz', 'W_in']): if key in params: density = alpha + (1 - alpha) * params[key][0] if verbose: print(f"[{self.step_counter}]: {key} density: {density}")
gru.weight_ih_l0[i * hidden_size : (i+1) * hidden_size, : ], new_mask = sparsify_matrix( gru.weight_ih_l0[i * hidden_size : (i + 1) * hidden_size, : ], density, # density params[key][1], # block_size params[key][2], # keep_diagonal (might want to set this to False) return_mask=True )
if type(self.last_masks[key]) != type(None): if not torch.all(self.last_masks[key] == new_mask) and self.step_counter > self.stop: print(f"sparsification mask {key} changed for gru {gru}")
self.last_masks[key] = new_mask
# recurrent weights for i, key in enumerate(['W_hr', 'W_hz', 'W_hn']): if key in params: density = alpha + (1 - alpha) * params[key][0] if verbose: print(f"[{self.step_counter}]: {key} density: {density}") gru.weight_hh_l0[i * hidden_size : (i+1) * hidden_size, : ], new_mask = sparsify_matrix( gru.weight_hh_l0[i * hidden_size : (i + 1) * hidden_size, : ], density, params[key][1], # block_size params[key][2], # keep_diagonal (might want to set this to False) return_mask=True )
if type(self.last_masks[key]) != type(None): if not torch.all(self.last_masks[key] == new_mask) and self.step_counter > self.stop: print(f"sparsification mask {key} changed for gru {gru}")
self.last_masks[key] = new_mask
if __name__ == "__main__": print("Testing sparsifier")
gru = torch.nn.GRU(10, 20) sparsify_dict = { 'W_ir' : (0.5, [2, 2], False), 'W_iz' : (0.6, [2, 2], False), 'W_in' : (0.7, [2, 2], False), 'W_hr' : (0.1, [4, 4], True), 'W_hz' : (0.2, [4, 4], True), 'W_hn' : (0.3, [4, 4], True), }
sparsifier = GRUSparsifier([(gru, sparsify_dict)], 0, 100, 10)
for i in range(100): sparsifier.step(verbose=True)123456789101112131415161718192021MIT License
Copyright (c) 2026 Xiaobin Rong
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280# Copyright (c) 2026 Xiaobin Rong and contributors. MIT license.# Extracted from upstream ulunas_onnx/stream/ulunas_stream.py; demo-only imports removed.import osimport time
import numpy as npimport soundfile as sfimport torchimport torch.nn as nnfrom tqdm import tqdm
from ulunas import ULUNAS
class StreamULUNAS(nn.Module): """Frame-wise streaming ULUNAS for ONNX export.""" CONV_CACHE_SHAPES = [ (1, 2, 129), (24, 1, 65), (24, 1, 33), (24, 1, 33), (12, 1, 33), (12, 2, 65), ] TFA_CACHE_HIDDEN = [24, 48, 48, 64, 32, 64, 48, 48, 24, 2] INTER_CACHE_SHAPES = [(33, 16), (33, 16)]
def __init__(self): super().__init__() base = ULUNAS() self.erb = base.erb self.encoder = base.encoder self.dpgrnn = base.dpgrnn self.decoder = base.decoder
@classmethod def init_caches(cls, batch_size=1, device=None): conv_size = sum(int(np.prod(shape)) for shape in cls.CONV_CACHE_SHAPES) tfa_size = sum(cls.TFA_CACHE_HIDDEN) inter_size = sum(int(np.prod(shape)) for shape in cls.INTER_CACHE_SHAPES) conv_cache = torch.zeros(batch_size, conv_size, device=device) tfa_cache = torch.zeros(batch_size, tfa_size, device=device) inter_cache = torch.zeros(batch_size, inter_size, device=device) return conv_cache, tfa_cache, inter_cache
@classmethod def _unpack_conv_cache(cls, conv_cache): bsz = conv_cache.shape[0] caches = [] offset = 0 for shape in cls.CONV_CACHE_SHAPES: n = int(np.prod(shape)) caches.append(conv_cache[:, offset : offset + n].view(bsz, *shape)) offset += n return caches
@classmethod def _pack_conv_cache(cls, caches): return torch.cat([cache.reshape(cache.shape[0], -1) for cache in caches], dim=1)
@classmethod def _unpack_tfa_cache(cls, tfa_cache): bsz = tfa_cache.shape[0] caches = [] offset = 0 for hidden in cls.TFA_CACHE_HIDDEN: caches.append(tfa_cache[:, offset : offset + hidden].view(1, bsz, hidden)) offset += hidden return caches
@classmethod def _pack_tfa_cache(cls, caches): return torch.cat([cache.reshape(cache.shape[1], -1) for cache in caches], dim=1)
@classmethod def _unpack_inter_cache(cls, inter_cache): bsz = inter_cache.shape[0] caches = [] offset = 0 for shape in cls.INTER_CACHE_SHAPES: n = int(np.prod(shape)) caches.append(inter_cache[:, offset : offset + n].view(bsz, *shape)) offset += n return caches
@classmethod def _pack_inter_cache(cls, caches): return torch.cat([cache.reshape(cache.shape[0], -1) for cache in caches], dim=1)
@staticmethod def _stream_temporal_conv(x, conv, cache): inp = torch.cat([cache, x], dim=2) if isinstance(conv, nn.ConvTranspose2d): # Match offline path: ZeroPad2d([0, 0, kt-1, 0]) + ConvTranspose2d, then # keep only the current-step output frame. kt = conv.kernel_size[0] inp_padded = torch.nn.functional.pad(inp, (0, 0, kt - 1, 0)) y = conv(inp_padded)[:, :, -1:, :] else: y = conv(inp) new_cache = inp[:, :, 1:, :] return y, new_cache
@staticmethod def _stream_ctfa(ctfa, x, h_cache): zt = torch.mean(x.pow(2), dim=-1) # (B,C,T) at, h_cache = ctfa.ta_gru(zt.transpose(1, 2), h_cache) at = torch.sigmoid(ctfa.ta_fc(at).transpose(1, 2))
af = torch.sigmoid(ctfa.fa(x)) y = at[..., None] * x * af[:, None] return y, h_cache
def _stream_xconv(self, block, x, conv_cache, tfa_cache): x, conv_cache = self._stream_temporal_conv(x, block.ops[1], conv_cache) x = block.ops[2](x) x = block.ops[3](x) x, tfa_cache = self._stream_ctfa(block.ops[4], x, tfa_cache) x = block.ops[5](x) return x, conv_cache, tfa_cache
def _stream_xdws(self, block, x, tfa_cache, conv_cache=None): h = block.pconv(x) if conv_cache is None: h = block.dconv[0](h) h = block.dconv[1](h) else: h, conv_cache = self._stream_temporal_conv(h, block.dconv[1], conv_cache) h = block.dconv[2](h) h = block.dconv[3](h) h, tfa_cache = self._stream_ctfa(block.dconv[4], h, tfa_cache) return h, conv_cache, tfa_cache
def _stream_xmb(self, block, x, tfa_cache, conv_cache=None): residual = x x = block.pconv1(x) if conv_cache is None: x = block.dconv(x) else: x, conv_cache = self._stream_temporal_conv(x, block.dconv[1], conv_cache) x = block.dconv[2](x) x = block.dconv[3](x)
x = block.pconv2[0](x) x = block.pconv2[1](x) x, tfa_cache = self._stream_ctfa(block.pconv2[2], x, tfa_cache)
if x.shape == residual.shape: x = x + residual x = block.shuffle(x) return x, conv_cache, tfa_cache
@staticmethod def _stream_dpgrnn(block, x, inter_cache): x = x.permute(0, 2, 3, 1) # (B,T,F,C)
intra_x = x.reshape(x.shape[0] * x.shape[1], x.shape[2], x.shape[3]) intra_x = block.intra_rnn(intra_x)[0] intra_x = block.intra_fc(intra_x) intra_x = intra_x.reshape(x.shape[0], -1, block.width, block.input_size) intra_x = block.intra_ln(intra_x) intra_out = x + intra_x
x = intra_out.permute(0, 2, 1, 3) # (B,F,T,C) inter_x = x.reshape(x.shape[0] * x.shape[1], x.shape[2], x.shape[3]) inter_x, inter_cache = block.inter_rnn(inter_x, inter_cache) inter_x = block.inter_fc(inter_x) inter_x = inter_x.reshape(x.shape[0], block.width, -1, block.input_size) inter_x = inter_x.permute(0, 2, 1, 3) # (B,T,F,C) inter_x = block.inter_ln(inter_x) inter_out = intra_out + inter_x
dual_out = inter_out.permute(0, 3, 1, 2) # (B,C,T,F) return dual_out, inter_cache
def forward( self, spec, conv_cache, tfa_cache, inter_cache, ): """ spec: (B,F,T,2), streaming T=1 """ spec_ref = spec spec = spec.permute(0, 3, 2, 1) # (B,2,T,F) feat = torch.log10(torch.norm(spec, dim=1, keepdim=True).clamp(1e-12)) feat = self.erb.bm(feat) # (B,1,T,129)
( conv_cache_e0, conv_cache_e1, conv_cache_e2, conv_cache_d2, conv_cache_d3, conv_cache_d4, ) = self._unpack_conv_cache(conv_cache) ( tfa_cache_0, tfa_cache_1, tfa_cache_2, tfa_cache_3, tfa_cache_4, tfa_cache_5, tfa_cache_6, tfa_cache_7, tfa_cache_8, tfa_cache_9, ) = self._unpack_tfa_cache(tfa_cache) inter_cache_0, inter_cache_1 = self._unpack_inter_cache(inter_cache)
en_outs = [] feat, conv_cache_e0, tfa_cache_0 = self._stream_xconv( self.encoder.en_convs[0], feat, conv_cache_e0, tfa_cache_0 ) en_outs.append(feat)
feat, conv_cache_e1, tfa_cache_1 = self._stream_xmb( self.encoder.en_convs[1], feat, tfa_cache_1, conv_cache_e1 ) en_outs.append(feat)
feat, conv_cache_e2, tfa_cache_2 = self._stream_xdws( self.encoder.en_convs[2], feat, tfa_cache_2, conv_cache_e2 ) en_outs.append(feat)
feat, _, tfa_cache_3 = self._stream_xmb(self.encoder.en_convs[3], feat, tfa_cache_3) en_outs.append(feat)
feat, _, tfa_cache_4 = self._stream_xdws(self.encoder.en_convs[4], feat, tfa_cache_4) en_outs.append(feat)
feat, inter_cache_0 = self._stream_dpgrnn(self.dpgrnn[0], feat, inter_cache_0) feat, inter_cache_1 = self._stream_dpgrnn(self.dpgrnn[1], feat, inter_cache_1)
feat, _, tfa_cache_5 = self._stream_xdws( self.decoder.de_convs[0], feat + en_outs[4], tfa_cache_5 ) feat, _, tfa_cache_6 = self._stream_xmb( self.decoder.de_convs[1], feat + en_outs[3], tfa_cache_6 ) feat, conv_cache_d2, tfa_cache_7 = self._stream_xdws( self.decoder.de_convs[2], feat + en_outs[2], tfa_cache_7, conv_cache_d2 ) feat, conv_cache_d3, tfa_cache_8 = self._stream_xmb( self.decoder.de_convs[3], feat + en_outs[1], tfa_cache_8, conv_cache_d3 ) feat, conv_cache_d4, tfa_cache_9 = self._stream_xconv( self.decoder.de_convs[4], feat + en_outs[0], conv_cache_d4, tfa_cache_9 ) m_feat = torch.sigmoid(feat)
m = self.erb.bs(m_feat) spec_enh = spec * m spec_enh = spec_enh.permute(0, 3, 2, 1) # (B,F,T,2)
conv_cache = self._pack_conv_cache( [conv_cache_e0, conv_cache_e1, conv_cache_e2, conv_cache_d2, conv_cache_d3, conv_cache_d4] ) tfa_cache = self._pack_tfa_cache( [ tfa_cache_0, tfa_cache_1, tfa_cache_2, tfa_cache_3, tfa_cache_4, tfa_cache_5, tfa_cache_6, tfa_cache_7, tfa_cache_8, tfa_cache_9, ] ) inter_cache = self._pack_inter_cache([inter_cache_0, inter_cache_1])
return spec_enh, conv_cache, tfa_cache, inter_cache
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561# Copyright (c) 2026 Xiaobin-Rong# Licensed under the MIT license.
import torchimport numpy as npimport torch.nn as nnfrom einops import rearrange
class ERB(nn.Module): def __init__(self, erb_subband_1, erb_subband_2, nfft=512, high_lim=8000, fs=16000): super().__init__() erb_filters = self.erb_filter_banks(erb_subband_1, erb_subband_2, nfft, high_lim, fs) nfreqs = nfft//2 + 1 self.erb_subband_1 = erb_subband_1 self.erb_fc = nn.Linear(nfreqs-erb_subband_1, erb_subband_2, bias=False) self.ierb_fc = nn.Linear(erb_subband_2, nfreqs-erb_subband_1, bias=False) self.erb_fc.weight = nn.Parameter(erb_filters, requires_grad=False) self.ierb_fc.weight = nn.Parameter(erb_filters.T, requires_grad=False)
def hz2erb(self, freq_hz): erb_f = 21.4*np.log10(0.00437*freq_hz + 1) return erb_f
def erb2hz(self, erb_f): freq_hz = (10**(erb_f/21.4) - 1)/0.00437 return freq_hz
def erb_filter_banks(self, erb_subband_1, erb_subband_2, nfft=512, high_lim=8000, fs=16000): low_lim = erb_subband_1/nfft * fs erb_low = self.hz2erb(low_lim) erb_high = self.hz2erb(high_lim) erb_points = np.linspace(erb_low, erb_high, erb_subband_2) bins = np.round(self.erb2hz(erb_points)/fs*nfft).astype(np.int32) erb_filters = np.zeros([erb_subband_2, nfft // 2 + 1], dtype=np.float32)
erb_filters[0, bins[0]:bins[1]] = (bins[1] - np.arange(bins[0], bins[1]) + 1e-12) \ / (bins[1] - bins[0] + 1e-12) for i in range(erb_subband_2-2): erb_filters[i + 1, bins[i]:bins[i+1]] = (np.arange(bins[i], bins[i+1]) - bins[i] + 1e-12)\ / (bins[i+1] - bins[i] + 1e-12) erb_filters[i + 1, bins[i+1]:bins[i+2]] = (bins[i+2] - np.arange(bins[i+1], bins[i + 2]) + 1e-12) \ / (bins[i + 2] - bins[i+1] + 1e-12)
erb_filters[-1, bins[-2]:bins[-1]+1] = 1- erb_filters[-2, bins[-2]:bins[-1]+1] erb_filters = erb_filters[:, erb_subband_1:] return torch.from_numpy(np.abs(erb_filters)) def bm(self, x): """x: (B,C,T,F)""" x_low = x[..., :self.erb_subband_1] x_high = self.erb_fc(x[..., self.erb_subband_1:]) return torch.cat([x_low, x_high], dim=-1) def bs(self, x_erb): """x: (B,C,T,F_erb)""" x_erb_low = x_erb[..., :self.erb_subband_1] x_erb_high = self.ierb_fc(x_erb[..., self.erb_subband_1:]) return torch.cat([x_erb_low, x_erb_high], dim=-1)
class AffinePReLU(nn.Module): def __init__(self, channels, width, init=0.25): super().__init__() self.affine_weight = nn.Parameter(torch.ones(channels, width)) self.affine_bias = nn.Parameter(torch.zeros(channels, width)) self.slope_weight = nn.Parameter(torch.empty(channels)) nn.init.constant_(self.slope_weight, init) def forward(self, x): y = self.affine_weight[None,:,None,:] * x + self.affine_bias[None,:,None,:] y = y + torch.where(x>0, x, self.slope_weight.view(1,-1,1,1) * x) return y
class FA(nn.Module): def __init__(self, nfreq, freq_comp_ratio=4): super().__init__() self.r = freq_comp_ratio
self.gru = nn.GRU(self.r, self.r, batch_first=True, bidirectional=True) self.fc = nn.Linear(2*self.r, self.r) remainder = nfreq % self.r if remainder != 0: self.pad_len = self.r - remainder else: self.pad_len = 0
self.F_pad = nfreq + self.pad_len self.H = self.F_pad // self.r
def forward(self, x): B, C, T, F = x.shape x = torch.mean(x.pow(2), dim=1) # (B,T,F)
x = nn.functional.pad(x, (0, self.pad_len)) x = x.view(B, T, self.H, self.r)
x = rearrange(x, 'b t h c -> (b t) h c') x, _ = self.gru(x) # (BT, H, 2C) x = self.fc(x) x = rearrange(x, '(b t) h c -> b t h c', b=B) x = x.reshape(B, T, self.F_pad) # (B, T, F)
if self.pad_len > 0: x = x[..., :F]
return x
class cTFA(nn.Module): """causal time-frequency attention""" def __init__(self, channels, width): super().__init__() self.channels = channels self.ta_gru = nn.GRU(channels, channels*2, 1, batch_first=True) self.ta_fc = nn.Linear(channels*2, channels) self.fa = FA(width)
def forward(self, x): """x: (B,C,T,F)""" zt = torch.mean(x.pow(2), dim=-1) # (B,C,T) at = self.ta_gru(zt.transpose(1,2))[0] at = self.ta_fc(at).transpose(1,2) # (B,C,T) at = torch.sigmoid(at) af = self.fa(x) af = torch.sigmoid(af) return at[...,None] * x * af[:, None]
class Shuffle(nn.Module): def __init__(self): super().__init__() def forward(self, x): """x: (B,2C,T,F)""" x1, x2 = torch.chunk(x, chunks=2, dim=1) x = torch.stack([x1, x2], dim=1) x = x.transpose(1, 2).contiguous() # (B,C,2,T,F) x = rearrange(x, 'b c g t f -> b (c g) t f') # (B,2C,T,F) return x
class XConvBlock(nn.Module): def __init__( self, in_channels, out_channels, width, kernel_size, stride: int = 1, groups: int = 1, use_deconv: bool =False, is_last: bool=False, ): super().__init__() self.g = groups if isinstance(kernel_size, int): kernel_size = [kernel_size, kernel_size] kt = kernel_size[0] if use_deconv: pt = kt - 1 conv_module = nn.ConvTranspose2d else: pt = 0 conv_module = nn.Conv2d pf = kernel_size[1]//2
self.ops = nn.Sequential( nn.ZeroPad2d([0, 0, kt - 1, 0]), conv_module(in_channels, out_channels, kernel_size, stride=(1, stride), padding=(pt, pf), groups=groups), nn.BatchNorm2d(out_channels), AffinePReLU(out_channels, width) if not is_last else nn.Identity(), cTFA(out_channels, width), Shuffle() if (not is_last and groups==2) else nn.Identity() ) def forward(self, x): x = self.ops(x) return x
class XDWSBlock(nn.Module): def __init__( self, in_channels, out_channels, width, kernel_size, stride: int = 1, groups: int = 1, use_deconv: bool = False, is_last: bool =False, ): super().__init__() if isinstance(kernel_size, int): kernel_size = [kernel_size, kernel_size] kt = kernel_size[0] if use_deconv: pt = kt - 1 conv_module = nn.ConvTranspose2d else: pt = 0 conv_module = nn.Conv2d pf = kernel_size[1]//2
if stride == 2: if not use_deconv: in_width = width * 2 -1 else: in_width = width // 2 + 1 else: in_width = width
self.pconv = nn.Sequential( nn.Conv2d(in_channels, out_channels, 1, groups=groups), nn.BatchNorm2d(out_channels), AffinePReLU(out_channels, in_width), Shuffle() if groups==2 else nn.Identity() ) self.dconv = nn.Sequential( nn.ZeroPad2d([0, 0, kt - 1, 0]), conv_module(out_channels, out_channels, kernel_size, stride=(1, stride), padding=(pt, pf), groups=out_channels), nn.BatchNorm2d(out_channels), AffinePReLU(out_channels, width) if not is_last else nn.Identity(), cTFA(out_channels, width) )
def forward(self, x): """x: (B, C, T, F)""" h = self.pconv(x) h = self.dconv(h)
return h
class XMBBlocks(nn.Module): def __init__( self, in_channels, out_channels, width, kernel_size, stride: int = 1, groups: int = 1, use_deconv: bool = False, is_last: bool = False, ): super().__init__() if isinstance(kernel_size, int): kernel_size = [kernel_size, kernel_size] kt = kernel_size[0] if use_deconv: pt = kt - 1 conv_module = nn.ConvTranspose2d else: pt = 0 conv_module = nn.Conv2d pf = kernel_size[1]//2
if stride == 2: if not use_deconv: in_width = width * 2 -1 else: in_width = width // 2 + 1 else: in_width = width
self.pconv1 = nn.Sequential( nn.Conv2d(in_channels, out_channels, 1, groups=groups), nn.BatchNorm2d(out_channels), AffinePReLU(out_channels, in_width), Shuffle() if groups == 2 else nn.Identity() ) self.dconv = nn.Sequential( nn.ZeroPad2d([0, 0, kt - 1, 0]), conv_module(out_channels, out_channels, kernel_size, stride=(1, stride), padding=(pt, pf), groups=out_channels), nn.BatchNorm2d(out_channels), AffinePReLU(out_channels, width) ) self.pconv2 = nn.Sequential( nn.Conv2d(out_channels, out_channels, 1, groups=groups), nn.BatchNorm2d(out_channels), cTFA(out_channels, width) ) self.shuffle = Shuffle() if (not is_last and groups==2) else nn.Identity()
def forward(self, x): input = x x = self.pconv1(x) x = self.dconv(x) x = self.pconv2(x) if x.shape == input.shape: x = x + input
x = self.shuffle(x)
return x
class GRNN(nn.Module): """Grouped RNN""" def __init__(self, input_size, hidden_size, num_layers=1, batch_first=True, bidirectional=False): super().__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.bidirectional = bidirectional self.rnn1 = nn.GRU(input_size//2, hidden_size//2, num_layers, batch_first=batch_first, bidirectional=bidirectional) self.rnn2 = nn.GRU(input_size//2, hidden_size//2, num_layers, batch_first=batch_first, bidirectional=bidirectional)
def forward(self, x, h=None): """ x: (B, seq_length, input_size) h: (num_layers, B, hidden_size) """ if h== None: if self.bidirectional: h = torch.zeros(self.num_layers*2, x.shape[0], self.hidden_size, device=x.device) else: h = torch.zeros(self.num_layers, x.shape[0], self.hidden_size, device=x.device) x1, x2 = torch.chunk(x, chunks=2, dim=-1) h1, h2 = torch.chunk(h, chunks=2, dim=-1) h1, h2 = h1.contiguous(), h2.contiguous() y1, h1 = self.rnn1(x1, h1) y2, h2 = self.rnn2(x2, h2) y = torch.cat([y1, y2], dim=-1) h = torch.cat([h1, h2], dim=-1) return y, h
class DPGRNN(nn.Module): """Grouped Dual-path RNN""" def __init__(self, input_size, width, hidden_size, **kwargs): super(DPGRNN, self).__init__(**kwargs) self.input_size = input_size self.width = width self.hidden_size = hidden_size
self.intra_rnn = GRNN(input_size=input_size, hidden_size=hidden_size//2, bidirectional=True) self.intra_fc = nn.Linear(hidden_size, input_size) self.intra_ln = nn.LayerNorm((width, input_size), eps=1e-8)
self.inter_rnn = GRNN(input_size=input_size, hidden_size=hidden_size, bidirectional=False) self.inter_fc = nn.Linear(hidden_size, input_size) self.inter_ln = nn.LayerNorm(((width, input_size)), eps=1e-8) def forward(self, x): """x: (B, C, T, F)""" ## Intra RNN x = x.permute(0, 2, 3, 1) # (B,T,F,C) intra_x = x.reshape(x.shape[0] * x.shape[1], x.shape[2], x.shape[3]) # (B*T,F,C) intra_x = self.intra_rnn(intra_x)[0] # (B*T,F,C) intra_x = self.intra_fc(intra_x) # (B*T,F,C) intra_x = intra_x.reshape(x.shape[0], -1, self.width, self.input_size) # (B,T,F,C) intra_x = self.intra_ln(intra_x) intra_out = torch.add(x, intra_x)
## Inter RNN x = intra_out.permute(0,2,1,3) # (B,F,T,C) inter_x = x.reshape(x.shape[0] * x.shape[1], x.shape[2], x.shape[3]) inter_x = self.inter_rnn(inter_x)[0] # (B*F,T,C) inter_x = self.inter_fc(inter_x) # (B*F,T,C) inter_x = inter_x.reshape(x.shape[0], self.width, -1, self.input_size) # (B,F,T,C) inter_x = inter_x.permute(0,2,1,3) # (B,T,F,C) inter_x = self.inter_ln(inter_x) inter_out = torch.add(intra_out, inter_x) dual_out = inter_out.permute(0,3,1,2) # (B,C,T,F) return dual_out
class Encoder(nn.Module): def __init__( self, types, channels, widths, kernels, strides, groups ): super().__init__() block_types = [XConvBlock, XDWSBlock, XMBBlocks] n_blocks = len(types) en_convs = [] in_channels = 1 for i in range(n_blocks): module = block_types[types[i]] out_channels = channels[i] en_convs.append(module(in_channels, out_channels, widths[i], kernels[i], strides[i], groups=groups[i])) in_channels = out_channels self.en_convs = nn.ModuleList(en_convs)
def forward(self, x): en_outs = [] for i in range(len(self.en_convs)): x = self.en_convs[i](x) en_outs.append(x) # print(i, x.shape)
return x, en_outs
class Decoder(nn.Module): def __init__( self, types, channels, widths, kernels, strides, groups, final_width ): super().__init__() block_types = [XConvBlock, XDWSBlock, XMBBlocks] n_blocks = len(types) de_convs = [] in_channels = channels[-1] for i in range(n_blocks-1, 0, -1): module = block_types[types[i]] out_channels = channels[i-1]
de_convs.append(module(in_channels, out_channels, widths[i-1], kernels[i], strides[i], groups[i], use_deconv=True)) in_channels = out_channels
module = block_types[types[0]] de_convs.append(module(in_channels, 1, final_width, kernels[0], strides[0], groups[0], use_deconv=True, is_last=True)) self.de_convs = nn.ModuleList(de_convs)
def forward(self, x, en_outs): n_blocks = len(self.de_convs) for i in range(n_blocks): x = self.de_convs[i](x + en_outs[n_blocks-i-1]) # print(i, x.shape) x = torch.sigmoid(x) return x
class ULUNAS(nn.Module): def __init__( self, n_fft=512, hop_len=256, win_len=512, erb_low=65, erb_high=64, types=[0, 2, 1, 2, 1], strides=[2, 2, 1, 1, 1], groups=[1, 2, 2, 2, 2], channels=[12, 24, 24, 32, 16], kernels=[(3, 3), (2, 3), (2, 3), (1, 5), (1, 5)], widths=[65, 33, 33, 33, 33] ): super().__init__() self.n_fft = n_fft self.hop_len = hop_len self.win_len = win_len self.erb = ERB(erb_low, erb_high, nfft=n_fft, high_lim=8000, fs=16000)
self.encoder = Encoder(types, channels, widths, kernels, strides, groups) self.dpgrnn = nn.Sequential( *[DPGRNN(channels[-1], widths[-1], channels[-1]) \ for i in range(2)] ) self.decoder = Decoder(types, channels, widths, kernels, strides, groups, final_width=erb_low+erb_high)
def forward(self, input): """ input: (batch, n_samples) """ device = input.device assert input.ndim == 2 # mono input n_samples = input.shape[1] stft_kwargs = {'n_fft': self.n_fft, 'hop_length': self.hop_len, 'win_length': self.win_len, 'window': torch.hann_window(self.win_len).to(device), 'onesided': True} spec = torch.stft(input, **stft_kwargs, return_complex=True) spec = torch.view_as_real(spec) # (B,F,T,2)
spec = spec.permute(0,3,2,1) # (B,2,T,F) feat = torch.log10(torch.norm(spec, dim=1, keepdim=True).clamp(1e-12))
feat = self.erb.bm(feat) # (B,4,T,129) feat, en_outs = self.encoder(feat)
feat = self.dpgrnn(feat) # (B,16,T,33)
m_feat = self.decoder(feat, en_outs) m = self.erb.bs(m_feat)
spec_enh = spec * m spec_enh = spec_enh.permute(0,3,2,1) # (B,F,T,2) spec_enh = torch.complex(spec_enh[...,0], spec_enh[...,1]) output = torch.istft(spec_enh, **stft_kwargs) output = torch.nn.functional.pad(output, (0, n_samples-output.shape[1])) return output
if __name__ == "__main__": model = ULUNAS().eval()
"""complexity count""" from ptflops import get_model_complexity_info macs, params = get_model_complexity_info(model, (16000,), as_strings=False, print_per_layer_stat=False, verbose=False) params = 0 for p in model.parameters(): params += p.numel() print(f"The complexity of ULUNAS: MACs={macs/1e6:.2f} M, Params={params/1e3:.2f} k\n")
"""causality check""" a = torch.randn(1, 16000) b = torch.randn(1, 16000) c = torch.randn(1, 16000) x1 = torch.cat([a, b], dim=1) x2 = torch.cat([a, c], dim=1)
y1 = model(x1)[0] y2 = model(x2)[0]
stft_latency = 256*2 err = (y1[:16000-stft_latency] - y2[:16000-stft_latency]).abs().max() if err < 1e-8: print("The model is causal, without any look ahead.")123version https://git-lfs.github.com/spec/v1oid sha256:1f495605b553ce1f64643e3732249ede58a72c062f42c53e9f929bbd1b1ff31csize 11544286123version https://git-lfs.github.com/spec/v1oid sha256:ff1f6b2a63dcf3b74eff95a77d4deb1b75e26a3a7fa6e4921210086313f412basize 11544286.gitattributes+2
LICENSEAdded+32
README.mdAdded+104
SHA256SUMSAdded+27
THIRD_PARTY_NOTICES.mdAdded+11
convert.pyAdded+167
docs/rnnoise10Ga_12_float32_validation.jsonAdded+16
docs/rnnoise10Gb_15_float32_validation.jsonAdded+16
enhance.pyAdded+61
exports/rnnoise10Ga_12_float32_streaming.aimodel/main.hashAdded
exports/rnnoise10Ga_12_float32_streaming.aimodel/main.mlirbAdded+3
exports/rnnoise10Ga_12_float32_streaming.aimodel/metadata.jsonAdded+8
exports/rnnoise10Gb_15_float32_streaming.aimodel/main.hashAdded+1
exports/rnnoise10Gb_15_float32_streaming.aimodel/main.mlirbAdded+3
exports/rnnoise10Gb_15_float32_streaming.aimodel/metadata.jsonAdded+8
models.pyAdded+92
provenance.jsonAdded+28
pyproject.tomlAdded+7
uv.lockAdded
vendor/rnnoise/LICENSEAdded+32
vendor/rnnoise/rnnoise.pyAdded+109
vendor/rnnoise/sparsification/__init__.pyAdded+2
vendor/rnnoise/sparsification/common.pyAdded+121
vendor/rnnoise/sparsification/gru_sparsifier.pyAdded+187
vendor/ulunas/LICENSEAdded+21
vendor/ulunas/stream.pyAdded+280
vendor/ulunas/ulunas.pyAdded+561
weights/rnnoise10Ga_12.pthAdded+3
weights/rnnoise10Gb_15.pthAdded+3