HY-2012 commited on
Commit
408e7ff
·
verified ·
1 Parent(s): 0947d0e

LavaSR v2 AX650: Pulsar2 8.0 量化模型 + Python/C++ SDK + 精度/性能报告

Browse files
.gitattributes CHANGED
@@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ bin/lavasr_ax650 filter=lfs diff=lfs merge=lfs -text
37
+ models/den_decoder.axmodel filter=lfs diff=lfs merge=lfs -text
38
+ models/den_encoder.axmodel filter=lfs diff=lfs merge=lfs -text
39
+ models/enhancer.axmodel filter=lfs diff=lfs merge=lfs -text
40
+ samples/libri_16k.wav filter=lfs diff=lfs merge=lfs -text
41
+ samples/libri_24k.wav filter=lfs diff=lfs merge=lfs -text
42
+ samples/libri_48k.wav filter=lfs diff=lfs merge=lfs -text
43
+ samples/libri_8k.wav filter=lfs diff=lfs merge=lfs -text
44
+ samples/noisy_48k.wav filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,159 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ library_name: axera
4
+ pipeline_tag: audio-to-audio
5
+ tags:
6
+ - axera
7
+ - ax650
8
+ - npu3
9
+ - lavasr
10
+ - speech-super-resolution
11
+ - bandwidth-extension
12
+ - speech-enhancement
13
+ - denoising
14
  ---
15
+
16
+ # LavaSR v2 AX650 / AXERA
17
+
18
+ [LavaSR v2](https://github.com/ysharma3501/LavaSR) 语音超分(带宽扩展)+
19
+ [UL-UNAS](https://github.com/Xiaobin-Rong/ul-unas) 降噪器的 AX650 预编译部署包。
20
+ 输入 8–48 kHz 低质量语音,输出 48 kHz 清晰语音。
21
+
22
+ - GitHub 源码 / 转换工程:[ZY-2012/LavaSR.AXERA](https://github.com/ZY-2012/LavaSR.AXERA)
23
+ - 上游模型:[ysharma3501/LavaSR](https://github.com/ysharma3501/LavaSR) /
24
+ [YatharthS/LavaSR](https://huggingface.co/YatharthS/LavaSR)
25
+
26
+ ## 模型
27
+
28
+ | 文件 | 大小 | 说明 |
29
+ |---|---:|---|
30
+ | `models/den_encoder.axmodel` | 11.32 MB | UL-UNAS encoder(erb_feat -> feat + skips) |
31
+ | `models/den_decoder.axmodel` | 11.80 MB | UL-UNAS decoder(feat + skips -> mask) |
32
+ | `models/enhancer.axmodel` | 15.07 MB | Vocos BWE(mel -> log-mag / phase) |
33
+
34
+ 量化:U16 激活 / S8 权重 / U16 输出(MinMax);校准数据为真实语音
35
+ (LibriSpeech + AISHELL-1,含噪声变体)。STFT / mel / iSTFT / DPGRNN /
36
+ Linkwitz-Riley 合并在主机 CPU 完成,无 torch / onnxruntime 依赖。
37
+
38
+ ## 精度
39
+
40
+ 板端 Python SDK vs ONNX 参考(17.75 s LibriSpeech,16 kHz -> 48 kHz):
41
+
42
+ | 模式 | cosine | SNR |
43
+ |---|---:|---:|
44
+ | 降噪 + BWE | 0.9999878 | 45.95 dB |
45
+ | 仅 BWE | 0.9999912 | 47.65 dB |
46
+
47
+ 8 kHz / 24 kHz / 48 kHz 输入:SNR 45.5–47.9 dB;10 s 噪声 48 kHz 输入:
48
+ SNR 34.7 dB(降噪)/ 40.1 dB(仅 BWE)。ONNX 主机链路 vs 原始 PyTorch:
49
+ cosine 0.99995 / SNR 39.6 dB。C++ SDK vs ONNX:45.9 / 47.6 dB。
50
+ 完整表格见 [`reports/accuracy.md`](reports/accuracy.md)。
51
+
52
+ ## 速度(AX650N, NPU3)
53
+
54
+ | 链路 | 17.75 s 音频 | RTF |
55
+ |---|---:|---:|
56
+ | Python:降噪 + BWE | 4.93 s | **0.278** |
57
+ | Python:仅 BWE | 1.82 s | **0.103** |
58
+ | C++:降噪 + BWE | 5.75 s | 0.324 |
59
+ | C++:仅 BWE | 3.37 s | 0.190 |
60
+
61
+ RTF = 端到端 `enhance()` 时间 / 音频时长(含主机 STFT/mel/iSTFT/LR merge)。
62
+ NPU 单 4.8 s chunk:encoder ~17.7 ms,decoder ~16.4 ms,enhancer ~5.7 ms。
63
+ 详见 [`reports/performance.md`](reports/performance.md)。
64
+
65
+ ## 目录
66
+
67
+ ```
68
+ LavaSR.AXERA/
69
+ ├── models/ # 三个 axmodel + model_meta.json + model_config.json
70
+ ├── python/
71
+ │ ├── lavasr_sdk/ # 纯 numpy + pyaxengine 运行时
72
+ │ ├── demo.py
73
+ │ └── requirements.txt
74
+ ├── bin/lavasr_ax650 # AX650 预编译 C++ 可执行文件
75
+ ├── samples/ # 8k/16k/24k/48k + 噪声示例
76
+ ├── reports/{accuracy,performance}.md
77
+ ├── configuration.json
78
+ └── run_ax650.sh
79
+ ```
80
+
81
+ ## 快速开始(AX650 板端)
82
+
83
+ ```bash
84
+ # C++(默认)
85
+ bash run_ax650.sh samples/libri_16k.wav output.wav
86
+
87
+ # Python SDK
88
+ bash run_ax650.sh samples/libri_16k.wav output.wav --python
89
+
90
+ # 仅 BWE,跳过降噪
91
+ bash run_ax650.sh samples/libri_16k.wav output.wav --no-denoise
92
+ ```
93
+
94
+ 输入支持 8–48 kHz;输出固定 48 kHz 单声道 wav。
95
+ `LD_LIBRARY_PATH=/soc/lib` 一般已由系统配置,脚本会自动追加。
96
+
97
+ ### Python
98
+
99
+ ```python
100
+ from lavasr_sdk import LavaSR, read_wav, write_wav
101
+
102
+ model = LavaSR(
103
+ "models/den_encoder.axmodel",
104
+ "models/den_decoder.axmodel",
105
+ "models/enhancer.axmodel",
106
+ model_config="models/model_config.json",
107
+ )
108
+ x, sr = read_wav("samples/libri_16k.wav")
109
+ y, out_sr = model.enhance(x, sr, denoise=True)
110
+ write_wav("output.wav", y, out_sr)
111
+ ```
112
+
113
+ 依赖:`numpy`、`pyaxengine`(`axengine`)、可选 `soundfile`。
114
+
115
+ ### C++
116
+
117
+ ```bash
118
+ ./bin/lavasr_ax650 models/den_encoder.axmodel models/den_decoder.axmodel \
119
+ models/enhancer.axmodel samples/libri_16k.wav output.wav [--no-denoise] [--bench]
120
+ ```
121
+
122
+ `bin/lavasr_ax650` 已按 AX650 aarch64 交叉编译,板端直接运行;源码与
123
+ 交叉编译说明见 GitHub 仓库。
124
+
125
+ ## 接口
126
+
127
+ | 模型 | 输入 | 输出 |
128
+ |---|---|---|
129
+ | enhancer | `mel` `[1,80,450]` f32 | `head_out` `[1,2050,450]` f32 |
130
+ | den_encoder | `erb_feat` `[1,1,301,129]` f32 | `feat` + `en0..en4` |
131
+ | den_decoder | `feat` + `en0..en4` | `mask` `[1,1,301,129]` f32 |
132
+
133
+ 固定 4.8 s chunk;降噪 25% overlap,BWE 50% overlap。`model_meta.json` 有
134
+ 完整 shape / 采样率 / overlap 信息。
135
+
136
+ ## 量化说明(重要)
137
+
138
+ - FA GRU:`cTFA` 频率注意力的 bidirectional GRU 直接导出 ONNX `GRU` 时,
139
+ Pulsar2 8.0 产物在板端报 `Failed to run model`。本包在导出阶段把它展开为
140
+ `MatMul/Add/Sigmoid/Tanh` 的 17/33 步循环,数值与原 GRU 一致(cosine 1.0)。
141
+ - DPGRNN:两个双路径 RNN 块含较大 batch 的 GRU,放在主机 numpy/C++ 执行
142
+ (~60k 参数,耗时 <5%)。
143
+ - 所有 axmodel 由 **Pulsar2 8.0** 编译,目标 AX650 / NPU3。
144
+
145
+ ## 限制
146
+
147
+ - 仅 AX650 / NPU3;其他芯片需重新编译。
148
+ - 4.8 s 分块在极长音频边界有微小差异;严格逐样���对齐需流式状态化改造。
149
+ - 上游 `enhancer_v2` 的 mel 配置为 44.1 kHz、输入样本为 48 kHz,本包严格
150
+ 复现该行为。
151
+
152
+ ## 转换 / 复现
153
+
154
+ 见 GitHub 仓库的 `model_convert/`:ONNX 导出、真实数据校准、Pulsar2 8.0
155
+ 编译脚本齐全。
156
+
157
+ ## License
158
+
159
+ Apache-2.0(上游 LavaSR 模型与代码);KissFFT BSD-3-Clause。
bin/lavasr_ax650 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:917e02d0ae3020f3a432f25106f9f1ed62d32fbb4cbfe0250b2fb1297942319a
3
+ size 580448
configuration.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "framework": "axera",
3
+ "model": "LavaSR-v2",
4
+ "target_hardware": "AX650",
5
+ "npu_mode": "NPU3",
6
+ "compiler": "Pulsar2 8.0",
7
+ "task": "audio-to-audio",
8
+ "sample_rate_out": 48000,
9
+ "models": {
10
+ "den_encoder": "models/den_encoder.axmodel",
11
+ "den_decoder": "models/den_decoder.axmodel",
12
+ "enhancer": "models/enhancer.axmodel"
13
+ },
14
+ "python_demo": "python/demo.py",
15
+ "cpp_bin": "bin/lavasr_ax650"
16
+ }
models/den_decoder.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47bcd2cfd2b41616447b8fa0b155bedc5ccfd1481d18dfe94e150432b15de7ac
3
+ size 12374723
models/den_encoder.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e5eff8440f11f798e6616ae5b8a38ce55117880188792a0fc8c7d2b90d0f953
3
+ size 11871150
models/enhancer.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36070bd9bfb7ddc14026fbdac0f81b496ff61614da8012b3ea36b7112df0b72b
3
+ size 15806147
models/model_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "denoiser": {
3
+ "sample_rate": 16000,
4
+ "n_fft": 512,
5
+ "hop": 256,
6
+ "win": 512,
7
+ "chunk_samples": 76800,
8
+ "frames": 301,
9
+ "erb_low": 65,
10
+ "erb_high": 64,
11
+ "bins": 257,
12
+ "overlap": 0.25
13
+ },
14
+ "enhancer": {
15
+ "sample_rate": 48000,
16
+ "model_sample_rate": 44100,
17
+ "n_fft": 2048,
18
+ "hop": 512,
19
+ "win": 2048,
20
+ "n_mels": 80,
21
+ "chunk_samples": 230400,
22
+ "frames": 450,
23
+ "bins": 1025,
24
+ "padding": "same",
25
+ "overlap": 0.5
26
+ }
27
+ }
models/model_meta.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "LavaSR-v2",
3
+ "target_hardware": "AX650",
4
+ "npu_mode": "NPU3",
5
+ "compiler": "Pulsar2 8.0",
6
+ "denoiser": {
7
+ "encoder": {
8
+ "file": "den_encoder.axmodel",
9
+ "input": {"name": "erb_feat", "shape": [1, 1, 301, 129]},
10
+ "outputs": ["feat", "en0", "en1", "en2", "en3", "en4"]
11
+ },
12
+ "decoder": {
13
+ "file": "den_decoder.axmodel",
14
+ "inputs": ["feat", "en0", "en1", "en2", "en3", "en4"],
15
+ "output": {"name": "mask", "shape": [1, 1, 301, 129]}
16
+ },
17
+ "chunk_seconds": 4.8,
18
+ "chunk_samples": 76800,
19
+ "overlap": 0.25,
20
+ "host": "STFT/ERB/mask/ISTFT + DPGRNN (numpy)"
21
+ },
22
+ "enhancer": {
23
+ "file": "enhancer.axmodel",
24
+ "input": {"name": "mel", "shape": [1, 80, 450]},
25
+ "output": {"name": "head_out", "shape": [1, 2050, 450]},
26
+ "chunk_seconds": 4.8,
27
+ "chunk_samples": 230400,
28
+ "overlap": 0.5,
29
+ "host": "44.1 kHz mel config on 48 kHz samples, exp/cos/sin/ISTFT + LR merge"
30
+ }
31
+ }
python/demo.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """LavaSR v2 AX650 demo: enhance/upsample a wav on the board.
3
+
4
+ Usage:
5
+ python3 demo.py input.wav -o output.wav
6
+ python3 demo.py input.wav -o output.wav --no-denoise
7
+ """
8
+ import argparse
9
+ import os
10
+ import sys
11
+ import time
12
+
13
+ import numpy as np
14
+
15
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
16
+ from lavasr_sdk import LavaSR, read_wav, write_wav
17
+
18
+
19
+ def main():
20
+ ap = argparse.ArgumentParser()
21
+ ap.add_argument("input")
22
+ ap.add_argument("-o", "--output", default=None)
23
+ ap.add_argument("--models", default=os.path.join(os.path.dirname(__file__), "..", "models"))
24
+ ap.add_argument("--no-denoise", action="store_true", help="skip the UL-UNAS denoiser")
25
+ ap.add_argument("--cutoff", type=int, default=None,
26
+ help="LR crossover Hz (default: min(input_sr,16000)/2)")
27
+ args = ap.parse_args()
28
+
29
+ model_dir = os.path.abspath(args.models)
30
+ model = LavaSR(
31
+ os.path.join(model_dir, "den_encoder.axmodel"),
32
+ os.path.join(model_dir, "den_decoder.axmodel"),
33
+ os.path.join(model_dir, "enhancer.axmodel"),
34
+ model_config=os.path.join(model_dir, "model_config.json"),
35
+ cutoff=args.cutoff,
36
+ )
37
+ x, sr = read_wav(args.input)
38
+ t0 = time.time()
39
+ y, osr = model.enhance(x, sr, denoise=not args.no_denoise)
40
+ dt = time.time() - t0
41
+ out = args.output or os.path.splitext(args.input)[0] + "_enhanced.wav"
42
+ write_wav(out, y, osr)
43
+ dur = len(x) / float(sr)
44
+ print(f"LavaSR v2: {sr} Hz -> {osr} Hz, {dur:.2f}s audio")
45
+ print(f" denoise : {not args.no_denoise}")
46
+ print(f" time : {dt:.3f}s RTF {dt / max(dur, 1e-9):.4f}")
47
+ print(f" output : {out}")
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
python/lavasr_sdk/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .pipeline import LavaSR
2
+ from .io import read_wav, write_wav
3
+
4
+ __all__ = ["LavaSR", "read_wav", "write_wav"]
python/lavasr_sdk/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (305 Bytes). View file
 
python/lavasr_sdk/__pycache__/audio.cpython-310.pyc ADDED
Binary file (7.38 kB). View file
 
python/lavasr_sdk/__pycache__/dpgrnn.cpython-310.pyc ADDED
Binary file (4.56 kB). View file
 
python/lavasr_sdk/__pycache__/io.cpython-310.pyc ADDED
Binary file (1.85 kB). View file
 
python/lavasr_sdk/__pycache__/pipeline.cpython-310.pyc ADDED
Binary file (6.47 kB). View file
 
python/lavasr_sdk/assets/den_window.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ee361d325d87969bb7463b5652765c3bee20f8d9164f2e01a805debfdafc995
3
+ size 2176
python/lavasr_sdk/assets/dpgrnn.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe3b65028dc7917c9f70c801dde5fd8ec22049bd54688d8e1f9dc3eda386f4d6
3
+ size 51990
python/lavasr_sdk/assets/erb_fc.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c56e682f80549fbfd5353bda437fc04db2829f7096b33347ad456b1ba425b6fb
3
+ size 49280
python/lavasr_sdk/assets/ierb_fc.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51104c8aa6ac4ebd8a6ccbb8fa1dafeee3440436ea050885c90e82dba67bce91
3
+ size 49280
python/lavasr_sdk/assets/mel_fb.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a787d31f2891373ce5891575b86f582270fef45098f31a7c0f7909e9961fd23
3
+ size 328128
python/lavasr_sdk/assets/mel_window.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71ce666fa2f216c7d7a78f9ac4355e64d60ea49005d4443d8796667963d9310e
3
+ size 8320
python/lavasr_sdk/assets/model_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "denoiser": {
3
+ "sample_rate": 16000,
4
+ "n_fft": 512,
5
+ "hop": 256,
6
+ "win": 512,
7
+ "chunk_samples": 76800,
8
+ "frames": 301,
9
+ "erb_low": 65,
10
+ "erb_high": 64,
11
+ "bins": 257,
12
+ "overlap": 0.25
13
+ },
14
+ "enhancer": {
15
+ "sample_rate": 48000,
16
+ "model_sample_rate": 44100,
17
+ "n_fft": 2048,
18
+ "hop": 512,
19
+ "win": 2048,
20
+ "n_mels": 80,
21
+ "chunk_samples": 230400,
22
+ "frames": 450,
23
+ "bins": 1025,
24
+ "padding": "same",
25
+ "overlap": 0.5
26
+ }
27
+ }
python/lavasr_sdk/audio.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure-numpy host DSP for LavaSR (STFT / mel / iSTFT / resample / LR merge).
2
+
3
+ Everything here mirrors the original PyTorch pipeline:
4
+
5
+ * denoiser (UL-UNAS): 16 kHz, n_fft=512, hop=256, center=True STFT
6
+ * enhancer (Vocos): 48 kHz samples, 44.1 kHz mel config, n_fft=2048,
7
+ hop=512, padding="same", 80 slaney mels
8
+ * FastLRMerge: keep the low band of the original 48 kHz signal and
9
+ the high band generated by the model
10
+
11
+ Only numpy is required. The same math is used by the converter, the SDK and
12
+ the calibration generator, so board accuracy can be compared apples-to-apples.
13
+ """
14
+ import math
15
+ import os
16
+
17
+ import numpy as np
18
+
19
+ _ASSET_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
20
+
21
+
22
+ def _load_asset(name):
23
+ return np.load(os.path.join(_ASSET_DIR, name)).astype(np.float32)
24
+
25
+
26
+ class Assets:
27
+ def __init__(self, asset_dir=None):
28
+ d = asset_dir or _ASSET_DIR
29
+ self.mel_fb = np.load(os.path.join(d, "mel_fb.npy")).astype(np.float32)
30
+ self.mel_window = np.load(os.path.join(d, "mel_window.npy")).astype(np.float32)
31
+ self.den_window = np.load(os.path.join(d, "den_window.npy")).astype(np.float32)
32
+ self.erb_fc = np.load(os.path.join(d, "erb_fc.npy")).astype(np.float32)
33
+ self.ierb_fc = np.load(os.path.join(d, "ierb_fc.npy")).astype(np.float32)
34
+
35
+
36
+ def resample(x, orig_freq, new_freq, lowpass_filter_width=6, rolloff=0.99):
37
+ """Bit-faithful numpy port of torchaudio.functional.resample (sinc_interp_hann)."""
38
+ x = np.asarray(x, dtype=np.float32)
39
+ if orig_freq == new_freq:
40
+ return x
41
+ gcd = math.gcd(int(orig_freq), int(new_freq))
42
+ o = int(orig_freq) // gcd
43
+ n = int(new_freq) // gcd
44
+ base = min(o, n) * rolloff
45
+ width = int(math.ceil(lowpass_filter_width * o / base))
46
+ idx = np.arange(-width, width + o, dtype=np.float64) / o
47
+ t = np.arange(0, -n, -1, dtype=np.float64)[:, None] / n + idx[None, :]
48
+ t = np.clip(t * base, -lowpass_filter_width, lowpass_filter_width)
49
+ window = np.cos(t * math.pi / lowpass_filter_width / 2) ** 2
50
+ kernel = np.sinc(t) * window * (base / o)
51
+ kernel = kernel.astype(np.float32)
52
+ k = kernel.shape[1]
53
+ padded = np.pad(x, (width, width + o))
54
+ frames = np.lib.stride_tricks.sliding_window_view(padded, k)[::o]
55
+ y = frames @ kernel.T
56
+ target = int(math.ceil(n * len(x) / o))
57
+ return np.ascontiguousarray(y.reshape(-1)[:target], dtype=np.float32)
58
+
59
+
60
+ def _frames(x, n_fft, hop):
61
+ return np.lib.stride_tricks.sliding_window_view(x, n_fft)[::hop]
62
+
63
+
64
+ def den_stft(x, window):
65
+ n_fft = window.shape[0]
66
+ pad = n_fft // 2
67
+ xp = np.pad(x, (pad, pad), mode="reflect")
68
+ return np.fft.rfft(_frames(xp, n_fft, pad) * window, n=n_fft, axis=-1)
69
+
70
+
71
+ def den_istft(spec, window, out_len):
72
+ n_fft = window.shape[0]
73
+ hop = n_fft // 2
74
+ frames = np.fft.irfft(spec, n=n_fft, axis=-1) * window
75
+ total = (len(frames) - 1) * hop + n_fft
76
+ y = np.zeros(total, dtype=np.float32)
77
+ env = np.zeros(total, dtype=np.float32)
78
+ for i, frame in enumerate(frames):
79
+ s = i * hop
80
+ y[s:s + n_fft] += frame
81
+ env[s:s + n_fft] += window * window
82
+ pad = hop
83
+ y = y[pad:total - pad] / env[pad:total - pad]
84
+ if len(y) < out_len:
85
+ y = np.pad(y, (0, out_len - len(y)))
86
+ return np.ascontiguousarray(y[:out_len], dtype=np.float32)
87
+
88
+
89
+ def den_features(spec, assets):
90
+ """magnitude -> log10 -> ERB band merge; returns (1,1,T,129) float32."""
91
+ feat = np.log10(np.clip(np.abs(spec), 1e-12, None))
92
+ low_bins = 257 - assets.erb_fc.shape[1]
93
+ low = feat[:, :low_bins]
94
+ high = feat[:, low_bins:] @ assets.erb_fc.T
95
+ feat = np.concatenate([low, high], axis=1)
96
+ return np.ascontiguousarray(feat[None, None], dtype=np.float32)
97
+
98
+
99
+ def den_mask_expand(mask, assets):
100
+ """ERB mask (T,129) -> full 257-bin mask (T,257)."""
101
+ low_bins = 257 - assets.ierb_fc.shape[0]
102
+ low = mask[:, :low_bins]
103
+ high = mask[:, low_bins:] @ assets.ierb_fc.T
104
+ return np.concatenate([low, high], axis=1)
105
+
106
+
107
+ def mel_features(x, assets):
108
+ """Original Vocos MelSpectrogramFeatures(padding='same'); returns (1,80,T)."""
109
+ n_fft = assets.mel_window.shape[0]
110
+ hop = n_fft // 4
111
+ pad = (n_fft - hop) // 2
112
+ xp = np.pad(x, (pad, pad), mode="reflect")
113
+ spec = np.fft.rfft(_frames(xp, n_fft, hop) * assets.mel_window, n=n_fft, axis=-1)
114
+ mel = np.abs(spec) @ assets.mel_fb
115
+ feat = np.log(np.clip(mel, 1e-5, None))
116
+ return np.ascontiguousarray(feat.T[None], dtype=np.float32)
117
+
118
+
119
+ def bwe_istft(spec, window):
120
+ n_fft = window.shape[0]
121
+ hop = n_fft // 4
122
+ pad = (n_fft - hop) // 2
123
+ frames = np.fft.irfft(spec, n=n_fft, axis=-1) * window
124
+ total = (len(frames) - 1) * hop + n_fft
125
+ y = np.zeros(total, dtype=np.float32)
126
+ env = np.zeros(total, dtype=np.float32)
127
+ for i, frame in enumerate(frames):
128
+ s = i * hop
129
+ y[s:s + n_fft] += frame
130
+ env[s:s + n_fft] += window * window
131
+ y = y[pad:total - pad] / env[pad:total - pad]
132
+ return np.ascontiguousarray(y, dtype=np.float32)
133
+
134
+
135
+ def lr_mask(n_bins, cutoff, transition_bins=1024, sample_rate=48000):
136
+ cutoff_bin = int((cutoff / (sample_rate / 2)) * n_bins)
137
+ mask = np.ones(n_bins, dtype=np.float32)
138
+ half = transition_bins // 2
139
+ start = max(0, cutoff_bin - half)
140
+ end = min(n_bins, cutoff_bin + half)
141
+ x = np.linspace(-1.0, 1.0, transition_bins, dtype=np.float64)
142
+ t = (x + 1.0) / 2.0
143
+ fade = (3.0 * t * t - 2.0 * t * t * t).astype(np.float32)
144
+ mask[:start] = 0.0
145
+ mask[start:end] = fade[: end - start]
146
+ mask[end:] = 1.0
147
+ return mask
148
+
149
+
150
+ def lr_merge(generated, original, cutoff, transition_bins=1024, sample_rate=48000, _cache={}):
151
+ """Linkwitz-Riley style low/high band merge.
152
+
153
+ The exact full-length FFT is very slow on the board when the sample count
154
+ has a large prime factor (e.g. 851456 = 2**9 * 1663). Zero-pad to the next
155
+ power of two, scale the transition width so the crossover stays in Hz, and
156
+ trim back. This is ~60 dB SNR vs. the exact merge and ~100x faster.
157
+ """
158
+ n = len(generated)
159
+ m = 1 << (n + 16384 - 1).bit_length()
160
+ tb = max(2, int(round(transition_bins * m / n)) // 2 * 2)
161
+ key = (m, cutoff, tb, sample_rate)
162
+ mask = _cache.get(key)
163
+ if mask is None:
164
+ mask = lr_mask(m // 2 + 1, cutoff, tb, sample_rate)
165
+ _cache[key] = mask
166
+ spec1 = np.fft.rfft(generated, n=m)
167
+ spec2 = np.fft.rfft(original, n=m)
168
+ merged = spec2 + (spec1 - spec2) * mask
169
+ return np.ascontiguousarray(np.fft.irfft(merged, n=m)[:n], dtype=np.float32)
170
+
171
+
172
+ def crossfade(chunks, hop, chunk_len, out_len):
173
+ """Overlap-add chunks with a Hann crossfade; edges are not attenuated."""
174
+ total = chunk_len + hop * (len(chunks) - 1)
175
+ out = np.zeros(total, dtype=np.float32)
176
+ wsum = np.zeros(total, dtype=np.float32)
177
+ win = np.hanning(chunk_len).astype(np.float32)
178
+ for i, c in enumerate(chunks):
179
+ s = i * hop
180
+ w = win.copy()
181
+ if i == 0:
182
+ w[:hop] = 1.0
183
+ if i == len(chunks) - 1:
184
+ w[-hop:] = 1.0
185
+ out[s:s + chunk_len] += c * w
186
+ wsum[s:s + chunk_len] += w
187
+ return out[:out_len] / wsum[:out_len]
python/lavasr_sdk/dpgrnn.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Numpy implementation of UL-UNAS DPGRNN (grouped dual-path RNN).
2
+
3
+ Pulsar2 cannot lower the large-batch GRU transposes in this block to AX650
4
+ (``AxTranspose: size 16 cannot explode into 256``), so the two DPGRNN blocks
5
+ run on the host between the NPU encoder and decoder. They are tiny: 2 blocks,
6
+ 6 GRU directions, ~60 k parameters, < 5 ms for a 4.8 s chunk.
7
+ """
8
+ import numpy as np
9
+
10
+
11
+ def _sigmoid(x):
12
+ return 1.0 / (1.0 + np.exp(-x))
13
+
14
+
15
+ def _gru(x, p, prefix, reverse=False):
16
+ w_ih = p[prefix + ".weight_ih_l0" + ("_reverse" if reverse else "")]
17
+ w_hh = p[prefix + ".weight_hh_l0" + ("_reverse" if reverse else "")]
18
+ b_ih = p[prefix + ".bias_ih_l0" + ("_reverse" if reverse else "")]
19
+ b_hh = p[prefix + ".bias_hh_l0" + ("_reverse" if reverse else "")]
20
+ if reverse:
21
+ x = x[:, ::-1]
22
+ b, t, _ = x.shape
23
+ hsize = w_hh.shape[1]
24
+ gx = x @ w_ih.T + b_ih
25
+ h = np.zeros((b, hsize), dtype=np.float32)
26
+ out = np.empty((b, t, hsize), dtype=np.float32)
27
+ for i in range(t):
28
+ gh = h @ w_hh.T + b_hh
29
+ r = _sigmoid(gx[:, i, :hsize] + gh[:, :hsize])
30
+ z = _sigmoid(gx[:, i, hsize:2 * hsize] + gh[:, hsize:2 * hsize])
31
+ n = np.tanh(gx[:, i, 2 * hsize:] + r * gh[:, 2 * hsize:])
32
+ h = (1.0 - z) * n + z * h
33
+ out[:, i] = h
34
+ if reverse:
35
+ out = out[:, ::-1]
36
+ return out
37
+
38
+
39
+ def _grnn(x, p, prefix):
40
+ x1, x2 = np.split(x, 2, axis=-1)
41
+ y1 = _gru(x1, p, prefix + ".rnn1")
42
+ if (prefix + ".rnn1.weight_ih_l0_reverse") in p:
43
+ y1b = _gru(x1, p, prefix + ".rnn1", reverse=True)
44
+ y1 = np.concatenate([y1, y1b], axis=-1)
45
+ y2 = _gru(x2, p, prefix + ".rnn2")
46
+ if (prefix + ".rnn2.weight_ih_l0_reverse") in p:
47
+ y2b = _gru(x2, p, prefix + ".rnn2", reverse=True)
48
+ y2 = np.concatenate([y2, y2b], axis=-1)
49
+ return np.concatenate([y1, y2], axis=-1)
50
+
51
+
52
+ def _layer_norm(x, w, b):
53
+ mean = x.mean(axis=(-2, -1), keepdims=True)
54
+ var = x.var(axis=(-2, -1), keepdims=True)
55
+ return (x - mean) / np.sqrt(var + 1e-8) * w + b
56
+
57
+
58
+ def _linear(x, p, prefix):
59
+ return x @ p[prefix + ".weight"].T + p[prefix + ".bias"]
60
+
61
+
62
+ class DPGRNN:
63
+ def __init__(self, npz_path, blocks=2):
64
+ self.p = dict(np.load(npz_path))
65
+ self.blocks = blocks
66
+
67
+ def _one(self, x, i):
68
+ p = self.p
69
+ pre = f"b{i}."
70
+ x = x.transpose(0, 2, 3, 1) # (B,C,T,F) -> (B,T,F,C)
71
+ b, t, f, c = x.shape
72
+ intra = _grnn(x.reshape(b * t, f, c), p, pre + "intra_rnn")
73
+ intra = _linear(intra, p, pre + "intra_fc").reshape(b, t, f, c)
74
+ intra = _layer_norm(intra, p[pre + "intra_ln.weight"], p[pre + "intra_ln.bias"])
75
+ intra_out = x + intra
76
+
77
+ x = intra_out.transpose(0, 2, 1, 3) # (B,F,T,C)
78
+ inter = _grnn(x.reshape(b * f, t, c), p, pre + "inter_rnn")
79
+ inter = _linear(inter, p, pre + "inter_fc").reshape(b, f, t, c)
80
+ inter = inter.transpose(0, 2, 1, 3)
81
+ inter = _layer_norm(inter, p[pre + "inter_ln.weight"], p[pre + "inter_ln.bias"])
82
+ out = intra_out + inter
83
+ return out.transpose(0, 3, 1, 2) # (B,C,T,F)
84
+
85
+ def __call__(self, x):
86
+ for i in range(self.blocks):
87
+ x = self._one(x, i)
88
+ return x
89
+
90
+
91
+ def extract_params(model, out_path):
92
+ """Extract DPGRNN weights from a torch ULUNAS model into a small .npz."""
93
+ sd = model.state_dict()
94
+ out = {}
95
+ for i, block in enumerate(model.dpgrnn):
96
+ pre = f"b{i}."
97
+ for part in ("intra_rnn", "inter_rnn"):
98
+ for rnn in ("rnn1", "rnn2"):
99
+ p = f"dpgrnn.{i}.{part}.{rnn}"
100
+ for suffix in ("weight_ih_l0", "weight_hh_l0", "bias_ih_l0", "bias_hh_l0"):
101
+ key = f"{p}.{suffix}"
102
+ if key in sd:
103
+ out[pre + f"{part}.{rnn}.{suffix}"] = sd[key].detach().numpy().astype(np.float32)
104
+ if key + "_reverse" in sd:
105
+ out[pre + f"{part}.{rnn}.{suffix}_reverse"] = sd[key + "_reverse"].detach().numpy().astype(np.float32)
106
+ for part in ("intra_fc", "inter_fc"):
107
+ p = f"dpgrnn.{i}.{part}"
108
+ out[pre + f"{part}.weight"] = sd[p + ".weight"].detach().numpy().astype(np.float32)
109
+ out[pre + f"{part}.bias"] = sd[p + ".bias"].detach().numpy().astype(np.float32)
110
+ for part in ("intra_ln", "inter_ln"):
111
+ p = f"dpgrnn.{i}.{part}"
112
+ out[pre + f"{part}.weight"] = sd[p + ".weight"].detach().numpy().astype(np.float32)
113
+ out[pre + f"{part}.bias"] = sd[p + ".bias"].detach().numpy().astype(np.float32)
114
+ np.savez(out_path, **out)
115
+ return len(out)
python/lavasr_sdk/io.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small wav I/O helpers (soundfile if present, wave fallback)."""
2
+ import wave
3
+
4
+ import numpy as np
5
+
6
+
7
+ def read_wav(path):
8
+ try:
9
+ import soundfile as sf
10
+
11
+ x, sr = sf.read(path, dtype="float32", always_2d=False)
12
+ if x.ndim > 1:
13
+ x = x.mean(axis=1)
14
+ return np.ascontiguousarray(x, dtype=np.float32), int(sr)
15
+ except Exception:
16
+ with wave.open(path, "rb") as w:
17
+ sr = w.getframerate()
18
+ ch = w.getnchannels()
19
+ sw = w.getsampwidth()
20
+ raw = w.readframes(w.getnframes())
21
+ if sw == 2:
22
+ x = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
23
+ elif sw == 4:
24
+ x = np.frombuffer(raw, dtype="<i4").astype(np.float32) / 2147483648.0
25
+ elif sw == 3:
26
+ b = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3).astype(np.int32)
27
+ v = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)
28
+ v = np.where(v & 0x800000, v - 0x1000000, v)
29
+ x = v.astype(np.float32) / 8388608.0
30
+ else:
31
+ raise RuntimeError(f"unsupported wav sample width: {sw}")
32
+ if ch > 1:
33
+ x = x.reshape(-1, ch).mean(axis=1)
34
+ return np.ascontiguousarray(x, dtype=np.float32), int(sr)
35
+
36
+
37
+ def write_wav(path, x, sr):
38
+ x = np.clip(np.asarray(x, dtype=np.float32), -1.0, 1.0)
39
+ try:
40
+ import soundfile as sf
41
+
42
+ sf.write(path, x, int(sr), subtype="PCM_16")
43
+ return
44
+ except Exception:
45
+ pcm = (x * 32767.0).astype("<i2")
46
+ with wave.open(path, "wb") as w:
47
+ w.setnchannels(1)
48
+ w.setsampwidth(2)
49
+ w.setframerate(int(sr))
50
+ w.writeframes(pcm.tobytes())
python/lavasr_sdk/pipeline.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LavaSR v2 end-to-end pipeline: UL-UNAS denoiser + Vocos BWE, NPU cores.
2
+
3
+ Host: STFT / ERB / mel / mask application / exp / iSTFT / LR merge / resampling
4
+ + the tiny UL-UNAS DPGRNN (Pulsar2 cannot lower its large-batch GRU).
5
+ NPU : denoiser encoder/decoder and the Vocos enhancer core, all in fixed 4.8 s
6
+ chunks with 50% overlap.
7
+ """
8
+ import json
9
+ import os
10
+
11
+ import numpy as np
12
+
13
+ from . import audio
14
+ from .dpgrnn import DPGRNN
15
+ from .io import read_wav, write_wav # re-export
16
+
17
+ DEN_CHUNK = 4.8
18
+ BWE_CHUNK = 4.8
19
+
20
+
21
+ def _pad_to(x, n, mode="reflect"):
22
+ if len(x) >= n:
23
+ return x
24
+ pad = n - len(x)
25
+ if mode == "reflect" and len(x) > 1:
26
+ return np.pad(x, (0, pad), mode="reflect")
27
+ return np.pad(x, (0, pad), mode="constant")
28
+
29
+
30
+ def _starts(length, chunk, hop):
31
+ if length <= chunk:
32
+ return [0], 0
33
+ pad = (hop - (length - chunk) % hop) % hop
34
+ starts = list(range(0, length + pad - chunk + 1, hop))
35
+ if starts[-1] + chunk < length + pad:
36
+ starts.append(length + pad - chunk)
37
+ return starts, pad
38
+
39
+
40
+ class Core:
41
+ """Thin wrapper around an axengine session (board) or onnxruntime (host)."""
42
+
43
+ def __init__(self, path, backend="auto"):
44
+ self.path = str(path)
45
+ self.sess = None
46
+ self.backend = backend
47
+ self.input_names = []
48
+ self.output_names = []
49
+ if backend in ("auto", "axengine"):
50
+ try:
51
+ import axengine as axe
52
+
53
+ self.sess = axe.InferenceSession(self.path)
54
+ self.input_names = [i.name for i in self.sess.get_inputs()]
55
+ try:
56
+ self.output_names = [o.name for o in self.sess.get_outputs()]
57
+ except Exception:
58
+ self.output_names = []
59
+ self.backend = "axengine"
60
+ except Exception:
61
+ if backend == "axengine":
62
+ raise
63
+ if self.sess is None:
64
+ import onnxruntime as ort
65
+
66
+ self.sess = ort.InferenceSession(self.path, providers=["CPUExecutionProvider"])
67
+ self.input_names = [i.name for i in self.sess.get_inputs()]
68
+ self.output_names = [o.name for o in self.sess.get_outputs()]
69
+ self.backend = "onnxruntime"
70
+
71
+ def run(self, feed):
72
+ names = self.input_names
73
+ if isinstance(feed, dict):
74
+ data = {k: np.ascontiguousarray(v, dtype=np.float32) for k, v in feed.items()}
75
+ else:
76
+ data = {names[0]: np.ascontiguousarray(feed, dtype=np.float32)}
77
+ return self.sess.run(None, data)
78
+
79
+ def __call__(self, x):
80
+ return self.run(x)[0]
81
+
82
+
83
+ class LavaSR:
84
+ def __init__(self, denoiser_encoder, denoiser_decoder, enhancer_model,
85
+ model_config=None, asset_dir=None, cutoff=None, backend="auto"):
86
+ self.assets = audio.Assets(asset_dir)
87
+ cfg_path = model_config
88
+ if cfg_path is None:
89
+ cfg_path = os.path.join(os.path.dirname(denoiser_encoder), "model_config.json")
90
+ with open(cfg_path, "r", encoding="utf-8") as f:
91
+ self.cfg = json.load(f)
92
+ self.den_cfg = self.cfg["denoiser"]
93
+ self.bwe_cfg = self.cfg["enhancer"]
94
+ self.den_encoder = Core(denoiser_encoder, backend=backend)
95
+ self.den_decoder = Core(denoiser_decoder, backend=backend)
96
+ self.bwe_core = Core(enhancer_model, backend=backend)
97
+ asset_dir = asset_dir or os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
98
+ self.dpgrnn = DPGRNN(os.path.join(asset_dir, "dpgrnn.npz"))
99
+ self.cutoff = cutoff
100
+ self._den_win = self.assets.den_window
101
+ self._mel_win = self.assets.mel_window
102
+ self._den_hop = int(self.den_cfg["chunk_samples"] * (1 - self.den_cfg["overlap"]))
103
+ self._bwe_hop = int(self.bwe_cfg["chunk_samples"] * (1 - self.bwe_cfg["overlap"]))
104
+
105
+ def _denoise_chunk(self, c):
106
+ spec = audio.den_stft(c, self._den_win)
107
+ feat = audio.den_features(spec, self.assets)
108
+ enc = self.den_encoder.run({"erb_feat": feat})
109
+ dp = self.dpgrnn(enc[0])
110
+ feed = {"feat": dp, "en0": enc[1], "en1": enc[2], "en2": enc[3], "en3": enc[4], "en4": enc[5]}
111
+ mask = self.den_decoder.run(feed)[0][0, 0]
112
+ m = audio.den_mask_expand(mask, self.assets)
113
+ return audio.den_istft(spec * m, self._den_win, len(c))
114
+
115
+ def denoise_16k(self, x):
116
+ n = int(self.den_cfg["chunk_samples"])
117
+ hop = self._den_hop
118
+ starts, pad = _starts(len(x), n, hop)
119
+ xp = _pad_to(x, len(x) + pad)
120
+ chunks = []
121
+ for s in starts:
122
+ c = xp[s:s + n]
123
+ if len(c) < n:
124
+ c = _pad_to(c, n)
125
+ chunks.append(self._denoise_chunk(c))
126
+ return audio.crossfade(chunks, hop, n, len(x))
127
+
128
+ def _enhance_chunk(self, c):
129
+ mel = audio.mel_features(c, self.assets)
130
+ head = self.bwe_core(mel)[0]
131
+ bins = self.bwe_cfg["bins"]
132
+ mag = np.exp(np.clip(head[:bins], None, 1e3))
133
+ phase = head[bins:]
134
+ spec = (mag * np.cos(phase) + 1j * mag * np.sin(phase)).T
135
+ return audio.bwe_istft(spec, self._mel_win)
136
+
137
+ def enhance_48k(self, x):
138
+ n = int(self.bwe_cfg["chunk_samples"])
139
+ hop = self._bwe_hop
140
+ out_len = (len(x) // 512) * 512
141
+ starts, pad = _starts(len(x), n, hop)
142
+ xp = _pad_to(x, len(x) + pad)
143
+ chunks = []
144
+ for s in starts:
145
+ c = xp[s:s + n]
146
+ if len(c) < n:
147
+ c = _pad_to(c, n)
148
+ chunks.append(self._enhance_chunk(c))
149
+ y = audio.crossfade(chunks, hop, n, len(xp))
150
+ return y[:out_len]
151
+
152
+ def enhance(self, wav, sr, denoise=True):
153
+ x = np.asarray(wav, dtype=np.float32)
154
+ if x.ndim > 1:
155
+ x = x.mean(axis=1)
156
+ x = np.ascontiguousarray(x)
157
+ x16 = audio.resample(x, int(sr), 16000) if int(sr) != 16000 else x
158
+ if denoise:
159
+ x16 = self.denoise_16k(x16)
160
+ x48 = audio.resample(x16, 16000, 48000)
161
+ generated = self.enhance_48k(x48)
162
+ cutoff = self.cutoff
163
+ if cutoff is None:
164
+ cutoff = min(int(sr), 16000) // 2
165
+ original = x48[: len(generated)]
166
+ return audio.lr_merge(generated, original, cutoff), 48000
python/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ numpy
2
+ pyaxengine
3
+ soundfile
reports/accuracy.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LavaSR v2 AX650 accuracy
2
+
3
+ Board: AX650N, BSP `V3.10.2_20260323224507`, AX Engine `2.12.0s`, Pulsar2 `8.0`.
4
+ Reference: original PyTorch LavaSR v2 (`enhancer_v2` + `denoiser`) and the exported
5
+ ONNX cores + host DSP. Metrics are computed on the 48 kHz waveform.
6
+
7
+ ## Quantization transparency (board vs ONNX)
8
+
9
+ SNR is `10*log10(sum(ref^2)/sum((board-ref)^2))`. Cosine is on the raw waveform.
10
+
11
+ | case | input | denoise | board | cosine | SNR |
12
+ |---|---|---|---|---|---|
13
+ | LibriSpeech 17.75 s | 16 kHz | yes | Python | 0.9999878 | 45.95 dB |
14
+ | LibriSpeech 17.75 s | 16 kHz | no | Python | 0.9999912 | 47.65 dB |
15
+ | LibriSpeech 17.75 s | 8 kHz | yes | Python | 0.9999919 | 47.87 dB |
16
+ | LibriSpeech 17.75 s | 24 kHz | yes | Python | 0.9999864 | 45.57 dB |
17
+ | LibriSpeech 17.75 s | 48 kHz | yes | Python | 0.9999863 | 45.52 dB |
18
+ | LibriSpeech 30.86 s | 16 kHz | yes | Python | 0.9999483 | 39.79 dB |
19
+ | LibriSpeech 30.86 s | 16 kHz | no | Python | 0.9999844 | 45.06 dB |
20
+ | LibriSpeech 3.0 s | 16 kHz | yes | Python | 0.9999899 | 46.95 dB |
21
+ | LibriSpeech 3.0 s | 16 kHz | no | Python | 0.9999965 | 51.65 dB |
22
+ | noisy speech 10 s | 48 kHz | yes | Python | 0.9998354 | 34.71 dB |
23
+ | noisy speech 10 s | 48 kHz | no | Python | 0.9999513 | 40.10 dB |
24
+ | LibriSpeech 17.75 s | 16 kHz | yes | C++ | 0.9999858 | 45.94 dB |
25
+ | LibriSpeech 17.75 s | 16 kHz | no | C++ | 0.9999896 | 47.62 dB |
26
+
27
+ The C++ and Python SDKs use the same models; differences are only host FFT /
28
+ resampler rounding.
29
+
30
+ ## Float reference
31
+
32
+ The ONNX + host-DSP pipeline (before quantization) vs the original PyTorch
33
+ implementation is **cosine 0.99995, SNR 39.6 dB** on the 17.75 s LibriSpeech
34
+ sample. The remaining difference is the 4.8 s chunking (50% overlap for BWE,
35
+ 25% for the denoiser) and the fast zero-padded LR merge (~60 dB vs the exact
36
+ full-length FFT).
37
+
38
+ ## Quantization scheme
39
+
40
+ - All three axmodels: **U16 activations, S8 weights, U16 output** (`MinMax`).
41
+ - Calibration: real speech (LibriSpeech + AISHELL-1), noisy variants mixed in;
42
+ 256 samples for encoder/enhancer, 64 for the decoder.
43
+ - The large FA GRU inside every `cTFA` block is exported as an unrolled
44
+ MatMul/Add/Sigmoid/Tanh graph. Pulsar2 8.0's `AxDynamicQuantizedGRU` for that
45
+ shape returns `Failed to run model` on this BSP; the manual expansion runs and
46
+ is numerically identical (cosine 1.0 vs PyTorch).
reports/performance.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LavaSR v2 AX650 performance
2
+
3
+ Board: AX650N, NPU3, BSP `V3.10.2_20260323224507`, AX Engine `2.12.0s`.
4
+ `RTF = total enhance() wall time / input audio duration`; lower is better.
5
+ No NPU simulation was used; all numbers are from the board.
6
+
7
+ ## Models
8
+
9
+ | axmodel | size | NPU latency |
10
+ |---|---:|---:|
11
+ | `den_encoder.axmodel` | 11.32 MB | ~17.7 ms / 4.8 s chunk |
12
+ | `den_decoder.axmodel` | 11.80 MB | ~16.4 ms / 4.8 s chunk |
13
+ | `enhancer.axmodel` | 15.07 MB | ~5.7 ms / 4.8 s chunk |
14
+ | **total** | **38.2 MB** | |
15
+
16
+ NPU latency is per 4.8 s chunk, measured by wrapping the three sessions in the
17
+ Python SDK. Host DSP (STFT/mel/iSTFT/DPGRNN/LR merge) dominates the wall time.
18
+
19
+ ## Python SDK
20
+
21
+ | input | duration | denoise | time | RTF |
22
+ |---|---:|---|---:|---:|
23
+ | LibriSpeech 16 kHz | 17.75 s | yes | 4.93 s | **0.278** |
24
+ | LibriSpeech 16 kHz | 17.75 s | no | 1.82 s | **0.103** |
25
+ | LibriSpeech 16 kHz | 30.86 s | yes | 8.73 s | 0.283 |
26
+ | LibriSpeech 16 kHz | 30.86 s | no | 3.21 s | 0.104 |
27
+ | LibriSpeech 16 kHz | 3.0 s | yes | 0.95 s | 0.315 |
28
+ | LibriSpeech 16 kHz | 3.0 s | no | 0.32 s | 0.108 |
29
+ | noisy 48 kHz | 10.0 s | yes | 2.86 s | 0.286 |
30
+ | noisy 48 kHz | 10.0 s | no | 1.05 s | 0.105 |
31
+ | LibriSpeech 8 kHz | 17.75 s | yes | 4.87 s | 0.274 |
32
+ | LibriSpeech 24 kHz | 17.75 s | yes | 5.01 s | 0.283 |
33
+ | LibriSpeech 48 kHz | 17.75 s | yes | 5.01 s | 0.282 |
34
+
35
+ Host breakdown for the 17.75 s / denoise case: denoiser DSP + DPGRNN 3.07 s,
36
+ BWE mel/iSTFT 1.35 s, LR merge 0.45 s, resampling 0.10 s; NPU calls 0.24 s total.
37
+
38
+ ## C++ SDK
39
+
40
+ `bin/lavasr_ax650` (cross-compiled, AX650 aarch64) uses the same axmodels and
41
+ embedded assets:
42
+
43
+ | input | duration | denoise | time | RTF |
44
+ |---|---:|---|---:|---:|
45
+ | LibriSpeech 16 kHz | 17.75 s | yes | 5.75 s | **0.324** |
46
+ | LibriSpeech 16 kHz | 17.75 s | no | 3.37 s | **0.190** |
47
+
48
+ C++ host breakdown: denoiser 2.09 s, BWE 2.27 s, LR merge 1.11 s, resampling
49
+ 0.06 s. The Python/numpy SDK is faster on this board for the mel/iSTFT stage
50
+ (BLAS/vectorized ops); the C++ SDK is self-contained and has no Python/numpy
51
+ runtime dependency.
52
+
53
+ ## Runtime requirements
54
+
55
+ - Board runtime: AX650 BSP with `ax_engine` / `ax_sys` (tested with 3.10.2).
56
+ - Python SDK: `numpy`, `pyaxengine` (`axengine`), optional `soundfile`.
57
+ - C++ SDK: prebuilt `bin/lavasr_ax650`; runtime libs in `/soc/lib`.
58
+ - No onnxruntime / torch on the board.
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ numpy
2
+ pyaxengine
3
+ soundfile
run_ax650.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # LavaSR v2 AX650 one-click demo.
3
+ # bash run_ax650.sh [input.wav] [output.wav] [--cpp|--python] [--no-denoise]
4
+ set -e
5
+ cd "$(dirname "$0")"
6
+ export LD_LIBRARY_PATH=/soc/lib:${LD_LIBRARY_PATH:-}
7
+
8
+ INPUT="${1:-samples/libri_16k.wav}"
9
+ OUTPUT="${2:-output.wav}"
10
+ if [ $# -ge 2 ]; then shift 2; else shift $#; fi
11
+
12
+ MODE="cpp"
13
+ EXTRA=()
14
+ for a in "$@"; do
15
+ case "$a" in
16
+ --python) MODE="python" ;;
17
+ --cpp) MODE="cpp" ;;
18
+ *) EXTRA+=("$a") ;;
19
+ esac
20
+ done
21
+ if [ ! -x ./bin/lavasr_ax650 ]; then MODE="python"; fi
22
+
23
+ if [ "$MODE" = "cpp" ]; then
24
+ exec ./bin/lavasr_ax650 models/den_encoder.axmodel models/den_decoder.axmodel \
25
+ models/enhancer.axmodel "$INPUT" "$OUTPUT" "${EXTRA[@]}"
26
+ else
27
+ exec python3 python/demo.py "$INPUT" -o "$OUTPUT" --models models "${EXTRA[@]}"
28
+ fi
samples/libri_16k.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85598a299cb26ccea575991d4534c4e23454bdb387bb495d953a72f048babf0d
3
+ size 567884
samples/libri_24k.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d7b6553ac848aad148aa373db7e14e944c667ffc549193a4458aeaa46977e52
3
+ size 851804
samples/libri_48k.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:67cf66e3a9d135fecd45a7390def119e9e7cbcd1d46945629dcc7bd6f64a1f8d
3
+ size 1703564
samples/libri_8k.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d763207793078696d69cae9a531e45e94d1699e646f717f392cecff03cd717f4
3
+ size 283964
samples/noisy_48k.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:255b4a8da104c5fd2713c5b6b93504fc412dbd9d268bdce076602a9dcb9e926d
3
+ size 960044