CuteTTS.AXERA: AX650 NPU zero-shot TTS (U16)
Browse filesFiles changed (24)
- .gitattributes+2
- README.md+130-123
- bin/cutetts_ax650Added
- config.jsonAdded+1
- models/assets/tokenizer.binAdded+3
- models/assets/vae_stream.jsonAdded+94
- models/dit_step.axmodel+2-2
- models/lm_decode.axmodel+2-2
- models/lm_prefill.axmodel+2-2
- models/locenc_step.axmodel+2-2
- models/spk_body.axmodel+2-2
- models/vae_dec_l128.axmodel+2-2
- models/vae_dec_l256.axmodel+2-2
- models/vae_dec_l64.axmodel+2-2
- models/vae_dec_stream.axmodelAdded+3
- models/vae_enc.axmodel+2-2
- python/cutetts_ax/tts.py+233-21
- python/demo.py+27-1
- run_ax650.sh+19-4
- samples/listen/en_default.wav+2-2
- samples/listen/en_long.wav+2-2
- samples/listen/en_other_voice.wav+2-2
- samples/listen/en_xlong.wavAdded+3
- samples/listen/zh_default.wav+2-2
48 unmodified lines49505148 unmodified linessamples/reference.wav filter=lfs diff=lfs merge=lfs -textsamples/reference_en.wav filter=lfs diff=lfs merge=lfs -textsamples/reference_zh.wav filter=lfs diff=lfs merge=lfs -text48 unmodified lines495051525348 unmodified linessamples/reference.wav filter=lfs diff=lfs merge=lfs -textsamples/reference_en.wav filter=lfs diff=lfs merge=lfs -textsamples/reference_zh.wav filter=lfs diff=lfs merge=lfs -textmodels/vae_dec_stream.axmodel filter=lfs diff=lfs merge=lfs -textsamples/listen/en_xlong.wav filter=lfs diff=lfs merge=lfs -text
123458 unmodified lines1415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180---license: apache-2.0language:- en- zh8 unmodified lines- voice-cloning- zero-shot- cutettslibrary_name: axerapipeline_tag: text-to-speechbase_model: OPPOer/CuteTTS-distill---# CuteTTS.AXERA**AX650 上的 0.2B 连续隐变量自回归 TTS:zero-shot 音色克隆,24 kHz 输出,全流程 NPU 推理。**  - HuggingFace(预编译模型 + SDK): https://huggingface.co/HY-2012/CuteTTS.AXERA- GitHub(源码 + 转换脚本): https://github.com/ZY-2012/CuteTTS.AXERA- 上游模型: https://huggingface.co/OPPOer/CuteTTS-distill## 模型简介CuteTTS 用"连续 latent 自回归 + 扩散头 + 因果 VAE"代替离散 codec token:LM 每步预测一个 token,扩散头生成 2 帧 64 维 latent(≈160 ms 音频 @ 24 kHz),VAE 解码成波形。本仓库量化的是 **CuteTTS-distill**(4 步蒸馏扩散头)。AX650 上拆成 7 类子图,全部跑在 NPU:| 子图 | 说明 ||---|---|| `vae_enc` | 参考音频 → 64 维 latent(5 s 静态输入) || `spk_body` | log-mel → ECAPA 主干 + attentive pooling(BN/linear/L2 在 host) || `locenc_step` | 单 patch latent → LM embedding || `lm_prefill` | 7 层 Qwen3 前缀(256 token,输出 KV cache) || `lm_decode` | 单 token 解码(384 长度 KV cache 输入) || `dit_step` | 单步 Euler 速度场(host 循环 4 步) || `vae_dec_l{64,128,256}` | latent → 24 kHz 波形(按长度分桶) |## 快速开始(AX650 板端)本仓库即完整包(`models/` + `python/` + `samples/`),下载后在包根目录运行:```bashbash setup.sh# 默认文本 + 默认参考音色bash run_ax650.sh# 指定文本 / 参考音频 / 输出bash run_ax650.sh "今天天气很好,我们一起去公园散步吧。" samples/reference.wav zh.wav# 调整 CFG 强度、随机种子、最长 patch 数(每个 patch ≈160 ms)bash run_ax650.sh "Hello from AX650!" samples/reference.wav en.wav --cfg 2.0 --seed 42 --max-new 128```Python SDK:```pythonimport sys; sys.path.insert(0, "python")from cutetts_ax import CuteTTSAXimport cutetts_ax.audio as Atts = CuteTTSAX("models", "models/assets")wav = tts.synthesize("The voice generated by this model sounds amazing!","samples/reference.wav")A.write_wav("out.wav", wav, tts.sr)print(tts.last_timing)```依赖:`numpy`、`sentencepiece`、`axengine`(AX650 BSP 镜像自带)。## 结果| 用例 | 文本 | 参考音色 | 输出 ||---|---|---|---|| en_default | The voice generated by this model sounds … | 默认英文参考音色 | [▶](samples/listen/en_default.wav) || en_long | Hello, this is a test of the CuteTTS text… | 长句(17 词) | [▶](samples/listen/en_long.wav) || zh_default | 今天天气很好,我们一起去公园散步吧。 | 中文,默认参考音色 | [▶](samples/listen/zh_default.wav) || en_other_voice | Quick brown fox jumps over the lazy dog. | 另一段参考音色(en_16k) | [▶](samples/listen/en_other_voice.wav) |ASR 校验(板端 SenseVoice):| 用例 | 目标文本 | 板端 ASR 结果 ||---|---|---|| en_default | The voice generated by this model sounds amazing! | The voice generated by this model sounds amazing. || en_long | Hello, this is a test of the CuteTTS text to speech system running on the AX650 neural processing unit. | Hello, this is a test of the Q TTS text to speech system starting on on the x 650 neuro processingces in yet. || zh_default | 今天天气很好,我们一起去公园散步吧。 | 今天天气很好,我们一起去公园散步吧。 || en_other_voice | Quick brown fox jumps over the lazy dog. | Goodick brown fox jumps off over the lazy dog. |## 精度(板端 vs fp32 ONNX)| 子图 | cosine | SNR (dB) ||---|---|---|| vae_enc | 0.9700 | 12.0 || spk_body stats | 0.9996 | 30.8 || speaker embedding | 0.9966 | 21.7 || locenc_step | 0.9994 | 28.3 || dit 4-step latent | 0.9849 | 14.9 || lm_prefill stop | 0.9258 | 7.4 || lm_prefill k0 | 0.9980 | 23.9 || lm_prefill v0 | 0.9969 | 22.0 || lm_prefill k1 | 0.9925 | 18.2 || lm_prefill v1 | 0.9648 | 11.6 || lm_prefill k2 | 0.9849 | 15.2 || lm_prefill v2 | 0.9413 | 9.4 || lm_prefill k3 | 0.9855 | 15.3 || lm_prefill v3 | 0.9272 | 8.5 || lm_prefill k4 | 0.9806 | 14.1 || lm_prefill v4 | 0.9116 | 7.6 || lm_prefill k5 | 0.9901 | 17.1 || lm_prefill v5 | 0.9057 | 7.2 || lm_prefill k6 | 0.9752 | 13.0 || lm_prefill v6 | 0.9243 | 8.3 || lm_prefill hidden(last) | 0.9750 | 12.8 || lm_decode hidden | 0.9905 | 16.2 || lm_decode stop | 0.9990 | 26.3 || vae_dec_l64 | 0.9774 | 13.5 || vae_dec_l128 | 0.9557 | 10.6 || vae_dec_l256 | 0.8841 | 6.6 |说明:LM 是 7 层 Qwen3 + 连续 latent 自回归,量化误差会在 20~40 步的 AR 循环里累积,长句(>10 s)偶有咬字退化;短句 ASR 逐词一致。## 推理速度en_default 用例(3.20 s 音频、20 patch):| 阶段 | 耗时 ||---|---|| VAE encoder(参考音频) | 430.5 ms || Speaker encoder | 76.2 ms || LocEnc + prompt 组装 | 44.3 ms || LM prefill(≈115 token) | 66.7 ms || AR 循环(含 DiT + LM decode) | 794.8 ms || └ DiT 4 步 | 333.4 ms || └ LM decode | 415.3 ms || VAE decoder | 300.9 ms || **端到端** | 1891.0 ms || 生成音频 | 3.20 s || **实时率(音频/耗时)** | **1.69×** |## 文件说明```models/ 预编译 axmodelmodels/assets/ embed_tokens.npy / lm_speaker_proj.npy / mel 滤波器 / tokenizer / config.jsonpython/cutetts_ax/ numpy-only SDK(audio.py, tts.py)python/demo.py 命令行入口samples/reference.wav 参考音色samples/listen/*.wav 板端生成样例```## 模型转换源码与完整转换脚本见 GitHub: https://github.com/ZY-2012/CuteTTS.AXERA## 已知限制- 参考音频最长 **5 s**(`vae_enc` 静态输入 120000 采样),更长的参考会被截断- 单次生成最长 **20.5 s**(VAE 解码 256 latent 桶),超过会报错- LM 是 7 层 Qwen3 + 连续 latent 自回归,U16 量化误差会在 20~40 步 AR 中累积,**长句(>10 s)ASR 可能有个别词退化**;短句逐词一致- 只提供 Python SDK(numpy + pyaxengine),暂无 C++ 版本- 建议把 `models/` 放在板载 eMMC/SD 上:从网络盘(NFS)冷读 686 MB 模型约需 25 s,本地盘首次加载约 2 s## LicenseApache-2.0。上游 CuteTTS(OPPO/Fudan)及 Qwen3、DAC 组件遵循其各自许可证,见 `NOTICE`。12345678 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187---library_name: axerapipeline_tag: text-to-speechbase_model: OPPOer/CuteTTS-distilllanguage:- en- zh8 unmodified lines- voice-cloning- zero-shot- cutetts- python- cpp---# CuteTTS.AXERA**AX650 上的 0.2B 连续隐变量自回归 TTS:zero-shot 音色克隆 · 24 kHz · 9 个 axmodel 全 NPU 推理**> **真流式(音频级,非切句)**:AR 循环不停,VAE 用带卷积状态的解码器逐 patch 输出,> **每 160 ms 一包、首包 TTFT 0.6~0.8 s**(缓存参考音色后 0.18 s);同时保留非流式整句模式。> C++ 流式 RTF 0.39~0.54 / 非流式 0.31~0.51。      [](https://github.com/ZY-2012/CuteTTS.AXERA)- HuggingFace: https://huggingface.co/HY-2012/CuteTTS.AXERA- GitHub(源码 + 转换脚本 + C++): https://github.com/ZY-2012/CuteTTS.AXERA- 原始模型: https://huggingface.co/OPPOer/CuteTTS-distill## 目录- [模型简介](#intro)- [模型转换](#convert)- [支持平台](#platform)- [上板部署](#deploy)- [快速开始](#quickstart)- [结果](#results)- [推理速度](#speed)- [参考](#refs)<a id="intro"></a>## 模型简介CuteTTS 用「连续 latent 自回归 + 扩散头 + 因果 VAE」代替离散 codec token:LM 每步预测一个 token,4 步蒸馏扩散头生成 2 帧 64 维 latent(≈160 ms 音频),VAE 解码成 24 kHz 波形。本仓库量化的是 **CuteTTS-distill**。| 子图 | 作用 ||---|---|| `vae_enc` | 参考音频 → 64 维 latent(5 s) || `spk_body` | log-mel → 音色向量(ECAPA 主干,BN/linear 在 host) || `locenc_step` | latent patch → LM embedding || `lm_prefill` | 7 层 Qwen3 前缀(256 token,输出 KV cache) || `lm_decode` | 单 token 解码(384 长度 KV cache) || `dit_step` | 单步 Euler 速度场(host 循环 4 步) || `vae_dec_l{64,128,256}` | latent → 24 kHz 波形(按长度分桶) |<a id="convert"></a>## 模型转换For those who are interested in model conversion, you can try to export axmodel through:- [The repo of AXera Platform](https://github.com/AXERA-TECH), where you can get the detailed guide.- [Pulsar2 Link, How to Convert ONNX to axmodel](https://pulsar2-docs.readthedocs.io/en/latest/pulsar2/introduction.html)完整转换脚本(ONNX 导出 / 真实语音校准 / Pulsar2 配置):[ZY-2012/CuteTTS.AXERA/model_convert](https://github.com/ZY-2012/CuteTTS.AXERA/tree/main/model_convert)<a id="platform"></a>## 支持平台- AX650N / AX8850- [M4N-Dock(爱芯派 Pro)](https://wiki.sipeed.com/hardware/zh/maixIV/m4ndock/m4ndock.html)- [AI Pyramid](https://docs.m5stack.com/zh_CN/ai_hardware/AI_Pyramid-Pro)- [M.2 Accelerator Card](https://docs.m5stack.com/zh_CN/ai_hardware/LLM-8850_Card)<a id="deploy"></a>## 上板部署- 以 root 权限登陆 AX650N 板卡设备- 已验证设备:AX650N DEMO Board### 目录结构```textCuteTTS.AXERA/├── bin/cutetts_ax650 # C++ 推理可执行文件├── models/│ ├── *.axmodel # 9 个子图│ └── assets/ # embedding 表、mel 滤波器、BN/linear、tokenizer├── python/│ ├── cutetts_ax/ # numpy-only SDK│ └── demo.py├── samples/�� ├── reference*.wav # 参考音色│ └── listen/*.wav # 板端生成样例├── config.json├── run_ax650.sh # 一键脚本(默认 C++)└── setup.sh```<a id="quickstart"></a>## 快速开始(AX650 板端)下载整仓库到板端,在包根目录运行:```bashbash setup.sh# C++(默认,最快)bash run_ax650.sh "The voice generated by this model sounds amazing!" samples/reference.wav out.wav# 真流式(每 160 ms 一包,首包 ≈0.7 s)bash run_ax650.sh "The voice generated by this model sounds amazing!" samples/reference.wav out.wav --stream# Python SDK(流式 / 非流式)bash run_ax650.sh "今天天气很好,我们一起去公园散步吧。" samples/reference.wav zh.wav --python --stream# 调 CFG / 随机种子 / 最长 patch 数(1 patch ≈ 160 ms)bash run_ax650.sh "Hello from AX650!" samples/reference.wav en.wav --cfg 2.0 --seed 42 --max-new 128```参考音频 ≤ 5 s;单次生成 ≤ 20.5 s;输出 24 kHz 单声道。<a id="results"></a>## 结果| 用例 | 文本 | 参考音色 | 输出 | 板端 ASR ||---|---|---|---|---|| en_default | The voice generated by this model sounds … | 默认英文参考音色 | [▶](samples/listen/en_default.wav) | The voice generated by this model sounds amazing. || en_long | Hello, this is a test of the CuteTTS text… | 长句(17 词) | [▶](samples/listen/en_long.wav) | Hello, this is a test of the Q TTs test to speech system running on the8650 neural processing. || zh_default | 今天天气很好,我们一起去公园散步吧。 | 中文,默认参考音色 | [▶](samples/listen/zh_default.wav) | 今天天气很好,我们一起去公园散步吧。 || en_other_voice | Quick brown fox jumps over the lazy dog. | 另一段参考音色(en_16k) | [▶](samples/listen/en_other_voice.wav) | Quick brown fox jumps over the lazy dog. || en_xlong | The quick brown fox jumps over the lazy d… | 默认英文参考音色(10.6 s,走 256 桶) | [▶](samples/listen/en_xlong.wav) | …carries a scent of fresh flowers across across the quiet meadow… morning song. |<a id="speed"></a>## 推理速度**流式 vs 非流式(同一组 axmodel):**| 模式 | 实现 | 音频 | TTFT | 总耗时 | RTF | 出包间隔 ||---|---|---|---|---|---|---|| **流式** | C++ | 3.04 s | **0.69 s** | 1.64 s | 0.541 | **160 ms** || **流式** | Python | 2.88 s | **0.79 s** | 1.90 s | 0.660 | **160 ms** || 非流式 | C++ | 3.04 s | 1.54 s | 1.54 s | **0.508** | — || 非流式 | Python | 2.88 s | 1.61 s | 1.61 s | 0.560 | — |10.2 s 长句:流式 C++ `TTFT 0.59 s / 总 3.95 s / RTF 0.386`,Python `TTFT 0.80 s / 总 5.06 s / RTF 0.479`。参考音色缓存后(同一参考音频反复合成),Python TTFT 可低至 **0.18 s**。**指标定义**- **RTF(Real-Time Factor)= 总耗时 / 音频时长**,越小越好;`RTF < 1` 表示合成快于实时。- **TTFT(Time To First Token,首包时延)= 发起请求到拿到第一段音频的时间**。流式下 = 参考特征提取 + 1 个 AR patch + 流式解码;非流式下 = 整句端到端耗时。**流式实现(真流式,不是切句)**- AR 循环只跑一次、latent 连续产生;`vae_dec_stream.axmodel` 把解码器 31 个因果卷积的左侧上下文做成 18 个显式状态张量(共 0.46 MB),每来 2 个 latent(160 ms)解码一次并输出。- 与离线解码对比:本机 fp32 下逐样本一致(cos 1.0000000);板端量化后 SNR 11.3 dB、ASR 逐词一致、底噪指标与离线持平。- `--windowed` 可切到「128-latent 滑动窗」精确模式(与离线逐样本一致,TTFT 1.3 s)。## 参考- 原始模型:https://huggingface.co/OPPOer/CuteTTS-distill- CuteTTS 官方代码 / 论文:https://github.com/OPPO-Mente-Lab/CuteTTS- Pulsar2 文档:https://pulsar2-docs.readthedocs.io- AXERA 开源仓库:https://github.com/AXERA-TECH## LicenseApache-2.0。上游 CuteTTS(OPPO/Fudan)及 Qwen3、DAC 组件遵循其各自许可证。
1{}123version https://git-lfs.github.com/spec/v1oid sha256:7fb5c39e6aae7a1b6000b218314e77053b6decdad126b43f7808e581642e4e90size 18316012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394{ "states": [ [ 1, 64, 6 ], [ 1, 1536, 1 ], [ 1, 768, 6 ], [ 1, 768, 18 ], [ 1, 768, 54 ], [ 1, 768, 1 ], [ 1, 384, 6 ], [ 1, 384, 18 ], [ 1, 384, 54 ], [ 1, 384, 1 ], [ 1, 192, 6 ], [ 1, 192, 18 ], [ 1, 192, 54 ], [ 1, 192, 1 ], [ 1, 96, 6 ], [ 1, 96, 18 ], [ 1, 96, 54 ], [ 1, 96, 6 ] ]}123version https://git-lfs.github.com/spec/v1oid sha256:9aad0a04bdcdf54d15b1e4fbfd8f56c06643d5a6a2bca7a661b3fd72cd1eea41size 76663899123version https://git-lfs.github.com/spec/v1oid sha256:572152b3ca424e09e8c8d59b5df2b2dcf9565c16177d6edbfccd8d015d50d2e2size 77699201
123version https://git-lfs.github.com/spec/v1oid sha256:1f69ff3b4e2ba32479fd2ae1e339a207540df222960d7c0262cd3caafd00ee58size 116868782123version https://git-lfs.github.com/spec/v1oid sha256:368627579337a7e947a7d0940f0d32ae9bac8f3ace98b1b4c2331fadbd97ec63size 119012602
123version https://git-lfs.github.com/spec/v1oid sha256:9252f84de5632e828f047a3003288e0a799f6dbec6d78c09067d53c5524bd1acsize 117243411123version https://git-lfs.github.com/spec/v1oid sha256:9b7b988746d14b645f755f8f702b336f20c6f5d1af198894287dd676d89b17a4size 119764435
123version https://git-lfs.github.com/spec/v1oid sha256:5d2cba31a03d452d0dff2c6169831727d7656aff1351069fe38fc302e21c659csize 32925690123version https://git-lfs.github.com/spec/v1oid sha256:852a9cfa4e76114700e52f252c6d3934ac06b27c1f14c3f8eacfe547c5f1790bsize 33403098
123version https://git-lfs.github.com/spec/v1oid sha256:32d42b497bcd3b606921ba1df21bdd5494165c5bc91c63930690b41b2282d48csize 28283929123version https://git-lfs.github.com/spec/v1oid sha256:ac983c08f59924bc1637c4d9486838be030b234112556e481b864a9c44504063size 28319833
123version https://git-lfs.github.com/spec/v1oid sha256:5ca1b7602a9fadf1102128745d26b79030d222c5655ca89d4363bb5b5767deddsize 59674076123version https://git-lfs.github.com/spec/v1oid sha256:a64418d67d4edd5fb3b93307ce3ada414656ad4d1606eb3b7de67fe11cf96e76size 60798124
123version https://git-lfs.github.com/spec/v1oid sha256:aed461c95ef85b1e3a829d20fc936b644c56ebf58dd3c535ad37f3b8bfb94aefsize 65808716123version https://git-lfs.github.com/spec/v1oid sha256:61b4edf0a672bb054aa2abd351d9d8ec0b3a8779ae2c4a9d1a879035723fab0fsize 67195004
123version https://git-lfs.github.com/spec/v1oid sha256:112d7c7fb0f07dc3f466826b079eacead58b6ce6e9fc4175b54b9ec5f2154dfcsize 56453122123version https://git-lfs.github.com/spec/v1oid sha256:3f3c8366690c1ea3eb02b517d43c9012cea7f998cc0fd599b42b5def7134b7e9size 57003154
123version https://git-lfs.github.com/spec/v1oid sha256:b4cc8b31c6da31f32d724c32a1536fc6ea4da43cae127cf54d7705f1be055e27size 91969661123version https://git-lfs.github.com/spec/v1oid sha256:f35e41664759f46c64ace21b87fe49b278eec0fbbbe5077e7172f03c896c702fsize 122810020123version https://git-lfs.github.com/spec/v1oid sha256:7570c671dd9d5846bb2b4a4f881b0c769c4dd336d7fc9566f23651552a9a49b0size 123589136
107 unmodified lines1081091101111121131145 unmodified lines12012112212312412512612712812913013113213313413513636 unmodified lines17317417517617717817918018153 unmodified lines2352362372382392402412422432442452462472482493 unmodified lines25325425525625725825926026126226360 unmodified lines3243253263273283293303313323333343353363373 unmodified lines341342343107 unmodified linesself.assets = os.path.abspath(assets_dir)self.cfg = json.load(open(os.path.join(self.assets, "config.json")))self.verbose = verbosemk = AxEngine if engine == "ax" else OnnxEngineonnx_dir = os.path.join(self.root, "onnx")def path(name):5 unmodified linesraise FileNotFoundError(name)self._find = pathself._vae_enc_path = Noneself._vae_enc = Noneself.m_spk = mk(path("spk_body"))self.m_loc_step = mk(path("locenc_step"))self.m_dit = mk(path("dit_step"))self.m_pref = mk(path("lm_prefill"))self.m_dec = mk(path("lm_decode"))self.m_vae_dec = {}for lb in (64, 128, 256):try:self.m_vae_dec[lb] = mk(path(f"vae_dec_l{lb}"))except FileNotFoundError:passself.embed = np.load(os.path.join(self.assets, "embed_tokens.npy")).astype(np.float32)36 unmodified linesnreal = len(x) // hopif len(x) < cap:x = np.pad(x, (0, cap - len(x)))if self._vae_enc is None:self._vae_enc_path = self._find("vae_enc")self._vae_enc = AxEngine(self._vae_enc_path) if self._vae_enc_path.endswith(".axmodel") else OnnxEngine(self._vae_enc_path)lat = self._vae_enc.run({"wav": x.reshape(1, 1, -1)})[0].reshape(-1, 64)return lat[:max(nreal, 1)].astype(np.float32)53 unmodified linesreturn (np.cos(emb).astype(np.float32).reshape(1, 1, 1, 128),np.sin(emb).astype(np.float32).reshape(1, 1, 1, 128))# --------------------------------------------------------------------- apidef synthesize(self, text, reference_audio, max_new=None, cfg_strength=None, seed=42,ref_max_seconds=5.0, rng=None):t0 = time.time()cfg_strength = self.cfg["cfg_strength"] if cfg_strength is None else float(cfg_strength)max_new = int(self.cfg["max_new_patches"] if max_new is None else max_new)self.rng = rng if rng is not None else np.random.default_rng(seed)# ---- reference features -------------------------------------------------wav, sr = A.read_wav(reference_audio)wav24 = A.resample_to(wav, sr, self.sr)cap = int(self.cfg["vae_enc_samples"]) / float(self.sr)3 unmodified lineswav16 = A.resample_to(wav, sr, 16000)[: 8 * 16000]if len(wav16) < 32000:wav16 = np.tile(wav16, int(np.ceil(32000 / len(wav16))))t1 = time.time()lat = self._ref_latents(wav24)t2 = time.time()spk = self._speaker_embedding(wav16)t3 = time.time()lat_scaled = (lat + self.bias) * self.scaleembeds, plen = self._prompt_embeds(text, lat_scaled, spk)t4 = time.time()60 unmodified lines# ---- decode -------------------------------------------------------------lat = np.concatenate(latents, axis=0) # [N,2,64]vae_lat = (lat / self.scale - self.bias).reshape(-1, 64).T[None] # [1,64,2N]n = vae_lat.shape[-1]bucket = next((b for b in sorted(self.m_vae_dec) if n <= b), max(self.m_vae_dec))if n > bucket:raise ValueError(f"audio too long for available decoders ({n} > {bucket} latents)")padded = np.zeros((1, 64, bucket), np.float32)padded[:, :, :n] = vae_latwav_out = self.m_vae_dec[bucket].run({"latent": padded})[0][0, 0, : n * int(self.cfg["vae_hop"])]t7 = time.time()self.last_timing = {3 unmodified lines"audio_seconds": len(wav_out) / self.sr,}return wav_out.astype(np.float32)107 unmodified lines1081091101111121131141151161171181191201211221231241251261271285 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016136 unmodified lines19819920020120220353 unmodified lines2572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013 unmodified lines30530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234360 unmodified lines4044054064074084094104114124134144154164174184194203 unmodified lines424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555107 unmodified linesself.assets = os.path.abspath(assets_dir)self.cfg = json.load(open(os.path.join(self.assets, "config.json")))self.verbose = verbosebase_mk = AxEngine if engine == "ax" else OnnxEnginedef mk(path_):# AX CMM is a shared pool; retry briefly on transient load failuresimport gclast = Nonefor _ in range(4):try:return base_mk(path_)except Exception as exc: # noqa: BLE001last = excgc.collect()time.sleep(0.4)raise lastonnx_dir = os.path.join(self.root, "onnx")def path(name):5 unmodified linesraise FileNotFoundError(name)self._find = pathself._vae_enc = mk(path("vae_enc"))self.m_vae_stream = Noneself.vae_state_shapes = Noneself._stream_path = Nonesp = os.path.join(self.assets, "vae_stream.json")if os.path.exists(sp):try:self._stream_path = path("vae_dec_stream")self.vae_state_shapes = [tuple(int(v) for v in sh)for sh in json.load(open(sp))["states"]]except FileNotFoundError:self._stream_path = Noneself.m_spk = mk(path("spk_body"))self.m_loc_step = mk(path("locenc_step"))self.m_dit = mk(path("dit_step"))self.m_pref = mk(path("lm_prefill"))self.m_dec = mk(path("lm_decode"))self.m_vae_dec = {}self._dec_paths = {}for lb in (64, 128, 256):try:self._dec_paths[lb] = path(f"vae_dec_l{lb}")except FileNotFoundError:passself.embed = np.load(os.path.join(self.assets, "embed_tokens.npy")).astype(np.float32)36 unmodified linesnreal = len(x) // hopif len(x) < cap:x = np.pad(x, (0, cap - len(x)))lat = self._vae_enc.run({"wav": x.reshape(1, 1, -1)})[0].reshape(-1, 64)return lat[:max(nreal, 1)].astype(np.float32)53 unmodified linesreturn (np.cos(emb).astype(np.float32).reshape(1, 1, 1, 128),np.sin(emb).astype(np.float32).reshape(1, 1, 1, 128))def _get_dec(self, bucket):if bucket not in self.m_vae_dec:if bucket not in self._dec_paths:raise ValueError(f"no VAE decoder for {bucket} latents")self.m_vae_dec[bucket] = self._find_engine(self._dec_paths[bucket])return self.m_vae_dec[bucket]def _find_engine(self, path_):mk = AxEngine if path_.endswith(".axmodel") else OnnxEngineimport gclast = Nonefor _ in range(4):try:return mk(path_)except Exception as exc: # noqa: BLE001last = excgc.collect()time.sleep(0.4)raise lastdef _get_stream_dec(self):if self.m_vae_stream is None and self._stream_path is not None:self.m_vae_stream = self._find_engine(self._stream_path)return self.m_vae_streamdef _prepare_reference(self, reference_audio, ref_max_seconds=5.0):"""Reference latents + speaker embedding, cached per (path, size, seconds)."""try:key = (os.path.abspath(reference_audio), os.path.getsize(reference_audio),float(ref_max_seconds))except OSError:key = Nonecache = getattr(self, "_ref_cache", None)if cache is None:cache = self._ref_cache = {}if key is not None and key in cache:self.ref_cache_hit = Truereturn cache[key]self.ref_cache_hit = Falsewav, sr = A.read_wav(reference_audio)wav24 = A.resample_to(wav, sr, self.sr)cap = int(self.cfg["vae_enc_samples"]) / float(self.sr)3 unmodified lineswav16 = A.resample_to(wav, sr, 16000)[: 8 * 16000]if len(wav16) < 32000:wav16 = np.tile(wav16, int(np.ceil(32000 / len(wav16))))lat = self._ref_latents(wav24)spk = self._speaker_embedding(wav16)if key is not None:cache[key] = (lat, spk)return lat, spk# ------------------------------------------------------------------ streamingdef _decode_window(self, vae_lat, start, end):"""Exact VAE decode of latents [start, end) using a 128-latent sliding window.The DAC decoder is causal with a 64-latent receptive field (verified: zeroingthe first 64 latents leaves all later samples bit-identical), so a window of``[end-128, end)`` reproduces the offline decode exactly."""w0 = max(0, end - 128)win = np.zeros((1, 64, 128), np.float32)n = end - w0win[0, :, :n] = np.stack(vae_lat[w0:end], axis=1)out = self._get_dec(128).run({"latent": win})[0][0, 0]return out[(start - w0) * 1920:(end - w0) * 1920]# --------------------------------------------------------------------- apidef synthesize(self, text, reference_audio, max_new=None, cfg_strength=None, seed=42,ref_max_seconds=5.0, rng=None):t0 = time.time()cfg_strength = self.cfg["cfg_strength"] if cfg_strength is None else float(cfg_strength)max_new = int(self.cfg["max_new_patches"] if max_new is None else max_new)self.rng = rng if rng is not None else np.random.default_rng(seed)# ---- reference features -------------------------------------------------t1 = time.time()lat, spk = self._prepare_reference(reference_audio, ref_max_seconds)t2 = t3 = time.time()lat_scaled = (lat + self.bias) * self.scaleembeds, plen = self._prompt_embeds(text, lat_scaled, spk)t4 = time.time()60 unmodified lines# ---- decode -------------------------------------------------------------lat = np.concatenate(latents, axis=0) # [N,2,64]self.last_patches = lat.copy()vae_lat = (lat / self.scale - self.bias).reshape(-1, 64).T[None] # [1,64,2N]n = vae_lat.shape[-1]bucket = next((b for b in sorted(self._dec_paths) if n <= b), max(self._dec_paths))if n > bucket:raise ValueError(f"audio too long for available decoders ({n} > {bucket} latents)")padded = np.zeros((1, 64, bucket), np.float32)padded[:, :, :n] = vae_latself.last_latents = vae_latself.last_bucket = bucketwav_out = self._get_dec(bucket).run({"latent": padded})[0][0, 0, : n * int(self.cfg["vae_hop"])]t7 = time.time()self.last_timing = {3 unmodified lines"audio_seconds": len(wav_out) / self.sr,}return wav_out.astype(np.float32)def synthesize_stream(self, text, reference_audio, max_new=None, cfg_strength=None, seed=42,ref_max_seconds=5.0, rng=None, first_chunk=16, chunk=32, windowed=False):"""True streaming synthesis: yields float32 PCM chunks while the AR loop runs.Nothing is sentence-split: the AR loop keeps generating latents and audio isdecoded/emitted every ``chunk`` latents (2.56 s) after an initial``first_chunk`` latents (1.28 s), using an exact 128-latent sliding window."""t0 = time.time()cfg_strength = self.cfg["cfg_strength"] if cfg_strength is None else float(cfg_strength)max_new = int(self.cfg["max_new_patches"] if max_new is None else max_new)self.rng = rng if rng is not None else np.random.default_rng(seed)lat, spk = self._prepare_reference(reference_audio, ref_max_seconds)lat_scaled = (lat + self.bias) * self.scaleembeds, plen = self._prompt_embeds(text, lat_scaled, spk)pre = self.m_pref.run({"embeds": embeds})hidden = pre[0][0, plen - 1].reshape(1, 1024)stop = pre[1].reshape(2)kvs = []for i in range(7):kk = np.zeros((1, 8, self.B, 128), np.float32)vv = np.zeros((1, 8, self.B, 128), np.float32)kk[0, :, :plen] = pre[2 + 2 * i][0, :, :plen]vv[0, :, :plen] = pre[3 + 2 * i][0, :, :plen]kvs += [kk, vv]mask = np.full((1, 1, 1, self.B + 1), -30.0, np.float32)mask[..., :plen] = 0.0cond = np.zeros((1, 2, 64), np.float32)cfg_t = np.array([cfg_strength], np.float32)vae_lat = [] # VAE-space latents, 64 floats eachemitted = 0if not windowed and self._get_stream_dec() is not None:states = [np.zeros(sh, np.float32) for sh in self.vae_state_shapes]else:states = Nonepos = plenn_steps = 0ttft = Nonen_chunks = 0t_dit = t_dec = 0.0def emit_patch(pred):"""stateful per-patch decode (160 ms per call)"""nonlocal states, ttft, n_chunksvae = pred[0] / self.scale - self.bias # scaled (LM) space -> VAE spacelat2 = np.ascontiguousarray(vae.T[None].astype(np.float32)) # [1,64,2]feed = {"latent": lat2}for i, st in enumerate(states):feed[f"s{i}"] = stout = self.m_vae_stream.run(feed)# copy: the engine reuses its output buffers, and we feed them back next stepstates = [np.array(o, copy=True) for o in out[1:]]n_chunks += 1if ttft is None:ttft = time.time() - t0return np.array(out[0][0, 0], copy=True)def emit(upto):nonlocal emitted, ttft, n_chunksaudio = self._decode_window(vae_lat, emitted, upto)emitted = upton_chunks += 1if ttft is None:ttft = time.time() - t0return audiofor step in range(max_new):stop_now = int(np.argmax(stop)) == 1x0 = self.rng.standard_normal((1, 2, 64)).astype(np.float32)t_a = time.time()x = x0for k in range(int(self.cfg["diffusion_steps"])):v = self.m_dit.run({"x": x, "z": hidden, "cond": cond, "speaker": spk,"cfg_strength": cfg_t, "t": np.array([k * 0.25], np.float32),"dt": np.array([0.25], np.float32)})[0]x = x + v * 0.25t_dit += time.time() - t_acond = xn_steps += 1for c in range(2):vae_lat.append((x[0, c] / self.scale - self.bias).astype(np.float32))if states is not None:yield emit_patch(x)if stop_now:if states is None and emitted < len(vae_lat):yield emit(len(vae_lat))breakemb = self.m_loc_step.run({"patches": x[None].astype(np.float32)})[0]if pos >= self.B - 1:if emitted < len(vae_lat):yield emit(len(vae_lat))breakmask[..., pos] = 0.0mask[..., self.B] = 0.0cos, sin = self._rope(pos)feed = {"embed": emb, "mask_add": mask, "cos": cos, "sin": sin}for i in range(7):feed[f"pk{i}"] = kvs[2 * i]feed[f"pv{i}"] = kvs[2 * i + 1]t_a = time.time()d = self.m_dec.run(feed)t_dec += time.time() - t_ahidden = d[0].reshape(1, 1024)stop = d[1].reshape(2)for i in range(7):kvs[2 * i][0, :, pos] = d[2 + 2 * i][0, :, 0]kvs[2 * i + 1][0, :, pos] = d[3 + 2 * i][0, :, 0]pos += 1if states is None:need = first_chunk if emitted == 0 else chunkif len(vae_lat) - emitted >= need:yield emit(len(vae_lat))if states is None and emitted < len(vae_lat):yield emit(len(vae_lat))self.last_timing = {"ttft": ttft or (time.time() - t0), "total": time.time() - t0,"audio_seconds": len(vae_lat) / 12.5, "steps": n_steps,"chunks": n_chunks, "dit": t_dit, "lm_decode": t_dec,"streaming": True,}
6 unmodified lines78910111211 unmodified lines242526272829303132336 unmodified linesimport osimport syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from cutetts_ax import CuteTTSAX # noqa: E40211 unmodified linesap.add_argument("--cfg", type=float, default=None)ap.add_argument("--max-new", type=int, default=None)ap.add_argument("--seed", type=int, default=42)ap.add_argument("--ref-seconds", type=float, default=12.0)a = ap.parse_args()tts = CuteTTSAX(a.model_dir, a.assets, engine=a.engine)wav = tts.synthesize(a.text, a.reference, max_new=a.max_new, cfg_strength=a.cfg,seed=a.seed, ref_max_seconds=a.ref_seconds)A.write_wav(a.output, wav, tts.sr)6 unmodified lines789101112131411 unmodified lines262728293031323334353637383940414243444546474849505152535455565758596 unmodified linesimport osimport sysimport numpy as npsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from cutetts_ax import CuteTTSAX # noqa: E40211 unmodified linesap.add_argument("--cfg", type=float, default=None)ap.add_argument("--max-new", type=int, default=None)ap.add_argument("--seed", type=int, default=42)ap.add_argument("--ref-seconds", type=float, default=5.0)ap.add_argument("--stream", action="store_true", help="true streaming: emit audio while generating")ap.add_argument("--first-chunk", type=int, default=16, help="latents in the first streamed chunk")ap.add_argument("--chunk", type=int, default=32, help="latents per streamed chunk afterwards")ap.add_argument("--windowed", action="store_true",help="exact windowed streaming (bit-identical to offline, higher latency)")a = ap.parse_args()tts = CuteTTSAX(a.model_dir, a.assets, engine=a.engine)if a.stream:import wavewith wave.open(a.output, "wb") as wf:wf.setnchannels(1)wf.setsampwidth(2)wf.setframerate(tts.sr)for chunk in tts.synthesize_stream(a.text, a.reference, max_new=a.max_new,cfg_strength=a.cfg, seed=a.seed,ref_max_seconds=a.ref_seconds,first_chunk=a.first_chunk, chunk=a.chunk,windowed=a.windowed):pcm = (np.clip(chunk, -1.0, 1.0) * 32767.0).astype("<i2")wf.writeframes(pcm.tobytes())tm = tts.last_timingprint(f"streaming: {tm['chunks']} chunks, TTFT {tm['ttft']:.2f}s, "f"audio {tm['audio_seconds']:.2f}s in {tm['total']:.2f}s "f"(RTF {tm['total']/max(tm['audio_seconds'],1e-6):.3f})")print("saved", a.output)returnwav = tts.synthesize(a.text, a.reference, max_new=a.max_new, cfg_strength=a.cfg,seed=a.seed, ref_max_seconds=a.ref_seconds)A.write_wav(a.output, wav, tts.sr)
1234564 unmodified lines111213141516#!/bin/bash# CuteTTS.AXERA one-click demo (voice cloning on AX650).# bash run_ax650.sh "text" [reference.wav] [output.wav] [--cfg 2.0] [--seed 42] [--max-new N]set -ecd "$(dirname "$0")"export LD_LIBRARY_PATH=/soc/lib:${LD_LIBRARY_PATH:-}4 unmodified linesOUT="${3:-output.wav}"if [ $# -ge 3 ]; then shift 3; elif [ $# -ge 2 ]; then shift 2; elif [ $# -ge 1 ]; then shift 1; fiexec python3 python/demo.py \--model-dir models --assets models/assets \--text "$TEXT" --reference "$REF" --output "$OUT" "$@"1234564 unmodified lines111213141516171819202122232425262728293031#!/bin/bash# CuteTTS.AXERA one-click demo (voice cloning on AX650).# bash run_ax650.sh "text" [reference.wav] [output.wav] [--python] [--cfg 2.0] [--seed 42] [--max-new N]set -ecd "$(dirname "$0")"export LD_LIBRARY_PATH=/soc/lib:${LD_LIBRARY_PATH:-}4 unmodified linesOUT="${3:-output.wav}"if [ $# -ge 3 ]; then shift 3; elif [ $# -ge 2 ]; then shift 2; elif [ $# -ge 1 ]; then shift 1; fiMODE="cpp"EXTRA=()for a in "$@"; docase "$a" in--python) MODE="python" ;;--cpp) MODE="cpp" ;;*) EXTRA+=("$a") ;;esacdoneif [ ! -x ./bin/cutetts_ax650 ]; then MODE="python"; fiif [ "$MODE" = "cpp" ]; thenexec ./bin/cutetts_ax650 --model-dir models --assets models/assets \--text "$TEXT" --reference "$REF" --output "$OUT" "${EXTRA[@]}"elseexec python3 python/demo.py --model-dir models --assets models/assets \--text "$TEXT" --reference "$REF" --output "$OUT" "${EXTRA[@]}"fi
123version https://git-lfs.github.com/spec/v1oid sha256:b5dd09871d42c2e4c553d1912a244052fbbb9569462aa53e5a728a558d88cebcsize 153644123version https://git-lfs.github.com/spec/v1oid sha256:d7ff8c8405625b33615db3fe38e859fe945eb5fa88900bcf63ec594a0ccbcfabsize 138284
123version https://git-lfs.github.com/spec/v1oid sha256:1f5359090c465c344b5cf0dd3377e00e9273fe3ddbd32b38259f87bec9822433size 284204123version https://git-lfs.github.com/spec/v1oid sha256:9056400a730eca769f3a585b3d5a9de0d66e67652576e5f9dcc219b2d29891d4size 268844
123version https://git-lfs.github.com/spec/v1oid sha256:18bbba6cf714d58f268b31745fcbf7a37c3d00c27997694cb82a83fbfa69ec67size 138284123version https://git-lfs.github.com/spec/v1oid sha256:0c23d7c39ac633b0cacf9475b552287b6b9a87ead3c695d0e16f72a31fcd27c3size 130604
123version https://git-lfs.github.com/spec/v1oid sha256:fd619ac368868cb174b0fd65d43c27c006947bdb2b2c06a8ceb576dd813ab51fsize 506924123version https://git-lfs.github.com/spec/v1oid sha256:c83201ebeae84506124a540e46ccd58ea22aa92f8606b364bc58b2ff6031109csize 169004123version https://git-lfs.github.com/spec/v1oid sha256:e1d9b86ae067d3e91210752fc447df999c6cfcd3644a4c3af8227b23d436df74size 138284
.gitattributes+2
README.md+130-123
bin/cutetts_ax650Added
config.jsonAdded+1
models/assets/tokenizer.binAdded+3
models/assets/vae_stream.jsonAdded+94
models/dit_step.axmodel+2-2
models/lm_decode.axmodel+2-2
models/lm_prefill.axmodel+2-2
models/locenc_step.axmodel+2-2
models/spk_body.axmodel+2-2
models/vae_dec_l128.axmodel+2-2
models/vae_dec_l256.axmodel+2-2
models/vae_dec_l64.axmodel+2-2
models/vae_dec_stream.axmodelAdded+3
models/vae_enc.axmodel+2-2
python/cutetts_ax/tts.py+233-21
python/demo.py+27-1
run_ax650.sh+19-4
samples/listen/en_default.wav+2-2
samples/listen/en_long.wav+2-2
samples/listen/en_other_voice.wav+2-2
samples/listen/en_xlong.wavAdded+3
samples/listen/zh_default.wav+2-2