Lua Nova V1 trained on oProfM/LuaNovaDataset: weights, ONNX, eval, code
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+9
- README.md+196
- checkpoints/bigvgan_base_optB_2k.ptAdded+3
- checkpoints/cfm_v5_fast2.ptAdded+3
- checkpoints/cfm_v5_soup50.ptAdded+3
- code/.gitignoreAdded+37
- code/LICENSEAdded+202
- code/README.mdAdded+208
- code/THIRD_PARTY_NOTICES.mdAdded+14
- code/docs/ARCHITECTURE.mdAdded+38
- code/docs/FINE_TUNING.mdAdded+139
- code/docs/OPTIMIZATION.mdAdded+113
- code/docs/TRAINING_FROM_SCRATCH.mdAdded+137
- code/pyproject.tomlAdded+60
- code/src/lua_nova_v1/__init__.pyAdded+26
- code/src/lua_nova_v1/config.pyAdded+199
- code/src/lua_nova_v1/data/__init__.pyAdded+15
- code/src/lua_nova_v1/data/aligner.pyAdded+301
- code/src/lua_nova_v1/data/annotate.pyAdded+324
- code/src/lua_nova_v1/data/dataset.pyAdded+179
- code/src/lua_nova_v1/data/journal.pyAdded+73
- code/src/lua_nova_v1/data/prepare.pyAdded+212
- code/src/lua_nova_v1/data/refine.pyAdded+152
- code/src/lua_nova_v1/export/__init__.pyAdded+30
- code/src/lua_nova_v1/export/onnx_export.pyAdded+526
- code/src/lua_nova_v1/inference/__init__.pyAdded+7
- code/src/lua_nova_v1/inference/cli.pyAdded+131
- code/src/lua_nova_v1/inference/onnx_engine.pyAdded+170
- code/src/lua_nova_v1/inference/streaming.pyAdded+96
- code/src/lua_nova_v1/inference/synthesizer.pyAdded+209
- code/src/lua_nova_v1/models/__init__.pyAdded+39
- code/src/lua_nova_v1/models/bigvgan.pyAdded+135
- code/src/lua_nova_v1/models/cfm.pyAdded+900
- code/src/lua_nova_v1/models/frontend.pyAdded+474
- code/src/lua_nova_v1/models/losses.pyAdded+130
- code/src/lua_nova_v1/text/__init__.pyAdded+69
- code/src/lua_nova_v1/text/normalizer.pyAdded+343
- code/src/lua_nova_v1/text/phonemizer.pyAdded+347
- code/src/lua_nova_v1/training/__init__.pyAdded+31
- code/src/lua_nova_v1/training/cfm.pyAdded+269
- code/src/lua_nova_v1/training/cfm_e2e.pyAdded+474
- code/src/lua_nova_v1/training/common.pyAdded+315
- code/src/lua_nova_v1/training/distill.pyAdded+376
- code/src/lua_nova_v1/training/prosody_flow.pyAdded+548
- code/src/lua_nova_v1/training/stage1.pyAdded+583
- code/src/lua_nova_v1/training/vocoder_ft.pyAdded+464
- code/src/lua_nova_v1/utils/__init__.pyAdded+31
- code/src/lua_nova_v1/utils/audio.pyAdded+141
- code/src/lua_nova_v1/utils/checkpoint.pyAdded+67
- code/tests/test_model.pyAdded+109
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 lines33343536373839404142434432 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 -textsamples/stress_cot_00.wav filter=lfs diff=lfs merge=lfs -textsamples/stress_emo_00.wav filter=lfs diff=lfs merge=lfs -textsamples/stress_est_00.wav filter=lfs diff=lfs merge=lfs -textsamples/test_01_gen.wav filter=lfs diff=lfs merge=lfs -textsamples/test_01_ref.wav filter=lfs diff=lfs merge=lfs -textsamples/test_02_gen.wav filter=lfs diff=lfs merge=lfs -textsamples/test_02_ref.wav filter=lfs diff=lfs merge=lfs -textsamples/test_03_gen.wav filter=lfs diff=lfs merge=lfs -textsamples/test_03_ref.wav filter=lfs diff=lfs merge=lfs -text
123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199---language:- ptlicense: apache-2.0library_name: pytorchpipeline_tag: text-to-speechtags:- text-to-speech- tts- brazilian-portuguese- pt-br- flow-matching- bigvgan- onnx- single-speakerdatasets:- oProfM/LuaNovaDataset---# Lua Nova V1 — voz LuaNovaDataset (PT-BR, 24 kHz)Modelo de **texto para fala em português do Brasil** (uma voz feminina, 24 kHz), treinado do zero sobre odataset [`oProfM/LuaNovaDataset`](https://huggingface.co/datasets/oProfM/LuaNovaDataset) com a arquiteturaLua Nova V1:- front end fonético eSpeak-NG (85 símbolos) + normalizador de texto PT-BR (números, datas, moeda);- encoder fonético + **DurationFlow / ProsodyFlow** generativos;- decodificador acústico **OT-CFM v5** (Conditional Flow Matching) em espaço log-mel Slaney 100 bandas, com Sway Sampling;- vocoder **BigVGAN-base** (`nvidia/bigvgan_base_24khz_100band`, MIT) com fine-tuning leve nesta voz;- versão **destilada de 2 passos Euler** (recomendada) e export **ONNX** para CPU sem PyTorch.> *Synthetic single-speaker Brazilian Portuguese female TTS trained from scratch on `oProfM/LuaNovaDataset`.> The dataset voice is synthetic; no real person was recorded or cloned.*## Arquivos| Arquivo | O que é | Tamanho ||---|---|---:|| `checkpoints/cfm_v5_fast2.pt` | **Recomendado.** CFM destilado, 2 passos Euler | 83 MB || `checkpoints/cfm_v5_soup50.pt` | Professor: soup 50/50 de CFM v5 + Opção A (E2E), 8 passos Midpoint + Sway | 83 MB || `checkpoints/bigvgan_base_optB_2k.pt` | BigVGAN-base com fine-tuning (Opção B, 2.000 passos) | 54 MB || `onnx/cfm_v5_fast2.onnx` + `.meta.json` | Grafo ONNX (opset 17) do acústico, 2 passos | 86 MB || `onnx/bigvgan_base_ft.onnx` | Grafo ONNX do vocoder | 55 MB || `samples/` | Exemplos de áudio (referência × gerado) | || `eval/` | `scores.json`, `latency.json`, `timings.json` (todas as etapas, com args) | || `code/` | Snapshot do código `lua_nova_v1` usado no treino (Apache-2.0; BigVGAN em `third_party/`, MIT) | || `scripts/` | Scripts deste treino (montagem do dataset, runner com cronômetro/VRAM, pipeline final, avaliação) | |## Uso rápidoRequer Python 3.11/3.12, [`uv`](https://docs.astral.sh/uv/) e `espeak-ng` no `PATH`.```bashgit clone https://huggingface.co/oProfM/LuaNovaV1cd LuaNovaV1/codeuv sync # + "uv sync --extra onnx" para ONNX Runtime``````pythonfrom lua_nova_v1 import Synthesizersynth = Synthesizer.from_checkpoints(cfm_path="../checkpoints/cfm_v5_fast2.pt",vocoder_path_or_id="../checkpoints/bigvgan_base_optB_2k.pt",device="cpu", # ou "cuda")wav = synth.speak("Olá! Dia 22/03 às 14h30 custou R$ 45,90; quer testar?",n_steps=2, solver="euler", sway_coef=0.0, temperature=0.35)synth.save_wav("saida.wav", wav)# streaming em chunks (~0,5 s até o primeiro áudio em CPU)for chunk in synth.speak_stream("Este áudio sai em partes.", n_steps=2, solver="euler",sway_coef=0.0, chunk_frames=24):...```ONNX (CPU, sem PyTorch):```pythonfrom lua_nova_v1 import OnnxSynthesizerox = OnnxSynthesizer("../onnx/cfm_v5_fast2.onnx", "../onnx/bigvgan_base_ft.onnx", threads=6)ox.save_wav("onnx.wav", ox.speak("Oi! Tudo bem com você?"))```Para o professor de 8 passos use `cfm_v5_soup50.pt` com `n_steps=8, solver="midpoint", sway_coef=-0.5`.## DadosFonte: `oProfM/LuaNovaDataset` (MIT, 10.916 áudios / 12,61 h, 48 kHz FLAC, uma voz feminina sintética).Filtragem e preparo (`scripts/build_dataset.py`):1. Removidos `low_utmos` (2.676) e `cer > 0,08` (87). Nenhuma rejeição por idioma, duração, duplicata ou fonemização.2. Todos os textos validados no fonemizador eSpeak-NG (0 fonemas desconhecidos).3. Reamostragem 48 kHz → 24 kHz mono WAV.4. Splits: **train 8.025** (8,98 h), **validation 64**, **test 64** (UTMOS médio ≈ 3,75; CER médio ≈ 0,15 %).5. Extração de features + alinhamento forçado CTC (wav2vec2) com 2 passes de refinamento de fronteiras.Gate de anotação ajustado (`--max-weak-phone-fraction 0.35 --min-token-probability 0.45`) para preservarfrases curtas e perguntas → **7.548 enunciados de treino (8,58 h)**, 61 validação, **57 teste**(96,95 % das transições fricativa→vogal dentro de 2 frames).## TreinamentoHardware (tudo local, uma única máquina):- **GPU:** NVIDIA GeForce RTX 4070 12 GB (driver 621.24)- **CPU:** AMD Ryzen 5 9600X (6 núcleos / 12 threads)- **RAM:** 31 GB- **SO:** Windows 11 Pro · Python 3.12.15 · PyTorch 2.14.1 + CUDA 13.0| # | Etapa | Passos | Tempo (GPU) | Pico VRAM (nvidia-smi) | Observações ||---|---|---:|---:|---:|---|| 0a | Montagem do dataset (filtro, fonemização, 48→24 kHz) | — | 3,4 min | — | 12 workers CPU || 0b | Features acústicas (`prepare`) | — | 2,2 min | 2,3 GB | 100 % aceitos || 0c | Alinhamento CTC + refino ×2 (`annotate`) + re-gate | — | 9,1 min | 6,0 GB | || 1 | Stage 1: encoder fonético, duração/pausa, prosódia | 0 → 8.000 | 24,4 min¹ | 11,6 GB | OOM no passo 9.020 ao ligar os críticos GAN do head temporário; retomado do checkpoint 8.000 || 1b | Stage 1 fase 2 (sem GAN, `batch-frames 8000`) | 8.000 → 28.000 | ~32,3 min² | 7,2 GB | interrompido por reinício no passo ~19.100, retomado do checkpoint 15.000 || 2 | ProsodyFlow (DurationFlow + ProsodyFlow) | 12.000 | 19,2 min | 3,2 GB | F0 1,16 st, vozeamento 97,98 %, MAE duração 0,93 frames || 3 | OT-CFM v5 (Slaney-100) | 25.000 | 42,8 min | 6,3 GB | `val_cfm = 0,1457` || 4 | Opção A: E2E através do BigVGAN congelado + MPD/MRD NVIDIA | 2.000 | ~53 min³ | 6,7 GB | duas partes (0→1.000, 1.000→2.000); soup 50/50 com o passo 1.500 || 5 | Opção B: fine-tuning do BigVGAN-base (60 % mels previstos / 40 % GT) | 2.000 | 20,7 min⁴ | 8,5 GB | || 6 | Destilação 8p Midpoint → 2p Euler (só o `flow`) | 3.000 | 12,6 min | 4,1 GB | || 7 | Export ONNX + verificação de paridade | — | 0,2 min | — | CFM máx. |Δ| 2,7e-5 · BigVGAN máx. |Δ| 1,3e-7 |**Tempo total efetivo do pipeline ≈ 3 h 40 min** de GPU (≈ 15 min de preparo de dados + ≈ 3 h 25 min de treino),numa única RTX 4070. Somando execuções perdidas (OOM, reinício do servidor, uma queda de luz que interrompeu ofine-tuning do vocoder, refeito do zero), o tempo de máquina foi um pouco maior. Os números exatos por execução,com argumentos de linha de comando, estão em `eval/timings.json`.¹ Inclui o trecho 8.000→9.020 descartado. ² 11,5 min (8k→15k, execução sem registro no `timings.json`) + 20,8 min (15k→28k).³ ≈ 29,8 min da 1ª parte (sem registro no `timings.json`, pelos timestamps dos arquivos) + 23,2 min da 2ª.⁴ Execução final completa; uma execução anterior foi interrompida (queda de luz) e descartada.Hiperparâmetros principais (receita `code/docs/TRAINING_FROM_SCRATCH.md`):- E2E: `batch 4 × accum 3`, `crop 40`, 4 passos ODE com `sway -0.5`, `lr 4e-5 → 4e-6`. A 2ª parte foiretomada do passo 1.000 com `lr 2,52e-5` (valor do cosseno original nesse ponto) e warmup de 20 passos.- BigVGAN FT: `--pretrained-disc --disc-warmup 0`, `batch 6 × accum 2`, `crop 32`, `cfm-prob 0.60`, `lr-g 1e-5`, `lr-d 1e-5`.- Destilação: professor `soup50` (8 passos Midpoint, sway -0,5, temp 0,35) → aluno 2 passos Euler, `lr 1e-4`, 3.000 passos.## AvaliaçãoJuízes do `tts-eval` (UTMOS22-strong, SCOREQ, DNSMOS P.835, Whisper-small para WER/CER, ECAPA para similaridadede locutor). A similaridade de locutor é o cosseno contra o centróide das **gravações de referência do split de teste**.- **test:** 57 frases do split de teste do LuaNovaDataset, nunca vistas no treino, com referência real.- **stress_ptbr:** 36 frases difíceis do `tts-eval` (perguntas, exclamações, frases longas, números, homógrafos,estrangeirismos), só texto.| Sistema | Conjunto | UTMOS22 ↑ | SCOREQ ↑ | DNSMOS OVR ↑ | WER ↓ | CER ↓ | Sim. locutor ↑ ||---|---|---:|---:|---:|---:|---:|---:|| Referência do dataset (24 kHz) | test (57) | 3,70 | 3,94 | 3,13 | 0,86 % | 0,19 % | 0,871 || **`fast2` (2p Euler) + BigVGAN FT** | test (57) | 3,69 | **4,03** | 3,26 | 1,57 % | 0,48 % | 0,885 || `soup50` (8p Midpoint) + BigVGAN FT | test (57) | **3,70** | 4,01 | 3,25 | 1,57 % | 0,48 % | 0,885 || **`fast2` (2p Euler) + BigVGAN FT** | stress (36) | **3,59** | **3,86** | **3,35** | 4,26 % | 1,11 % | 0,908 || `soup50` (8p Midpoint) + BigVGAN FT | stress (36) | 3,57 | 3,84 | 3,33 | 4,26 % | 1,11 % | 0,908 |No conjunto de teste o modelo fica praticamente empatado com as gravações do dataset em UTMOS e acima em SCOREQ eDNSMOS. A WER é pequena e concentrada em frases muito curtas: uma frase de 5 palavras sozinha pesa 0,4.A destilação para 2 passos não perdeu qualidade mensurável em relação ao professor de 8 passos.### Latência5 frases PT-BR (≈ 28 s de áudio no total), aquecimento excluído, CPU com 6 threads.| Modo | Latência média / frase | Velocidade (× tempo real) | 1º áudio (streaming) ||---|---:|---:|---:|| PyTorch GPU — `fast2` (2p) | 593 ms | 9,3× | — || PyTorch GPU — `soup50` (8p) | 640 ms | 8,6× | — || PyTorch CPU — `fast2` (2p) | 2.546 ms | 2,2× | — || PyTorch CPU — `soup50` (8p) | 3.033 ms | 1,9× | — || **PyTorch CPU — `fast2` streaming (`chunk=24`)** | 2.668 ms | 2,1× | **540 ms** || ONNX CPU — `fast2` | 3.535 ms | 1,6× | — || ONNX CPU — `fast2` streaming (`chunk=24`) | 5.029 ms | 1,1× | 627 ms |## Exemplos| | Texto | Referência | Lua Nova V1 (`fast2`) ||---|---|---|---|| 01 | Quem aqui acha que eu vou conseguir passar desse nível logo? | [ref](./samples/test_01_ref.wav) | [gerado](./samples/test_01_gen.wav) || 02 | Tem um cinema antigo que ainda exibe filmes clássicos. | [ref](./samples/test_02_ref.wav) | [gerado](./samples/test_02_gen.wav) || 03 | Eu vou deixar um recado com a sua irmã sobre o horário. | [ref](./samples/test_03_ref.wav) | [gerado](./samples/test_03_gen.wav) || cot_00 | Amanhã de manhã eu vou pôr o pão na mesa para os irmãos. | — | [gerado](./samples/stress_cot_00.wav) || emo_00 | Que notícia maravilhosa receber a aprovação logo na primeira tentativa! | — | [gerado](./samples/stress_emo_00.wav) || est_00 | Instalei o script em Python no Windows e conectei o fone via Bluetooth sem erro. | — | [gerado](./samples/stress_est_00.wav) |## Limitações- Uma única voz (`F1`), só português do Brasil. Sem controle de emoção além da pontuação.- A voz de origem é sintética, então o teto de qualidade é o do dataset (UTMOS ≈ 3,7).- Frases muito curtas (1–3 palavras) têm WER relativa mais alta.- `code/README.md` e `code/docs/` são a documentação do código e trazem benchmarks de outra voz/dataset. Os números**deste** modelo são os desta página.- Não use para se passar por pessoas reais nem para gerar conteúdo enganoso.## Licenças- Pesos e código deste repositório: **Apache-2.0**.- `code/third_party/bigvgan` e o vocoder base `nvidia/bigvgan_base_24khz_100band`: **MIT** (NVIDIA).- Dataset de treino `oProfM/LuaNovaDataset`: **MIT**.
123version https://git-lfs.github.com/spec/v1oid sha256:db0fe65486dd98892b282bb5c07c02f18e43bdb946dd1a58134dcd7206ff53easize 56285259123version https://git-lfs.github.com/spec/v1oid sha256:89431d10d153160fa54b41f3a6a2db7dbe917ea9ce959a5e4ad2a772b6406885size 87242383123version https://git-lfs.github.com/spec/v1oid sha256:ce6297351ce0e8b5535e77f8be61b7f946aa07895c76cf4c1166442416df734bsize 8724301312345678910111213141516171819202122232425262728293031323334353637# Model weights, binaries, tensors, and caches (publish checkpoints to Hugging Face, not Git)
*.pt
*.pth
*.onnx
*.onnx.data
*.safetensors
*.ckpt
*.bin
*.npy
*.npz
# Python & environments
.venv/
__pycache__/
*.py[cod]
*$py.class
build/
dist/
*.egg-info/
.pytest_cache/
.mypy_cache/
.ruff_cache/
# Local datasets, training runs, and caches (root-anchored so src packages are never ignored)
/data/
/runs/
/outputs/
/models/
/checkpoints/
/hf_home/
/torch_home/
/tmp/
/.cache/
# OS & editor artifacts
.DS_Store
Thumbs.db123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208# Lua Nova V1
A compact, high-naturalness **24 kHz Brazilian Portuguese (PT-BR)** neural Text-to-Speech system combining an **85-symbol eSpeak-NG phonetic front end**, **ProsodyFlow** (generative DurationFlow & ProsodyFlow), an **Optimal-Transport Conditional Flow Matching (OT-CFM)** acoustic decoder operating in universal **Slaney 100-band log-mel space**, **Sway Sampling**, and a gently adapted **MIT BigVGAN-base** vocoder.
This release packages the **`CFM v5 (Option A + Weight Soup) + BigVGAN-base FT (Option B)`** architecture (`~35.8M` total inference parameters, `~137 MB` FP32 / `~68 MB` FP16) cleanly for public reproduction, fine-tuning, **2-step Euler distillation (`v1.1.0`)**, **split ONNX Runtime CPU inference**, and **overlap-crossfaded chunked streaming** — with **zero binary checkpoints committed to Git** (weights belong on Hugging Face).
---
## Highlights & Benchmarks (`tts-eval` v1.0.0)
Evaluated on a frozen multi-metric suite across `heldout_ref` (30 paired studio utterances) and `stress_ptbr` (36 challenging PT-BR sentences covering questions, exclamations, long clauses, numbers, homographs, and foreign/tech terms):
| System | Held-out (30) Pass | Held-out Comp ↑ | Nat ↑ | Anti-Rob ↑ | SCOREQ ↑ | UTMOS22 ↑ | Stress (36) Comp ↑ | Stress Anti-Rob ↑ | Stress WER ↓ | Stress CER Phon ↓ |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| Real Studio Recording (`24 kHz`) | 30/30 | 88.1 | 95.1 | 77.8 | 3.77 | 3.61 | — | — | — | — |
| `BigVGAN v1 Large` Copy-GT *(stock oracle)* | 30/30 | 82.7 | 88.4 | 63.8 | 3.59 | 3.42 | — | — | — | — |
| `BigVGAN-base` Copy-GT *(stock oracle)* | 30/30 | 78.8 | 84.1 | 53.9 | 3.51 | 3.28 | — | — | — | — |
| `CFM v5 + BigVGAN-base` *(stock)* | 30/30 | 81.9 | 88.1 | 54.4 | 3.60 | 3.43 | 79.9 | 50.9 | 1.84% | 0.31% |
| `CFM v5 Option A (Soup50+Sway)` + `BigVGAN-base` | 30/30 | 81.3 | 86.7 | 52.9 | 3.60 | 3.44 | 80.7 | 54.3 | 1.85% | 0.33% |
| `CFM v5 Option A+B + BigVGAN-base FT` (`8p` Sway Midpoint) | **30/30** | **83.9** | **91.6** | 59.1 | **3.74** | 3.49 | **85.0** | **65.4** | 1.85% | 0.28% |
| **`CFM v5 Fast (2p Euler) + BigVGAN-base FT` (`v1.1.0`)** | **30/30** | **85.2** | 91.0 | **64.4** | **3.74** | **3.51** | **84.8** | 64.3 | **1.67%** | **0.23%** |
| `CFM v5 Option A+B + BigVGAN v1 Large FT` (`8p` Sway Midpoint) | **30/30** | **83.5** | 90.9 | 58.5 | 3.72 | 3.48 | 84.1 | 61.9 | 1.68% | 0.33% |
### CPU, GPU & Streaming Latency (`v1.0.0` vs. `v1.1.0`)
Measured across 5 representative PT-BR sentences (`24.5 s` audio total, warmup excluded; 6 physical / 12 logical CPU cores + RTX 4070 GPU):
| Mode | Avg Latency / Sentence | Speed (RT ↑) | Streaming TTFA (avg) | Model Size |
|---|---:|---:|---:|---:|
| PyTorch CPU — `v1.0.0` Baseline (`8p` Sway Midpoint) | 3,213 ms | `1.53×` | 3,213 ms | 188.8 MB (`135.1 + 53.7`) |
| **PyTorch CPU — `v1.1.0` Distilled (`2p` Euler)** | **2,337 ms** | **`2.10×`** | 2,337 ms | **136.9 MB** (`83.2 + 53.7`) |
| **PyTorch CPU — `v1.1.0` Streaming (`2p` Euler, `chunk=24`)** | 2,610 ms | `1.88×` | **`465.3 ms`** | **136.9 MB** (`83.2 + 53.7`) |
| ONNX CPU (`6` threads) — `8p` Sway Midpoint | 4,223 ms | `1.16×` | 4,223 ms | 145.0 MB (`90.3 + 54.7`) |
| ONNX CPU (`6` threads) — `v1.1.0` Distilled (`2p` Euler) | 3,469 ms | `1.41×` | 3,469 ms | **141.0 MB** (`86.3 + 54.7`) |
| **ONNX CPU (`6` threads) — Streaming (`2p` Euler, `chunk=24`)** | 5,166 ms | `0.95×` | **`554.9 ms`** | **141.0 MB** (`86.3 + 54.7`) |
| PyTorch GPU — `8p` -> **`2p` Euler** | 535 ms -> **437 ms** | `9.10×` -> **`11.13×`** | — | `192 MB` loaded / `319 MB` peak VRAM |
See [CPU & Latency Optimization Guide](./docs/OPTIMIZATION.md) for distillation training, split ONNX export, and chunked streaming details.
---
## Audio Comparison Samples
Reference 24 kHz studio recordings compared side-by-side against unconstrained `CFM v5 Option A+B + BigVGAN-base FT` synthesis from raw text:
| Sample | Text | Reference (`24 kHz`) | Synthesized (`Lua Nova V1`) |
|---|---|---|---|
| `01` | *"Se crivarmos a proposta da permissionária, eu premo por essa decisão."* | [sample_01_ref.wav](./assets/samples/sample_01_ref.wav) | [sample_01_gen.wav](./assets/samples/sample_01_gen.wav) |
| `02` | *"Precisamos frisarmos que eles pensassem em visitar a praia de Arribá."* | [sample_02_ref.wav](./assets/samples/sample_02_ref.wav) | [sample_02_gen.wav](./assets/samples/sample_02_gen.wav) |
| `03` | *"Você sustentas a ideia de que o sínodo aguentou a pressão?"* | [sample_03_ref.wav](./assets/samples/sample_03_ref.wav) | [sample_03_gen.wav](./assets/samples/sample_03_gen.wav) |
---
## Installation
### Prerequisites
1. **Python 3.11 or 3.12** and [`uv`](https://docs.astral.sh/uv/).
2. **`espeak-ng`** available on `PATH` (used at runtime and alignment for PT-BR G2P, invoked only as an external subprocess):
- **Linux (Debian/Ubuntu):** `sudo apt-get install espeak-ng`
- **macOS:** `brew install espeak-ng`
- **Windows:** install [eSpeak NG](https://github.com/espeak-ng/espeak-ng/releases) and ensure `espeak-ng.exe` is in `PATH`.
### Install with `uv`
```bash
# Inference only
uv sync
# Inference + full training & forced alignment stack
uv sync --extra train
# Optional: ONNX tools
uv sync --extra onnx
```
> **Note on NVIDIA CUDA PyTorch wheels:** If you are training on GPU and `uv sync` resolves CPU-only wheels on your platform, install matching `torch`/`torchaudio` CUDA wheels via `--extra-index-url https://download.pytorch.org/whl/cu126` (or your CUDA version) after syncing dependencies.
---
## Model Weights (Hugging Face)
Binary model weights (`*.pt`, `*.onnx`, `*.safetensors`) are **excluded from this Git repository** and distributed via Hugging Face. Place downloaded weights in a local `checkpoints/` folder (git-ignored):
- **CFM checkpoints:**
- `cfm_v5_fast2.pt` *(recommended, `v1.1.0`)* — 2-step Euler distilled from `cfm_v5_soup50.pt` (`2.10× RT` CPU / `465 ms` TTFA)
- `cfm_v5_soup50.pt` *(baseline, `v1.0.0`)* — 8-step Sway Midpoint teacher (50/50 weight soup of `CFM v5` + `Option A` E2E)
- **Vocoder checkpoint:** `bigvgan_base_optB_2k.pt` (fine-tuned MIT `nvidia/bigvgan_base_24khz_100band`) or pass any compatible HF ID directly (`nvidia/bigvgan_base_24khz_100band` or `nvidia/bigvgan_24khz_100band`)
You can also strip legacy `Vocos` buffers from a training checkpoint before uploading to Hugging Face:
```python
from lua_nova_v1.utils import strip_legacy_vocoder
strip_legacy_vocoder("runs/cfm_v5_e2e/inference_v5_soup50.pt", "release_weights/cfm_v5_soup50_fp16.pt", fp16=True)
```
---
## Quickstart
### CLI Inference
```bash
uv run lua-nova-speak \
--text "Olá! Dia 22/03 às 14h30 custou R$ 45,90; você prefere testar o modelo agora?" \
--out output.wav \
--cfm checkpoints/cfm_v5_soup50.pt \
--vocoder checkpoints/bigvgan_base_optB_2k.pt \
--device cpu
```
### Python API (PyTorch Streaming & 2-Step Fast Mode)
```python
import numpy as np
from lua_nova_v1 import Synthesizer
synth = Synthesizer.from_checkpoints(
cfm_path="checkpoints/cfm_v5_fast2.pt",
vocoder_path_or_id="checkpoints/bigvgan_base_optB_2k.pt",
device="cpu",
)
# Full utterance (2 Euler steps)
wav = synth.speak(
"Você tem certeza de que o modelo já fala perguntas com naturalidade?",
n_steps=2,
solver="euler",
sway_coef=0.0,
temperature=0.35,
)
synth.save_wav("output.wav", wav)
# Low-latency chunked streaming (TTFA ~465 ms on CPU)
chunks = list(
synth.speak_stream(
"Olá! Este áudio está sendo gerado em partes com transição suave.",
n_steps=2,
solver="euler",
sway_coef=0.0,
chunk_frames=24,
)
)
synth.save_wav("output_stream.wav", np.concatenate(chunks))
```
### ONNX Runtime CPU (PyTorch-free Deployment)
```bash
# Export split opset-17 ONNX graphs
uv run lua-nova-export-onnx \
--cfm checkpoints/cfm_v5_fast2.pt \
--vocoder checkpoints/bigvgan_base_optB_2k.pt \
--out-dir checkpoints/onnx \
--steps 2 --solver euler --sway-coef 0.0 --verify
# Synthesize directly with ONNX Runtime CPU + streaming
uv run lua-nova-speak \
--onnx-cfm checkpoints/onnx/cfm_v5.onnx \
--onnx-vocoder checkpoints/onnx/bigvgan_base_ft.onnx \
--text "Síntese em CPU via ONNX Runtime com streaming por chunks." \
--out output_onnx.wav --stream --chunk-frames 24
```
```python
from lua_nova_v1 import OnnxSynthesizer
ox = OnnxSynthesizer("checkpoints/onnx/cfm_v5.onnx", "checkpoints/onnx/bigvgan_base_ft.onnx")
wav = ox.speak("Oi! Tudo bem com você?")
ox.save_wav("onnx.wav", wav)
```
---
## Documentation & Guides
- [Architecture & Key Design Choices](./docs/ARCHITECTURE.md)
- [CPU & Latency Optimization Guide (Distillation, ONNX & Streaming)](./docs/OPTIMIZATION.md)
- [Fine-Tuning on a New Voice](./docs/FINE_TUNING.md)
- [Training From Scratch Guide](./docs/TRAINING_FROM_SCRATCH.md)
- [Third-Party Notices & Licenses](./THIRD_PARTY_NOTICES.md)
---
## Repository Layout
```text
lua-nova-v1/
├── assets/samples/ # Paired 24 kHz studio reference & generated audio examples
├── docs/ # Architecture, optimization, training, and fine-tuning guides
├── src/lua_nova_v1/
│ ├── config.py # ModelConfig & CFMConfig dataclasses
│ ├── text/ # PT-BR normalizer (numbers, currency, dates) & eSpeak G2P
│ ├── models/ # Front end, ProsodyFlow, OT-CFM v5 + Sway Sampling, BigVGAN wrapper
│ ├── data/ # Acoustic prep, wav2vec2 CTC forced aligner, Dataset & BucketSampler
│ ├── training/ # Stage 1, ProsodyFlow, CFM v5, Option A (E2E), Option B (Vocoder FT), Distill
│ ├── export/ # Split opset-17 ONNX exporters for CFM v5 and BigVGAN
│ ├── inference/ # PyTorch Synthesizer, OnnxSynthesizer, overlap-crossfade streaming, CLI
│ └── utils/ # RMS/fade/PCM16 post-processing, weight souping, checkpoint stripping
├── tests/ # Unit & end-to-end synthetic verification tests
└── third_party/bigvgan/ # MIT-licensed NVIDIA BigVGAN generator, losses & discriminators
```
---
## License
Code authored in this repository is released under the **Apache License 2.0** ([LICENSE](./LICENSE)). Components under `third_party/bigvgan/` are MIT-licensed by NVIDIA ([third_party/bigvgan/LICENSE](./third_party/bigvgan/LICENSE)). See [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md).1234567891011121314# Third-Party Notices
This repository includes and builds upon the following permissively licensed open-source projects:
1. **tiny-voca** (Apache License 2.0)
- Upstream front end, alignment pipeline, prosody/acoustic backbone, and Source-Filter architecture.
- License: see [LICENSE](./LICENSE).
2. **NVIDIA BigVGAN** (MIT License)
- Files included under `third_party/bigvgan/` (`bigvgan.py`, `activations.py`, `env.py`, `utils.py`, `meldataset.py`, `discriminators.py`, `loss.py`, `alias_free_activation/`).
- License: see [third_party/bigvgan/LICENSE](./third_party/bigvgan/LICENSE).
3. **eSpeak NG** (GPL-3.0+, invoked strictly as an external subprocess binary at runtime)
- Phonetic G2P (`espeak-ng -v pt-br`) is executed as an external system command and is not bundled in this repository.1234567891011121314151617181920212223242526272829303132333435363738# Architecture Overview
Lua Nova V1 decouples **Brazilian Portuguese linguistic/prosodic generation** from **universal waveform reconstruction**, allowing fast acoustic training (`< 3.5 GB` VRAM) and plug-and-play compatibility with MIT-licensed `BigVGAN` vocoders.
```text
Raw Text
└─▶ PT-BR Normalizer (numbers, currency, dates, ordinals, time, abbreviations)
└─▶ eSpeak-NG G2P (`pt-br`, 85-symbol inventory + primary/secondary lexical stress)
└─▶ 4-layer RoPE Text Encoder
├─▶ LinguisticContextAdapter (26 word/stress/clause geometry features)
├─▶ Duration Predictor + 4-step Generative DurationFlow
└─▶ Frame Expansion + 4-step Multiscale ProsodyFlow (F0, voicing, energy)
└─▶ 5-layer RoPE Acoustic Prior
└─▶ 8-layer FlowDecoder (OT-CFM, d=320, Sway Sampling s=-0.5)
└─▶ Slaney 100-Band Physical Log-Mel [24 kHz, hop=256]
└─▶ BigVGAN-base (MIT, gently adapted via Option B)
└─▶ 24 kHz PCM Waveform
```
## Core Components
### 1. Deterministic Text Normalizer & Unified G2P (`src/lua_nova_v1/text/`)
- **`normalizer.py`:** Pure Python normalizer converting cardinals, ordinals, percentages, `R$` currencies, `DD/MM(/YYYY)` dates, `HHhMM` times, Roman numerals, and common PT-BR abbreviations before phonemization.
- **`phonemizer.py`:** Tokenizes `espeak-ng --ipa` output into a fixed 85-symbol vocabulary (`PHONES + PUNCTUATION + SPECIALS`) paired with a parallel stress tensor (`0 = unstressed`, `1 = primary`, `2 = secondary`). Explicit `<sp>` and punctuation tokens carry predicted silence pauses.
### 2. Generative Prosody & Context (`src/lua_nova_v1/models/cfm.py`)
- **`LinguisticContextAdapter`:** Computes 26 ONNX-safe utterance, word, stress-distance, and clause geometry features so questions (`?`), exclamations (`!`), and comma boundaries modulate intonation globally.
- **`DurationFlow`:** 4-step OT-CFM flow predictor over phoneme `log1p(frames)`, paired with a separate binary pause-presence head.
- **`ProsodyFlow`:** 4-step OT-CFM contour generator over `(log_F0, energy)` fed with a smooth multiscale 1D-convolved Gaussian prior (`smooth_prosody_noise`) to avoid robotic frame-to-frame pitch jitter.
### 3. Slaney-100 OT-CFM Decoder (`FlowDecoder`)
- 8 AdaLN-Zero RoPE + depthwise-conv blocks (`d=320`, `8` heads, `ff=1024`, `16.27M` flow/acoustic parameters) centered on the deterministic `AcousticStack` prior mel (`x0 = prior + sigma * gate * eps`).
- Trained with `t` logit-normal sampling, temporal (`dt`) and cross-band (`df`) mel derivative losses, high-frequency mel weighting (`40` top bands × `1.4`), and **Sway Sampling** (`sway_coef = -0.5` concentrating ODE steps near noisy initial flow where global structure forms).
### 4. Artifact Elimination Strategy (Option A + Option B)
Why two gentle stages beat brute-force training:
1. **Option A (`training/cfm_e2e.py` + `utils/checkpoint.py`):** Unrolls 4 checkpointed ODE steps through a **frozen MIT BigVGAN** and **frozen NVIDIA 5M-step pretrained MPD/MRD discriminators** (`bigvgan_discriminator_optimizer.pt`), plus a **50/50 weight soup** (`soup_checkpoints`) with the base CFM v5 weights. This fixes mel oversmoothing and acoustic–vocoder mismatch without drifting harmonics.
2. **Option B (`training/vocoder_ft.py`):** Fine-tunes `BigVGAN-base` (`14M` params) for 2,000 steps using **NVIDIA's pretrained 5M-step MIT MPD/MRD discriminators** (`--pretrained-disc --disc-warmup 0`) on 60% Option A predicted mels + 40% ground-truth `24 kHz` recordings. Starting from pretrained discriminators prevents phase/harmonic collapse (`CPP` rises rather than falls) and boosts even Copy-GT reconstruction.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139# Fine-Tuning Guide (New PT-BR Speaker or Domain)
Because **Lua Nova V1** predicts spectrograms in BigVGAN's universal **24 kHz 100-band Slaney log-mel space**, adapting to a new Brazilian Portuguese speaker or speaking style is fast and does **not** require training a vocoder from scratch.
---
## Requirements
- **GPU:** NVIDIA GPU with `6–8 GB` VRAM (`CFM` training uses `< 3.5 GB`; optional `Option B` vocoder adaptation on `BigVGAN-base` uses `~6.8 GB`).
- **Audio Data:**
- **Minimum:** `30–60 minutes` of clean `24 kHz` mono speech (single speaker, quiet studio or denoised).
- **Recommended:** `2–4 hours` for maximum voice likeness and prosody stability.
- **Estimated Time (RTX 4070 class GPU):**
- Data preparation + CTC alignment: `~3–6 min` for 1h of audio
- Acoustic CFM adaptation (`10k–15k` steps): `~15–22 min`
- *(Optional)* Gentle BigVGAN-base Option B polish (`1k–2k` steps): `~8–15 min`
---
## 1. Prepare Your Dataset Manifest
Create two manifests (`train.jsonl` and `validation.jsonl`) with **no overlapping text or IDs** between splits. Paths in `audio` are resolved relative to the JSONL file:
```json
{"id": "utt_0001", "text": "Olá, esta é uma frase de teste em português.", "voice_id": "F1", "audio": "wavs/utt_0001.wav"}
```
> Resample all WAVs explicitly to **24,000 Hz mono PCM** beforehand (`ffmpeg -i in.wav -ar 24000 -ac 1 out.wav`). Keep peak amplitude $\le 1.0$.
> **Speaker ID tip:** For single-speaker fine-tuning starting from our pretrained checkpoint, keeping `"voice_id": "F1"` reuses existing speaker embeddings directly without resizing model parameters.
---
## 2. Extract Acoustic Features & Forced Alignments
```bash
# Step A: Acoustic feature extraction (wave, 80-mel, F0 pitch via Parselmouth, RMS energy)
uv run lua-nova-prepare --inputs data/raw/train.jsonl --split train --output data/features
uv run lua-nova-prepare --inputs data/raw/validation.jsonl --split validation --output data/features
# Step B: Forced alignment via pretrained wav2vec2 CTC espeak recognizer
uv run lua-nova-annotate \
--features data/features \
--output data/annotations \
--dataset-revision my-voice-v1 \
--device cuda \
--refine 2 --stage refined-2
```
> Both steps are resumable via `--resume`. Alignments check phoneme rate, vowel voicing, and silence pauses automatically, writing rejected outliers to `rejected.jsonl`.
---
## 3. Fine-Tune `LuaNovaCFM v5` on Your Voice
Start directly from the pretrained `cfm_v5_soup50.pt` checkpoint downloaded from Hugging Face:
```bash
uv run lua-nova-train-cfm \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--init-cfm checkpoints/cfm_v5_soup50.pt \
--no-freeze-frontend \
--output runs/my_voice_cfm \
--steps 12000 \
--lr 1.5e-4 --min-lr 1e-5 --warmup 300 \
--save-every 3000 --val-every 500 \
--device cuda
```
- Use `--no-freeze-frontend` when adapting timbre **plus** speaking cadence/pitch range to a brand-new speaker.
- Use `--freeze-frontend` if your voice has very few minutes (`< 45 min`) or matches existing speaking cadence closely and only needs acoustic timbre tuning.
*(Optional)* If your voice expresses notably different intonation patterns (questions, pauses, stress shifts), run a short ProsodyFlow stage first before `lua-nova-train-cfm`:
```bash
uv run lua-nova-train-prosody \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--init-cfm checkpoints/cfm_v5_soup50.pt \
--output runs/my_voice_prosody \
--steps 4000 --eval-every 1000 --save-every 2000 --device cuda
```
---
## 4. *(Optional)* Option A + Option B Final Polish
Once `runs/my_voice_cfm/inference_v5_ema.pt` converges, you can optionally remove subtle acoustic-vocoder mismatch:
1. **Option A (E2E through frozen BigVGAN + frozen NVIDIA MIT discriminators):**
```bash
uv run lua-nova-train-e2e \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--init-v5 runs/my_voice_cfm/inference_v5_ema.pt \
--output runs/my_voice_optA \
--steps 1500 --save-steps 1000 1500 --device cuda
```
And create a 50/50 weight soup in Python:
```python
from lua_nova_v1.utils import soup_checkpoints
soup_checkpoints(
"runs/my_voice_cfm/inference_v5_ema.pt",
"runs/my_voice_optA/inference_v5_e2e_step-001500.pt",
"runs/my_voice_optA/inference_v5_soup50.pt",
alpha=0.5,
)
```
2. **Option B (Gentle `BigVGAN-base` FT with NVIDIA 5M-step pretrained discriminators):**
```bash
uv run lua-nova-train-vocoder \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--cfm-ckpt runs/my_voice_optA/inference_v5_soup50.pt \
--model-id nvidia/bigvgan_base_24khz_100band \
--pretrained-disc --disc-warmup 0 \
--output runs/my_voice_vocoder_optB \
--steps 2000 --save-steps 1000 1500 2000 \
--batch-size 6 --grad-accum 2 --lr-g 1e-5 --lr-d 1e-5 --device cuda
```
---
## 5. Run Inference on Your New Voice
```bash
uv run lua-nova-speak \
--text "Minha nova voz em português está pronta para falar!" \
--out test_voice.wav \
--cfm runs/my_voice_optA/inference_v5_soup50.pt \
--vocoder runs/my_voice_vocoder_optB/bigvgan_ft_step-002000.pt \
--device cpu
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# CPU & Latency Optimization Guide (`v1.1.0`)
Lua Nova V1 v1.1 adds three production optimizations on top of the baseline `CFM v5 Option A+B + BigVGAN-base FT` stack (`~35.8M` active parameters):
1. **Trajectory Distillation (`8-step Sway Midpoint -> 2-step Euler`)** via `lua-nova-train-distill`
2. **Split ONNX Runtime CPU Export (opset 17)** via `lua-nova-export-onnx` and `OnnxSynthesizer`
3. **Overlap-Crossfaded Chunked Streaming** (`Synthesizer.speak_stream` / `OnnxSynthesizer.speak_stream`)
---
## 1. Benchmark Results (Before vs. After)
Measured across 5 representative PT-BR sentences totaling **24.5 s** of 24 kHz audio (warmup excluded; desktop 6 physical / 12 logical CPU cores + RTX 4070 GPU) and audited on the frozen **`tts-eval` v1.0.0** suite (`30` held-out studio sentences + `36` PT-BR stress sentences).
### Latency & Throughput
| Runtime & Configuration | Audio / Wall (avg per utt) | Speed (RT ↑) | Streaming TTFA (avg) | Model Footprint |
|---|---:|---:|---:|---:|
| PyTorch CPU — Baseline (`8p` Sway Midpoint) | 3,213 ms | `1.53×` | 3,213 ms | 188.8 MB (`135.1 + 53.7`) |
| **PyTorch CPU — Distilled (`2p` Euler)** | **2,337 ms** | **`2.10×`** | 2,337 ms | **136.9 MB** (`83.2 + 53.7`) |
| **PyTorch CPU — Streaming (`2p` Euler, `chunk=24`)** | 2,610 ms | `1.88×` | **`465.3 ms`** | **136.9 MB** (`83.2 + 53.7`) |
| ONNX CPU (`6` threads) — Baseline (`8p` Sway Midpoint) | 4,223 ms | `1.16×` | 4,223 ms | 145.0 MB (`90.3 + 54.7`) |
| ONNX CPU (`6` threads) — Distilled (`2p` Euler) | 3,469 ms | `1.41×` | 3,469 ms | **141.0 MB** (`86.3 + 54.7`) |
| **ONNX CPU (`6` threads) — Streaming (`2p` Euler, `chunk=24`)** | 5,166 ms | `0.95×` | **`554.9 ms`** | **141.0 MB** (`86.3 + 54.7`) |
| PyTorch GPU — Baseline (`8p` Sway Midpoint) | 535 ms | `9.10×` | 535 ms | — |
| **PyTorch GPU — Distilled (`2p` Euler)** | **437 ms** | **`11.13×`** | 437 ms | — |
> **Runtime selection tip:** On x86 CPUs, PyTorch (`oneDNN` / MKL-DNN) executes `BigVGAN`'s grouped dilated 1D convolutions and `SnakeBeta` activations faster than ONNX Runtime CPU (`2.10× RT` / `465 ms` TTFA vs. `1.41× RT` / `555 ms` TTFA), whereas **ONNX Runtime** removes the PyTorch runtime dependency for C++/Go/Rust or edge hosts and still achieves `555 ms` first-audio latency in streaming mode. If physical core count is `P`, passing `--threads P` avoids Hyper-Threading contention.
### Frozen `tts-eval` v1.0.0 Quality Preservation
| Model Variant | Held-out (30) | Nat | Anti-Rob | SCOREQ ↑ | Stress PT-BR (36) | WER ↓ | Phonetic CER ↓ |
|---|---:|---:|---:|---:|---:|---:|---:|
| Human Studio Reference (`24 kHz`) | **88.1** | 95.1 | 77.8 | 3.77 | — | — | — |
| `v1.0.0` Baseline (`8p` Sway Midpoint) | **83.9** | 91.6 | 59.1 | 3.74 | **85.0** | 1.85% | 0.28% |
| **`v1.1.0` Distilled (`2p` Euler, 3k steps)** | **85.2** | 91.0 | **64.4** | 3.74 | **84.8** | **1.67%** | **0.23%** |
Cutting the ODE solver from **16 FlowDecoder evaluations** (`8` Midpoint steps) down to **2 Euler evaluations** preserves and even improves held-out naturalness stability and lowers stress-suite transcription error rate (`1.67%` WER).
---
## 2. How to Run Each Optimization
### A. Distill an `8-step Sway Midpoint` Model to `2-step Euler`
Only `flow` (`14.3M` params) is trained while the phonetic encoder, duration flow, prosody flow, and prior head remain frozen, matching the inference noise scale (`teacher_temp=0.35`):
```bash
lua-nova-train-distill \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--teacher runs/cfm_v5_e2e/inference_v5_soup50.pt \
--output runs/cfm_v5_fast2 \
--steps 3000 \
--teacher-steps 8 \
--teacher-sway -0.5 \
--teacher-temp 0.35 \
--student-steps 2 \
--lr 1e-4 \
--save-every 3000
```
Synthesize with the distilled checkpoint in PyTorch:
```bash
lua-nova-speak \
--cfm runs/cfm_v5_fast2/inference_v5_fast2_step-003000.pt \
--vocoder runs/bigvgan_base_optB/bigvgan_ft_step-002000.pt \
--steps 2 --solver euler --sway-coef 0.0 --temperature 0.35 \
--text "Olá! A destilação reduziu a geração para dois passos Euler." \
--out fast2.wav --stream --chunk-frames 24
```
### B. Export Split ONNX Graphs (opset 17)
Lua Nova V1 exports two composable ONNX graphs so clients can reuse the same vocoder across acoustic checkpoints or decode mel chunks for streaming:
- **`cfm_v5_fast2.onnx`**: `("tokens", "stress", "voice", "speed", "pitch_shift", "pitch_range") -> ("phys_mel", "frame_lengths")` plus `<stem>.meta.json`
- **`bigvgan_base_ft.onnx`**: `("mel",) -> ("audio",)` with dynamic `frames` axis (`[1, T, 100] -> [1, T*256]`) and folded alias-free resampling weights
```bash
lua-nova-export-onnx \
--cfm runs/cfm_v5_fast2/inference_v5_fast2_step-003000.pt \
--vocoder runs/bigvgan_base_optB/bigvgan_ft_step-002000.pt \
--out-dir runs/onnx_v5 \
--cfm-name cfm_v5_fast2.onnx \
--vocoder-name bigvgan_base_ft.onnx \
--steps 2 --solver euler --sway-coef 0.0 --temperature 0.35 --verify
```
### C. Streaming Python & CLI Inference
```python
import numpy as np
from lua_nova_v1 import OnnxSynthesizer
synth = OnnxSynthesizer("runs/onnx_v5/cfm_v5_fast2.onnx", "runs/onnx_v5/bigvgan_base_ft.onnx")
chunks = list(synth.speak_stream("Primeira frase curta. Segunda frase longa com pausas.", chunk_frames=24))
wav = np.concatenate(chunks)
synth.save_wav("streamed.wav", wav)
```
Or via CLI:
```bash
lua-nova-speak \
--onnx-cfm runs/onnx_v5/cfm_v5_fast2.onnx \
--onnx-vocoder runs/onnx_v5/bigvgan_base_ft.onnx \
--text "Síntese em CPU sem PyTorch e com streaming por chunks." \
--out onnx_stream.wav --stream --chunk-frames 24
```
Chunk seams use symmetric `context_frames=8` receptive-field overlap during vocoder decoding plus a raised-cosine Hann crossfade across `fade_frames=4` (`1,024` samples), preserving exact waveform length without boundary clicks.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# Training From Scratch Guide
Full end-to-end training pipeline to train **Lua Nova V1** from raw audio and text without relying on any pre-trained Lua Nova V1 acoustic weights.
---
## Recommended Hardware & Dataset Size
- **Dataset:** `6–10+ hours` (`~5,000–8,000` clean 24 kHz mono utterances, e.g., multi-thousand sentence single-speaker studio corpus).
- **Hardware:** NVIDIA GPU with `>= 8 GB` VRAM (`RTX 3070 / 4070` or better; peak VRAM during Option B vocoder FT is `6.76 GB`), `16+ GB` system RAM, `~15 GB` free disk for feature tensors and HF caches.
- **Total Wall Time (RTX 4070 reference):** `~2 hours` across all stages.
---
## Stage 0 — Acoustic Features & CTC Forced Alignment
Ensure `train.jsonl` and `validation.jsonl` share **zero texts or IDs**. Audio files must be `24,000 Hz` mono WAV.
```bash
uv run lua-nova-prepare --inputs data/raw/train.jsonl --split train --output data/features
uv run lua-nova-prepare --inputs data/raw/validation.jsonl --split validation --output data/features
uv run lua-nova-annotate \
--features data/features \
--output data/annotations \
--dataset-revision ptbr-scratch-v1 \
--device cuda \
--refine 2 --stage refined-2
```
For multi-speaker datasets, provide a `--config my_config.json` defining `"speakers": ["F1", "M1", ...]` to both `lua-nova-prepare`, `lua-nova-annotate`, and `lua-nova-train-stage1`.
---
## Stage 1 — Phonetic Front End & Baseline (`lua-nova-train-stage1`)
Trains the 4-layer RoPE phonetic encoder, duration/pause predictors, prosody predictor, and 5-layer acoustic stack (`SourceFilter` head is used only to bootstrap strong encoder/prosody representations cleanly without BigVGAN backprop):
```bash
uv run lua-nova-train-stage1 \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--output runs/stage1 \
--steps 40000 \
--batch-frames 9000 --max-batch 32 \
--learning-rate 3e-4 --warmup 1000 \
--save-every 5000 --keep-every 10000 --device cuda
```
---
## Stage 2 — Linguistic Context & ProsodyFlow (`lua-nova-train-prosody`)
Freezes encoder/acoustic modules and trains the 26-channel `LinguisticContextAdapter`, 4-step `DurationFlow`, and 4-step multiscale `ProsodyFlow`:
```bash
uv run lua-nova-train-prosody \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--init-stage1 runs/stage1/inference.pt \
--output runs/prosody_flow \
--steps 12000 \
--learning-rate 2e-4 --warmup 600 \
--eval-every 2000 --save-every 3000 --sample-every 0 --device cuda
```
---
## Stage 3 — OT-CFM v5 in Slaney-100 Mel Space (`lua-nova-train-cfm`)
Precomputes exact `BigVGAN` Slaney 100-band log-mels in RAM (leaving disk feature files untouched) and trains the 8-layer `FlowDecoder` (`d=320`) with CFG dropout and temporal/spectral derivative losses:
```bash
uv run lua-nova-train-cfm \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--init-cfm runs/prosody_flow/inference_item3.pt \
--output runs/cfm_v5 \
--steps 25000 \
--batch-frames 6000 --max-batch 24 \
--lr 3e-4 --min-lr 1.5e-5 --warmup 500 \
--save-every 5000 --val-every 1000 --device cuda
```
---
## Stage 4 — Option A: E2E Polish Through Frozen BigVGAN + NVIDIA MIT Discriminators
Unrolls 4 ODE steps with `sway_coef=-0.5` through frozen `nvidia/bigvgan_base_24khz_100band` and frozen NVIDIA 5M-step pretrained `MPD`/`MRD` critics (`bigvgan_discriminator_optimizer.pt`), then averages 50/50 with Stage 3 weights:
```bash
uv run lua-nova-train-e2e \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--init-v5 runs/cfm_v5/inference_v5_ema.pt \
--output runs/cfm_v5_e2e \
--steps 2000 --save-steps 1000 1500 2000 \
--batch-size 4 --grad-accum 3 --crop-frames 40 \
--lr 4e-5 --min-lr 4e-6 --device cuda
```
Create the 50/50 weight soup (`1500` steps gave the best trade-off between perceptual cleanliness and spectral sharpness):
```python
from lua_nova_v1.utils import soup_checkpoints
soup_checkpoints(
"runs/cfm_v5/inference_v5_ema.pt",
"runs/cfm_v5_e2e/inference_v5_e2e_step-001500.pt",
"runs/cfm_v5_e2e/inference_v5_soup50.pt",
alpha=0.5,
)
```
---
## Stage 5 — Option B: Gentle Vocoder Adaptation (`lua-nova-train-vocoder`)
Fine-tunes `nvidia/bigvgan_base_24khz_100band` for 2,000 steps using **pretrained NVIDIA MPD/MRD discriminators** (`--pretrained-disc --disc-warmup 0`) on 60% Stage-4 predicted mels + 40% ground-truth mels:
```bash
uv run lua-nova-train-vocoder \
--train data/annotations/train.jsonl \
--validation data/annotations/validation.jsonl \
--cfm-ckpt runs/cfm_v5_e2e/inference_v5_soup50.pt \
--cfm-steps 8 --cfm-temp 0.35 --sway-coef -0.5 \
--model-id nvidia/bigvgan_base_24khz_100band \
--pretrained-disc --disc-warmup 0 \
--output runs/bigvgan_base_optB \
--steps 2000 --save-steps 500 1000 1500 2000 \
--batch-size 6 --grad-accum 2 --crop-frames 32 --cfm-prob 0.60 \
--lr-g 1e-5 --min-lr-g 1e-6 --warmup-g 100 \
--lr-d 1e-5 --lr-d-post 1e-5 --min-lr-d 1e-6 \
--val-every 250 --log-every 10 --device cuda
```
> If adapting `nvidia/bigvgan_24khz_100band` (`112M` params) on `8–12 GB` VRAM GPUs, add `--ema-on-cpu --batch-size 2 --grad-accum 6 --lr-g 5e-6 --lr-d 5e-6`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "lua-nova-v1"
version = "1.1.0"
description = "Compact 24 kHz Brazilian Portuguese TTS combining OT-CFM, ProsodyFlow, Sway Sampling, and BigVGAN-base"
readme = "README.md"
license = { text = "Apache-2.0" }
requires-python = ">=3.11,<3.13"
dependencies = [
"torch>=2.7",
"torchaudio>=2.7",
"numpy>=1.24,<3",
"soundfile>=0.12,<1",
"librosa>=0.10.2,<1",
"huggingface-hub>=0.34,<2",
"scipy>=1.10,<2",
"truststore>=0.10",
"matplotlib>=3.8",
"tqdm>=4.66",
]
[project.optional-dependencies]
train = [
"vocos>=0.1.0",
"pyarrow>=15",
"transformers>=4.40,<5",
"praat-parselmouth>=0.4.7",
"faster-whisper>=1.2.1",
"av<19",
"jiwer>=3,<5",
]
onnx = [
"onnx>=1.16",
"onnxruntime>=1.18",
"onnxscript>=0.1",
]
dev = [
"pytest>=8",
]
[project.scripts]
lua-nova-speak = "lua_nova_v1.inference.cli:main"
lua-nova-prepare = "lua_nova_v1.data.prepare:main"
lua-nova-annotate = "lua_nova_v1.data.annotate:main"
lua-nova-train-stage1 = "lua_nova_v1.training.stage1:main"
lua-nova-train-prosody = "lua_nova_v1.training.prosody_flow:main"
lua-nova-train-cfm = "lua_nova_v1.training.cfm:main"
lua-nova-train-e2e = "lua_nova_v1.training.cfm_e2e:main"
lua-nova-train-vocoder = "lua_nova_v1.training.vocoder_ft:main"
lua-nova-train-distill = "lua_nova_v1.training.distill:main"
lua-nova-export-onnx = "lua_nova_v1.export.onnx_export:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.uv]
package = true1234567891011121314151617181920212223242526"""Lua Nova V1: Compact 24 kHz Brazilian Portuguese Text-to-Speech."""
from .config import ANNOTATION_VERSION, CHECKPOINT_FORMAT, CFMConfig, Config, ModelConfig
from .inference import OnnxSynthesizer, Synthesizer
from .models import BigVGANMelExtractor, BigVGANVocoderWrapper, LuaNovaBase, LuaNovaCFM
from .text import normalize_ptbr_text, phonemize, phonemize_ptbr
__version__ = "1.1.0"
__all__ = [
"ANNOTATION_VERSION",
"BigVGANMelExtractor",
"BigVGANVocoderWrapper",
"CFMConfig",
"CHECKPOINT_FORMAT",
"Config",
"ModelConfig",
"OnnxSynthesizer",
"Synthesizer",
"LuaNovaBase",
"LuaNovaCFM",
"__version__",
"normalize_ptbr_text",
"phonemize",
"phonemize_ptbr",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199"""Model and Flow-Matching configuration dataclasses for Lua Nova V1."""
from __future__ import annotations
from dataclasses import asdict, dataclass
import hashlib
import json
CHECKPOINT_FORMAT = 4
ANNOTATION_VERSION = 3
def _digest(value: object) -> str:
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
@dataclass(frozen=True)
class Config:
"""Acoustic front-end configuration (24 kHz PT-BR, 85-symbol eSpeak-NG inventory)."""
sample_rate: int = 24000
hop: int = 256
n_fft: int = 1024
n_mels: int = 80
f0_min: float = 50.0
f0_max: float = 600.0
speakers: tuple[str, ...] = ("F1",)
vocab_size: int = 85
channels: int = 192
heads: int = 4
feedforward: int = 640
kernel: int = 7
encoder_layers: int = 4
prosody_layers: int = 2
acoustic_layers: int = 5
dropout: float = 0.1
predictor_channels: int = 128
synth_fft: int = 512
synth_hop: int = 128
noise_fft: int = 256
noise_hop: int = 64
cep_causal: int = 80
cep_anti: int = 16
noise_cep: int = 32
harmonic_limit: float = 0.47
vocoder_type: str = "source_filter"
vocos_model: str = "charactr/vocos-mel-24khz"
vocos_n_mels: int = 100
max_tokens: int = 512
max_frames: int = 3000
mel_mean: float = -5.0
mel_scale: float = 5.0
energy_mean: float = -4.0
energy_scale: float = 2.0
pitch_reference_hz: float = 200.0
def __post_init__(self) -> None:
from .text.phonemizer import SYMBOLS
if self.vocab_size != len(SYMBOLS):
raise ValueError(f"vocab_size must equal the phoneme inventory size {len(SYMBOLS)}")
if self.channels % self.heads or (self.channels // self.heads) % 2:
raise ValueError("channels must be divisible by heads with an even head width")
if not self.speakers or len(set(self.speakers)) != len(self.speakers):
raise ValueError("speaker names must be unique and nonempty")
for fft, hop in ((self.synth_fft, self.synth_hop), (self.noise_fft, self.noise_hop)):
if fft != 4 * hop or self.hop % hop:
raise ValueError("synthesis windows need 4x overlap and a hop dividing the acoustic hop")
if self.cep_causal + self.cep_anti >= self.synth_fft // 2 or self.noise_cep >= self.noise_fft // 2:
raise ValueError("cepstrum orders must be well below half the synthesis FFT size")
if min(self.encoder_layers, self.prosody_layers, self.acoustic_layers, self.kernel) < 1 or not self.kernel % 2:
raise ValueError("layer counts must be positive and the kernel odd")
if min(self.mel_scale, self.energy_scale) <= 0 or not 0 < self.harmonic_limit < 0.5:
raise ValueError("invalid normalization scale or harmonic limit")
if self.vocoder_type not in ("source_filter", "vocos") or self.vocos_n_mels < 1:
raise ValueError("invalid vocoder_type or vocos_n_mels")
def to_dict(self) -> dict:
return asdict(self)
@classmethod
def from_dict(cls, value: dict) -> "Config":
return cls(**{**value, "speakers": tuple(value["speakers"])})
@property
def fingerprint(self) -> str:
return _digest(self.to_dict())
@property
def acoustic_config(self) -> dict:
"""Settings that determine stored wave/mel/prosody tensors."""
fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max")
return {
**{key: getattr(self, key) for key in fields},
"feature_version": 2,
"pitch_reference_hz": 200,
"log_floor": 1e-5,
}
@property
def acoustic_fingerprint(self) -> str:
return _digest(self.acoustic_config)
@property
def legacy_feature_fingerprint(self) -> str:
fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max", "speakers")
return _digest(
{
**{key: getattr(self, key) for key in fields},
"vocab_size": 259,
"feature_version": 2,
"frontend_version": 2,
"pitch_reference_hz": 200,
"log_floor": 1e-5,
}
)
ModelConfig = Config
@dataclass
class CFMConfig:
"""Conditional Flow Matching + ProsodyFlow configuration."""
base: Config
flow_channels: int = 256
flow_layers: int = 6
flow_heads: int = 4
flow_feedforward: int = 768
flow_kernel: int = 5
flow_dropout: float = 0.05
prior_sigma: float = 0.40
cfg_dropout: float = 0.10
use_acoustic_prior: bool = True
use_f0_harmonics: bool = True
prosody_hidden_dropout: float = 0.15
acoustic_from_frames: bool = False
use_energy_gate: bool = False
use_ling_context: bool = False
use_duration_flow: bool = False
use_prosody_flow: bool = False
prosody_context_layers: int = 2
dur_flow_channels: int = 128
dur_flow_layers: int = 3
dur_flow_heads: int = 4
dur_flow_feedforward: int = 384
dur_flow_kernel: int = 3
dur_flow_sigma: float = 0.25
dur_flow_steps: int = 4
dur_flow_temp: float = 0.50
prosody_flow_channels: int = 128
prosody_flow_layers: int = 4
prosody_flow_heads: int = 4
prosody_flow_feedforward: int = 384
prosody_flow_kernel: int = 7
prosody_flow_sigma: float = 0.22
prosody_flow_steps: int = 4
prosody_flow_temp: float = 0.75
default_pitch_range: float = 1.0
mel_space: str = "vocos"
def to_dict(self) -> dict:
d = asdict(self)
d["base"] = self.base.to_dict()
return d
@classmethod
def from_dict(cls, data: dict) -> "CFMConfig":
d = dict(data)
d["base"] = Config.from_dict(d["base"])
d.setdefault("use_acoustic_prior", False)
d.setdefault("use_f0_harmonics", False)
d.setdefault("prior_sigma", 0.65)
d.setdefault("prosody_hidden_dropout", 0.0)
d.setdefault("acoustic_from_frames", False)
d.setdefault("use_energy_gate", False)
d.setdefault("use_ling_context", False)
d.setdefault("use_duration_flow", False)
d.setdefault("use_prosody_flow", False)
d.setdefault("prosody_context_layers", 2)
d.setdefault("dur_flow_channels", 128)
d.setdefault("dur_flow_layers", 3)
d.setdefault("dur_flow_heads", 4)
d.setdefault("dur_flow_feedforward", 384)
d.setdefault("dur_flow_kernel", 3)
d.setdefault("dur_flow_sigma", 0.25)
d.setdefault("dur_flow_steps", 4)
d.setdefault("dur_flow_temp", 0.50)
d.setdefault("prosody_flow_channels", 128)
d.setdefault("prosody_flow_layers", 4)
d.setdefault("prosody_flow_heads", 4)
d.setdefault("prosody_flow_feedforward", 384)
d.setdefault("prosody_flow_kernel", 7)
d.setdefault("prosody_flow_sigma", 0.22)
d.setdefault("prosody_flow_steps", 4)
d.setdefault("prosody_flow_temp", 0.75)
d.setdefault("default_pitch_range", 1.0)
d.setdefault("mel_space", "vocos")
return cls(**d)123456789101112131415"""Dataset loading, alignment, and preparation tools."""
from .aligner import ALIGNER_MODEL, AlignmentSettings, PhoneRecognizer, align_utterance
from .dataset import AnnotatedDataset, BucketSampler, collate, continuous_pitch
__all__ = [
"ALIGNER_MODEL",
"AlignmentSettings",
"AnnotatedDataset",
"BucketSampler",
"PhoneRecognizer",
"align_utterance",
"collate",
"continuous_pitch",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301"""Offline phoneme-level forced alignment. Annotation time only.
A pretrained multilingual phoneme recogniser (wav2vec 2.0 fine-tuned with CTC on
eSpeak phoneme labels, ``facebook/wav2vec2-lv-60-espeak-cv-ft``) labels the
existing recordings. It is used ONLY to annotate training data: none of its
weights, features or outputs enter the TTS model, which never sees it.
Why this replaces the learned Gaussian aligner: that objective normalised scores
over the token positions of one utterance, so a frequent token whose key matched
the average spectrum (first BOS, later the word spaces) won the softmax on most
frames and every other token was left with single frames. Here each frame is
scored against phoneme classes shared by the whole language, and the transcript
only constrains their order.
Per utterance:
1. CTC Viterbi alignment of the eSpeak phoneme sequence (20 ms frames).
2. This recogniser emits a label once, at the START of the phone (measured on
our recordings against pitch-tracker voicing flips: a phone begins about
19 ms before the start of its first emission frame, for both voices; see
``scripts/calibrate_aligner_timing.py``). A phone therefore lasts from its
own onset to the next phone's onset.
3. Silence is found from signal energy at acoustic resolution and given to the
explicit pause-capable token at that position (BOS, EOS, punctuation, word
boundary). Tokens without a pause get zero frames.
4. Durations are counted on the acoustic frame grid, so they sum to the frame
count exactly and every phoneme has at least one frame.
``refine.py`` can then sharpen the boundaries with a classifier trained from
scratch on these labels.
"""
from dataclasses import dataclass
import math
import numpy as np
from ..text.phonemizer import PHONE_SET, PUNCTUATION, SP, UNK, VOICELESS, VOWEL_SET
ALIGNER_MODEL = "facebook/wav2vec2-lv-60-espeak-cv-ft"
ALIGNER_RATE = 16000
ALIGNER_STRIDE = 320 # samples at 16 kHz: 20 ms
ALIGNER_CENTER = 200 # a frame's centre: 12.5 ms after its start
ALIGNMENT_VERSION = 2
PAUSING = (",", ".", "?", "!", ";", ":", "—", "…")
# Every inventory phone is a label of the recogniser (checked when it loads);
# only the unknown-phone token needs a stand-in.
ALIGNER_LABEL_FALLBACK = {UNK: "<unk>"}
@dataclass(frozen=True)
class AlignmentSettings:
onset_offset_seconds: float = -0.019 # phone onset relative to the start of its first emission frame
min_pause_frames: int = 7 # ~75 ms of silence: less stays with the neighbouring phones (stop closures)
silence_below_peak_db: float = 45.0
silence_above_floor_db: float = 8.0
silence_ceiling_below_peak_db: float = 30.0
energy_window: int = 512
def to_dict(self):
return {"alignment_version": ALIGNMENT_VERSION, "aligner": ALIGNER_MODEL, **self.__dict__}
def ctc_viterbi(log_probs, labels, blank=0):
"""Best CTC path. Returns per-frame extended-state indices (token k is state 2k+1).
Plain numpy reference, also used when torchaudio's implementation is absent.
"""
frames, count = log_probs.shape[0], len(labels)
if count < 1:
raise ValueError("no labels to align")
states = 2 * count + 1
extended = np.full(states, blank, dtype=np.int64)
extended[1::2] = labels
skip = np.zeros(states, dtype=bool)
skip[3::2] = extended[3::2] != extended[1:-2:2]
score = np.full(states, -np.inf)
score[0] = log_probs[0, blank]
score[1] = log_probs[0, extended[1]]
back = np.zeros((frames, states), dtype=np.int8)
for t in range(1, frames):
one = np.concatenate(([-np.inf], score[:-1]))
two = np.concatenate(([-np.inf, -np.inf], score[:-2]))
two[~skip] = -np.inf
options = np.stack((score, one, two))
choice = options.argmax(0)
score = options[choice, np.arange(states)] + log_probs[t, extended]
back[t] = choice
state = states - 1 if score[states - 1] >= score[states - 2] else states - 2
if not np.isfinite(score[state]):
raise ValueError("audio is too short for this phoneme sequence")
path = np.empty(frames, dtype=np.int64)
for t in range(frames - 1, -1, -1):
path[t] = state
state -= back[t, state]
return path
def spans_from_states(states, count):
spans = []
for index in range(count):
where = np.flatnonzero(states == 2 * index + 1)
if not where.size:
raise ValueError("forced alignment did not visit every phoneme")
spans.append((int(where[0]), int(where[-1])))
return spans
def token_spans(log_probs, labels, blank=0):
"""Inclusive ``(first, last)`` emission frames of every label on the best CTC path."""
count = len(labels)
repeats = sum(1 for a, b in zip(labels[:-1], labels[1:]) if a == b)
if log_probs.shape[0] < count + repeats:
raise ValueError("audio is too short for this phoneme sequence")
try:
import torch
from torchaudio.functional import forced_align
except ImportError:
return spans_from_states(ctc_viterbi(log_probs, np.asarray(labels), blank), count)
path, _ = forced_align(torch.from_numpy(np.ascontiguousarray(log_probs, dtype=np.float32))[None],
torch.tensor([list(labels)], dtype=torch.long), blank=blank)
spans, previous = [], blank
for frame, label in enumerate(path[0].tolist()):
if label != blank and (previous == blank or label != previous):
spans.append([frame, frame])
elif label != blank:
spans[-1][1] = frame
previous = label
if len(spans) != count:
raise ValueError("forced alignment did not visit every phoneme")
return [(a, b) for a, b in spans]
def frame_energy_db(wave, hop, window=512):
"""RMS level per acoustic frame, window centred on the frame centre i*hop."""
frames = len(wave) // hop
padded = np.pad(np.asarray(wave, dtype=np.float64), (window // 2, window // 2))
squares = np.concatenate(([0.0], np.cumsum(padded ** 2)))
starts = np.arange(frames) * hop
mean = (squares[starts + window] - squares[starts]) / window
return 10 * np.log10(np.maximum(mean, 1e-12))
def silence_mask(level_db, settings):
loud, floor = np.percentile(level_db, 95), np.percentile(level_db, 2)
threshold = min(loud - settings.silence_ceiling_below_peak_db,
max(loud - settings.silence_below_peak_db, floor + settings.silence_above_floor_db))
return level_db < threshold, float(threshold)
def pause_carrier(symbols, group):
"""Index of the token that receives a pause inside a run of non-phone tokens."""
for wanted in (PAUSING, PUNCTUATION, (SP,)):
for index in group:
if symbols[index] in wanted:
return index
return group[0]
def assemble(symbols, spans, frames, silent, hop, sample_rate, settings):
"""Durations in acoustic frames for every token (sums to ``frames``).
Acoustic frame i is centred on sample ``i * hop`` (the convention of the
stored mel/pitch features and of the synthesis frames).
"""
phones = [i for i, s in enumerate(symbols) if s in PHONE_SET or s == UNK]
count = len(phones)
if count != len(spans) or count < 1:
raise ValueError("phoneme count differs from alignment")
stride = ALIGNER_STRIDE / ALIGNER_RATE
emission = np.array([first for first, _ in spans], dtype=np.float64) * stride
seconds = np.arange(frames) * hop / sample_rate
# One protected frame per phone at its emission centre; phones cannot lose it.
keep = np.clip(np.round((emission + ALIGNER_CENTER / ALIGNER_RATE) * sample_rate / hop).astype(np.int64), 0, frames - 1)
for k in range(1, count):
keep[k] = max(keep[k], keep[k - 1] + 1)
if keep[-1] > frames - 1:
raise ValueError("audio is too short for this phoneme sequence")
starts = np.minimum(np.searchsorted(seconds, emission + settings.onset_offset_seconds, side="left"), keep)
starts[0] = 0
for k in range(1, count):
starts[k] = max(starts[k], keep[k - 1] + 1)
token = np.empty(frames, dtype=np.int64)
bounds = np.append(starts, frames)
for k in range(count):
token[bounds[k]:bounds[k + 1]] = phones[k]
# A pause runs from the first to the last silent frame between two protected
# frames. Whatever lies between them (a breath, a stop release) is not part
# of either phone's steady sound and stays with the pause.
quiet = np.flatnonzero(silent[:keep[0]])
if quiet.size: # leading silence -> BOS
token[:quiet[-1] + 1] = 0
quiet = np.flatnonzero(silent[keep[-1] + 1:]) + keep[-1] + 1
if quiet.size: # trailing silence -> EOS
token[quiet[0]:] = len(symbols) - 1
for k in range(count - 1): # interior pauses -> pause-capable token
left, right = phones[k], phones[k + 1]
if right == left + 1:
continue
quiet = np.flatnonzero(silent[keep[k] + 1:keep[k + 1]]) + keep[k] + 1
if quiet.size < settings.min_pause_frames:
continue
token[keep[k] + 1:quiet[0]] = left
token[quiet[0]:quiet[-1] + 1] = pause_carrier(symbols, range(left + 1, right))
token[quiet[-1] + 1:keep[k + 1]] = right
if np.any(np.diff(token) < 0):
raise ValueError("alignment is not monotonic")
durations = np.bincount(token, minlength=len(symbols)).astype(np.int64)
if durations.sum() != frames or np.any(durations[phones] < 1):
raise ValueError("durations do not cover the acoustic frames")
return durations
def quality(symbols, durations, spans, log_probs, labels, voiced, level_db, hop, sample_rate):
"""Label-free checks of one alignment against the recording itself."""
durations = np.asarray(durations)
ends = np.cumsum(durations)
starts = ends - durations
token_probability = np.array([float(np.exp(log_probs[a:b + 1, label]).mean()) for (a, b), label in zip(spans, labels)])
phone_frames = np.array([d for s, d in zip(symbols, durations) if s in PHONE_SET or s == UNK])
def voiced_share(wanted):
total = hits = 0
for symbol, start, end in zip(symbols, starts, ends):
if wanted(symbol) and end - start >= 3: # interior frames only
total += end - start - 2
hits += float(voiced[start + 1:end - 1].sum())
return round(hits / total, 4) if total else None
pause = np.zeros(len(voiced), dtype=bool)
for symbol, start, end in zip(symbols, starts, ends):
if symbol not in PHONE_SET and symbol != UNK:
pause[start:end] = True
speech_seconds = float((~pause).sum() * hop / sample_rate)
return {
"token_probability_mean": round(float(token_probability.mean()), 4),
"weak_phone_fraction": round(float((token_probability < 0.1).mean()), 4),
"max_phone_frames": int(phone_frames.max()),
"one_frame_phone_fraction": round(float((phone_frames == 1).mean()), 4),
"phones_per_second": round(len(phone_frames) / max(speech_seconds, 1e-6), 2),
"pause_frames": int(pause.sum()),
"leading_frames": int(durations[0]),
"trailing_frames": int(durations[-1]),
"vowel_voiced": voiced_share(lambda s: s in VOWEL_SET),
"voiceless_voiced": voiced_share(lambda s: s in VOICELESS),
"pause_voiced": round(float(voiced[pause].mean()), 4) if pause.any() else None,
"pause_level_db": round(float(level_db[pause].mean()), 1) if pause.any() else None,
"speech_level_db": round(float(np.percentile(level_db[~pause], 95)), 1) if (~pause).any() else None,
}
class PhoneRecognizer:
"""Pretrained multilingual CTC phoneme recognizer for offline forced alignment."""
def __init__(self, device="cuda", name=ALIGNER_MODEL, local_files_only=False):
import json
from pathlib import Path
import torch
from huggingface_hub import hf_hub_download
from transformers import Wav2Vec2ForCTC
self.torch, self.device = torch, torch.device(device)
self.model = Wav2Vec2ForCTC.from_pretrained(name, local_files_only=local_files_only).to(self.device).eval()
if self.device.type == "cuda":
self.model = self.model.half()
vocabulary = Path(hf_hub_download(name, "vocab.json", local_files_only=local_files_only))
self.vocabulary = json.loads(vocabulary.read_text(encoding="utf-8"))
self.blank = int(self.model.config.pad_token_id)
self.name = name
self.revision = vocabulary.parent.name # snapshot directory = commit hash
missing = [p for p in sorted(PHONE_SET) if p not in self.vocabulary and p not in ALIGNER_LABEL_FALLBACK]
if missing:
raise ValueError(f"recogniser has no label for inventory phones {missing}")
def label(self, symbol):
symbol = symbol if symbol in self.vocabulary else ALIGNER_LABEL_FALLBACK[symbol]
return int(self.vocabulary[symbol])
def log_probs(self, wave, sample_rate):
from scipy.signal import resample_poly
torch = self.torch
factor = math.gcd(sample_rate, ALIGNER_RATE)
audio = resample_poly(np.asarray(wave, dtype=np.float64), ALIGNER_RATE // factor, sample_rate // factor)
audio = (audio - audio.mean()) / np.sqrt(audio.var() + 1e-7)
with torch.inference_mode():
values = torch.from_numpy(audio.astype(np.float32))[None].to(self.device, self.model.dtype)
return self.model(values).logits[0].float().log_softmax(-1).cpu().numpy()
def align_utterance(recognizer, phonemized, wave, voiced, config, settings):
"""Return ``(durations, qc)`` for one recording or raise ``ValueError``."""
symbols = phonemized.symbols
frames = len(wave) // config.hop
if len(wave) != frames * config.hop or len(voiced) != frames:
raise ValueError("waveform length must be frames * hop")
labels = [recognizer.label(s) for s in symbols if s in PHONE_SET or s == UNK]
log_probs = recognizer.log_probs(wave, config.sample_rate)
spans = token_spans(log_probs, labels, recognizer.blank)
level = frame_energy_db(wave, config.hop, settings.energy_window)
silent, threshold = silence_mask(level, settings)
durations = assemble(symbols, spans, frames, silent, config.hop, config.sample_rate, settings)
qc = quality(symbols, durations, spans, log_probs, labels, np.asarray(voiced) > 0.5, level, config.hop, config.sample_rate)
qc["silence_threshold_db"] = round(threshold, 1)
return durations.tolist(), qc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324"""Versioned annotation layer: phoneme tokens and validated CTC durations."""
import argparse
from collections import Counter, defaultdict
import concurrent.futures
import hashlib
import json
from pathlib import Path
import time
import numpy as np
import torch
from .aligner import ALIGNER_MODEL, AlignmentSettings, PhoneRecognizer, align_utterance
from ..config import ANNOTATION_VERSION, Config
from .journal import append, atomic_json, file_hash, recover
from ..text.phonemizer import (PHONE_SET, SYMBOL_TO_ID, UNK, VOICELESS, VOWEL_SET, Phonemized, frontend_fingerprint,
frontend_identity, frontend_runtime, phonemize)
SPLITS = ("train", "validation", "test")
FRICATIVES = frozenset(("f", "θ", "s", "ʃ", "x"))
def load_acoustic_rows(features, split, config):
metadata = features / (split + ".preparation.json")
if not metadata.exists() or not json.loads(metadata.read_text()).get("complete"):
raise ValueError(f"acoustic preparation for {split} is missing or incomplete")
rows = [json.loads(line) for line in (features / (split + ".jsonl")).read_text(encoding="utf-8").split("\n") if line.strip()]
for row in rows:
# Current acoustic-only files, or files from the byte-token preparation:
# same audio/DSP settings, stale tokens that are ignored here.
if row.get("acoustic") != config.acoustic_fingerprint and row.get("features") != config.legacy_feature_fingerprint:
raise ValueError("feature files were not produced with compatible audio/DSP settings; rerun acoustic preparation")
if row["speaker"] not in config.speakers:
raise ValueError(f"unknown speaker {row['speaker']!r}")
return rows
def text_key(text):
return hashlib.sha256(text.strip().encode()).hexdigest()
def phonemize_texts(rows, cache, workers=16, log=print):
known = {}
for record in recover(cache):
known[record["text_hash"]] = Phonemized(tuple(record["symbols"]), tuple(SYMBOL_TO_ID[s] for s in record["symbols"]),
tuple(record["stress"]), tuple(record["unknown"]))
todo = {}
for row in rows:
if row["text_hash"] != text_key(row["text"]):
raise ValueError(f"text hash mismatch for {row['id']}")
if row["text_hash"] not in known:
todo[row["text_hash"]] = row["text"]
if todo:
log(f"phonemizing {len(todo)} distinct texts")
with cache.open("a", encoding="utf-8") as stream, concurrent.futures.ThreadPoolExecutor(workers) as pool:
for key, result in zip(todo, pool.map(phonemize, todo.values())):
known[key] = result
append(stream, {"text_hash": key, "symbols": list(result.symbols), "stress": list(result.stress),
"unknown": list(result.unknown)}, sync=False)
return known
def boundary_offsets(symbols, durations, voiced, reach=6):
"""Label-free timing probe. At vowel -> voiceless-consonant and voiceless
fricative -> vowel boundaries the pitch tracker's voicing must flip; return
the signed distance (frames) from the aligned boundary to the nearest flip."""
found = {"vowel_to_voiceless": [], "fricative_to_vowel": []}
ends = np.cumsum(durations)
active = [i for i, d in enumerate(durations) if d > 0]
for a, b in zip(active[:-1], active[1:]):
if symbols[a] in VOWEL_SET and symbols[b] in VOICELESS:
kind, before = "vowel_to_voiceless", True
elif symbols[a] in FRICATIVES and symbols[b] in VOWEL_SET:
kind, before = "fricative_to_vowel", False
else:
continue
boundary = int(ends[a])
best = None
for shift in range(-reach, reach + 1):
f = boundary + shift
if 0 < f < len(voiced) and bool(voiced[f - 1]) == before and bool(voiced[f]) != before:
if best is None or abs(shift) < abs(best):
best = shift
found[kind].append(best)
return found
def summarize_offsets(collected):
summary = {}
for kind, values in collected.items():
hits = np.array([v for v in values if v is not None], dtype=np.float64)
summary[kind] = {"boundaries": len(values), "flip_found": round(len(hits) / max(len(values), 1), 4)}
if len(hits):
summary[kind].update(mean_offset_frames=round(float(hits.mean()), 3), mean_abs_frames=round(float(np.abs(hits).mean()), 3),
within_1_frame=round(float((np.abs(hits) <= 1).mean()), 4),
within_2_frames=round(float((np.abs(hits) <= 2).mean()), 4))
return summary
def gate(row, limits):
qc, reasons = row["qc"], []
if row["unknown"]:
reasons.append("unknown_phoneme")
if qc["weak_phone_fraction"] > limits["max_weak_phone_fraction"]:
reasons.append("weak_alignment")
if qc["token_probability_mean"] < limits["min_token_probability"]:
reasons.append("low_confidence")
if qc["max_phone_frames"] > limits["max_phone_frames"]:
reasons.append("overlong_phone")
if qc["vowel_voiced"] is not None and qc["vowel_voiced"] < limits["min_vowel_voiced"]:
reasons.append("vowels_not_voiced")
if not limits["min_phones_per_second"] <= qc["phones_per_second"] <= limits["max_phones_per_second"]:
reasons.append("implausible_rate")
return reasons
def quantiles(values):
values = np.asarray([v for v in values if v is not None], dtype=np.float64)
if not len(values):
return None
return {str(q): round(float(np.percentile(values, q)), 4) for q in (0, 1, 5, 25, 50, 75, 95, 99, 100)}
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--features", type=Path, required=True, help="Directory with <split>.jsonl acoustic manifests")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--dataset-revision", required=True)
parser.add_argument("--config", type=Path)
parser.add_argument("--device", default="cuda")
parser.add_argument("--splits", nargs="+", default=list(SPLITS), choices=SPLITS)
parser.add_argument("--limit", type=int, help="Annotate only the first N rows per split (smoke test; never complete)")
parser.add_argument("--resume", action="store_true")
parser.add_argument("--refine", type=int, default=0, help="Boundary refinement passes with the from-scratch frame classifier")
parser.add_argument("--refine-band", type=int, default=4)
parser.add_argument("--stage", default="ctc", help="Durations used for the final manifests: ctc or refined-<n>")
parser.add_argument("--min-pause-frames", type=int, default=AlignmentSettings.min_pause_frames)
parser.add_argument("--max-weak-phone-fraction", type=float, default=0.25)
parser.add_argument("--min-token-probability", type=float, default=0.5)
parser.add_argument("--max-phone-frames", type=int, default=70)
parser.add_argument("--min-vowel-voiced", type=float, default=0.5)
parser.add_argument("--min-phones-per-second", type=float, default=4.0)
parser.add_argument("--max-phones-per-second", type=float, default=30.0)
parser.add_argument("--local-files-only", action="store_true", help="Load aligner weights from local Hugging Face cache only")
args = parser.parse_args()
config = Config.from_dict(json.loads(args.config.read_text())) if args.config else Config()
settings = AlignmentSettings(min_pause_frames=args.min_pause_frames)
limits = {key: getattr(args, key) for key in ("max_weak_phone_fraction", "min_token_probability", "max_phone_frames",
"min_vowel_voiced", "min_phones_per_second", "max_phones_per_second")}
started = time.time()
def log(message):
print(json.dumps({"elapsed": round(time.time() - started, 1), "message": message}), flush=True)
rows = {split: load_acoustic_rows(args.features, split, config) for split in args.splits}
if args.limit:
rows = {split: value[:args.limit] for split, value in rows.items()}
recognizer = PhoneRecognizer(args.device, local_files_only=args.local_files_only)
identity = {
"annotation_version": ANNOTATION_VERSION, "acoustic": config.acoustic_fingerprint, "frontend": frontend_fingerprint(),
**frontend_runtime(), "aligner": {"model": ALIGNER_MODEL, "revision": recognizer.revision},
"alignment": settings.to_dict(), "dataset_revision": args.dataset_revision, "limit": args.limit,
"sources": {split: file_hash(args.features / (split + ".jsonl")) for split in args.splits},
}
fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
args.output.mkdir(parents=True, exist_ok=True)
metadata_path = args.output / "annotations.json"
if metadata_path.exists():
if not args.resume:
raise FileExistsError("annotation directory exists; use --resume or a new directory")
if json.loads(metadata_path.read_text())["identity"] != identity:
raise ValueError("front end, aligner, settings or sources changed: these annotations are stale; use a new directory")
atomic_json(metadata_path, {"identity": identity, "fingerprint": fingerprint, "complete": False})
(args.output / "raw").mkdir(exist_ok=True)
every = [row for split in args.splits for row in rows[split]]
phonemes = phonemize_texts(every, args.output / "phonemes.jsonl", log=log)
hashes = {split: {row["text_hash"] for row in rows[split]} for split in args.splits}
for i, a in enumerate(args.splits):
for b in args.splits[i + 1:]:
if hashes[a] & hashes[b]:
raise ValueError(f"sentence leakage between {a} and {b}")
# 1. CTC alignment, journalled per utterance.
raw = {}
voicing = {}
for split in args.splits:
journal = args.output / "raw" / (split + ".jsonl")
done = {record["id"]: record for record in recover(journal)}
pending = [row for row in rows[split] if row["id"] not in done]
log(f"aligning {split}: {len(pending)} pending, {len(done)} done")
with journal.open("a", encoding="utf-8") as stream:
for count, row in enumerate(pending, 1):
item = torch.load(args.features / row["path"], map_location="cpu", weights_only=True)
voicing[row["id"]] = item["prosody"][:, 1].numpy() > 0.5
try:
if item["mel"].shape[0] != row["frames"]:
raise ValueError("frame count differs from the manifest")
durations, qc = align_utterance(recognizer, phonemes[row["text_hash"]], item["wave"].numpy(),
item["prosody"][:, 1].numpy(), config, settings)
record = {"id": row["id"], "ok": True, "durations": durations, "qc": qc}
except (ValueError, RuntimeError) as error:
record = {"id": row["id"], "ok": False, "reason": f"{type(error).__name__}: {error}"}
append(stream, record, sync=count % 200 == 0 or count == len(pending))
done[row["id"]] = record
if count % 500 == 0:
log(f"aligned {split} {count}/{len(pending)}")
raw[split] = done
del recognizer
if args.device.startswith("cuda"):
torch.cuda.empty_cache()
# 2. Optional boundary refinement over all splits together.
stages = {"ctc": {split: {key: value["durations"] for key, value in raw[split].items() if value["ok"]} for split in args.splits}}
if args.refine:
from .refine import refine
directories = [args.output / f"refined-{n + 1}" for n in range(args.refine)]
if all((d / (split + ".jsonl")).exists() for d in directories for split in args.splits):
for n, directory in enumerate(directories):
stages[f"refined-{n + 1}"] = {split: {r["id"]: r["durations"] for r in recover(directory / (split + ".jsonl"))} for split in args.splits}
else:
items, owners = [], []
for split in args.splits:
for row in rows[split]:
if raw[split][row["id"]]["ok"]:
item = torch.load(args.features / row["path"], map_location="cpu", weights_only=True)
items.append({"symbols": phonemes[row["text_hash"]].symbols, "durations": raw[split][row["id"]]["durations"],
"mel": item["mel"], "speaker": config.speakers.index(row["speaker"]), "group": row["text_hash"]})
owners.append((split, row["id"]))
log(f"refining {len(items)} alignments")
for n, durations in enumerate(refine(items, config, args.device, args.refine, args.refine_band, log=log)):
directory = directories[n]
directory.mkdir(exist_ok=True)
stage = {split: {} for split in args.splits}
for (split, identifier), value in zip(owners, durations):
stage[split][identifier] = value
for split in args.splits:
temporary = directory / (split + ".jsonl.tmp")
temporary.write_text("".join(json.dumps({"id": k, "durations": v}) + "\n" for k, v in stage[split].items()))
temporary.replace(directory / (split + ".jsonl"))
stages[f"refined-{n + 1}"] = stage
del items
if args.stage not in stages:
raise ValueError(f"unknown stage {args.stage!r}; available: {sorted(stages)}")
# 3. Label-free timing probe for every stage, then gate and write manifests.
probe = {}
for name, stage in stages.items():
collected = {voice: defaultdict(list) for voice in config.speakers}
for split in args.splits:
for row in rows[split]:
if row["id"] not in stage[split]:
continue
if row["id"] not in voicing:
voicing[row["id"]] = torch.load(args.features / row["path"], map_location="cpu", weights_only=True)["prosody"][:, 1].numpy() > 0.5
found = boundary_offsets(phonemes[row["text_hash"]].symbols, stage[split][row["id"]], voicing[row["id"]])
for kind, values in found.items():
collected[row["speaker"]][kind].extend(values)
probe[name] = {voice: summarize_offsets(collected[voice]) for voice in config.speakers}
log({"timing_probe": name, **probe[name]})
summary = {"limits": limits, "stage": args.stage, "timing_probe": probe, "splits": {}}
chosen = stages[args.stage]
phone_frames = {voice: defaultdict(list) for voice in config.speakers}
pause_tokens = Counter()
pause_nonzero = Counter()
for split in args.splits:
accepted, rejected = [], []
for row in rows[split]:
record = raw[split][row["id"]]
result = phonemes[row["text_hash"]]
if not record["ok"]:
rejected.append({"id": row["id"], "speaker": row["speaker"], "text": row["text"], "reasons": [record["reason"]]})
continue
durations = chosen[split][row["id"]]
entry = {"id": row["id"], "split": split, "speaker": row["speaker"], "text": row["text"], "text_hash": row["text_hash"],
"path": row["path"], "frames": row["frames"], "symbols": " ".join(result.symbols), "tokens": list(result.ids),
"stress": list(result.stress), "durations": durations, "unknown": list(result.unknown), "qc": record["qc"],
"provenance": {**row.get("provenance", {}), "dataset_revision": args.dataset_revision},
"acoustic": config.acoustic_fingerprint, "frontend": frontend_fingerprint(), "annotation": fingerprint}
if sum(durations) != row["frames"] or len(durations) != len(result.ids):
raise RuntimeError(f"durations of {row['id']} do not match its frames/tokens")
reasons = gate(entry, limits)
if reasons:
rejected.append({"id": row["id"], "speaker": row["speaker"], "text": row["text"], "reasons": reasons, "qc": record["qc"]})
continue
accepted.append(entry)
for symbol, frames in zip(result.symbols, durations):
if symbol in PHONE_SET or symbol == UNK:
phone_frames[row["speaker"]][symbol].append(frames)
else:
pause_tokens[symbol] += 1
pause_nonzero[symbol] += frames > 0
for name, payload in ((split + ".jsonl", accepted), (split + ".rejected.jsonl", rejected)):
temporary = args.output / (name + ".tmp")
temporary.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in payload), encoding="utf-8")
temporary.replace(args.output / name)
by_voice = {voice: sum(r["speaker"] == voice for r in accepted) for voice in config.speakers}
summary["splits"][split] = {
"accepted": len(accepted), "rejected": len(rejected), "accepted_by_voice": by_voice,
"accepted_hours": round(sum(r["frames"] for r in accepted) * config.hop / config.sample_rate / 3600, 3),
"rejection_reasons": dict(Counter(reason.split(":")[0] for r in rejected for reason in r["reasons"])),
"qc_quantiles": {key: quantiles([raw[split][r["id"]]["qc"].get(key) for r in rows[split] if raw[split][r["id"]]["ok"]])
for key in ("token_probability_mean", "weak_phone_fraction", "max_phone_frames", "one_frame_phone_fraction",
"phones_per_second", "vowel_voiced", "voiceless_voiced", "pause_voiced", "leading_frames",
"trailing_frames", "pause_level_db")},
}
summary["phone_duration_frames"] = {
voice: {symbol: {"count": len(values), "mean": round(float(np.mean(values)), 2), "median": float(np.median(values)),
"one_frame": round(float(np.mean(np.asarray(values) == 1)), 3)}
for symbol, values in sorted(table.items(), key=lambda kv: -len(kv[1]))}
for voice, table in phone_frames.items()}
summary["pause_tokens"] = {symbol: {"count": pause_tokens[symbol], "with_frames": round(pause_nonzero[symbol] / pause_tokens[symbol], 4)}
for symbol in pause_tokens}
complete = not args.limit and set(args.splits) == set(SPLITS)
atomic_json(args.output / "summary.json", summary)
atomic_json(metadata_path, {"identity": identity, "fingerprint": fingerprint, "complete": complete, "stage": args.stage,
"acoustic_root": str(args.features.resolve()), "limits": limits,
"counts": {split: summary["splits"][split]["accepted"] for split in args.splits}})
log({"complete": complete, "splits": {s: {k: v for k, v in summary["splits"][s].items() if k != "qc_quantiles"} for s in args.splits}})
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""Training data: acoustic feature files joined with the annotation layer."""
import hashlib
import json
from pathlib import Path
import torch
from torch.nn.utils.rnn import pad_sequence
from ..text.phonemizer import PHONE_IDS, SYMBOL_TO_ID, VOWELS, frontend_fingerprint
VOWEL_IDS = frozenset(SYMBOL_TO_ID[v] for v in VOWELS)
def continuous_pitch(pitch, voiced, default=0.0, window=5, tolerance=0.45):
"""Clean a pitch track and make it continuous.
``pitch`` is log(F0/reference) on voiced frames. Values further than
``tolerance`` (about 0.65 octave) from the local median are tracker errors
(octave jumps); they stay voiced but their value is not trusted. Untrusted
and unvoiced frames are filled by linear interpolation so the oscillator and
the pitch predictor see one smooth curve. Returns ``(curve, trusted)``.
"""
voiced = voiced > 0.5
trusted = voiced.clone()
if int(voiced.sum()) >= 3:
values = pitch[voiced]
padded = torch.nn.functional.pad(values[None, None], (window // 2, window // 2), mode="replicate")[0, 0]
median = padded.unfold(0, window, 1).median(dim=1).values
trusted[voiced.nonzero().squeeze(1)[(values - median).abs() > tolerance]] = False
index = trusted.nonzero().squeeze(1)
if index.numel() == 0:
return torch.full_like(pitch, default), trusted.float()
position = torch.arange(pitch.numel())
right = torch.searchsorted(index, position).clamp(max=index.numel() - 1)
left = (torch.searchsorted(index, position, right=True) - 1).clamp(min=0)
a, b = index[left], index[right]
span = (b - a).clamp(min=1).float()
weight = ((position - a).float() / span).clamp(0, 1)
curve = pitch[a] * (1 - weight) + pitch[b] * weight
return curve, trusted.float()
class AnnotatedDataset:
def __init__(self, manifest, config, acoustic_root=None, cache=True, voiced_vowels=False, require_vocos_mel=False):
self.manifest = Path(manifest)
metadata_path = self.manifest.parent / "annotations.json"
if not metadata_path.exists():
raise ValueError("not an annotation manifest (legacy byte-token manifests are stale): run lua-nova-annotate")
metadata = json.loads(metadata_path.read_text())
if not metadata.get("complete"):
raise ValueError("annotation run is incomplete; finish it with --resume before training")
self.annotation = metadata["fingerprint"]
self.root = Path(acoustic_root or metadata["acoustic_root"])
self.fingerprint = hashlib.sha256(self.manifest.read_bytes()).hexdigest()
# Physical LF-delimited records: Unicode separators inside text are data.
self.rows = [json.loads(line) for line in self.manifest.read_text(encoding="utf-8").split("\n") if line.strip()]
self.config = config
self.require_vocos_mel = bool(require_vocos_mel)
if not self.rows:
raise ValueError("empty dataset")
frontend = frontend_fingerprint()
for row in self.rows:
if "durations" not in row or row.get("frontend") != frontend:
raise ValueError("tokens were produced by a different front end; re-run annotation")
if row.get("acoustic") != config.acoustic_fingerprint:
raise ValueError("acoustic feature settings differ from this configuration")
if row.get("annotation") != self.annotation:
raise ValueError("manifest rows come from a different annotation run")
if len(row["tokens"]) != len(row["durations"]) or len(row["tokens"]) != len(row["stress"]):
raise ValueError(f"token/duration length mismatch: {row['id']}")
if sum(row["durations"]) != row["frames"] or min(row["durations"]) < 0:
raise ValueError(f"durations do not cover the frames exactly: {row['id']}")
if any(d < 1 for t, d in zip(row["tokens"], row["durations"]) if t in PHONE_IDS):
raise ValueError(f"phoneme without frames: {row['id']}")
if not 0 < len(row["tokens"]) <= config.max_tokens or not 0 < row["frames"] <= config.max_frames:
raise ValueError(f"utterance exceeds model limits: {row['id']}")
if max(row["tokens"]) >= config.vocab_size or min(row["tokens"]) < 1 or row["speaker"] not in config.speakers:
raise ValueError(f"invalid token or speaker: {row['id']}")
ids = [r["id"] for r in self.rows]
if len(ids) != len(set(ids)):
raise ValueError("duplicate IDs in manifest")
self.lengths = [r["frames"] for r in self.rows]
self._cache = {} if cache else None
self.voiced_vowels = voiced_vowels
def __len__(self):
return len(self.rows)
def preload(self, indices=None, workers=8):
"""Read feature files into memory up front (about 10 ms each otherwise
lands on the first training steps). Needs ``cache=True``."""
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(workers) as pool:
list(pool.map(self.__getitem__, range(len(self)) if indices is None else indices))
def __getitem__(self, index):
if self._cache is not None and index in self._cache:
return self._cache[index]
row, c = self.rows[index], self.config
path = (self.root / row["path"]).resolve()
if not path.is_relative_to(self.root.resolve()):
raise ValueError("feature file escapes the acoustic root")
stored = torch.load(path, map_location="cpu", weights_only=True)
t = row["frames"]
if stored["mel"].shape != (t, c.n_mels) or stored["prosody"].shape != (t, 3) or stored["wave"].shape != (t * c.hop,):
raise ValueError(f"feature dimensions differ from the manifest: {path.name}")
if any(not torch.isfinite(stored[k]).all() for k in ("mel", "prosody", "wave")):
raise ValueError("non-finite features")
if self.require_vocos_mel and c.vocoder_type == "vocos":
if "vocos_mel" not in stored:
raise ValueError(f"missing vocos_mel in {path.name}")
if stored["vocos_mel"].shape != (t, c.vocos_n_mels) or not torch.isfinite(stored["vocos_mel"]).all():
raise ValueError(f"vocos_mel dimensions/values invalid in {path.name}")
pitch, trusted = continuous_pitch(stored["prosody"][:, 0], stored["prosody"][:, 1])
voiced = stored["prosody"][:, 1]
if self.voiced_vowels:
# The pitch tracker misses low, creaky vowels (12% of M2's vowel frames),
# and a model trained on those labels drops whole vowels. A vowel is voiced
# by definition: mark its frames voiced. Their pitch stays interpolated and
# untrusted, so the pitch loss still ignores what the tracker did not measure.
vowel = torch.repeat_interleave(torch.tensor([t in VOWEL_IDS for t in row["tokens"]]), torch.tensor(row["durations"]))
voiced = torch.maximum(voiced, vowel.to(voiced.dtype))
item = {
"tokens": torch.tensor(row["tokens"], dtype=torch.long), "stress": torch.tensor(row["stress"], dtype=torch.long),
"durations": torch.tensor(row["durations"], dtype=torch.long), "speaker": c.speakers.index(row["speaker"]),
"wave": stored["wave"], "mel": stored["mel"],
# Continuous log pitch, voiced flag, normalized log energy.
"prosody": torch.stack((pitch, voiced, (stored["prosody"][:, 2] - c.energy_mean) / c.energy_scale), dim=-1),
"pitch_trusted": trusted,
}
if "vocos_mel" in stored:
item["vocos_mel"] = stored["vocos_mel"]
if self._cache is not None:
self._cache[index] = item
return item
def collate(items, device="cpu"):
keys = ["tokens", "stress", "durations", "mel", "prosody", "pitch_trusted", "wave"]
if "vocos_mel" in items[0]:
keys.append("vocos_mel")
batch = {key: pad_sequence([x[key] for x in items], batch_first=True).to(device) for key in keys}
batch["token_lengths"] = torch.tensor([x["tokens"].numel() for x in items], device=device)
batch["frame_lengths"] = torch.tensor([x["mel"].shape[0] for x in items], device=device)
batch["speakers"] = torch.tensor([x["speaker"] for x in items], device=device)
return batch
class BucketSampler:
"""Random batches of similar length under a padded-frame budget.
Sampling is with replacement from pools; the generator state and the
not-yet-used batches are checkpointed, so a resumed run sees the same data.
"""
def __init__(self, lengths, frame_budget, max_batch, seed, pool=256):
self.lengths, self.frame_budget, self.max_batch, self.pool = lengths, frame_budget, max_batch, pool
self.generator = torch.Generator().manual_seed(seed)
self.pending = []
def next(self):
if not self.pending:
indices = sorted(torch.randint(len(self.lengths), (self.pool,), generator=self.generator).tolist(), key=lambda i: self.lengths[i])
batches, current = [], []
for index in indices:
if current and (len(current) == self.max_batch or (len(current) + 1) * self.lengths[index] > self.frame_budget):
batches.append(current)
current = []
current.append(index)
batches.append(current)
self.pending = [batches[i] for i in torch.randperm(len(batches), generator=self.generator).tolist()]
return self.pending.pop()
def state(self):
return {"generator": self.generator.get_state(), "pending": [list(b) for b in self.pending]}
def load_state(self, state):
self.generator.set_state(state["generator"].cpu())
self.pending = [list(b) for b in state["pending"]]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Durable JSONL preparation journals. A partial final write is recoverable."""
import hashlib
import json
import math
import os
from pathlib import Path
def file_hash(path):
digest = hashlib.sha256()
with Path(path).open("rb") as stream:
for chunk in iter(lambda: stream.read(1024*1024), b""):
digest.update(chunk)
return digest.hexdigest()
def json_safe(value):
if value is None or isinstance(value, (str, bool, int)):
return value
if isinstance(value, float):
return value if math.isfinite(value) else str(value)
if isinstance(value, (bytes, bytearray, memoryview)):
return {"binary_bytes":len(value), "sha256":hashlib.sha256(value).hexdigest()}
if isinstance(value, dict):
return {str(k):json_safe(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [json_safe(v) for v in value]
raise TypeError(f"unsupported provenance type: {type(value).__name__}")
def recover(path):
"""Read physical LF-delimited records and truncate only an incomplete tail.
A malformed complete line is corruption, not an interrupted append: fail.
The caller must hold the split's exclusive preparation lock.
"""
path = Path(path)
if not path.exists():
return []
records = []
with path.open("r+b") as stream:
while True:
position = stream.tell()
line = stream.readline()
if not line:
break
if not line.endswith(b"\n"):
stream.seek(position)
stream.truncate()
stream.flush()
os.fsync(stream.fileno())
break
records.append(json.loads(line))
return records
def append(stream, value, sync=True):
"""Append one record. ``sync=False`` batches the fsync (the caller must end
with a synced record); a torn tail is still recoverable either way."""
payload = json.dumps(value, ensure_ascii=False, allow_nan=False)+"\n"
stream.write(payload)
stream.flush()
if sync:
os.fsync(stream.fileno())
def atomic_json(path, value):
path = Path(path)
temporary = path.with_suffix(path.suffix+".tmp")
with temporary.open("w", encoding="utf-8") as stream:
append(stream, value)
os.replace(temporary, path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212"""Acoustic feature preparation from local JSONL or Parquet datasets."""
import argparse
try:
import fcntl
except ImportError:
fcntl = None
import hashlib
import io
import json
import math
import os
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from ..config import Config
from .journal import append, atomic_json, file_hash, json_safe, recover
MIN_FRAMES = 32
_MEL_CACHE: dict[tuple[int, int, int], np.ndarray] = {}
def _mel_filters(sample_rate: int, n_fft: int, n_mels: int) -> np.ndarray:
key = (sample_rate, n_fft, n_mels)
if key not in _MEL_CACHE:
import librosa
_MEL_CACHE[key] = librosa.filters.mel(sr=sample_rate, n_fft=n_fft, n_mels=n_mels)
return _MEL_CACHE[key]
def _extract_pitch(wave: np.ndarray, frames: int, c: Config) -> tuple[np.ndarray, np.ndarray]:
try:
import parselmouth
except ImportError:
parselmouth = None
if parselmouth is not None and len(wave) >= int(c.sample_rate * 3.0 / c.f0_min) + 16:
sound = parselmouth.Sound(wave.astype(np.float64), sampling_frequency=float(c.sample_rate))
pitch_obj = sound.to_pitch_ac(
time_step=c.hop / c.sample_rate,
pitch_floor=float(c.f0_min),
pitch_ceiling=float(c.f0_max),
)
freq = pitch_obj.selected_array["frequency"]
f0 = np.zeros(frames, dtype=np.float32)
if freq.size:
t = np.arange(frames) * (c.hop / c.sample_rate)
idx = np.rint((t - pitch_obj.x1) / pitch_obj.dx).astype(np.int64)
ok = (idx >= 0) & (idx < freq.size)
f0[ok] = freq[idx[ok]]
return f0, f0 > 0
import librosa
f0, voiced, _ = librosa.pyin(
wave, fmin=c.f0_min, fmax=c.f0_max, sr=c.sample_rate,
frame_length=c.n_fft, hop_length=c.hop, center=True, pad_mode="constant",
)
return f0[:frames], voiced[:frames]
def records(source):
if source.suffix == ".jsonl":
with source.open(encoding="utf-8") as stream:
for line in stream:
if line.strip():
try:
yield json.loads(line)
except json.JSONDecodeError as error:
yield {"_input_error":str(error)}
elif source.suffix == ".parquet":
import pyarrow.parquet as pq
for batch in pq.ParquetFile(source).iter_batches(batch_size=16):
yield from batch.to_pylist()
else:
raise ValueError("input must be .jsonl or .parquet")
def extract(wave, config):
import librosa
c = config
if wave.ndim != 1 or not np.isfinite(wave).all() or not wave.size:
raise ValueError("expected finite mono audio")
frames = math.ceil(len(wave)/c.hop)
if frames < 1:
raise ValueError("empty audio")
if np.max(np.abs(wave)) > 1.01 or np.sqrt(np.mean(wave**2)) < 1e-5:
raise ValueError("audio is clipped/out of range or effectively silent")
wave = np.pad(wave, (0, frames*c.hop-len(wave))).astype(np.float32)
spectrum = librosa.stft(wave, n_fft=c.n_fft, hop_length=c.hop, center=True, pad_mode="constant")[:, :frames]
filters = _mel_filters(c.sample_rate, c.n_fft, c.n_mels)
mel = np.log(np.maximum(filters @ np.abs(spectrum)**2, 1e-5)).T
f0, voiced = _extract_pitch(wave, frames, c)
pitch = np.where(voiced, np.log(np.maximum(np.nan_to_num(f0, nan=200.0), 1)/200.0), 0)
rms = librosa.feature.rms(y=wave, frame_length=c.n_fft, hop_length=c.hop, center=True, pad_mode="constant")[0, :frames]
prosody = np.stack((pitch, voiced.astype(np.float32), np.log(np.maximum(rms, 1e-5))), axis=-1)
return {"wave": torch.from_numpy(wave), "mel": torch.from_numpy(mel.astype(np.float32)),
"prosody": torch.from_numpy(prosody.astype(np.float32))}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--inputs", nargs="+", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--text-column", default="text")
parser.add_argument("--speaker-column", default="voice_id")
parser.add_argument("--config", type=Path)
parser.add_argument("--split", choices=("train", "validation", "test"), required=True)
parser.add_argument("--resume", action="store_true", help="Skip durably accepted/rejected records from these same inputs")
args = parser.parse_args()
c = Config.from_dict(json.loads(args.config.read_text())) if args.config else Config()
args.output.mkdir(parents=True, exist_ok=True)
# Lock is held through completion or an exception. Different splits may run separately.
with (args.output/(args.split+".lock")).open("a") as lock:
if fcntl is not None:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
prepare_split(args, c)
def prepare_split(args, c):
manifest = args.output / (args.split+".jsonl")
rejects = args.output / (args.split+".rejected.jsonl")
metadata_path = args.output/(args.split+".preparation.json")
identity = {"acoustic":c.acoustic_fingerprint,
"sources":[{"path":str(p.resolve()), "sha256":file_hash(p)} for p in args.inputs],
"text_column":args.text_column, "speaker_column":args.speaker_column, "speakers":list(c.speakers),
# Admission limits affect which rows finish as rejects, not tensor contents.
"admission":{"max_frames":c.max_frames, "min_frames":MIN_FRAMES}}
if metadata_path.exists():
if not args.resume:
raise FileExistsError("preparation exists; use --resume or a new directory")
if json.loads(metadata_path.read_text())["identity"] != identity:
raise ValueError("resume inputs, feature schema or admission limits changed")
elif manifest.exists() or rejects.exists():
raise ValueError("manifest has no compatible preparation metadata; use a new directory")
feature_schema = args.output/"features.json"
if feature_schema.exists() and json.loads(feature_schema.read_text())["fingerprint"] != c.acoustic_fingerprint:
raise ValueError("feature schema differs from other splits in this directory")
atomic_json(feature_schema, {"fingerprint":c.acoustic_fingerprint, "fields":c.acoustic_config})
atomic_json(metadata_path, {"identity":identity, "complete":False})
feature_dir = args.output / args.split
feature_dir.mkdir(exist_ok=True)
entries, rejected = recover(manifest), recover(rejects)
done = {r["record_key"] for r in entries+rejected}
seen = {r["id"] for r in entries}
for entry in entries:
if not (args.output/entry["path"]).is_file():
raise ValueError(f"committed feature file is missing: {entry['path']}")
accepted_count, rejected_count = len(entries), len(rejected)
with manifest.open("a", encoding="utf-8") as accepted_stream, rejects.open("a", encoding="utf-8") as rejected_stream:
for source_index, source in enumerate(args.inputs):
for index, row in enumerate(records(source)):
record_key = f"{source_index}:{index}"
if record_key in done:
continue
identifier = None
try:
if not isinstance(row, dict):
raise ValueError("row must be an object")
if "_input_error" in row:
raise ValueError(row["_input_error"])
identifier = row.get("id")
if not isinstance(identifier, str) or not identifier:
raise ValueError("row must have a stable nonempty string id")
if identifier in seen:
raise ValueError("duplicate id")
if row.get("split", args.split) != args.split:
raise ValueError("row split differs from --split")
text, speaker = row[args.text_column], row[args.speaker_column]
if not isinstance(text, str) or not text.strip():
raise ValueError("text must be a nonempty string")
if speaker not in c.speakers:
raise ValueError(f"unknown speaker {speaker!r}; expected {c.speakers}")
provenance = json_safe({k:row[k] for k in ("text_id", "origin", "source_id", "source_license", "source_url", "teacher_model", "reference_audio") if k in row})
audio = row["audio"]
if isinstance(audio, dict):
audio = io.BytesIO(audio["bytes"]) if audio.get("bytes") is not None else source.parent / audio["path"]
else:
audio = source.parent / audio
wave, sr = sf.read(audio, dtype="float32")
if sr != c.sample_rate:
raise ValueError(f"expected {c.sample_rate} Hz; got {sr}. Resample explicitly before preparation")
frames = math.ceil(len(wave)/c.hop)
if not MIN_FRAMES <= frames <= c.max_frames:
raise ValueError("audio duration outside admission limits")
name = hashlib.sha256(identifier.encode()).hexdigest()+".pt"
entry = {"record_key":record_key, "id":identifier, "path":f"{args.split}/{name}", "acoustic":c.acoustic_fingerprint,
"text_hash":hashlib.sha256(text.strip().encode()).hexdigest(), "text":text,
"speaker":speaker, "source_file":str(source), "frames":frames, "provenance":provenance}
json.dumps(entry, ensure_ascii=False, allow_nan=False) # Validate before expensive DSP.
sample = extract(wave, c)
sample.update(speaker=c.speakers.index(speaker))
temporary = feature_dir/(name+".tmp")
with temporary.open("wb") as stream:
torch.save(sample, stream)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, feature_dir/name)
except Exception as error:
append(rejected_stream, {"record_key":record_key, "id":str(identifier), "source":str(source), "reason":f"{type(error).__name__}: {error}"})
rejected_count += 1
else:
# Journal write failures must abort, not masquerade as bad source rows.
append(accepted_stream, entry)
seen.add(identifier)
accepted_count += 1
atomic_json(metadata_path, {"identity":identity, "complete":True, "accepted":accepted_count, "rejected":rejected_count})
print(json.dumps({"accepted":accepted_count, "rejected":rejected_count, "manifest":str(manifest)}))
if not accepted_count:
raise SystemExit("no usable records; inspect rejected.jsonl")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Boundary refinement with a small frame classifier trained from scratch.
The pretrained recogniser works on 20 ms frames and its CTC emissions are
sparse, so phone boundaries from it are coarse. This module trains a tiny
convolutional phone classifier on OUR recordings (random initialisation, labels
from the CTC alignment), then moves each boundary by at most ``band`` acoustic
frames to where that classifier sees the change. It never adds or removes a
pause and never reorders tokens. Like the recogniser it is annotation-only.
"""
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from ..text.phonemizer import PHONES, PHONE_SET
SILENCE_CLASS = len(PHONES)
OTHER_CLASS = len(PHONES) + 1
CLASSES = len(PHONES) + 2
_PHONE_CLASS = {phone: index for index, phone in enumerate(PHONES)}
def symbol_class(symbol):
if symbol in PHONE_SET:
return _PHONE_CLASS[symbol]
return OTHER_CLASS if symbol == "<unk>" else SILENCE_CLASS
class FrameClassifier(nn.Module):
"""Receptive field of 11 acoustic frames: it labels what a frame sounds
like, with too little context to learn a systematic timing offset."""
def __init__(self, n_mels, speakers, channels=256):
super().__init__()
self.speaker = nn.Embedding(speakers, channels)
self.input = nn.Conv1d(n_mels, channels, 5, padding=2)
self.blocks = nn.ModuleList(nn.Conv1d(channels, channels, 3, padding=1) for _ in range(3))
self.output = nn.Conv1d(channels, CLASSES, 1)
def forward(self, mel, speaker):
x = self.input(mel.transpose(1, 2)) + self.speaker(speaker).transpose(1, 2)
for block in self.blocks:
x = x + block(F.gelu(x))
return self.output(F.gelu(x)).transpose(1, 2)
def frame_labels(symbols, durations):
return np.repeat([symbol_class(s) for s in symbols], durations)
def banded_viterbi(scores, starts, ends, band):
"""Re-time a fixed state sequence. ``scores`` is [frames, states]; state s
originally covered ``starts[s]:ends[s]`` and may move by ``band`` frames."""
frames, states = scores.shape
low = np.maximum(np.asarray(starts) - band, 0)
high = np.minimum(np.asarray(ends) + band, frames)
low[0], high[-1] = 0, frames
time = np.arange(frames)[:, None]
scores = np.where((time >= low[None]) & (time < high[None]), scores, -np.inf)
previous = np.full(states, -np.inf)
previous[0] = scores[0, 0]
advanced = np.zeros((frames, states), dtype=bool)
for t in range(1, frames):
shifted = np.concatenate(([-np.inf], previous[:-1]))
advanced[t] = shifted > previous
previous = np.where(advanced[t], shifted, previous) + scores[t]
if not np.isfinite(previous[-1]):
raise ValueError("no path inside the band")
durations = np.zeros(states, dtype=np.int64)
state = states - 1
for t in range(frames - 1, -1, -1):
durations[state] += 1
if advanced[t, state]:
state -= 1
if state != 0 or np.any(durations < 1):
raise ValueError("invalid refined path")
return durations
def refine(items, config, device="cuda", iterations=2, band=4, steps=3000, batch=256, window=128,
prior_scale=0.5, seed=20261113, log=print):
"""Refine durations for ``items``: dicts with ``symbols``, ``durations``,
``mel`` (float tensor [frames, n_mels]), ``speaker`` (int) and ``group``
(hex text hash; both voices of a sentence share a fold).
Returns one list of per-utterance duration lists per iteration.
"""
generator = torch.Generator().manual_seed(seed)
torch.manual_seed(seed)
# Two-fold cross-fitting by sentence: a recording is re-timed only by a
# classifier that never saw it (or the other voice's reading of its text),
# so the classifier cannot simply reproduce the labels it was given.
fold = np.array([int(str(item["group"])[:8], 16) % 2 for item in items])
order = np.argsort(fold, kind="stable")
items = [items[i] for i in order]
fold = fold[order]
lengths = [int(item["mel"].shape[0]) for item in items]
offsets = np.concatenate(([0], np.cumsum(lengths)))
split = int(offsets[int((fold == 0).sum())])
if min(split, offsets[-1] - split) <= 2 * window:
raise ValueError("too few recordings for cross-fitted refinement")
mel = ((torch.cat([item["mel"] for item in items]) - config.mel_mean) / config.mel_scale).to(device)
speaker = torch.cat([torch.full((n,), int(item["speaker"]), dtype=torch.long) for item, n in zip(items, lengths)]).to(device)
reference = [np.asarray(item["durations"], dtype=np.int64) for item in items]
current = [d.copy() for d in reference]
results = []
for iteration in range(iterations):
labels = torch.from_numpy(np.concatenate([frame_labels(item["symbols"], d) for item, d in zip(items, current)])).to(device)
refined, moved, agree = [None] * len(items), [], []
for held_out in (0, 1):
low_train, high_train = (split, int(offsets[-1])) if held_out == 0 else (0, split)
model = FrameClassifier(config.n_mels, len(config.speakers)).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-2)
schedule = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=2e-3, total_steps=steps)
model.train()
for step in range(steps):
start = torch.randint(low_train, high_train - window, (batch,), generator=generator).to(device)
index = start[:, None] + torch.arange(window, device=device)[None]
loss = F.cross_entropy(model(mel[index], speaker[index]).flatten(0, 1), labels[index].flatten(), label_smoothing=0.05)
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
schedule.step()
if step % 1000 == 0 or step == steps - 1:
log(f"refine iteration={iteration + 1} held_out_fold={held_out} step={step + 1} loss={loss.item():.4f}")
model.eval()
prior = torch.bincount(labels[low_train:high_train], minlength=CLASSES).float().clamp_min(1)
prior = (prior / prior.sum()).log()
with torch.inference_mode():
for number in np.flatnonzero(fold == held_out):
item, low, high = items[number], int(offsets[number]), int(offsets[number + 1])
original, now = reference[number], current[number]
logits = model(mel[low:high][None], speaker[low:high][None])[0]
agree.append(float((logits.argmax(-1) == labels[low:high]).float().mean()))
scores = (logits.log_softmax(-1) - prior_scale * prior).cpu().numpy().astype(np.float64)
active = np.flatnonzero(original > 0)
ends = np.cumsum(original)[active]
classes = [symbol_class(item["symbols"][i]) for i in active]
durations = np.zeros_like(original)
durations[active] = banded_viterbi(scores[:, classes], ends - original[active], ends, band)
refined[number] = durations
moved.append(np.abs(np.cumsum(durations)[active][:-1] - np.cumsum(now)[active][:-1]))
shift = np.concatenate(moved) if moved else np.zeros(1)
log(f"refine iteration={iteration + 1} held_out_frame_accuracy={np.mean(agree):.4f} "
f"boundary_shift_mean={shift.mean():.3f} unchanged={np.mean(shift == 0):.3f} max={shift.max()}")
current = refined
restored = [None] * len(items)
for position, source in enumerate(order):
restored[source] = refined[position].tolist()
results.append(restored)
return results123456789101112131415161718192021222324252627282930"""ONNX export utilities for Lua Nova V1 (acoustic CFM v5 and BigVGAN vocoder)."""
from __future__ import annotations
from .onnx_export import (
BIGVGAN_INPUTS,
BIGVGAN_OUTPUTS,
CFM_INPUTS,
CFM_OUTPUTS,
ExportableBigVGAN,
ExportableCFMAcoustic,
example_cfm_inputs,
export_bigvgan_onnx,
export_cfm_onnx,
verify_bigvgan_onnx,
verify_cfm_onnx,
)
__all__ = [
"BIGVGAN_INPUTS",
"BIGVGAN_OUTPUTS",
"CFM_INPUTS",
"CFM_OUTPUTS",
"ExportableBigVGAN",
"ExportableCFMAcoustic",
"example_cfm_inputs",
"export_bigvgan_onnx",
"export_cfm_onnx",
"verify_bigvgan_onnx",
"verify_cfm_onnx",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526"""Split ONNX Runtime CPU export (opset 17) for LuaNovaCFM v5 and BigVGAN."""
from __future__ import annotations
import argparse
import copy
import json
import math
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from ..models.bigvgan import BigVGANVocoderWrapper
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_prosody_noise
from ..text.phonemizer import frontend_fingerprint, frontend_identity, phonemize
from ..training.common import load_cfm_model
CFM_INPUTS = ("tokens", "stress", "voice", "speed", "pitch_shift", "pitch_range")
CFM_OUTPUTS = ("phys_mel", "frame_lengths")
BIGVGAN_INPUTS = ("mel",)
BIGVGAN_OUTPUTS = ("audio",)
def example_cfm_inputs(text: str = "Olá, tudo bem?", device: str = "cpu") -> tuple[torch.Tensor, ...]:
"""Build valid dummy inputs matching the exported ``CFM_INPUTS`` signature."""
phones = phonemize(text)
return (
torch.tensor([phones.ids], dtype=torch.long, device=device),
torch.tensor([phones.stress], dtype=torch.long, device=device),
torch.tensor([0], dtype=torch.long, device=device),
torch.tensor([1.0], dtype=torch.float32, device=device),
torch.tensor([0.0], dtype=torch.float32, device=device),
torch.tensor([1.05], dtype=torch.float32, device=device),
)
class ExportableCFMAcoustic(nn.Module):
"""ONNX-traceable unrolled acoustic front-end + OT-CFM ODE predicting physical 100-band log-mel."""
def __init__(
self,
model: LuaNovaCFM,
n_steps: int = 2,
cfg_scale: float = 1.0,
temperature: float = 0.35,
solver: str = "euler",
sway_coef: float = 0.0,
seed: int = 0,
dur_steps: int | None = None,
dur_temp: float | None = None,
prosody_steps: int | None = None,
prosody_temp: float | None = None,
) -> None:
super().__init__()
self.model = model.eval()
self.n_steps = int(n_steps)
self.cfg_scale = float(cfg_scale)
self.temperature = float(temperature)
self.solver = str(solver)
self.sway_coef = float(sway_coef)
cc = model.cfm_config
c = model.config
self.dur_steps = int(cc.dur_flow_steps if dur_steps is None else dur_steps)
self.dur_temp = float(cc.dur_flow_temp if dur_temp is None else dur_temp)
self.prosody_steps = int(cc.prosody_flow_steps if prosody_steps is None else prosody_steps)
self.prosody_temp = float(cc.prosody_flow_temp if prosody_temp is None else prosody_temp)
gen = torch.Generator().manual_seed(int(seed))
self.register_buffer(
"base_noise",
torch.randn((1, c.max_frames, c.vocos_n_mels), generator=gen, dtype=torch.float32),
persistent=False,
)
if model.dur_flow is not None:
dur_gen = torch.Generator().manual_seed(int(seed) + 101)
self.register_buffer(
"base_dur_noise",
torch.randn((1, c.max_tokens, 1), generator=dur_gen, dtype=torch.float32),
persistent=False,
)
if model.prosody_flow is not None:
pros_gen = torch.Generator().manual_seed(int(seed) + 202)
self.register_buffer(
"base_prosody_noise",
torch.randn((1, c.max_frames, 2), generator=pros_gen, dtype=torch.float32),
persistent=False,
)
def _velocity(
self,
x: torch.Tensor,
t_val: float,
cond: torch.Tensor,
prior_mel: torch.Tensor,
frame_mask: torch.Tensor,
f0_feats: torch.Tensor | None,
) -> torch.Tensor:
t_vec = torch.full((1,), float(t_val), device=x.device, dtype=torch.float32)
v_c = self.model.flow(x, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
if self.cfg_scale == 1.0:
return v_c
v_u = self.model.flow(
x,
t_vec,
torch.zeros_like(cond),
torch.zeros_like(prior_mel),
frame_mask,
f0_feats=torch.zeros_like(f0_feats) if f0_feats is not None else None,
)
return v_u + self.cfg_scale * (v_c - v_u)
def forward(
self,
tokens: torch.Tensor,
stress: torch.Tensor,
voice: torch.Tensor,
speed: torch.Tensor,
pitch_shift: torch.Tensor,
pitch_range: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
m, c = self.model, self.model.config
mask = torch.ones_like(tokens, dtype=torch.bool)
hidden = m.encoder(m.tokens(tokens) + m.stress(stress) + m.voices(voice)[:, None], mask)
prosody_token_ctx, clause_ctx_tok = m.encode_prosody_context(hidden, tokens, stress, mask)
raw = m.duration(prosody_token_ctx, mask).float()
prior_z = raw[..., 0].clamp(0.0, math.log1p(400.0))
if m.dur_flow is not None:
sigma_d = m.cfm_config.dur_flow_sigma * self.dur_temp
z = prior_z[..., None] + sigma_d * self.base_dur_noise[:, : tokens.shape[1], :]
dt_d = 1.0 / max(self.dur_steps, 1)
for i in range(self.dur_steps):
t_d = torch.full((1,), i * dt_d, device=tokens.device, dtype=torch.float32)
v_d = m.dur_flow(z, t_d, prior_z[..., None], prosody_token_ctx, mask)
z = z + dt_d * v_d
z1 = z.squeeze(-1)
else:
z1 = prior_z
frames = torch.round((torch.exp(z1.clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
durations = torch.where(m.phone_tokens[tokens] | (raw[..., 1] > 0), frames, torch.zeros_like(frames))
ends = durations.cumsum(1)
total = ends[0, -1]
frame = torch.arange(total, device=tokens.device)[None]
# Cumulative comparison avoids torch.searchsorted which is absent from ONNX opset 17.
index = (ends[:, :, None] <= frame[:, None, :]).sum(1).clamp(max=tokens.shape[1] - 1)
owned = durations.gather(1, index).clamp_min(1)
offset = frame - (ends.gather(1, index) - durations.gather(1, index))
relative = (offset.float() + 0.5) / owned.float()
features = torch.stack((relative, 1.0 - relative, torch.log1p(owned.float()) / 4.0), dim=-1)
pos_voice = m.frame_position(features) + m.frame_voices(voice)[:, None]
expanded = hidden.gather(1, index[..., None].expand(-1, -1, c.channels)) + pos_voice
frame_mask = torch.ones((1, total), device=tokens.device, dtype=torch.bool)
if m.context_adapter is not None or m.frame_ctx_proj is not None:
prosody_frames = prosody_token_ctx.gather(1, index[..., None].expand(-1, -1, c.channels)) + pos_voice
if m.frame_ctx_proj is not None:
f_pos = (frame.float() + 0.5) / total.float()
f_rem = 1.0 - f_pos
c_f = clause_ctx_tok.gather(1, index[..., None].expand(-1, -1, 4))
ctx_6 = torch.cat((f_pos[..., None], f_rem[..., None], c_f.float()), dim=-1)
prosody_frames = prosody_frames + m.frame_ctx_proj(ctx_6)
else:
prosody_frames = expanded
prosody_hidden, prosody = m.predict_prosody(prosody_frames, frame_mask)
if m.prosody_flow is not None:
eps_sm = smooth_prosody_noise(self.base_prosody_noise[:, :total, :], frame_mask, m.prosody_noise_kernel)
prior_fe = torch.stack((prosody[..., 0].float(), prosody[..., 2].float()), dim=-1)
voicing_prob = torch.sigmoid(prosody[..., 1:2].float())
sigma_p = m.cfm_config.prosody_flow_sigma * self.prosody_temp
y = prior_fe + sigma_p * eps_sm
dt_p = 1.0 / max(self.prosody_steps, 1)
for i in range(self.prosody_steps):
t_p = torch.full((1,), i * dt_p, device=tokens.device, dtype=torch.float32)
v_p = m.prosody_flow(y, t_p, prior_fe, voicing_prob, prosody_hidden, frame_mask)
y = y + dt_p * v_p
prosody = torch.cat((y[..., :1], prosody[..., 1:2].float(), y[..., 1:2]), dim=-1)
is_vowel = m.vowel_tokens[tokens.gather(1, index)]
prosody = torch.cat(
(
prosody[..., :1],
torch.where(is_vowel, prosody[..., 1].clamp_min(1.0), prosody[..., 1])[..., None],
prosody[..., 2:],
),
dim=-1,
)
voiced = (prosody[..., 1] > 0).float()
mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1.0)
pitch = mean + (prosody[..., 0] - mean) * pitch_range + pitch_shift
prosody = torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1)
hard_p = m.hard_prosody(prosody)
base_h = expanded if m.cfm_config.acoustic_from_frames else prosody_hidden
cond, prior_mel = m.condition_and_prior(base_h, hard_p, frame_mask)
f0_feats = f0_features(hard_p, frame_mask) if m.cfm_config.use_f0_harmonics else None
sigma = m.cfm_config.prior_sigma * self.temperature
noise_gate = energy_noise_gate(hard_p, frame_mask) if m.cfm_config.use_energy_gate else 1.0
x = prior_mel + sigma * noise_gate * self.base_noise[:, :total, :]
t_grid = m.sway_time_grid(self.n_steps, self.sway_coef)
for i in range(self.n_steps):
t0, t1 = t_grid[i], t_grid[i + 1]
dt_i = t1 - t0
v0 = self._velocity(x, t0, cond, prior_mel, frame_mask, f0_feats)
if self.solver == "midpoint":
v_mid = self._velocity(x + 0.5 * dt_i * v0, t0 + 0.5 * dt_i, cond, prior_mel, frame_mask, f0_feats)
x = x + dt_i * v_mid
else:
x = x + dt_i * v0
phys_mel = (x * m.vocoder.mel_scale + m.vocoder.mel_mean).clamp(min=-11.512925)
frame_lengths = ends[:, -1].long()
return phys_mel, frame_lengths
class _OnnxUpSample1d(nn.Module):
"""Static-channel ONNX-safe replacement for ``alias_free_activation.UpSample1d``."""
def __init__(self, orig: nn.Module, channels: int) -> None:
super().__init__()
self.stride = int(orig.stride)
self.pad = int(orig.pad)
self.pad_left = int(orig.pad_left)
self.pad_right = int(orig.pad_right)
self.channels = int(channels)
scaled = orig.filter.detach() * float(orig.ratio)
self.register_buffer("weight", scaled.expand(self.channels, 1, -1).contiguous())
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.pad > 0:
left = x[:, :, :1].expand(-1, -1, self.pad)
right = x[:, :, -1:].expand(-1, -1, self.pad)
x = torch.cat((left, x, right), dim=-1)
x = F.conv_transpose1d(x, self.weight, stride=self.stride, groups=self.channels)
return x[:, :, self.pad_left : -self.pad_right]
class _OnnxLowPassFilter1d(nn.Module):
"""Static-channel ONNX-safe replacement for ``alias_free_activation.LowPassFilter1d``."""
def __init__(self, orig: nn.Module, channels: int) -> None:
super().__init__()
self.stride = int(orig.stride)
self.padding = bool(orig.padding)
self.pad_left = int(orig.pad_left)
self.pad_right = int(orig.pad_right)
self.channels = int(channels)
self.register_buffer("weight", orig.filter.detach().expand(self.channels, 1, -1).contiguous())
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.padding:
left = x[:, :, :1].expand(-1, -1, self.pad_left)
right = x[:, :, -1:].expand(-1, -1, self.pad_right)
x = torch.cat((left, x, right), dim=-1)
return F.conv1d(x, self.weight, stride=self.stride, groups=self.channels)
def _make_bigvgan_onnx_safe(net: nn.Module) -> nn.Module:
net_copy = copy.deepcopy(net).eval()
for mod in net_copy.modules():
if hasattr(mod, "act") and hasattr(mod, "upsample") and hasattr(mod, "downsample"):
channels = int(getattr(mod.act, "in_features"))
mod.upsample = _OnnxUpSample1d(mod.upsample, channels)
mod.downsample.lowpass = _OnnxLowPassFilter1d(mod.downsample.lowpass, channels)
return net_copy
class ExportableBigVGAN(nn.Module):
"""ONNX-traceable BigVGAN wrapper mapping physical log-mel ``[B, T, 100]`` -> audio ``[B, T*256]``."""
def __init__(self, vocoder: BigVGANVocoderWrapper) -> None:
super().__init__()
self.net = _make_bigvgan_onnx_safe(vocoder.net)
def forward(self, mel: torch.Tensor) -> torch.Tensor:
return self.net(mel.transpose(1, 2).contiguous()).squeeze(1)
def _export_torch_onnx(
module: nn.Module,
args: tuple[torch.Tensor, ...],
out_path: Path,
input_names: list[str],
output_names: list[str],
dynamic_axes: dict[str, dict[int, str]],
opset: int,
) -> Path:
import onnx
out_path.parent.mkdir(parents=True, exist_ok=True)
kwargs = dict(
input_names=input_names,
output_names=output_names,
dynamic_axes=dynamic_axes,
opset_version=opset,
do_constant_folding=True,
)
try:
torch.onnx.export(module, args, str(out_path), dynamo=False, **kwargs)
except TypeError:
torch.onnx.export(module, args, str(out_path), **kwargs)
onnx_model = onnx.load(str(out_path))
onnx.checker.check_model(onnx_model)
return out_path
def export_cfm_onnx(
cfm_path_or_model: Path | str | LuaNovaCFM,
out_path: Path | str,
n_steps: int = 2,
cfg_scale: float = 1.0,
temperature: float = 0.35,
solver: str = "euler",
sway_coef: float = 0.0,
seed: int = 0,
opset: int = 17,
) -> Path:
"""Export LuaNovaCFM acoustic predictor to ONNX + companion ``.meta.json``."""
model = (
cfm_path_or_model
if isinstance(cfm_path_or_model, LuaNovaCFM)
else load_cfm_model(cfm_path_or_model, device="cpu", load_vocos=False)
).cpu().eval()
wrapper = ExportableCFMAcoustic(
model,
n_steps=n_steps,
cfg_scale=cfg_scale,
temperature=temperature,
solver=solver,
sway_coef=sway_coef,
seed=seed,
).eval()
dummy = example_cfm_inputs()
target = Path(out_path)
with torch.no_grad():
_export_torch_onnx(
wrapper,
dummy,
target,
input_names=list(CFM_INPUTS),
output_names=list(CFM_OUTPUTS),
dynamic_axes={"tokens": {1: "tokens"}, "stress": {1: "tokens"}, "phys_mel": {1: "frames"}},
opset=opset,
)
meta = {
"sample_rate": int(model.config.sample_rate),
"hop": int(model.config.hop),
"n_mels": int(model.config.vocos_n_mels),
"max_tokens": int(model.config.max_tokens),
"speakers": list(model.config.speakers),
"n_steps": int(n_steps),
"solver": str(solver),
"sway_coef": float(sway_coef),
"temperature": float(temperature),
"cfg_scale": float(cfg_scale),
"seed": int(seed),
"frontend": {**frontend_identity(), "fingerprint": frontend_fingerprint()},
}
meta_path = target.with_suffix(".meta.json")
meta_path.write_text(json.dumps(meta, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return target
def export_bigvgan_onnx(
vocoder_path_or_id: Path | str | BigVGANVocoderWrapper,
out_path: Path | str,
opset: int = 17,
dummy_frames: int = 40,
) -> Path:
"""Export MIT BigVGAN 24 kHz 100-band vocoder to dynamic-length ONNX."""
if isinstance(vocoder_path_or_id, BigVGANVocoderWrapper):
vocoder = vocoder_path_or_id.cpu().eval()
else:
voc_target = Path(vocoder_path_or_id)
if voc_target.is_file():
vocoder = BigVGANVocoderWrapper(ckpt_path=voc_target, device="cpu")
else:
vocoder = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device="cpu")
wrapper = ExportableBigVGAN(vocoder).eval()
dummy_mel = torch.full((1, int(dummy_frames), 100), -5.0, dtype=torch.float32)
target = Path(out_path)
with torch.no_grad():
return _export_torch_onnx(
wrapper,
(dummy_mel,),
target,
input_names=list(BIGVGAN_INPUTS),
output_names=list(BIGVGAN_OUTPUTS),
dynamic_axes={"mel": {1: "frames"}, "audio": {1: "samples"}},
opset=opset,
)
def verify_cfm_onnx(
cfm_path_or_model: Path | str | LuaNovaCFM,
onnx_path: Path | str,
n_steps: int = 2,
cfg_scale: float = 1.0,
temperature: float = 0.35,
solver: str = "euler",
sway_coef: float = 0.0,
seed: int = 0,
text: str = "Olá, tudo bem com você hoje?",
) -> dict[str, float]:
"""Compare exported ONNX acoustic predictions against PyTorch ``ExportableCFMAcoustic``."""
import onnxruntime as ort
model = (
cfm_path_or_model
if isinstance(cfm_path_or_model, LuaNovaCFM)
else load_cfm_model(cfm_path_or_model, device="cpu", load_vocos=False)
).cpu().eval()
wrapper = ExportableCFMAcoustic(
model,
n_steps=n_steps,
cfg_scale=cfg_scale,
temperature=temperature,
solver=solver,
sway_coef=sway_coef,
seed=seed,
).eval()
inputs = example_cfm_inputs(text=text, device="cpu")
with torch.no_grad():
mel_pt, flen_pt = wrapper(*inputs)
sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
feed = {name: arr.numpy() for name, arr in zip(CFM_INPUTS, inputs)}
mel_ort, flen_ort = sess.run(list(CFM_OUTPUTS), feed)
diff = np.abs(mel_pt.numpy() - mel_ort)
return {
"max_abs_diff": float(diff.max()),
"mean_abs_diff": float(diff.mean()),
"frames_match": float(int(flen_pt.item()) == int(flen_ort.item())),
"frames": float(int(flen_ort.item())),
}
def verify_bigvgan_onnx(
vocoder_path_or_id: Path | str | BigVGANVocoderWrapper,
onnx_path: Path | str,
test_frames: int = 67,
) -> dict[str, float]:
"""Compare exported BigVGAN ONNX output against PyTorch at an arbitrary frame length."""
import onnxruntime as ort
if isinstance(vocoder_path_or_id, BigVGANVocoderWrapper):
vocoder = vocoder_path_or_id.cpu().eval()
else:
voc_target = Path(vocoder_path_or_id)
if voc_target.is_file():
vocoder = BigVGANVocoderWrapper(ckpt_path=voc_target, device="cpu")
else:
vocoder = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device="cpu")
mel = torch.randn((1, int(test_frames), 100), dtype=torch.float32) * 0.5 - 5.0
flen = torch.tensor([test_frames], dtype=torch.long)
with torch.no_grad():
wav_pt = vocoder.decode_raw_mel(mel, flen).numpy()
sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
(wav_ort,) = sess.run(list(BIGVGAN_OUTPUTS), {"mel": mel.numpy()})
diff = np.abs(wav_pt - wav_ort)
return {
"max_abs_diff": float(diff.max()),
"mean_abs_diff": float(diff.mean()),
"samples": float(wav_ort.shape[-1]),
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cfm", type=Path, default=None, help="Path to CFM v5 checkpoint (.pt)")
parser.add_argument("--vocoder", default=None, help="Path to BigVGAN .pt checkpoint or HF model ID")
parser.add_argument("--out-dir", type=Path, required=True)
parser.add_argument("--cfm-name", default="cfm_v5.onnx")
parser.add_argument("--vocoder-name", default="bigvgan_base_ft.onnx")
parser.add_argument("--steps", type=int, default=2)
parser.add_argument("--solver", default="euler", choices=["euler", "midpoint"])
parser.add_argument("--sway-coef", type=float, default=0.0)
parser.add_argument("--temperature", type=float, default=0.35)
parser.add_argument("--cfg-scale", type=float, default=1.0)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--opset", type=int, default=17)
parser.add_argument("--verify", action="store_true")
args = parser.parse_args()
if args.cfm is None and args.vocoder is None:
parser.error("provide at least --cfm or --vocoder")
args.out_dir.mkdir(parents=True, exist_ok=True)
if args.cfm is not None:
cfm_out = export_cfm_onnx(
args.cfm,
args.out_dir / args.cfm_name,
n_steps=args.steps,
cfg_scale=args.cfg_scale,
temperature=args.temperature,
solver=args.solver,
sway_coef=args.sway_coef,
seed=args.seed,
opset=args.opset,
)
print(f"Exported CFM ONNX -> {cfm_out}", flush=True)
if args.verify:
stats = verify_cfm_onnx(
args.cfm,
cfm_out,
n_steps=args.steps,
cfg_scale=args.cfg_scale,
temperature=args.temperature,
solver=args.solver,
sway_coef=args.sway_coef,
seed=args.seed,
)
print("CFM parity:", json.dumps(stats), flush=True)
if args.vocoder is not None:
voc_out = export_bigvgan_onnx(args.vocoder, args.out_dir / args.vocoder_name, opset=args.opset)
print(f"Exported BigVGAN ONNX -> {voc_out}", flush=True)
if args.verify:
stats = verify_bigvgan_onnx(args.vocoder, voc_out)
print("BigVGAN parity:", json.dumps(stats), flush=True)
if __name__ == "__main__":
main()1234567"""Inference synthesizers, streaming helpers, and CLI entrypoints."""
from .onnx_engine import OnnxSynthesizer
from .streaming import iter_speakable_pieces, stream_vocoder_chunks
from .synthesizer import Synthesizer
__all__ = ["OnnxSynthesizer", "Synthesizer", "iter_speakable_pieces", "stream_vocoder_chunks"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""Command-line interface for Lua Nova V1 PyTorch & ONNX Runtime CPU synthesis."""
from __future__ import annotations
import argparse
from pathlib import Path
import time
import numpy as np
from .onnx_engine import OnnxSynthesizer
from .synthesizer import Synthesizer
def main() -> None:
parser = argparse.ArgumentParser(description="Synthesize 24 kHz PT-BR speech with LuaNovaBase CFM v5 + BigVGAN")
parser.add_argument("--text", required=True, help="Input Portuguese text")
parser.add_argument("--out", type=Path, required=True, help="Output .wav path")
# PyTorch backend
parser.add_argument("--cfm", type=Path, default=None, help="Path to CFM v5 checkpoint (.pt)")
parser.add_argument(
"--vocoder",
default="nvidia/bigvgan_base_24khz_100band",
help="Path to fine-tuned BigVGAN .pt checkpoint or Hugging Face model ID",
)
parser.add_argument("--device", default="cpu")
parser.add_argument("--steps", type=int, default=8)
parser.add_argument("--solver", default="midpoint", choices=["euler", "midpoint"])
parser.add_argument("--temperature", type=float, default=0.35)
parser.add_argument("--cfg-scale", type=float, default=1.0)
parser.add_argument("--sway-coef", type=float, default=-0.5)
parser.add_argument("--seed", type=int, default=0)
# ONNX Runtime CPU backend
parser.add_argument("--onnx-cfm", type=Path, default=None, help="Path to exported cfm_v5.onnx")
parser.add_argument("--onnx-vocoder", type=Path, default=None, help="Path to exported bigvgan.onnx")
parser.add_argument("--threads", type=int, default=None, help="ONNX Runtime intra-op CPU threads")
# Shared & streaming options
parser.add_argument("--voice", default="F1")
parser.add_argument("--pitch-range", type=float, default=1.05)
parser.add_argument("--speed", type=float, default=1.0)
parser.add_argument("--no-normalize", action="store_true", help="Disable PT-BR text normalization")
parser.add_argument("--no-postprocess", action="store_true", help="Disable RMS normalization and edge fades")
parser.add_argument("--stream", action="store_true", help="Synthesize via chunked streaming and report TTFA")
parser.add_argument("--chunk-frames", type=int, default=36, help="Mel frames per streamed vocoder chunk")
args = parser.parse_args()
use_onnx = args.onnx_cfm is not None or args.onnx_vocoder is not None
if use_onnx:
if args.onnx_cfm is None or args.onnx_vocoder is None:
parser.error("both --onnx-cfm and --onnx-vocoder are required for ONNX inference")
synth = OnnxSynthesizer(args.onnx_cfm, args.onnx_vocoder, threads=args.threads)
t0 = time.perf_counter()
if args.stream:
chunks: list[np.ndarray] = []
ttfa_ms = None
for chunk in synth.speak_stream(
args.text,
voice=args.voice,
speed=args.speed,
pitch_range=args.pitch_range,
normalize=not args.no_normalize,
chunk_frames=args.chunk_frames,
):
if ttfa_ms is None:
ttfa_ms = (time.perf_counter() - t0) * 1000.0
chunks.append(chunk)
wav = np.concatenate(chunks, axis=0) if chunks else np.zeros(0, dtype=np.float32)
else:
ttfa_ms = None
wav = synth.speak(
args.text,
voice=args.voice,
speed=args.speed,
pitch_range=args.pitch_range,
normalize=not args.no_normalize,
postprocess=not args.no_postprocess,
)
else:
if args.cfm is None:
parser.error("provide --cfm (PyTorch) or --onnx-cfm/--onnx-vocoder (ONNX Runtime)")
synth = Synthesizer.from_checkpoints(args.cfm, args.vocoder, device=args.device)
t0 = time.perf_counter()
if args.stream:
chunks = []
ttfa_ms = None
for chunk in synth.speak_stream(
args.text,
voice=args.voice,
n_steps=args.steps,
temperature=args.temperature,
cfg_scale=args.cfg_scale,
sway_coef=args.sway_coef,
solver=args.solver,
pitch_range=args.pitch_range,
speed=args.speed,
normalize=not args.no_normalize,
seed=args.seed,
chunk_frames=args.chunk_frames,
):
if ttfa_ms is None:
ttfa_ms = (time.perf_counter() - t0) * 1000.0
chunks.append(chunk)
wav = np.concatenate(chunks, axis=0) if chunks else np.zeros(0, dtype=np.float32)
else:
ttfa_ms = None
wav = synth.speak(
args.text,
voice=args.voice,
n_steps=args.steps,
temperature=args.temperature,
cfg_scale=args.cfg_scale,
sway_coef=args.sway_coef,
solver=args.solver,
pitch_range=args.pitch_range,
speed=args.speed,
normalize=not args.no_normalize,
postprocess=not args.no_postprocess,
seed=args.seed,
)
elapsed = time.perf_counter() - t0
out_path = synth.save_wav(args.out, wav)
dur_s = len(wav) / synth.sample_rate
ttfa_info = f", TTFA={ttfa_ms:.1f}ms" if ttfa_ms is not None else ""
print(f"Saved {out_path} ({dur_s:.2f}s audio in {elapsed:.3f}s, {dur_s / max(elapsed, 1e-6):.2f}x RT{ttfa_info})")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""Pure-CPU ONNX Runtime synthesizer and chunked streaming engine for Lua Nova V1."""
from __future__ import annotations
from collections.abc import Iterator
import json
import os
from pathlib import Path
import numpy as np
import soundfile as sf
from ..text.phonemizer import phonemize
from ..utils.audio import DEFAULT_FADE_MS, DEFAULT_TARGET_RMS_DB, pcm16, postprocess_audio
from .streaming import iter_speakable_pieces, stream_vocoder_chunks
class OnnxSynthesizer:
"""Fast CPU TTS engine running split ``cfm_v5.onnx`` + ``bigvgan.onnx`` via ONNX Runtime."""
def __init__(
self,
cfm_onnx_path: Path | str,
vocoder_onnx_path: Path | str,
threads: int | None = None,
speakers: tuple[str, ...] | None = None,
sample_rate: int | None = None,
hop: int | None = None,
max_tokens: int | None = None,
) -> None:
import onnxruntime as ort
cfm_path = Path(cfm_onnx_path)
voc_path = Path(vocoder_onnx_path)
meta_path = cfm_path.with_suffix(".meta.json")
meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.is_file() else {}
self.speakers = tuple(speakers or meta.get("speakers", ("F1",)))
self.sample_rate = int(sample_rate or meta.get("sample_rate", 24000))
self.hop = int(hop or meta.get("hop", 256))
self.max_tokens = int(max_tokens or meta.get("max_tokens", 512))
self.threads = int(threads) if threads is not None else max(1, (os.cpu_count() or 4) // 2)
opts = ort.SessionOptions()
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
opts.intra_op_num_threads = self.threads
opts.inter_op_num_threads = 1
opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
self.cfm_sess = ort.InferenceSession(str(cfm_path), sess_options=opts, providers=["CPUExecutionProvider"])
self.voc_sess = ort.InferenceSession(str(voc_path), sess_options=opts, providers=["CPUExecutionProvider"])
self.cfm_meta = meta
def predict_mel(
self,
piece: str,
voice: str = "F1",
speed: float = 1.0,
pitch_shift: float = 0.0,
pitch_range: float = 1.05,
) -> np.ndarray:
"""Predict unnormalized physical 100-band log-mel ``[T, 100]`` for one phrase piece."""
if voice not in self.speakers:
raise ValueError(f"unknown speaker {voice!r}; available: {self.speakers}")
phones = phonemize(piece)
feed = {
"tokens": np.asarray([phones.ids], dtype=np.int64),
"stress": np.asarray([phones.stress], dtype=np.int64),
"voice": np.asarray([self.speakers.index(voice)], dtype=np.int64),
"speed": np.asarray([speed], dtype=np.float32),
"pitch_shift": np.asarray([pitch_shift], dtype=np.float32),
"pitch_range": np.asarray([pitch_range], dtype=np.float32),
}
phys_mel, flen = self.cfm_sess.run(["phys_mel", "frame_lengths"], feed)
n_frames = int(flen[0])
return phys_mel[0, :n_frames, :].astype(np.float32, copy=False)
def decode_mel(self, phys_mel: np.ndarray) -> np.ndarray:
"""Decode physical log-mel ``[T, 100]`` (or ``[1, T, 100]``) to mono 24 kHz float32 audio."""
mel = np.asarray(phys_mel, dtype=np.float32)
if mel.ndim == 2:
mel = mel[None, :, :]
(wav,) = self.voc_sess.run(["audio"], {"mel": mel})
return wav[0].astype(np.float32, copy=False)
def decode_mel_stream(
self,
phys_mel: np.ndarray,
chunk_frames: int = 36,
context_frames: int = 8,
fade_frames: int = 4,
) -> Iterator[np.ndarray]:
"""Yield overlap-crossfaded 24 kHz waveform chunks from physical log-mel ``[T, 100]``."""
return stream_vocoder_chunks(
self.decode_mel,
phys_mel,
hop=self.hop,
chunk_frames=chunk_frames,
context_frames=context_frames,
fade_frames=fade_frames,
)
def speak(
self,
text: str,
voice: str = "F1",
speed: float = 1.0,
pitch_shift: float = 0.0,
pitch_range: float = 1.05,
normalize: bool = True,
postprocess: bool = True,
pause_ms: float = 120.0,
) -> np.ndarray:
"""Synthesize full-utterance mono 24 kHz float32 waveform in ``[-1, 1]``."""
pieces = iter_speakable_pieces(text, self.max_tokens, normalize=normalize)
waves = [self.decode_mel(self.predict_mel(p, voice, speed, pitch_shift, pitch_range)) for p in pieces]
if len(waves) == 1:
combined = waves[0]
else:
gap = np.zeros(int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0)), dtype=np.float32)
parts: list[np.ndarray] = []
for idx, w in enumerate(waves):
if idx > 0 and gap.size:
parts.append(gap)
parts.append(w)
combined = np.concatenate(parts, axis=0)
if postprocess:
combined = postprocess_audio(
combined,
sample_rate=self.sample_rate,
target_rms_db=DEFAULT_TARGET_RMS_DB,
fade_ms=DEFAULT_FADE_MS,
)
pcm, _ = pcm16(combined)
return pcm.astype(np.float32)
def speak_stream(
self,
text: str,
voice: str = "F1",
speed: float = 1.0,
pitch_shift: float = 0.0,
pitch_range: float = 1.05,
normalize: bool = True,
pause_ms: float = 120.0,
chunk_frames: int = 36,
context_frames: int = 8,
fade_frames: int = 4,
) -> Iterator[np.ndarray]:
"""Stream 24 kHz mono float32 audio chunks phrase-by-phrase and mel-chunk-by-chunk."""
pieces = iter_speakable_pieces(text, self.max_tokens, normalize=normalize)
gap_samples = int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0))
for idx, piece in enumerate(pieces):
if idx > 0 and gap_samples > 0:
yield np.zeros(gap_samples, dtype=np.float32)
mel = self.predict_mel(piece, voice=voice, speed=speed, pitch_shift=pitch_shift, pitch_range=pitch_range)
yield from self.decode_mel_stream(
mel,
chunk_frames=chunk_frames,
context_frames=context_frames,
fade_frames=fade_frames,
)
def save_wav(self, path: Path | str, wav: np.ndarray) -> Path:
"""Save synthesized audio as 16-bit 24 kHz PCM WAV."""
out_path = Path(path)
out_path.parent.mkdir(parents=True, exist_ok=True)
pcm, _ = pcm16(wav)
sf.write(out_path, pcm, self.sample_rate, subtype="PCM_16")
return out_path123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Shared streaming and chunk-stitching helpers for PyTorch and ONNX synthesizers."""
from __future__ import annotations
from collections.abc import Callable, Iterator
import numpy as np
from ..text.normalizer import normalize_ptbr_text
from ..text.phonemizer import phonemize
from ..utils.audio import finished, sentences, shorter
def _split_piece_by_tokens(piece: str, max_tokens: int) -> list[str]:
phones = phonemize(piece)
if len(phones) <= max_tokens:
return [piece]
halves = shorter(piece)
if len(halves) > 1:
out: list[str] = []
for sub in halves:
if sub.strip():
out.extend(_split_piece_by_tokens(sub, max_tokens))
return out
raise ValueError(f"chunk exceeds max_tokens={max_tokens}: {piece[:80]!r}")
def iter_speakable_pieces(text: str, max_tokens: int, normalize: bool = True) -> list[str]:
"""Normalize text and split it into sentence/clause pieces fitting within ``max_tokens``."""
if not text or not text.strip():
raise ValueError("input text must not be empty")
clean = normalize_ptbr_text(text) if normalize else text.strip()
sent_list = [finished(s) for s in sentences(clean)] or [finished(clean)]
pieces: list[str] = []
for sent in sent_list:
pieces.extend(_split_piece_by_tokens(sent, max_tokens))
return pieces
def stream_vocoder_chunks(
decode_mel_fn: Callable[[np.ndarray], np.ndarray],
phys_mel: np.ndarray,
hop: int = 256,
chunk_frames: int = 36,
context_frames: int = 8,
fade_frames: int = 4,
) -> Iterator[np.ndarray]:
"""Yield click-free mono waveform chunks from physical log-mel ``[T, 100]``.
Each chunk includes symmetrical convolutional lookback/lookahead ``context_frames`` when
decoding and applies a raised-cosine Hann crossfade across ``fade_frames`` at boundaries so
concatenating all yielded chunks matches exact length ``T * hop``.
"""
mel = np.asarray(phys_mel, dtype=np.float32)
if mel.ndim == 3:
mel = mel[0]
total_frames = int(mel.shape[0])
if total_frames <= 0:
return
chunk = max(int(chunk_frames), 4)
ctx = max(int(context_frames), 0)
fade = min(max(int(fade_frames), 0), chunk // 2)
pending_tail: np.ndarray | None = None
start = 0
while start < total_frames:
end = min(total_frames, start + chunk)
if total_frames - end <= max(fade, chunk // 3):
end = total_frames
out_start = start - fade if pending_tail is not None and fade > 0 else start
in_start = max(0, out_start - ctx)
in_end = min(total_frames, end + ctx)
raw = np.asarray(decode_mel_fn(mel[in_start:in_end]), dtype=np.float32).reshape(-1)
left_trim = (out_start - in_start) * hop
out_samples = (end - out_start) * hop
seg = raw[left_trim : left_trim + out_samples].copy()
if pending_tail is not None and pending_tail.size > 0:
n_fade = int(pending_tail.size)
t = np.linspace(0.0, 1.0, n_fade, dtype=np.float32)
w = 0.5 * (1.0 - np.cos(np.pi * t))
seg[:n_fade] = (1.0 - w) * pending_tail + w * seg[:n_fade]
if end < total_frames and fade > 0:
tail_samples = fade * hop
pending_tail = seg[-tail_samples:].copy()
emit = seg[:-tail_samples]
else:
pending_tail = None
emit = seg
if emit.size > 0:
yield np.clip(emit, -0.99, 0.99).astype(np.float32, copy=False)
start = end123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209"""High-level PyTorch inference synthesizer for Lua Nova V1."""
from __future__ import annotations
from collections.abc import Iterator
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from ..models.bigvgan import BigVGANVocoderWrapper
from ..models.cfm import LuaNovaCFM
from ..text.phonemizer import phonemize
from ..training.common import load_cfm_model
from ..utils.audio import (
DEFAULT_FADE_MS,
DEFAULT_TARGET_RMS_DB,
pcm16,
postprocess_audio,
)
from .streaming import iter_speakable_pieces, stream_vocoder_chunks
class Synthesizer:
"""End-to-end Brazilian Portuguese TTS pipeline (CFM v5 + BigVGAN 24 kHz)."""
def __init__(self, cfm: LuaNovaCFM, vocoder: BigVGANVocoderWrapper, device: str = "cpu") -> None:
self.cfm = cfm.to(device).eval()
self.vocoder = vocoder.to(device).eval()
self.device = str(device)
self.sample_rate = int(self.cfm.config.sample_rate)
self.hop = int(self.cfm.config.hop)
@classmethod
def from_checkpoints(
cls,
cfm_path: Path | str,
vocoder_path_or_id: Path | str = "nvidia/bigvgan_base_24khz_100band",
device: str = "cpu",
) -> "Synthesizer":
"""Load acoustic CFM weights and either a local fine-tuned vocoder `.pt` or Hugging Face repo ID."""
cfm = load_cfm_model(cfm_path, device=device, load_vocos=False)
voc_target = Path(vocoder_path_or_id)
if voc_target.is_file():
voc = BigVGANVocoderWrapper(ckpt_path=voc_target, device=device)
else:
voc = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device=device)
return cls(cfm=cfm, vocoder=voc, device=device)
def _predict_piece_mel(
self,
piece: str,
voice: str,
n_steps: int,
temperature: float,
cfg_scale: float,
sway_coef: float,
solver: str,
pitch_range: float | None,
speed: float,
pitch_shift: float,
seed: int,
) -> tuple[torch.Tensor, torch.Tensor]:
if voice not in self.cfm.config.speakers:
raise ValueError(f"unknown speaker {voice!r}; available: {self.cfm.config.speakers}")
phones = phonemize(piece)
tok = torch.tensor([phones.ids], device=self.device)
st = torch.tensor([phones.stress], device=self.device)
ln = torch.tensor([len(phones)], device=self.device)
sp = torch.tensor([self.cfm.config.speakers.index(voice)], device=self.device)
with torch.inference_mode():
phys_mel, flen, _ = self.cfm.predict_physical_mel(
tok,
st,
ln,
sp,
speed=speed,
pitch_shift=pitch_shift,
seed=seed,
pitch_range=pitch_range,
n_steps=n_steps,
cfg_scale=cfg_scale,
temperature=temperature,
solver=solver,
sway_coef=sway_coef,
)
return phys_mel, flen
def _decode_mel_slice(self, mel_chunk: np.ndarray) -> np.ndarray:
mel_t = torch.from_numpy(mel_chunk[None, :, :]).to(device=self.device, dtype=torch.float32)
flen = torch.tensor([mel_t.shape[1]], device=self.device, dtype=torch.long)
with torch.inference_mode():
wav = self.vocoder.decode_raw_mel(mel_t, flen)[0, : int(flen[0]) * self.hop]
return wav.cpu().numpy()
def speak(
self,
text: str,
voice: str = "F1",
n_steps: int = 8,
temperature: float = 0.35,
cfg_scale: float = 1.0,
sway_coef: float = -0.5,
solver: str = "midpoint",
pitch_range: float | None = 1.05,
speed: float = 1.0,
pitch_shift: float = 0.0,
normalize: bool = True,
postprocess: bool = True,
pause_ms: float = 120.0,
seed: int = 0,
) -> np.ndarray:
"""Synthesize arbitrary-length PT-BR text into a mono 24 kHz float32 waveform in [-1, 1]."""
pieces = iter_speakable_pieces(text, self.cfm.config.max_tokens, normalize=normalize)
waves: list[torch.Tensor] = []
for idx, piece in enumerate(pieces):
phys_mel, flen = self._predict_piece_mel(
piece,
voice,
n_steps,
temperature,
cfg_scale,
sway_coef,
solver,
pitch_range,
speed,
pitch_shift,
seed + idx,
)
with torch.inference_mode():
wav = self.vocoder.decode_raw_mel(phys_mel, flen)[0, : int(flen[0]) * self.hop]
waves.append(wav.cpu())
if len(waves) == 1:
combined = waves[0]
else:
gap = torch.zeros(int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0)), dtype=torch.float32)
parts: list[torch.Tensor] = []
for idx, w in enumerate(waves):
if idx > 0 and gap.numel():
parts.append(gap)
parts.append(w)
combined = torch.cat(parts, dim=0)
if postprocess:
combined = postprocess_audio(
combined,
sample_rate=self.sample_rate,
target_rms_db=DEFAULT_TARGET_RMS_DB,
fade_ms=DEFAULT_FADE_MS,
)
pcm, _ = pcm16(combined)
return pcm.astype(np.float32)
def speak_stream(
self,
text: str,
voice: str = "F1",
n_steps: int = 8,
temperature: float = 0.35,
cfg_scale: float = 1.0,
sway_coef: float = -0.5,
solver: str = "midpoint",
pitch_range: float | None = 1.05,
speed: float = 1.0,
pitch_shift: float = 0.0,
normalize: bool = True,
pause_ms: float = 120.0,
seed: int = 0,
chunk_frames: int = 36,
context_frames: int = 8,
fade_frames: int = 4,
) -> Iterator[np.ndarray]:
"""Yield low-latency 24 kHz waveform chunks via overlap-crossfaded mel streaming."""
pieces = iter_speakable_pieces(text, self.cfm.config.max_tokens, normalize=normalize)
gap_samples = int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0))
for idx, piece in enumerate(pieces):
if idx > 0 and gap_samples > 0:
yield np.zeros(gap_samples, dtype=np.float32)
phys_mel, flen = self._predict_piece_mel(
piece,
voice,
n_steps,
temperature,
cfg_scale,
sway_coef,
solver,
pitch_range,
speed,
pitch_shift,
seed + idx,
)
mel_np = phys_mel[0, : int(flen[0]), :].cpu().numpy()
yield from stream_vocoder_chunks(
self._decode_mel_slice,
mel_np,
hop=self.hop,
chunk_frames=chunk_frames,
context_frames=context_frames,
fade_frames=fade_frames,
)
def save_wav(self, path: Path | str, wav: np.ndarray) -> Path:
"""Save synthesized audio as 16-bit 24 kHz PCM WAV."""
out_path = Path(path)
out_path.parent.mkdir(parents=True, exist_ok=True)
pcm, _ = pcm16(wav)
sf.write(out_path, pcm, self.sample_rate, subtype="PCM_16")
return out_path123456789101112131415161718192021222324252627282930313233343536373839"""Neural acoustic, prosody, flow-matching, and BigVGAN vocoder modules."""
from .bigvgan import BigVGANMelExtractor, BigVGANVocoderWrapper
from .cfm import (
DurationFlow,
FlowDecoder,
LinguisticContextAdapter,
MelStatsHead,
ProsodyFlow,
LuaNovaCFM,
energy_noise_gate,
f0_features,
smooth_f0_channel,
smooth_prosody_noise,
)
from .frontend import LuaNovaBase, UtteranceTooLong
from .losses import Discriminators, SpectralLoss, discriminator_loss, generator_gan_loss, masked_mean
__all__ = [
"BigVGANMelExtractor",
"BigVGANVocoderWrapper",
"Discriminators",
"DurationFlow",
"FlowDecoder",
"LinguisticContextAdapter",
"MelStatsHead",
"ProsodyFlow",
"SpectralLoss",
"LuaNovaBase",
"LuaNovaCFM",
"UtteranceTooLong",
"discriminator_loss",
"energy_noise_gate",
"f0_features",
"generator_gan_loss",
"masked_mean",
"smooth_f0_channel",
"smooth_prosody_noise",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""MIT-licensed BigVGAN-v2 / BigVGAN-base 24 kHz 100-band Slaney mel extractor and vocoder wrapper."""
from __future__ import annotations
from pathlib import Path
import sys
from librosa.filters import mel as librosa_mel_fn
import torch
from torch import nn
import torch.nn.functional as F
_REPO_ROOT = Path(__file__).resolve().parents[3]
_BIGVGAN_DIR = _REPO_ROOT / "third_party" / "bigvgan"
def _ensure_bigvgan_importable() -> None:
if str(_BIGVGAN_DIR) not in sys.path:
sys.path.insert(0, str(_BIGVGAN_DIR))
try:
import truststore
truststore.inject_into_ssl()
except ImportError:
pass
class BigVGANMelExtractor(nn.Module):
"""Exact 24 kHz 100-band Slaney log-mel extractor matching MIT BigVGAN ``meldataset.py``."""
def __init__(
self,
sample_rate: int = 24000,
n_fft: int = 1024,
hop_size: int = 256,
win_size: int = 1024,
n_mels: int = 100,
fmin: float = 0.0,
fmax: float | None = None,
) -> None:
super().__init__()
self.sample_rate = int(sample_rate)
self.n_fft = int(n_fft)
self.hop_size = int(hop_size)
self.win_size = int(win_size)
self.n_mels = int(n_mels)
self.fmin = float(fmin)
self.fmax = fmax
mel_np = librosa_mel_fn(
sr=self.sample_rate,
n_fft=self.n_fft,
n_mels=self.n_mels,
fmin=self.fmin,
fmax=self.fmax,
)
self.register_buffer("mel_basis", torch.from_numpy(mel_np).float(), persistent=False)
self.register_buffer("hann_window", torch.hann_window(self.win_size).float(), persistent=False)
def forward(self, wave: torch.Tensor) -> torch.Tensor:
"""Compute BigVGAN Slaney log-mel ``[B, T, 100]`` from 24 kHz waveform ``[B, T*256]`` (or ``[T*256]``)."""
w = wave.float()
if w.dim() == 1:
w = w.unsqueeze(0)
pad = (self.n_fft - self.hop_size) // 2
if w.shape[-1] <= pad:
w = F.pad(w.unsqueeze(1), (pad, pad), mode="constant").squeeze(1)
else:
w = F.pad(w.unsqueeze(1), (pad, pad), mode="reflect").squeeze(1)
spec = torch.stft(
w,
self.n_fft,
hop_length=self.hop_size,
win_length=self.win_size,
window=self.hann_window,
center=False,
pad_mode="reflect",
normalized=False,
onesided=True,
return_complex=True,
)
mag = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9)
mel = torch.matmul(self.mel_basis, mag)
log_mel = torch.log(torch.clamp(mel, min=1e-5))
return log_mel.transpose(1, 2).contiguous()
class BigVGANVocoderWrapper(nn.Module):
"""Thin inference wrapper over MIT NVIDIA BigVGAN-v2 / BigVGAN-base 24 kHz 100-band."""
def __init__(
self,
model_id: str = "nvidia/bigvgan_v2_24khz_100band_256x",
ckpt_path: Path | None = None,
device: str = "cuda",
use_cuda_kernel: bool = False,
) -> None:
super().__init__()
_ensure_bigvgan_importable()
import bigvgan
from env import AttrDict
if ckpt_path is not None:
ck = torch.load(ckpt_path, map_location="cpu", weights_only=True)
self.model_id = str(ck.get("model_id", model_id))
if "h" in ck:
model = bigvgan.BigVGAN(AttrDict(ck["h"]), use_cuda_kernel=use_cuda_kernel)
else:
model = bigvgan.BigVGAN.from_pretrained(self.model_id, use_cuda_kernel=use_cuda_kernel)
if ck.get("weight_norm_removed", False):
model.remove_weight_norm()
model.load_state_dict(ck["state_dict"], strict=True)
else:
model.load_state_dict(ck["state_dict"], strict=True)
model.remove_weight_norm()
else:
self.model_id = str(model_id)
model = bigvgan.BigVGAN.from_pretrained(self.model_id, use_cuda_kernel=use_cuda_kernel)
model.remove_weight_norm()
self.net = model.eval().to(device)
for p in self.net.parameters():
p.requires_grad_(False)
self.hop_size = int(self.net.h.hop_size)
self.sample_rate = int(self.net.h.sampling_rate)
@torch.inference_mode()
def decode_raw_mel(self, phys_mel: torch.Tensor, lengths: torch.Tensor | None = None) -> torch.Tensor:
"""Synthesize 24 kHz waveform ``[B, T*hop]`` from physical log-mel ``[B, T, 100]``."""
mel_bct = phys_mel.float().transpose(1, 2).contiguous()
wav = self.net(mel_bct).squeeze(1)
if lengths is not None:
total = phys_mel.shape[1] * self.hop_size
if wav.shape[1] > total:
wav = wav[:, :total]
sample_mask = (torch.arange(wav.shape[1], device=wav.device)[None] < (lengths.to(wav.device)[:, None] * self.hop_size)).float()
wav = wav * sample_mask
return wav123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900"""LuaNovaCFM: PT-BR phonetic front end, ProsodyFlow, and OT-CFM Slaney-100 mel decoder."""
from __future__ import annotations
import math
import torch
from torch import nn
from torch.nn import functional as F
from ..config import CFMConfig, Config
from ..text.phonemizer import PHONE_IDS, PUNCTUATION, SYMBOL_TO_ID, VOICELESS, VOWELS
from .frontend import (
Predictor,
Stack,
UtteranceTooLong,
VocosHead,
length_mask,
rotary_table,
rotate,
)
_SP_ID = SYMBOL_TO_ID["<sp>"]
_COMMA_ID = SYMBOL_TO_ID[","]
_PERIOD_ID = SYMBOL_TO_ID["."]
_QUESTION_ID = SYMBOL_TO_ID["?"]
_EXCLAM_ID = SYMBOL_TO_ID["!"]
_SEMICOLON_ID = SYMBOL_TO_ID[";"]
_COLON_ID = SYMBOL_TO_ID[":"]
_DASH_ID = SYMBOL_TO_ID["—"]
_ELLIPSIS_ID = SYMBOL_TO_ID["…"]
_CLAUSE_PUNCT_IDS = tuple(SYMBOL_TO_ID[p] for p in (",", ";", ":", "—", "…", ".", "?", "!"))
class MelStatsHead(nn.Module):
"""Lightweight mel normalization statistics container for external vocoders such as BigVGAN."""
def __init__(self, c: Config) -> None:
super().__init__()
self.config = c
self.vocos = None
self.frozen = True
self.register_buffer("mel_mean", torch.zeros(c.vocos_n_mels, dtype=torch.float32))
self.register_buffer("mel_scale", torch.ones(c.vocos_n_mels, dtype=torch.float32))
def freeze_vocoder(self, frozen: bool = True) -> None:
self.frozen = frozen
def set_mel_stats(self, mean, scale) -> None:
mean_t = torch.as_tensor(mean, dtype=torch.float32, device=self.mel_mean.device)
scale_t = torch.as_tensor(scale, dtype=torch.float32, device=self.mel_scale.device).clamp_min(1e-6)
if mean_t.shape != (self.config.vocos_n_mels,) or scale_t.shape != (self.config.vocos_n_mels,):
raise ValueError("vocoder mel stats shape mismatch")
self.mel_mean.copy_(mean_t)
self.mel_scale.copy_(scale_t)
def decode_mel(self, mel_norm: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
raise RuntimeError("External BigVGAN vocoder wrapper is required to decode waveforms in BigVGAN mel space")
def make_prosody_noise_kernel(length: int = 25, sigma_wide: float = 5.0, sigma_narrow: float = 1.5) -> torch.Tensor:
"""Kernel 1D multiescala normalizado para variancia unitaria do ruido prosodico [2, 1, K]."""
half = length // 2
idx = torch.arange(length, dtype=torch.float32) - float(half)
g_wide = torch.exp(-0.5 * (idx / sigma_wide) ** 2)
g_wide = g_wide / g_wide.sum()
g_narrow = torch.exp(-0.5 * (idx / sigma_narrow) ** 2)
g_narrow = g_narrow / g_narrow.sum()
w = 0.65 * g_wide + 0.35 * g_narrow
w = w / torch.sqrt((w ** 2).sum()).clamp_min(1e-8)
return w[None, None, :].expand(2, 1, length).contiguous()
def smooth_prosody_noise(eps: torch.Tensor, frame_mask: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
"""Convolucao multiescala ONNX-safe em ruido gaussiano [B, T, 2] para eliminar micro-jitter de F0."""
pad = kernel.shape[-1] // 2
sm = F.conv1d(eps.float().transpose(1, 2), kernel.to(eps.device, dtype=torch.float32), padding=pad, groups=2)
return sm.transpose(1, 2) * frame_mask[..., None].float()
def linguistic_context_features(
tokens: torch.Tensor,
stress: torch.Tensor,
token_mask: torch.Tensor,
phone_tokens: torch.Tensor,
vowel_tokens: torch.Tensor,
voiceless_tokens: torch.Tensor,
clause_punct_tokens: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Extrai 26 canais de contexto palavra/tonica/clausula/frase + matriz same_word (100% ONNX opset 17)."""
mask_f = token_mask.float()
is_phone = (phone_tokens[tokens] & token_mask).float()
is_vowel = (vowel_tokens[tokens] & token_mask).float()
is_voiceless = (voiceless_tokens[tokens] & token_mask).float()
is_voiced_cons = is_phone * (1.0 - is_vowel) * (1.0 - is_voiceless)
is_sp = ((tokens == _SP_ID) & token_mask).float()
is_cb = (clause_punct_tokens[tokens] & token_mask).float()
l_dim = tokens.shape[1]
idx_f = torch.arange(l_dim, device=tokens.device, dtype=torch.float32)[None, :]
tri_le = (idx_f[:, :, None] >= idx_f[:, None, :]).float()
# 1..6: Utterance-level structure and punctuation indicators
utt_len = mask_f.sum(dim=1, keepdim=True).clamp_min(1.0)
utt_pos = ((idx_f + 0.5) / utt_len) * mask_f
utt_rem = ((utt_len - 1.0 - idx_f).clamp_min(0.0) / utt_len) * mask_f
utt_log_len = (torch.log1p(utt_len) / 6.0) * mask_f
utt_has_q = ((tokens == _QUESTION_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f
utt_has_ex = ((tokens == _EXCLAM_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f
utt_has_comma = ((tokens == _COMMA_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f
# 7..13: Word-level & lexical stress geometry
is_delim = (1.0 - is_phone) * mask_f
word_id = is_delim.long().cumsum(dim=1)
same_word = (word_id[:, :, None] == word_id[:, None, :]).float() * (is_phone[:, :, None] * is_phone[:, None, :])
word_phones = same_word.sum(dim=-1)
word_log_phones = (torch.log1p(word_phones) / 4.0) * is_phone
word_vowels = (same_word * is_vowel[:, None, :]).sum(dim=-1)
word_log_vowels = (torch.log1p(word_vowels) / 3.0) * is_phone
is_prim_stress = ((stress == 1) & token_mask).float() * is_phone
stress_weights = same_word * is_prim_stress[:, None, :]
stress_sum = stress_weights.sum(dim=-1)
word_has_stress = stress_sum.clamp(0.0, 1.0) * is_phone
pos_in_word = (((same_word * tri_le).sum(dim=-1) - 0.5).clamp_min(0.0) / word_phones.clamp_min(1.0)) * is_phone
stress_idx = (stress_weights * idx_f[None, ...]).sum(dim=-1) / stress_sum.clamp_min(1.0)
dist_to_stress = ((idx_f - stress_idx) / 6.0).clamp(-2.0, 2.0) * word_has_stress
prev_phone = torch.cat((torch.zeros_like(is_phone[:, :1]), is_phone[:, :-1]), dim=1)
word_start = is_phone * (1.0 - prev_phone)
total_words = word_start.sum(dim=1, keepdim=True).clamp_min(1.0)
cum_words = word_start.cumsum(dim=1)
word_pos_utt = ((cum_words - 0.5).clamp_min(0.0) / total_words) * is_phone
log_total_words = (torch.log1p(total_words) / 4.0) * mask_f
# 14..21: Clause-level structure (segmented at , ; : — … . ? !)
cb_prev = torch.cat((torch.zeros_like(is_cb[:, :1]), is_cb[:, :-1]), dim=1)
clause_id = cb_prev.long().cumsum(dim=1)
same_clause = (clause_id[:, :, None] == clause_id[:, None, :]).float() * (mask_f[:, :, None] * mask_f[:, None, :])
clause_len = same_clause.sum(dim=-1).clamp_min(1.0)
clause_log_len = (torch.log1p(clause_len) / 5.0) * mask_f
pos_in_clause_raw = (same_clause * tri_le).sum(dim=-1)
pos_in_clause = ((pos_in_clause_raw - 0.5).clamp_min(0.0) / clause_len) * mask_f
clause_rem = ((clause_len - pos_in_clause_raw).clamp_min(0.0) / clause_len) * mask_f
q_tok = ((tokens == _QUESTION_ID) & token_mask).float()
ex_tok = ((tokens == _EXCLAM_ID) & token_mask).float()
comma_tok = ((tokens == _COMMA_ID) & token_mask).float()
period_tok = ((tokens == _PERIOD_ID) & token_mask).float()
other_cb_tok = (
((tokens == _SEMICOLON_ID) | (tokens == _COLON_ID) | (tokens == _DASH_ID) | (tokens == _ELLIPSIS_ID))
& token_mask
).float()
clause_ends_q = (same_clause * q_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
clause_ends_ex = (same_clause * ex_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
clause_ends_comma = (same_clause * comma_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
clause_ends_period = (same_clause * period_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
clause_ends_other = (same_clause * other_cb_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
ling_feats = torch.stack(
(
utt_pos, utt_rem, utt_log_len, utt_has_q, utt_has_ex, utt_has_comma,
word_log_phones, word_log_vowels, word_has_stress, pos_in_word, dist_to_stress, word_pos_utt, log_total_words,
clause_log_len, pos_in_clause, clause_rem,
clause_ends_q, clause_ends_ex, clause_ends_comma, clause_ends_period, clause_ends_other,
is_vowel, is_voiced_cons, is_voiceless, is_sp, is_cb,
),
dim=-1,
) * mask_f[..., None]
clause_ctx_tok = torch.stack((pos_in_clause, clause_rem, clause_ends_q, clause_ends_comma), dim=-1) * mask_f[..., None]
return ling_feats, same_word, clause_ctx_tok
def energy_noise_gate(
condition: torch.Tensor,
frame_mask: torch.Tensor,
center: float = -1.6,
slope: float = 2.5,
floor: float = 0.05,
) -> torch.Tensor:
"""Porta suave por energia e vozeamento para zerar ruido inicial em pausas (ONNX opset 17)."""
eng = condition[..., 2].float()
voiced = condition[..., 1].float()
g = torch.sigmoid(slope * (eng - center))
g = torch.maximum(g, 0.85 * voiced)
g = floor + (1.0 - floor) * g
return g[..., None] * frame_mask[..., None].float()
def smooth_f0_channel(condition: torch.Tensor, prob: float) -> torch.Tensor:
"""Aplica filtro caixa 3-frames no canal F0 em uma fracao ``prob`` do batch."""
if prob <= 0.0 or condition.shape[1] < 2:
return condition
mask = (torch.rand(condition.shape[0], device=condition.device) < prob)[:, None]
if not bool(mask.any()):
return condition
f0 = condition[..., 0].float()
sm = F.avg_pool1d(F.pad(f0.unsqueeze(1), (1, 1), mode="replicate"), 3, stride=1).squeeze(1)
f0_out = torch.where(mask, sm.to(condition.dtype), condition[..., 0])
return torch.cat((f0_out[..., None], condition[..., 1:]), dim=-1)
def f0_features(condition: torch.Tensor, frame_mask: torch.Tensor) -> torch.Tensor:
"""Extrai 12 canais prosodicos/harmonicos explicitos de ``condition`` [B, T, 3] (100% ONNX opset 17)."""
c = condition.float()
log_f0 = c[..., 0]
voiced = c[..., 1]
energy = c[..., 2]
delta_f0 = F.pad(log_f0[:, 1:] - log_f0[:, :-1], (1, 0))
f0_norm = torch.exp(log_f0.clamp(-2.0, 1.5))
feats = [log_f0, delta_f0, voiced, energy]
for k in (1.0, 2.0, 3.0, 4.0):
ang = (2.0 * math.pi * k) * f0_norm
feats.append(voiced * torch.sin(ang))
feats.append(voiced * torch.cos(ang))
return torch.stack(feats, dim=-1) * frame_mask[..., None].float()
class SinusoidalTimeEmbedding(nn.Module):
def __init__(self, dim: int):
super().__init__()
self.dim = dim
self.mlp = nn.Sequential(
nn.Linear(dim, dim * 2),
nn.SiLU(),
nn.Linear(dim * 2, dim),
)
def forward(self, t: torch.Tensor) -> torch.Tensor:
half = self.dim // 2
freqs = torch.exp(
-math.log(10000.0) * torch.arange(half, device=t.device, dtype=torch.float32) / max(half - 1, 1)
)
args = t.float()[:, None] * freqs[None, :] * 1000.0
emb = torch.cat((args.sin(), args.cos()), dim=-1)
return self.mlp(emb)
class FlowAttention(nn.Module):
def __init__(self, channels: int, heads: int, dropout: float):
super().__init__()
self.heads = heads
self.dropout = dropout
self.qkv = nn.Linear(channels, 3 * channels)
self.out = nn.Linear(channels, channels)
def forward(self, x: torch.Tensor, mask: torch.Tensor, table: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
b, t, c = x.shape
q, k, v = self.qkv(x).view(b, t, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4)
y = F.scaled_dot_product_attention(
rotate(q, table),
rotate(k, table),
v,
attn_mask=mask[:, None, None, :],
dropout_p=self.dropout if self.training else 0.0,
)
return self.out(y.transpose(1, 2).reshape(b, t, c))
class FlowBlock(nn.Module):
"""Bloco Transformer RoPE + Conv depthwise com modulação AdaLN-Zero pelo tempo t."""
def __init__(self, channels: int, heads: int, feedforward: int, kernel: int, dropout: float):
super().__init__()
self.norm1 = nn.LayerNorm(channels, elementwise_affine=False)
self.attention = FlowAttention(channels, heads, dropout)
self.norm2 = nn.LayerNorm(channels, elementwise_affine=False)
self.depthwise = nn.Conv1d(channels, channels, kernel, padding=kernel // 2, groups=channels)
self.expand = nn.Linear(channels, feedforward)
self.project = nn.Linear(feedforward, channels)
self.dropout = nn.Dropout(dropout)
# 6 modulations: shift1, scale1, gate1, shift2, scale2, gate2
self.ada = nn.Sequential(nn.SiLU(), nn.Linear(channels, 6 * channels))
nn.init.zeros_(self.ada[1].weight)
nn.init.zeros_(self.ada[1].bias)
def forward(self, x: torch.Tensor, t_emb: torch.Tensor, mask: torch.Tensor, table) -> torch.Tensor:
keep = mask[..., None]
s1, sc1, g1, s2, sc2, g2 = self.ada(t_emb)[:, None, :].chunk(6, dim=-1)
h = self.norm1(x) * (1.0 + sc1) + s1
x = (x + g1 * self.dropout(self.attention(h, mask, table))) * keep
h2 = (self.norm2(x) * (1.0 + sc2) + s2) * keep
y = self.depthwise(h2.transpose(1, 2)).transpose(1, 2)
y = self.project(self.dropout(F.gelu(self.expand(y))))
return (x + g2 * self.dropout(y)) * keep
class FlowDecoder(nn.Module):
"""Preditor de velocidade v_theta(x_t, t | cond, prior_mel, f0_feats) no espaço mel-100 do Vocos."""
def __init__(self, cfg: CFMConfig):
super().__init__()
c = cfg.base
d = cfg.flow_channels
self.n_mels = c.vocos_n_mels
self.use_f0_harmonics = bool(cfg.use_f0_harmonics)
in_dim = self.n_mels * 2 + c.channels + (12 if self.use_f0_harmonics else 0)
self.time_emb = SinusoidalTimeEmbedding(d)
self.in_proj = nn.Linear(in_dim, d)
self.blocks = nn.ModuleList(
FlowBlock(d, cfg.flow_heads, cfg.flow_feedforward, cfg.flow_kernel, cfg.flow_dropout)
for _ in range(cfg.flow_layers)
)
self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
self.out_proj = nn.Linear(d, self.n_mels)
nn.init.zeros_(self.final_ada[1].weight)
nn.init.zeros_(self.final_ada[1].bias)
nn.init.zeros_(self.out_proj.weight)
nn.init.zeros_(self.out_proj.bias)
self.head_width = d // cfg.flow_heads
def forward(
self,
x_t: torch.Tensor,
t: torch.Tensor,
cond: torch.Tensor,
prior_mel: torch.Tensor,
frame_mask: torch.Tensor,
f0_feats: torch.Tensor | None = None,
) -> torch.Tensor:
keep = frame_mask[..., None]
t_emb = self.time_emb(t)
parts = (x_t, prior_mel, cond, f0_feats) if (self.use_f0_harmonics and f0_feats is not None) else (x_t, prior_mel, cond)
h = self.in_proj(torch.cat(parts, dim=-1)) * keep
table = rotary_table(x_t.shape[1], self.head_width, x_t.device)
for block in self.blocks:
h = block(h, t_emb, frame_mask, table)
shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
h = self.final_norm(h) * (1.0 + scale) + shift
return self.out_proj(h) * keep
class LinguisticContextAdapter(nn.Module):
"""Adaptador residual zero-inicializado para contexto de palavra, tonica e clausula."""
def __init__(self, c: Config, layers: int = 2, ling_dim: int = 26):
super().__init__()
self.ling_proj = nn.Linear(ling_dim, c.channels)
self.word_proj = nn.Linear(c.channels, c.channels)
self.stack = Stack(c, layers)
self.out_proj = nn.Linear(c.channels, c.channels)
nn.init.zeros_(self.out_proj.weight)
nn.init.zeros_(self.out_proj.bias)
def forward(
self,
hidden: torch.Tensor,
ling_feats: torch.Tensor,
same_word: torch.Tensor,
token_mask: torch.Tensor,
) -> torch.Tensor:
w = same_word.to(hidden.dtype)
w = w / w.sum(dim=-1, keepdim=True).clamp_min(1.0)
word_mean = torch.bmm(w, hidden)
x = (hidden + self.ling_proj(ling_feats.to(hidden.dtype)) + self.word_proj(word_mean)) * token_mask[..., None]
return (hidden + self.out_proj(self.stack(x, token_mask))) * token_mask[..., None]
class DurationFlow(nn.Module):
"""Preditor generativo OT-CFM para log1p(duracao) de fonemas e pausas."""
def __init__(self, cfg: CFMConfig):
super().__init__()
d = cfg.dur_flow_channels
in_dim = 2 + cfg.base.channels
self.time_emb = SinusoidalTimeEmbedding(d)
self.in_proj = nn.Linear(in_dim, d)
self.blocks = nn.ModuleList(
FlowBlock(d, cfg.dur_flow_heads, cfg.dur_flow_feedforward, cfg.dur_flow_kernel, 0.05)
for _ in range(cfg.dur_flow_layers)
)
self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
self.out_proj = nn.Linear(d, 1)
nn.init.zeros_(self.final_ada[1].weight)
nn.init.zeros_(self.final_ada[1].bias)
nn.init.zeros_(self.out_proj.weight)
nn.init.zeros_(self.out_proj.bias)
self.head_width = d // cfg.dur_flow_heads
def forward(
self,
z_t: torch.Tensor,
t: torch.Tensor,
prior_log_dur: torch.Tensor,
token_ctx: torch.Tensor,
token_mask: torch.Tensor,
) -> torch.Tensor:
keep = token_mask[..., None]
t_emb = self.time_emb(t)
h = self.in_proj(torch.cat((z_t.float(), prior_log_dur.float(), token_ctx.float()), dim=-1)) * keep
table = rotary_table(z_t.shape[1], self.head_width, z_t.device)
for block in self.blocks:
h = block(h, t_emb, token_mask, table)
shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
h = self.final_norm(h) * (1.0 + scale) + shift
return self.out_proj(h) * keep
class ProsodyFlow(nn.Module):
"""Preditor generativo OT-CFM para contorno [log_F0, energia] em nivel de frame."""
def __init__(self, cfg: CFMConfig):
super().__init__()
d = cfg.prosody_flow_channels
in_dim = 5 + cfg.base.channels
self.time_emb = SinusoidalTimeEmbedding(d)
self.in_proj = nn.Linear(in_dim, d)
self.blocks = nn.ModuleList(
FlowBlock(d, cfg.prosody_flow_heads, cfg.prosody_flow_feedforward, cfg.prosody_flow_kernel, 0.05)
for _ in range(cfg.prosody_flow_layers)
)
self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
self.out_proj = nn.Linear(d, 2)
nn.init.zeros_(self.final_ada[1].weight)
nn.init.zeros_(self.final_ada[1].bias)
nn.init.zeros_(self.out_proj.weight)
nn.init.zeros_(self.out_proj.bias)
self.head_width = d // cfg.prosody_flow_heads
def forward(
self,
y_t: torch.Tensor,
t: torch.Tensor,
prior_fe: torch.Tensor,
voicing_prob: torch.Tensor,
prosody_hidden: torch.Tensor,
frame_mask: torch.Tensor,
) -> torch.Tensor:
keep = frame_mask[..., None]
t_emb = self.time_emb(t)
h = self.in_proj(
torch.cat((y_t.float(), prior_fe.float(), voicing_prob.float(), prosody_hidden.float()), dim=-1)
) * keep
table = rotary_table(y_t.shape[1], self.head_width, y_t.device)
for block in self.blocks:
h = block(h, t_emb, frame_mask, table)
shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
h = self.final_norm(h) * (1.0 + scale) + shift
return self.out_proj(h) * keep
class LuaNovaCFM(nn.Module):
"""Front-end fonético CTC do LuaNovaBase + Prior Mel + FlowDecoder OT-CFM + Vocos 24 kHz."""
FRONTEND_MODULES = (
"tokens", "stress", "voices", "encoder", "duration",
"frame_voices", "frame_position", "prosody_stack", "prosody_head",
)
ITEM3_MODULES = ("context_adapter", "frame_ctx_proj", "dur_flow", "prosody_flow")
def __init__(self, cfg: CFMConfig, vocos_model=None, load_vocos: bool | None = None):
super().__init__()
self.cfm_config = cfg
self.config = c = cfg.base
# Front-end idêntico ao LuaNovaBase (carrega pesos direto do checkpoint Stage 1!)
self.tokens = nn.Embedding(c.vocab_size, c.channels, padding_idx=0)
self.stress = nn.Embedding(3, c.channels)
self.voices = nn.Embedding(len(c.speakers), c.channels)
self.encoder = Stack(c, c.encoder_layers)
self.duration = Predictor(c, 2)
self.frame_voices = nn.Embedding(len(c.speakers), c.channels)
self.frame_position = nn.Linear(3, c.channels)
self.prosody_stack = Stack(c, c.prosody_layers)
self.prosody_head = nn.Linear(c.channels, 3)
self.prosody_projection = nn.Linear(3, c.channels)
# Item 3 (opcionais para manter retrocompatibilidade v1/v2/v3)
self.context_adapter = LinguisticContextAdapter(c, layers=cfg.prosody_context_layers) if cfg.use_ling_context else None
if cfg.use_ling_context:
self.frame_ctx_proj = nn.Linear(6, c.channels)
nn.init.zeros_(self.frame_ctx_proj.weight)
nn.init.zeros_(self.frame_ctx_proj.bias)
else:
self.frame_ctx_proj = None
self.dur_flow = DurationFlow(cfg) if cfg.use_duration_flow else None
self.prosody_flow = ProsodyFlow(cfg) if cfg.use_prosody_flow else None
# Prior mel determinístico (5 camadas RoPE quando use_acoustic_prior=True) + Flow Matching decoder
self.acoustic_stack = Stack(c, c.acoustic_layers) if cfg.use_acoustic_prior else None
self.prior_head = nn.Linear(c.channels, c.vocos_n_mels)
self.flow = FlowDecoder(cfg)
use_vocos = (cfg.mel_space == "vocos") if load_vocos is None else bool(load_vocos)
self.vocoder = VocosHead(c, vocos_model=vocos_model) if (use_vocos or vocos_model is not None) else MelStatsHead(c)
self.vocoder.freeze_vocoder(True)
phones = torch.zeros(c.vocab_size, dtype=torch.bool)
phones[sorted(PHONE_IDS)] = True
self.register_buffer("phone_tokens", phones, persistent=False)
vowels = torch.zeros(c.vocab_size, dtype=torch.bool)
vowels[[SYMBOL_TO_ID[v] for v in VOWELS]] = True
self.register_buffer("vowel_tokens", vowels, persistent=False)
voiceless = torch.zeros(c.vocab_size, dtype=torch.bool)
voiceless[[SYMBOL_TO_ID[v] for v in VOICELESS]] = True
self.register_buffer("voiceless_tokens", voiceless, persistent=False)
puncts = torch.zeros(c.vocab_size, dtype=torch.bool)
puncts[[SYMBOL_TO_ID[p] for p in PUNCTUATION]] = True
self.register_buffer("punct_tokens", puncts, persistent=False)
clause_puncts = torch.zeros(c.vocab_size, dtype=torch.bool)
clause_puncts[list(_CLAUSE_PUNCT_IDS)] = True
self.register_buffer("clause_punct_tokens", clause_puncts, persistent=False)
self.register_buffer("prosody_noise_kernel", make_prosody_noise_kernel(), persistent=False)
self._frontend_frozen = False
def freeze_frontend(self, frozen: bool = True) -> None:
self._frontend_frozen = frozen
for name in self.FRONTEND_MODULES + self.ITEM3_MODULES:
mod = getattr(self, name)
if mod is None:
continue
for p in mod.parameters():
p.requires_grad_(not frozen)
if frozen:
mod.eval()
def train(self, mode: bool = True):
super().train(mode)
if self.vocoder.frozen and getattr(self.vocoder, "vocos", None) is not None:
self.vocoder.vocos.eval()
if self._frontend_frozen:
for name in self.FRONTEND_MODULES + self.ITEM3_MODULES:
mod = getattr(self, name)
if mod is not None:
mod.eval()
return self
def load_frontend(
self, state_dict: dict, prosody_state_dict: dict | None = None
) -> list[str]:
"""Carrega pesos do front-end (+ acoustic_stack/prior_head/Vocos se use_acoustic_prior) e prosodia refinada."""
loaded = []
own = self.state_dict()
prefix = "model." if any(k.startswith("model.encoder.") for k in state_dict) else ""
keep_prefixes = tuple(f"{m}." for m in self.FRONTEND_MODULES) + (
"prosody_projection.",
"vocoder.mel_mean",
"vocoder.mel_scale",
)
if self.acoustic_stack is not None:
keep_prefixes = keep_prefixes + ("acoustic_stack.",)
for k, v in state_dict.items():
if prefix and not k.startswith(prefix):
continue
key = k[len(prefix):] if prefix else k
if self.acoustic_stack is not None and key == "vocoder.proj.weight" and "prior_head.weight" in own:
if own["prior_head.weight"].shape == v.shape:
own["prior_head.weight"] = v
loaded.append("prior_head.weight")
continue
if self.acoustic_stack is not None and key == "vocoder.proj.bias" and "prior_head.bias" in own:
if own["prior_head.bias"].shape == v.shape:
own["prior_head.bias"] = v
loaded.append("prior_head.bias")
continue
if any(key == p or key.startswith(p) for p in keep_prefixes) and key in own and own[key].shape == v.shape:
own[key] = v
loaded.append(key)
if prosody_state_dict is not None:
ppref = "model." if any(k.startswith("model.prosody_stack.") for k in prosody_state_dict) else ""
for k, v in prosody_state_dict.items():
if ppref and not k.startswith(ppref):
continue
key = k[len(ppref):] if ppref else k
if key.startswith(("prosody_stack.", "prosody_head.")) and key in own and own[key].shape == v.shape:
own[key] = v
if key not in loaded:
loaded.append(key)
self.load_state_dict(own, strict=True)
return loaded
def encode(self, tokens, stress, lengths, speakers):
mask = length_mask(lengths, tokens.shape[1])
x = (self.tokens(tokens) + self.stress(stress) + self.voices(speakers)[:, None]) * mask[..., None]
return self.encoder(x, mask), mask
def encode_prosody_context(
self,
hidden: torch.Tensor,
tokens: torch.Tensor,
stress: torch.Tensor,
token_mask: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if self.context_adapter is None:
return hidden, None
ling_feats, same_word, clause_ctx_tok = linguistic_context_features(
tokens,
stress,
token_mask,
self.phone_tokens,
self.vowel_tokens,
self.voiceless_tokens,
self.clause_punct_tokens,
)
prosody_token_ctx = self.context_adapter(hidden, ling_feats, same_word, token_mask)
return prosody_token_ctx, clause_ctx_tok
def _expand_indices(self, durations: torch.Tensor):
lengths = durations.sum(1)
if bool((lengths < 1).any()):
raise ValueError("utterance has no frames")
if bool((lengths > self.config.max_frames).any()):
raise UtteranceTooLong("utterance exceeds max_frames; split the input")
size = int(lengths.max())
ends = durations.cumsum(1)
frame = torch.arange(size, device=durations.device)[None].expand(durations.shape[0], size).contiguous()
index = torch.searchsorted(ends, frame, right=True).clamp(max=durations.shape[1] - 1)
owned = durations.gather(1, index).clamp_min(1)
offset = frame - (ends.gather(1, index) - durations.gather(1, index))
relative = (offset.float() + 0.5) / owned.float()
features = torch.stack((relative, 1.0 - relative, torch.log1p(owned.float()) / 4.0), dim=-1)
mask = frame < lengths[:, None]
return frame, index, features, mask, lengths
def expand(self, hidden, durations, token_mask, speakers):
_frame, index, features, mask, lengths = self._expand_indices(durations)
expanded = hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1]))
expanded = expanded + self.frame_position(features.to(hidden.dtype)) + self.frame_voices(speakers)[:, None]
return expanded * mask[..., None], mask, lengths
def expand_with_context(
self,
hidden: torch.Tensor,
prosody_token_ctx: torch.Tensor,
clause_ctx_tok: torch.Tensor | None,
durations: torch.Tensor,
token_mask: torch.Tensor,
speakers: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
frame, index, features, mask, lengths = self._expand_indices(durations)
pos_voice = self.frame_position(features.to(hidden.dtype)) + self.frame_voices(speakers)[:, None]
acoustic_frames = (hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1])) + pos_voice) * mask[..., None]
if self.context_adapter is None and self.frame_ctx_proj is None:
return acoustic_frames, acoustic_frames, mask, lengths
prosody_frames = prosody_token_ctx.gather(1, index[..., None].expand(-1, -1, prosody_token_ctx.shape[-1])) + pos_voice
if self.frame_ctx_proj is not None:
if clause_ctx_tok is None:
raise ValueError("clause_ctx_tok required when frame_ctx_proj is enabled")
f_pos = (frame.float() + 0.5) / lengths.clamp_min(1).float()[:, None]
f_rem = 1.0 - f_pos
c_f = clause_ctx_tok.gather(1, index[..., None].expand(-1, -1, 4))
ctx_6 = torch.cat((f_pos[..., None], f_rem[..., None], c_f.float()), dim=-1) * mask[..., None].float()
prosody_frames = prosody_frames + self.frame_ctx_proj(ctx_6.to(prosody_frames.dtype))
return acoustic_frames, prosody_frames * mask[..., None], mask, lengths
def predict_prosody(self, frames, frame_mask):
hidden = self.prosody_stack(frames, frame_mask)
return hidden, self.prosody_head(hidden) * frame_mask[..., None]
@staticmethod
def hard_prosody(prediction):
return torch.stack(
(prediction[..., 0].clamp(-2.0, 1.5), (prediction[..., 1] > 0).to(prediction.dtype), prediction[..., 2].clamp(-4.5, 3.0)),
dim=-1,
)
def predict_durations(self, hidden, mask, tokens, speed=1.0):
output = self.duration(hidden, mask).float()
frames = torch.round((torch.exp(output[..., 0].clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
present = self.phone_tokens[tokens] | (output[..., 1] > 0)
return torch.where(present, frames, torch.zeros_like(frames)) * mask
def sample_durations(
self,
prosody_token_ctx: torch.Tensor,
token_mask: torch.Tensor,
tokens: torch.Tensor,
speed: float = 1.0,
seed: int = 0,
temperature: float | None = None,
steps: int | None = None,
noise: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
raw = self.duration(prosody_token_ctx, token_mask).float()
prior_z = raw[..., 0].clamp(0.0, math.log1p(400.0))
if self.dur_flow is not None:
n_steps = int(self.cfm_config.dur_flow_steps if steps is None else steps)
temp = float(self.cfm_config.dur_flow_temp if temperature is None else temperature)
b, l_len, _ = prosody_token_ctx.shape
if noise is None:
gen = torch.Generator(device=prosody_token_ctx.device).manual_seed(int(seed) + 101)
eps = torch.randn((b, l_len, 1), generator=gen, device=prosody_token_ctx.device, dtype=torch.float32)
else:
eps = noise.float()
sigma = self.cfm_config.dur_flow_sigma * temp
z = (prior_z[..., None] + sigma * eps) * token_mask[..., None].float()
dt = 1.0 / max(n_steps, 1)
for i in range(n_steps):
t_vec = torch.full((b,), i * dt, device=z.device, dtype=torch.float32)
v = self.dur_flow(z, t_vec, prior_z[..., None], prosody_token_ctx, token_mask)
z = (z + dt * v) * token_mask[..., None].float()
z1 = z.squeeze(-1)
else:
z1 = prior_z
frames = torch.round((torch.exp(z1.clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
present = self.phone_tokens[tokens] | (raw[..., 1] > 0)
durations = torch.where(present, frames, torch.zeros_like(frames)) * token_mask
return durations, raw
def sample_prosody(
self,
prosody_frames: torch.Tensor,
frame_mask: torch.Tensor,
seed: int = 0,
temperature: float | None = None,
steps: int | None = None,
noise: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
prosody_hidden, prior_raw = self.predict_prosody(prosody_frames, frame_mask)
if self.prosody_flow is None:
return prosody_hidden, prior_raw, prior_raw
n_steps = int(self.cfm_config.prosody_flow_steps if steps is None else steps)
temp = float(self.cfm_config.prosody_flow_temp if temperature is None else temperature)
b, t_len, _ = prosody_frames.shape
if noise is None:
gen = torch.Generator(device=prosody_frames.device).manual_seed(int(seed) + 202)
eps = torch.randn((b, t_len, 2), generator=gen, device=prosody_frames.device, dtype=torch.float32)
else:
eps = noise.float()
eps_sm = smooth_prosody_noise(eps, frame_mask, self.prosody_noise_kernel)
prior_fe = torch.stack((prior_raw[..., 0].float(), prior_raw[..., 2].float()), dim=-1)
voicing_prob = torch.sigmoid(prior_raw[..., 1:2].float())
sigma = self.cfm_config.prosody_flow_sigma * temp
y = (prior_fe + sigma * eps_sm) * frame_mask[..., None].float()
dt = 1.0 / max(n_steps, 1)
for i in range(n_steps):
t_vec = torch.full((b,), i * dt, device=y.device, dtype=torch.float32)
v = self.prosody_flow(y, t_vec, prior_fe, voicing_prob, prosody_hidden, frame_mask)
y = (y + dt * v) * frame_mask[..., None].float()
prosody = torch.cat((y[..., :1], prior_raw[..., 1:2].float(), y[..., 1:2]), dim=-1) * frame_mask[..., None].float()
return prosody_hidden, prosody, prior_raw
def condition_and_prior(self, prosody_hidden, condition, frame_mask):
ph = prosody_hidden
if (
not self.cfm_config.acoustic_from_frames
and self.acoustic_stack is not None
and self.training
and self.cfm_config.prosody_hidden_dropout > 0
):
ph = F.dropout1d(ph.transpose(1, 2), p=self.cfm_config.prosody_hidden_dropout, training=True).transpose(1, 2)
proj = (ph + self.prosody_projection(condition.to(ph.dtype))) * frame_mask[..., None]
cond = self.acoustic_stack(proj, frame_mask) if self.acoustic_stack is not None else proj
prior_mel = self.prior_head(cond.float()) * frame_mask[..., None]
return cond, prior_mel
@staticmethod
def widen_pitch(prosody, frame_mask, pitch_range):
if pitch_range == 1.0:
return prosody
voiced = ((prosody[..., 1] > 0) & frame_mask).to(prosody.dtype)
mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1)
pitch = mean + (prosody[..., 0] - mean) * pitch_range
return torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
@staticmethod
def sway_time_grid(n_steps: int, sway_coef: float = 0.0) -> list[float]:
"""Return monotone ODE time schedule in [0, 1]; uniform when ``sway_coef == 0.0``."""
if sway_coef == 0.0:
return [i / n_steps for i in range(n_steps + 1)]
s = max(-1.0, min(1.0, float(sway_coef)))
return [u + s * (math.cos(0.5 * math.pi * u) - 1.0 + u) for u in (i / n_steps for i in range(n_steps + 1))]
def sample_mel(
self,
cond: torch.Tensor,
prior_mel: torch.Tensor,
frame_mask: torch.Tensor,
n_steps: int = 8,
cfg_scale: float = 1.2,
temperature: float = 0.85,
solver: str = "midpoint",
seed: int = 0,
f0_feats: torch.Tensor | None = None,
noise_gate: torch.Tensor | None = None,
sway_coef: float = 0.0,
) -> torch.Tensor:
"""Integra o campo de velocidade OT-CFM em ``n_steps`` passos (Euler ou Midpoint)."""
b, t_len, m = prior_mel.shape
gen = torch.Generator(device=prior_mel.device).manual_seed(int(seed))
sigma = self.cfm_config.prior_sigma * temperature
eps = torch.randn((b, t_len, m), generator=gen, device=prior_mel.device, dtype=torch.float32)
noise = sigma * eps if noise_gate is None else sigma * noise_gate * eps
x = (prior_mel + noise) * frame_mask[..., None]
zero_cond = torch.zeros_like(cond)
zero_prior = torch.zeros_like(prior_mel)
zero_f0 = torch.zeros_like(f0_feats) if f0_feats is not None else None
def velocity(x_cur: torch.Tensor, t_val: float) -> torch.Tensor:
t_vec = torch.full((b,), t_val, device=x_cur.device, dtype=torch.float32)
v_c = self.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
if cfg_scale == 1.0:
return v_c
v_u = self.flow(x_cur, t_vec, zero_cond, zero_prior, frame_mask, f0_feats=zero_f0)
return v_u + cfg_scale * (v_c - v_u)
if sway_coef == 0.0:
dt = 1.0 / n_steps
steps = [(i * dt, dt) for i in range(n_steps)]
else:
t_grid = self.sway_time_grid(n_steps, sway_coef)
steps = [(t_grid[i], t_grid[i + 1] - t_grid[i]) for i in range(n_steps)]
for t0, dt_i in steps:
if solver == "midpoint":
v0 = velocity(x, t0)
x_mid = (x + 0.5 * dt_i * v0) * frame_mask[..., None]
v_mid = velocity(x_mid, t0 + 0.5 * dt_i)
x = (x + dt_i * v_mid) * frame_mask[..., None]
else:
v0 = velocity(x, t0)
x = (x + dt_i * v0) * frame_mask[..., None]
return x
@torch.inference_mode()
def predict_physical_mel(
self,
tokens,
stress,
lengths,
speakers,
speed: float = 1.0,
pitch_shift: float = 0.0,
seed: int = 0,
pitch_range: float | None = None,
n_steps: int = 8,
cfg_scale: float = 1.0,
temperature: float = 0.35,
solver: str = "midpoint",
sway_coef: float = 0.0,
voiced_vowels: bool = True,
dur_steps: int | None = None,
dur_temp: float | None = None,
prosody_steps: int | None = None,
prosody_temp: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor, dict]:
"""Predict unnormalized physical log-mel ``[B, T, 100]``, ``frame_lengths``, and details."""
pr = self.cfm_config.default_pitch_range if pitch_range is None else float(pitch_range)
hidden, mask = self.encode(tokens, stress, lengths, speakers)
prosody_token_ctx, clause_ctx_tok = self.encode_prosody_context(hidden, tokens, stress, mask)
durations, _ = self.sample_durations(
prosody_token_ctx, mask, tokens, speed=speed, seed=seed, temperature=dur_temp, steps=dur_steps
)
acoustic_frames, prosody_frames, frame_mask, frame_lengths = self.expand_with_context(
hidden, prosody_token_ctx, clause_ctx_tok, durations, mask, speakers
)
prosody_hidden, prosody, _ = self.sample_prosody(
prosody_frames, frame_mask, seed=seed, temperature=prosody_temp, steps=prosody_steps
)
if voiced_vowels:
ends = durations.cumsum(1)
frame = torch.arange(prosody_frames.shape[1], device=tokens.device)[None].expand(len(lengths), -1).contiguous()
index = torch.searchsorted(ends, frame, right=True).clamp(max=tokens.shape[1] - 1)
is_vowel = self.vowel_tokens[tokens.gather(1, index)] & frame_mask
prosody = torch.cat((prosody[..., :1], torch.where(is_vowel, prosody[..., 1].clamp_min(1.0), prosody[..., 1])[..., None], prosody[..., 2:]), dim=-1)
prosody = self.widen_pitch(prosody, frame_mask, pr)
if pitch_shift != 0.0:
prosody = torch.cat((prosody[..., :1] + pitch_shift, prosody[..., 1:]), dim=-1) * frame_mask[..., None]
hard_p = self.hard_prosody(prosody)
base_h = acoustic_frames if self.cfm_config.acoustic_from_frames else prosody_hidden
cond, prior_mel = self.condition_and_prior(base_h, hard_p, frame_mask)
f0_feats = f0_features(hard_p, frame_mask) if self.cfm_config.use_f0_harmonics else None
noise_gate = energy_noise_gate(hard_p, frame_mask) if self.cfm_config.use_energy_gate else None
mel_norm = self.sample_mel(
cond, prior_mel, frame_mask, n_steps=n_steps, cfg_scale=cfg_scale,
temperature=temperature, solver=solver, seed=seed, f0_feats=f0_feats,
noise_gate=noise_gate, sway_coef=sway_coef,
)
phys_mel = (mel_norm * self.vocoder.mel_scale + self.vocoder.mel_mean).clamp(min=-11.512925)
return phys_mel, frame_lengths, {"durations": durations, "prosody": prosody, "mel_norm": mel_norm}
@torch.inference_mode()
def synthesize(
self,
tokens,
stress,
lengths,
speakers,
speed: float = 1.0,
pitch_shift: float = 0.0,
seed: int = 0,
pitch_range: float | None = None,
n_steps: int = 8,
cfg_scale: float = 1.2,
temperature: float = 0.85,
solver: str = "midpoint",
sway_coef: float = 0.0,
voiced_vowels: bool = True,
dur_steps: int | None = None,
dur_temp: float | None = None,
prosody_steps: int | None = None,
prosody_temp: float | None = None,
):
_, frame_lengths, details = self.predict_physical_mel(
tokens, stress, lengths, speakers,
speed=speed, pitch_shift=pitch_shift, seed=seed, pitch_range=pitch_range,
n_steps=n_steps, cfg_scale=cfg_scale, temperature=temperature, solver=solver,
sway_coef=sway_coef, voiced_vowels=voiced_vowels,
dur_steps=dur_steps, dur_temp=dur_temp, prosody_steps=prosody_steps, prosody_temp=prosody_temp,
)
audio = self.vocoder.decode_mel(details["mel_norm"], frame_lengths)
return audio, frame_lengths * self.config.hop, details123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474"""Lua Nova V1: feed-forward transformer with a pitch-driven source-filter head.
All weights start random. Tensor conventions: hidden [B,T,C], frame features
[B,T], waveform [B,S]. Acoustic frame i is centred on sample ``i * hop``.
phoneme + stress + voice -> transformer encoder -> duration predictor
-> repeat tokens by duration (supervised durations while training)
-> frame transformer A -> pitch / voicing / energy
-> frame transformer B -> filter parameters
-> harmonic pulse train (from pitch) and noise, each shaped by its
time-varying filter in the STFT domain -> 24 kHz waveform
The waveform head has no neural upsampling network. The oscillator supplies the
periodicity that a tiny decoder cannot render reliably on its own; the network
only has to predict slowly varying spectral envelopes (complex cepstra), which
is what keeps the voice from sounding buzzy or unstable at this size.
"""
import math
import os
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
from ..config import Config
from ..text.phonemizer import PHONE_IDS, SYMBOL_TO_ID, VOWELS
class UtteranceTooLong(ValueError):
"""The utterance needs more frames than ``max_frames``: split the input."""
def length_mask(lengths, size=None):
size = int(lengths.max()) if size is None else size
return torch.arange(size, device=lengths.device)[None, :] < lengths[:, None]
def rotary_table(size, width, device):
inverse = 1.0 / (10000 ** (torch.arange(0, width, 2, device=device, dtype=torch.float32) / width))
angle = torch.arange(size, device=device, dtype=torch.float32)[:, None] * inverse[None]
return angle.cos(), angle.sin()
def rotate(x, table):
cos, sin = table[0].to(x.dtype), table[1].to(x.dtype)
a, b = x[..., 0::2], x[..., 1::2]
return torch.stack((a * cos - b * sin, a * sin + b * cos), dim=-1).flatten(-2)
class Attention(nn.Module):
"""Self-attention with rotary (relative) positions: no absolute position
table, so utterances longer than those seen in training stay in range."""
def __init__(self, channels, heads, dropout):
super().__init__()
self.heads, self.dropout = heads, dropout
self.qkv = nn.Linear(channels, 3 * channels)
self.out = nn.Linear(channels, channels)
def forward(self, x, mask, table):
b, t, c = x.shape
q, k, v = self.qkv(x).view(b, t, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4)
y = F.scaled_dot_product_attention(rotate(q, table), rotate(k, table), v, attn_mask=mask[:, None, None, :],
dropout_p=self.dropout if self.training else 0.0)
return self.out(y.transpose(1, 2).reshape(b, t, c))
class Block(nn.Module):
def __init__(self, c):
super().__init__()
self.norm1 = nn.LayerNorm(c.channels)
self.attention = Attention(c.channels, c.heads, c.dropout)
self.norm2 = nn.LayerNorm(c.channels)
self.depthwise = nn.Conv1d(c.channels, c.channels, c.kernel, padding=c.kernel // 2, groups=c.channels)
self.expand = nn.Linear(c.channels, c.feedforward)
self.project = nn.Linear(c.feedforward, c.channels)
self.dropout = nn.Dropout(c.dropout)
def forward(self, x, mask, table):
keep = mask[..., None]
x = (x + self.dropout(self.attention(self.norm1(x), mask, table))) * keep
# Mask before the convolution so padded positions cannot leak back in.
y = self.depthwise((self.norm2(x) * keep).transpose(1, 2)).transpose(1, 2)
y = self.project(self.dropout(F.gelu(self.expand(y))))
return (x + self.dropout(y)) * keep
class Stack(nn.Module):
def __init__(self, c, layers):
super().__init__()
self.blocks = nn.ModuleList(Block(c) for _ in range(layers))
self.norm = nn.LayerNorm(c.channels)
self.width = c.channels // c.heads
def forward(self, x, mask):
table = rotary_table(x.shape[1], self.width, x.device)
for block in self.blocks:
x = block(x, mask, table)
return self.norm(x) * mask[..., None]
class Predictor(nn.Module):
def __init__(self, c, outputs):
super().__init__()
p = c.predictor_channels
self.conv1 = nn.Conv1d(c.channels, p, 3, padding=1)
self.conv2 = nn.Conv1d(p, p, 3, padding=1)
self.norm1, self.norm2 = nn.LayerNorm(p), nn.LayerNorm(p)
self.drop = nn.Dropout(c.dropout)
self.out = nn.Linear(p, outputs)
def forward(self, x, mask):
x = self.conv1((x * mask[..., None]).transpose(1, 2)).transpose(1, 2)
x = self.drop(self.norm1(F.gelu(x))) * mask[..., None]
x = self.conv2(x.transpose(1, 2)).transpose(1, 2)
x = self.drop(self.norm2(F.gelu(x)))
return self.out(x) * mask[..., None]
def pulse_train(f0, sample_rate, hop, limit=0.47, phase=None):
"""Band-limited pulse train [B, T*hop] with unit power for f0 [B, T] in Hz.
Frame values sit at samples i*hop and are interpolated in the log domain.
The sum of all harmonics below ``limit * sample_rate`` has the closed form
sin((K+1/2)x) / (2 sin(x/2)) - 1/2; the top harmonic fades in and out so the
signal stays continuous while the pitch glides. Float64 keeps the phase exact.
"""
frames = f0.shape[1]
knots = torch.log(f0.double().clamp_min(1.0))
knots = torch.cat((knots, knots[:, -1:]), dim=1)
position = torch.arange(frames * hop, device=f0.device, dtype=torch.float64) / hop
low = position.floor().long()
weight = position - low
frequency = torch.exp(knots[:, low] * (1 - weight) + knots[:, low + 1] * weight)
theta = 2 * math.pi * torch.cumsum(frequency / sample_rate, dim=1)
if phase is not None:
theta = theta + phase.double()[:, None]
theta = torch.remainder(theta, 2 * math.pi)
harmonics = (limit * sample_rate / frequency).clamp_min(1.0)
whole = torch.floor(harmonics)
denominator = 2 * torch.sin(theta / 2)
tiny = denominator.abs() < 1e-7
core = torch.where(tiny, whole, torch.sin((whole + 0.5) * theta) / torch.where(tiny, torch.ones_like(denominator), denominator) - 0.5)
wave = core + (harmonics - whole) * torch.cos((whole + 1) * theta)
return (wave * torch.sqrt(2.0 / harmonics)).float()
def filtered(source, response, fft, hop, window):
"""Time-varying filtering: response [B, frames, bins] multiplies the STFT."""
spectrum = torch.stft(source, fft, hop, window=window, center=True, pad_mode="constant", return_complex=True)
if spectrum.shape[-1] != response.shape[1]:
raise ValueError("filter frames do not match the source")
return torch.istft(spectrum * response.transpose(1, 2), fft, hop, window=window, center=True, length=source.shape[-1])
def cepstrum_response(causal, anticausal, fft):
"""Complex frequency response exp(FFT(cepstrum)). Causal coefficients give a
minimum-phase filter; anticausal ones add a maximum-phase part (glottal pulse)."""
buffer = causal.new_zeros(*causal.shape[:-1], fft)
buffer[..., :causal.shape[-1]] = causal
if anticausal is not None:
buffer[..., fft - anticausal.shape[-1]:] = anticausal.flip(-1)
spectrum = torch.fft.rfft(buffer, dim=-1)
return torch.polar(torch.exp(spectrum.real.clamp(-14, 6)), spectrum.imag)
class SourceFilter(nn.Module):
"""Harmonic-plus-noise synthesis controlled per frame by two linear heads."""
def __init__(self, c):
super().__init__()
self.config = c
self.harmonic_steps, self.noise_steps = c.hop // c.synth_hop, c.hop // c.noise_hop
self.harmonic = nn.Linear(c.channels, c.cep_causal + c.cep_anti + self.harmonic_steps)
self.noise = nn.Linear(c.channels, c.noise_cep + self.noise_steps)
for head, level in ((self.harmonic, -1.5), (self.noise, -2.5)): # start quiet and spectrally flat
nn.init.zeros_(head.weight)
nn.init.zeros_(head.bias)
head.bias.data[0] = level
def lifter(size, first):
scale = 1.0 / (1.0 + torch.arange(first, first + size, dtype=torch.float32) / 4)
if first == 0:
scale[0] = 2.0 # coefficient 0 is the log gain and needs range
return scale
self.register_buffer("causal_lifter", lifter(c.cep_causal, 0), persistent=False)
self.register_buffer("anti_lifter", lifter(c.cep_anti, 1), persistent=False)
self.register_buffer("noise_lifter", lifter(c.noise_cep, 0), persistent=False)
self.register_buffer("synth_window", torch.hann_window(c.synth_fft), persistent=False)
self.register_buffer("noise_window", torch.hann_window(c.noise_fft), persistent=False)
@staticmethod
def _take(values, index):
return values.gather(1, index[..., None].expand(-1, -1, values.shape[-1]))
def _subframes(self, frames, lengths, steps):
"""Sub-frame j uses frame j // steps; indices past an utterance's end
repeat its last sub-frame so padding never changes real audio. Two extra
sub-frames cover the half window of zeros appended to the source."""
sub = torch.arange(steps * frames + 3, device=lengths.device)[None].expand(len(lengths), -1)
return torch.minimum(sub, (steps * lengths - 1).clamp_min(0)[:, None])
@staticmethod
def _shape(source, response, fft, hop, window):
# Half a window of trailing zeros: the frames around an utterance's end are
# then the same whether it stands alone or is padded inside a batch.
return filtered(F.pad(source, (0, fft // 2)), response, fft, hop, window)[:, :source.shape[-1]]
def forward(self, hidden, f0, lengths, noise=None, phase=None):
c = self.config
frames = hidden.shape[1]
samples = frames * c.hop
with torch.autocast(device_type=hidden.device.type, enabled=False):
hidden = hidden.float()
audible = length_mask(lengths * c.hop, samples)
last = (lengths - 1).clamp_min(0)[:, None]
# Harmonic branch: envelope interpolated between frames, one gain per sub-frame.
h = self.harmonic(hidden)
split = c.cep_causal + c.cep_anti
sub = self._subframes(frames, lengths, self.harmonic_steps)
here, following = sub // self.harmonic_steps, torch.minimum((sub + 1) // self.harmonic_steps, last)
causal = 0.5 * (self._take(h[..., :c.cep_causal], here) + self._take(h[..., :c.cep_causal], following)) * self.causal_lifter
anti = 0.5 * (self._take(h[..., c.cep_causal:split], here) + self._take(h[..., c.cep_causal:split], following)) * self.anti_lifter
causal = torch.cat((causal[..., :1] + h[..., split:].flatten(1).gather(1, sub)[..., None], causal[..., 1:]), dim=-1)
harmonic_response = cepstrum_response(causal, anti, c.synth_fft)
# Noise branch: one envelope per frame, four gains per frame for sharp consonants.
n = self.noise(hidden)
sub = self._subframes(frames, lengths, self.noise_steps)
shape = self._take(n[..., :c.noise_cep], sub // self.noise_steps) * self.noise_lifter
shape = torch.cat((shape[..., :1] + n[..., c.noise_cep:].flatten(1).gather(1, sub)[..., None], shape[..., 1:]), dim=-1)
noise_response = cepstrum_response(shape, None, c.noise_fft)
# Hold the last real pitch value through padding: the pitch glide inside an
# utterance's final frame must not depend on what the batch was padded with.
f0 = f0.float().gather(1, torch.minimum(torch.arange(frames, device=f0.device)[None], last))
pulses = pulse_train(f0, c.sample_rate, c.hop, c.harmonic_limit, phase) * audible
if noise is None:
noise = torch.randn(hidden.shape[0], samples, device=hidden.device)
wave = (self._shape(pulses, harmonic_response, c.synth_fft, c.synth_hop, self.synth_window)
+ self._shape(noise * audible, noise_response, c.noise_fft, c.noise_hop, self.noise_window))
return wave * audible
def _load_vocos_pretrained(model_id):
from huggingface_hub import hf_hub_download
from vocos import Vocos
try:
cfg = hf_hub_download(repo_id=model_id, filename="config.yaml", local_files_only=True)
weights = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin", local_files_only=True)
model = Vocos.from_hparams(cfg)
state = torch.load(weights, map_location="cpu", weights_only=True)
model.load_state_dict(state)
return model
except Exception:
return Vocos.from_pretrained(model_id)
class VocosHead(nn.Module):
"""Linear mel projection followed by a pretrained 24 kHz Vocos ConvNeXt/iSTFT decoder."""
def __init__(self, c, vocos_model=None):
super().__init__()
self.config = c
self.frozen = False
self.proj = nn.Linear(c.channels, c.vocos_n_mels)
self.vocos = _load_vocos_pretrained(c.vocos_model) if vocos_model is None else vocos_model
self.register_buffer("mel_mean", torch.zeros(c.vocos_n_mels, dtype=torch.float32))
self.register_buffer("mel_scale", torch.ones(c.vocos_n_mels, dtype=torch.float32))
def freeze_vocoder(self, frozen=True):
self.frozen = frozen
for param in self.vocos.parameters():
param.requires_grad_(not frozen)
if frozen:
self.vocos.eval()
def train(self, mode=True):
super().train(mode)
if self.frozen:
self.vocos.eval()
return self
def set_mel_stats(self, mean, scale):
mean_t = torch.as_tensor(mean, dtype=torch.float32, device=self.mel_mean.device)
scale_t = torch.as_tensor(scale, dtype=torch.float32, device=self.mel_scale.device).clamp_min(1e-6)
if mean_t.shape != (self.config.vocos_n_mels,) or scale_t.shape != (self.config.vocos_n_mels,):
raise ValueError("vocos mel stats shape mismatch")
self.mel_mean.copy_(mean_t)
self.mel_scale.copy_(scale_t)
def predict_mel(self, hidden, frame_mask):
return self.proj(hidden.float()) * frame_mask[..., None]
def decode_mel(self, mel_norm, lengths, checkpointing=False):
c = self.config
frames = mel_norm.shape[1]
samples = frames * c.hop
if not self.training and mel_norm.shape[0] > 1:
waves = [
self.decode_mel(mel_norm[i : i + 1, : int(lengths[i])], lengths[i : i + 1])[0]
for i in range(mel_norm.shape[0])
]
out = nn.utils.rnn.pad_sequence(waves, batch_first=True)
if out.shape[1] < samples:
out = F.pad(out, (0, samples - out.shape[1]))
return out
with torch.autocast(device_type=mel_norm.device.type, enabled=False):
mel = mel_norm.float() * self.mel_scale + self.mel_mean
pos = torch.arange(frames + 1, device=mel.device)[None]
last = (lengths - 1).clamp_min(0)[:, None]
idx = torch.minimum(pos, last)
mel_bct = mel.gather(1, idx[..., None].expand(-1, -1, mel.shape[-1])).transpose(1, 2)
backbone = self.vocos.backbone
if checkpointing and self.training and mel_bct.requires_grad:
x = backbone.embed(mel_bct)
x = backbone.norm(x.transpose(1, 2)).transpose(1, 2)
for block in backbone.convnext:
x = checkpoint(block, x, use_reentrant=False)
x = backbone.final_layer_norm(x.transpose(1, 2))
else:
x = backbone(mel_bct)
wave = self.vocos.head(x)
audible = length_mask(lengths * c.hop, samples)
return wave * audible
class LuaNovaBase(nn.Module):
def __init__(self, config=Config()):
super().__init__()
self.config = c = config
self.tokens = nn.Embedding(c.vocab_size, c.channels, padding_idx=0)
self.stress = nn.Embedding(3, c.channels)
self.voices = nn.Embedding(len(c.speakers), c.channels)
self.encoder = Stack(c, c.encoder_layers)
# Outputs per token: log(1 + frames) and, for pause-capable tokens, a
# "has frames at all" logit. A pause is absent more often than present, so
# one regression would average both cases into a pause that is too short.
self.duration = Predictor(c, 2)
self.frame_voices = nn.Embedding(len(c.speakers), c.channels)
self.frame_position = nn.Linear(3, c.channels)
self.prosody_stack = Stack(c, c.prosody_layers)
# Outputs: continuous log(F0/reference), voiced logit, normalized log RMS energy.
self.prosody_head = nn.Linear(c.channels, 3)
self.prosody_projection = nn.Linear(3, c.channels)
self.acoustic_stack = Stack(c, c.acoustic_layers)
self.vocoder = VocosHead(c) if c.vocoder_type == "vocos" else SourceFilter(c)
phones = torch.zeros(c.vocab_size, dtype=torch.bool)
phones[sorted(PHONE_IDS)] = True
self.register_buffer("phone_tokens", phones, persistent=False)
vowels = torch.zeros(c.vocab_size, dtype=torch.bool)
vowels[[SYMBOL_TO_ID[v] for v in VOWELS]] = True
self.register_buffer("vowel_tokens", vowels, persistent=False)
def encode(self, tokens, stress, lengths, speakers):
if tokens.ndim != 2 or stress.shape != tokens.shape or lengths.shape != (tokens.shape[0],) or speakers.shape != lengths.shape:
raise ValueError("expected tokens[B,N], stress[B,N], lengths[B], speakers[B]")
if tokens.shape[1] > self.config.max_tokens or bool((lengths < 1).any()) or bool((lengths > tokens.shape[1]).any()):
raise ValueError("invalid token length")
mask = length_mask(lengths, tokens.shape[1])
x = (self.tokens(tokens) + self.stress(stress) + self.voices(speakers)[:, None]) * mask[..., None]
return self.encoder(x, mask), mask
def expand(self, hidden, durations, token_mask, speakers):
"""Repeat token states by integer durations (zero is allowed for pause
tokens) and add each frame's position inside its token."""
if durations.shape != token_mask.shape or bool((durations < 0).any()) or bool((durations[~token_mask] != 0).any()):
raise ValueError("invalid durations")
lengths = durations.sum(1)
if bool((lengths < 1).any()):
raise ValueError("utterance has no frames")
if bool((lengths > self.config.max_frames).any()):
raise UtteranceTooLong("utterance exceeds max_frames; split the input")
size = int(lengths.max())
ends = durations.cumsum(1)
frame = torch.arange(size, device=hidden.device)[None].expand(hidden.shape[0], size).contiguous()
index = torch.searchsorted(ends, frame, right=True).clamp(max=durations.shape[1] - 1)
owned = durations.gather(1, index).clamp_min(1)
offset = frame - (ends.gather(1, index) - durations.gather(1, index))
relative = (offset.to(hidden.dtype) + 0.5) / owned
features = torch.stack((relative, 1 - relative, torch.log1p(owned.to(hidden.dtype)) / 4), dim=-1)
mask = frame < lengths[:, None]
expanded = hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1]))
expanded = expanded + self.frame_position(features) + self.frame_voices(speakers)[:, None]
return expanded * mask[..., None], mask, lengths
def predict_prosody(self, frames, frame_mask):
hidden = self.prosody_stack(frames, frame_mask)
return hidden, self.prosody_head(hidden) * frame_mask[..., None]
@staticmethod
def hard_prosody(prediction):
"""What the decoder is conditioned on when it is not teacher-forced."""
return torch.stack((prediction[..., 0].clamp(-2.0, 1.5), (prediction[..., 1] > 0).to(prediction.dtype),
prediction[..., 2].clamp(-4.5, 3.0)), dim=-1)
def decode(self, prosody_hidden, condition, frame_mask):
return self.acoustic_stack((prosody_hidden + self.prosody_projection(condition)) * frame_mask[..., None], frame_mask)
def frequency(self, log_f0):
c = self.config
return (c.pitch_reference_hz * torch.exp(log_f0.float())).clamp(c.f0_min, c.f0_max)
def predict_durations(self, hidden, mask, tokens, speed=1.0):
output = self.duration(hidden, mask).float()
frames = torch.round(torch.expm1(output[..., 0].clamp(0, math.log1p(400))) / speed).long().clamp_min(1)
# Every phoneme is audible for at least one frame. A pause-capable token
# (edge, punctuation, word boundary) lasts its predicted length when the
# presence logit says there is a pause, and vanishes otherwise.
present = self.phone_tokens[tokens] | (output[..., 1] > 0)
return torch.where(present, frames, torch.zeros_like(frames)) * mask
@staticmethod
def widen_pitch(prosody, frame_mask, pitch_range):
"""Scale the predicted pitch movement around each utterance's voiced mean.
Regression predicts a flatter contour than the recordings; values above 1
restore range (1.0 leaves the prediction untouched)."""
if pitch_range == 1.0:
return prosody
voiced = ((prosody[..., 1] > 0) & frame_mask).to(prosody.dtype)
mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1)
pitch = mean + (prosody[..., 0] - mean) * pitch_range
return torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
@staticmethod
def pitch_wobble(shape, semitones, seed, device):
"""Small random pitch movement for the oscillator only (log-F0 units).
Recorded pitch has cycle-to-cycle irregularity that a predicted contour
lacks; two thirds of the wobble is slow drift, one third frame-level."""
generator = torch.Generator().manual_seed(seed + 7919)
fast = torch.randn(shape, generator=generator)
slow = F.avg_pool1d(torch.randn(shape[0], 1, shape[1] + 16, generator=generator), 17, stride=1)[:, 0]
slow = slow / slow.std().clamp_min(1e-6)
return ((2 * slow + fast) / 5 ** 0.5 * semitones * math.log(2) / 12).to(device)
@torch.inference_mode()
def synthesize(self, tokens, stress, lengths, speakers, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0, pitch_jitter=0.0,
voiced_vowels=True):
"""Free-running synthesis: predicted durations, pitch, voicing and energy."""
if not math.isfinite(speed) or not 0.25 <= speed <= 4 or not math.isfinite(pitch_shift) or not 0 <= pitch_range <= 3:
raise ValueError("speed must be between 0.25 and 4, pitch_shift finite and pitch_range between 0 and 3")
hidden, mask = self.encode(tokens, stress, lengths, speakers)
durations = self.predict_durations(hidden, mask, tokens, speed)
frames, frame_mask, frame_lengths = self.expand(hidden, durations, mask, speakers)
prosody_hidden, prosody = self.predict_prosody(frames, frame_mask)
if voiced_vowels:
# The pitch tracker missed creaky vowels in the recordings, and the
# voicing predictor learned to drop whole vowels (heard as a whispered
# word). A vowel is voiced by definition, so its frames are kept voiced.
ends = durations.cumsum(1)
frame = torch.arange(frames.shape[1], device=tokens.device)[None].expand(len(lengths), -1).contiguous()
owner = torch.searchsorted(ends, frame, right=True).clamp(max=tokens.shape[1] - 1)
vowel = self.vowel_tokens[tokens].gather(1, owner) & frame_mask
prosody = torch.cat((prosody[..., :1], torch.where(vowel, prosody[..., 1].clamp_min(2.0), prosody[..., 1])[..., None],
prosody[..., 2:]), dim=-1)
prosody = self.widen_pitch(prosody, frame_mask, pitch_range)
if self.config.vocoder_type == "vocos":
pitch = prosody[..., 0] + pitch_shift
if pitch_jitter > 0:
pitch = pitch + self.pitch_wobble(pitch.shape, pitch_jitter, seed, pitch.device)
prosody_in = torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
acoustic = self.decode(prosody_hidden, self.hard_prosody(prosody_in), frame_mask)
mel_norm = self.vocoder.predict_mel(acoustic, frame_mask)
wave = self.vocoder.decode_mel(mel_norm, frame_lengths)
return wave, frame_lengths * self.config.hop, {"durations": durations, "prosody": prosody, "frame_mask": frame_mask}
acoustic = self.decode(prosody_hidden, self.hard_prosody(prosody), frame_mask)
# One noise stream per row, drawn at the row's own length, so batching or
# padding never changes a row's audio.
noise = nn.utils.rnn.pad_sequence([torch.randn(int(n) * self.config.hop, generator=torch.Generator().manual_seed(seed + row))
for row, n in enumerate(frame_lengths)], batch_first=True)
pitch = prosody[..., 0] + pitch_shift
if pitch_jitter > 0:
pitch = pitch + self.pitch_wobble(pitch.shape, pitch_jitter, seed, pitch.device)
wave = self.vocoder(acoustic, self.frequency(pitch), frame_lengths, noise=noise.to(hidden.device))
return wave, frame_lengths * self.config.hop, {"durations": durations, "prosody": prosody, "frame_mask": frame_mask}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.utils.parametrizations import weight_norm
def masked_mean(value, mask):
return (value * mask).sum() / mask.sum().clamp_min(1)
def magnitude(wave, fft, hop, window):
spectrum = torch.stft(wave.float(), fft, hop, window=window, center=True, pad_mode="constant", return_complex=True)
# sqrt(re^2 + im^2 + eps): finite gradient at exact zeros (padding, silence).
return torch.view_as_real(spectrum).square().sum(-1).add(1e-9).sqrt()
def mel_filterbank(sample_rate, fft, n_mels):
"""Slaney-scale triangular filters with area normalisation, [n_mels, bins]."""
step, knee, slope = 200.0 / 3, 1000.0, math.log(6.4) / 27
def to_hz(mel):
return torch.where(mel < knee / step, mel * step, knee * torch.exp((mel - knee / step) * slope))
top = knee / step + math.log(sample_rate / 2 / knee) / slope if sample_rate / 2 > knee else sample_rate / 2 / step
points = to_hz(torch.linspace(0, top, n_mels + 2, dtype=torch.float64))
bins = torch.linspace(0, sample_rate / 2, fft // 2 + 1, dtype=torch.float64)
rising = (bins[None] - points[:-2, None]) / (points[1:-1] - points[:-2])[:, None]
falling = (points[2:, None] - bins[None]) / (points[2:] - points[1:-1])[:, None]
weights = torch.minimum(rising, falling).clamp_min(0) * (2.0 / (points[2:] - points[:-2]))[:, None]
return weights.float()
class SpectralLoss(nn.Module):
"""Multi-resolution STFT and log-mel distances over whole utterances.
Frames whose centre lies beyond an utterance's length are masked, so padded
batches give the same value as the utterances would alone. No parameters.
"""
def __init__(self, sample_rate, resolutions=((512, 128), (1024, 256), (2048, 512)), mel=(1024, 256, 80)):
super().__init__()
self.resolutions, self.mel = tuple(resolutions), tuple(mel)
for fft in {fft for fft, _ in self.resolutions} | {self.mel[0]}:
self.register_buffer(f"window_{fft}", torch.hann_window(fft), persistent=False)
self.register_buffer("filters", mel_filterbank(sample_rate, self.mel[0], self.mel[2]), persistent=False)
def log_mel(self, wave):
fft, hop, _ = self.mel
return torch.log((self.filters @ magnitude(wave, fft, hop, getattr(self, f"window_{fft}"))).clamp_min(1e-5))
def forward(self, predicted, target, lengths):
total = predicted.new_zeros((), dtype=torch.float32)
for fft, hop in self.resolutions:
window = getattr(self, f"window_{fft}")
p, t = magnitude(predicted, fft, hop, window), magnitude(target, fft, hop, window)
mask = (torch.arange(p.shape[-1], device=p.device)[None] * hop < lengths[:, None]).float()[:, None]
logarithmic = ((p.clamp_min(1e-5).log() - t.clamp_min(1e-5).log()).abs() * mask).sum() / (mask.sum() * p.shape[1]).clamp_min(1)
# Spectral convergence per utterance; the floor keeps silent input finite.
convergence = (((p - t).square() * mask).sum((1, 2)) + 1e-9).sqrt() / (t.square() * mask).sum((1, 2)).sqrt().clamp_min(1.0)
total = total + logarithmic + convergence.mean()
hop = self.mel[1]
p, t = self.log_mel(predicted), self.log_mel(target)
mask = (torch.arange(p.shape[-1], device=p.device)[None] * hop < lengths[:, None]).float()[:, None]
mel = ((p - t).abs() * mask).sum() / (mask.sum() * p.shape[1]).clamp_min(1)
return total / len(self.resolutions), mel
class PeriodDiscriminator(nn.Module):
def __init__(self, period, channels=(1, 32, 96, 192, 384)):
super().__init__()
self.period = period
self.layers = nn.ModuleList(weight_norm(nn.Conv2d(a, b, (5, 1), (3, 1), (2, 0))) for a, b in zip(channels[:-1], channels[1:]))
self.output = weight_norm(nn.Conv2d(channels[-1], 1, (3, 1), padding=(1, 0)))
def forward(self, wave):
wave = F.pad(wave, (0, (-wave.shape[-1]) % self.period))
x = wave.reshape(wave.shape[0], 1, -1, self.period)
features = []
for layer in self.layers:
x = F.leaky_relu(layer(x), 0.1)
features.append(x)
return self.output(x), features
class SpectrogramDiscriminator(nn.Module):
def __init__(self, fft, hop, channels=32):
super().__init__()
self.fft, self.hop = fft, hop
self.register_buffer("window", torch.hann_window(fft), persistent=False)
self.layers = nn.ModuleList([
weight_norm(nn.Conv2d(1, channels, (3, 9), padding=(1, 4))),
weight_norm(nn.Conv2d(channels, channels, (3, 9), stride=(1, 2), padding=(1, 4))),
weight_norm(nn.Conv2d(channels, channels, (3, 9), stride=(1, 2), padding=(1, 4))),
weight_norm(nn.Conv2d(channels, channels, (3, 9), stride=(1, 2), padding=(1, 4))),
weight_norm(nn.Conv2d(channels, channels, (3, 3), padding=(1, 1))),
])
self.output = weight_norm(nn.Conv2d(channels, 1, (3, 3), padding=(1, 1)))
def forward(self, wave):
x = magnitude(wave, self.fft, self.hop, self.window).transpose(1, 2)[:, None] # [B,1,frames,bins]
features = []
for layer in self.layers:
x = F.leaky_relu(layer(x), 0.1)
features.append(x)
return self.output(x), features
class Discriminators(nn.Module):
"""Training-only waveform critics. Never included in an inference export."""
def __init__(self, periods=(2, 3, 5, 7, 11), resolutions=((512, 128), (1024, 256), (2048, 512))):
super().__init__()
self.networks = nn.ModuleList([PeriodDiscriminator(p) for p in periods]
+ [SpectrogramDiscriminator(fft, hop) for fft, hop in resolutions])
def forward(self, wave):
return [network(wave) for network in self.networks]
def discriminator_loss(real, fake):
return sum((r-1).square().mean() + f.square().mean()
for (r, _), (f, _) in zip(real, fake)) / len(real)
def generator_gan_loss(real, fake):
adversarial = sum((f-1).square().mean() for f, _ in fake) / len(fake)
matching = sum(F.l1_loss(f, r.detach())
for (_, rs), (_, fs) in zip(real, fake) for r, f in zip(rs, fs))
matching = matching / sum(len(fs) for _, fs in fake)
return adversarial, matching123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Brazilian Portuguese text normalization and G2P phonemization."""
from .normalizer import normalize_ptbr_text
from .phonemizer import (
ABBREVIATIONS,
BOS,
EOS,
ESPEAK_VOICE,
FALLBACK,
FRONTEND_VARIABLE,
FRONTEND_VERSION,
FRONTENDS,
PAD,
PHONE_IDS,
PHONE_SET,
PHONES,
PUNCTUATION,
SP,
SYMBOL_TO_ID,
SYMBOLS,
UNK,
VOICELESS,
VOWEL_SET,
VOWELS,
NothingToPronounce,
Phonemized,
frontend,
frontend_fingerprint,
frontend_identity,
frontend_runtime,
is_phone,
phonemize,
phonemize_ptbr,
set_frontend,
)
__all__ = [
"ABBREVIATIONS",
"BOS",
"EOS",
"ESPEAK_VOICE",
"FALLBACK",
"FRONTEND_VARIABLE",
"FRONTEND_VERSION",
"FRONTENDS",
"NothingToPronounce",
"PAD",
"PHONE_IDS",
"PHONE_SET",
"PHONES",
"PUNCTUATION",
"Phonemized",
"SP",
"SYMBOLS",
"SYMBOL_TO_ID",
"UNK",
"VOICELESS",
"VOWELS",
"VOWEL_SET",
"frontend",
"frontend_fingerprint",
"frontend_identity",
"frontend_runtime",
"is_phone",
"normalize_ptbr_text",
"phonemize",
"phonemize_ptbr",
"set_frontend",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343"""Normalizador de texto PT-BR (números, moedas, horários, datas, ordinais e abreviações).
Converte expressões numéricas e abreviações comuns do português brasileiro para
texto por extenso antes da fonemização com eSpeak, preservando a pontuação e a
estrutura de frases. Sem dependências externas.
"""
from __future__ import annotations
import re
import unicodedata
_UNITS_M = [
"zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito",
"nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis",
"dezessete", "dezoito", "dezenove",
]
_UNITS_F = [
"zero", "uma", "duas", "três", "quatro", "cinco", "seis", "sete", "oito",
"nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis",
"dezessete", "dezoito", "dezenove",
]
_TENS = [
"", "dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta",
"setenta", "oitenta", "noventa",
]
_HUNDREDS_M = [
"", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos",
"seiscentos", "setecentos", "oitocentos", "novecentos",
]
_HUNDREDS_F = [
"", "cento", "duzentas", "trezentas", "quatrocentas", "quinhentas",
"seiscentas", "setecentas", "oitocentas", "novecentas",
]
_ORD_UNITS = [
"", "primeir", "segund", "terceir", "quart", "quint",
"sext", "sétim", "oitav", "non",
]
_ORD_TENS = [
"", "décim", "vigésim", "trigésim", "quadragésim", "quinquagésim",
"sexagésim", "septuagésim", "octogésim", "nonagésim",
]
_ORD_HUNDREDS = [
"", "centésim", "ducentésim", "trecentésim", "quadringentésim",
"quingentésim", "sexcentésim", "septingentésim", "octingentésim",
"nongentésim",
]
_MONTHS = {
1: "janeiro", 2: "fevereiro", 3: "março", 4: "abril",
5: "maio", 6: "junho", 7: "julho", 8: "agosto",
9: "setembro", 10: "outubro", 11: "novembro", 12: "dezembro",
}
def _under_1000(n: int, feminine: bool = False) -> str:
if n == 0:
return "zero"
if n == 100:
return "cem"
units = _UNITS_F if feminine else _UNITS_M
hundreds_tbl = _HUNDREDS_F if feminine else _HUNDREDS_M
parts = []
hundreds, rest = divmod(n, 100)
if hundreds:
parts.append(hundreds_tbl[hundreds])
if rest:
if rest < 20:
parts.append(units[rest])
else:
ten, unit = divmod(rest, 10)
parts.append(f"{_TENS[ten]} e {units[unit]}" if unit else _TENS[ten])
return " e ".join(parts)
def int_to_ptbr(n: int, feminine: bool = False) -> str:
"""Converte inteiro (-999_999_999..999_999_999) para extenso em PT-BR."""
if n < 0:
return f"menos {int_to_ptbr(-n, feminine=feminine)}"
if n < 1000:
return _under_1000(n, feminine=feminine)
if n < 1_000_000:
thousands, rest = divmod(n, 1000)
t_word = "mil" if thousands == 1 else f"{_under_1000(thousands, feminine=feminine)} mil"
if rest == 0:
return t_word
joiner = " e " if (rest < 100 or rest % 100 == 0) else " "
return t_word + joiner + _under_1000(rest, feminine=feminine)
if n < 1_000_000_000:
millions, rest = divmod(n, 1_000_000)
m_word = "um milhão" if millions == 1 else f"{_under_1000(millions, feminine=False)} milhões"
if rest == 0:
return m_word
if rest < 1000 and (rest < 100 or rest % 100 == 0):
return f"{m_word} e {_under_1000(rest, feminine=feminine)}"
return f"{m_word} {int_to_ptbr(rest, feminine=feminine)}"
return " ".join(_UNITS_M[int(ch)] for ch in str(n))
def ordinal_to_ptbr(n: int, feminine: bool = False) -> str:
"""Converte ordinal (1..999) para extenso em PT-BR."""
if n < 1 or n > 999:
return int_to_ptbr(n, feminine=feminine)
suf = "a" if feminine else "o"
h, rem = divmod(n, 100)
t, u = divmod(rem, 10)
parts = []
if h:
parts.append(_ORD_HUNDREDS[h] + suf)
if t:
parts.append(_ORD_TENS[t] + suf)
if u:
parts.append(_ORD_UNITS[u] + suf)
return " ".join(parts)
def decimal_to_ptbr(int_str: str, frac_str: str, feminine: bool = False) -> str:
whole = int_to_ptbr(int(int_str.replace(".", "")), feminine=feminine)
if frac_str.startswith("0") and len(frac_str) > 1:
frac = " ".join(_UNITS_M[int(d)] for d in frac_str)
else:
frac = int_to_ptbr(int(frac_str))
return f"{whole} vírgula {frac}"
_CURRENCY_RE = re.compile(
r"R\$\s*(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d{1,2}))?(?![\d,])"
)
_PERCENT_RE = re.compile(
r"(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?\s*%"
)
_DATE_RE = re.compile(
r"\b([0-3]?\d)/([01]?\d)(?:/(\d{2,4}))?\b"
)
_TIME_H_RE = re.compile(
r"\b([01]?\d|2[0-3])\s*h(?:(\d{2}))?(?:min)?\b", re.IGNORECASE
)
_TIME_COLON_RE = re.compile(
r"\b([01]?\d|2[0-3]):([0-5]\d)\b"
)
_ORDINAL_RE = re.compile(
r"\b(\d{1,3})\s*([º°ª])\b"
)
_TEMP_RE = re.compile(
r"(-?\d+)(?:,(\d+))?\s*°\s*C\b"
)
_UNIT_RE = re.compile(
r"\b(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?\s*(kHz|Hz|km|kg|cm|mm|mL|ml|GB|MB|KB)\b"
)
_THOUSANDS_RE = re.compile(
r"\b(\d{1,3}(?:\.\d{3})+)(?:,(\d+))?\b"
)
_DECIMAL_RE = re.compile(
r"\b(\d+),(\d+)\b"
)
_INT_RE = re.compile(
r"\b(\d+)\b"
)
_ABBREV_RULES = [
(re.compile(r"\bDra\.", re.IGNORECASE), "doutora"),
(re.compile(r"\bDr\.", re.IGNORECASE), "doutor"),
(re.compile(r"\bSrta\.", re.IGNORECASE), "senhorita"),
(re.compile(r"\bSra\.", re.IGNORECASE), "senhora"),
(re.compile(r"\bSr\.", re.IGNORECASE), "senhor"),
(re.compile(r"\bProfa\.", re.IGNORECASE), "professora"),
(re.compile(r"\bProf\.", re.IGNORECASE), "professor"),
(re.compile(r"\betc\.", re.IGNORECASE), "etcétera"),
]
_ACRONYM_MAP = {
"CPU": "cê pê u",
"GPU": "gê pê u",
"API": "a pê i",
"URL": "u érre éle",
"ONNX": "ônics",
"JSON": "jeizon",
"PDF": "pê dê éfe",
"TTS": "tê tê ésse",
"IA": "i a",
"RAM": "rã",
"SSD": "ésse ésse dê",
"USB": "u ésse bê",
"SQL": "ésse quê éle",
"HTTP": "agá tê tê pê",
"HTTPS": "agá tê tê pê ésse",
"HTML": "agá tê eme éle",
"RGB": "érre gê bê",
"CPF": "cê pê éfe",
"CNPJ": "cê ene pê jóta",
"CEP": "cépi",
"RG": "érre gê",
"IBGE": "i bê gê é",
"LLM": "éle éle eme",
"GPT": "gê pê tê",
"CSV": "cê ésse vê",
"CLI": "cê éle i",
"WAV": "uávi",
"PIX": "pics",
}
_ACRONYM_RE = re.compile(
r"(?<![A-Za-zÀ-ÿ])(?:"
+ "|".join(re.escape(k) for k in sorted(_ACRONYM_MAP, key=len, reverse=True))
+ r")(?![A-Za-zÀ-ÿ])"
)
_LOANWORD_RULES = [
(re.compile(r"(?<![A-Za-zÀ-ÿ])wi-?fi(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uái-fái"),
(re.compile(r"(?<![A-Za-zÀ-ÿ])bluetooth(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "blutuf"),
(re.compile(r"(?<![A-Za-zÀ-ÿ])python(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "páiton"),
(re.compile(r"(?<![A-Za-zÀ-ÿ])youtube(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "iutúbi"),
(re.compile(r"(?<![A-Za-zÀ-ÿ])whatsapp(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uátsápi"),
(re.compile(r"(?<![A-Za-zÀ-ÿ])windows(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uíndous"),
]
_SEDE_RE = re.compile(
r"\b(a|na|da|pela|essa|esta|sua|nossa|nova)\s+(sede)\s+"
r"(da|do|de|dos|das|central|principal|própria|nova|antiga|nacional|regional|local|social|administrativa)\b",
re.IGNORECASE,
)
_VERB_OPEN_O_RE = re.compile(
r"\b(não|sempre|nunca|já|ainda|também|hoje|amanhã|quando|se|só)\s+(almoço|começo)\b",
re.IGNORECASE,
)
_HOMOGRAPH_RULES = [
(_SEDE_RE, lambda m: f"{m.group(1)} {'Séde' if m.group(2)[0].isupper() else 'séde'} {m.group(3)}"),
(
_VERB_OPEN_O_RE,
lambda m: f"{m.group(1)} {'Almóço' if m.group(2) == 'Almoço' else 'almóço' if m.group(2).lower() == 'almoço' else 'Coméço' if m.group(2)[0].isupper() else 'coméço'}",
),
]
_UNIT_NAMES = {
"kHz": ("quilohertz", "quilohertz", False),
"Hz": ("hertz", "hertz", False),
"km": ("quilômetro", "quilômetros", False),
"kg": ("quilo", "quilos", False),
"cm": ("centímetro", "centímetros", False),
"mm": ("milímetro", "milímetros", False),
"mL": ("mililitro", "mililitros", False),
"ml": ("mililitro", "mililitros", False),
"GB": ("gigabyte", "gigabytes", False),
"MB": ("megabyte", "megabytes", False),
"KB": ("quilobyte", "quilobytes", False),
}
def _rep_currency(m: re.Match) -> str:
reais = int(m.group(1).replace(".", ""))
cents_raw = m.group(2)
cents = int(cents_raw.ljust(2, "0")) if cents_raw else 0
parts = []
if reais > 0 or cents == 0:
unit = "real" if reais == 1 else "reais"
parts.append(f"{int_to_ptbr(reais)} {unit}")
if cents > 0:
c_unit = "centavo" if cents == 1 else "centavos"
parts.append(f"{int_to_ptbr(cents)} {c_unit}")
return " e ".join(parts)
def _rep_percent(m: re.Match) -> str:
if m.group(2):
return f"{decimal_to_ptbr(m.group(1), m.group(2))} por cento"
return f"{int_to_ptbr(int(m.group(1).replace('.', '')))} por cento"
def _rep_date(m: re.Match) -> str:
day, month = int(m.group(1)), int(m.group(2))
if not (1 <= day <= 31 and 1 <= month <= 12):
return m.group(0)
day_word = "primeiro" if day == 1 else int_to_ptbr(day)
out = f"{day_word} de {_MONTHS[month]}"
if m.group(3):
year = int(m.group(3))
if len(m.group(3)) == 2:
year += 2000 if year < 50 else 1900
out += f" de {int_to_ptbr(year)}"
return out
def _format_time(hour: int, minute: int) -> str:
h_word = int_to_ptbr(hour, feminine=True)
h_unit = "hora" if hour == 1 else "horas"
if minute == 0:
return f"{h_word} {h_unit}"
m_unit = "minuto" if minute == 1 else "minutos"
return f"{h_word} {h_unit} e {int_to_ptbr(minute)} {m_unit}"
def _rep_time_h(m: re.Match) -> str:
hour = int(m.group(1))
minute = int(m.group(2)) if m.group(2) else 0
return _format_time(hour, minute)
def _rep_time_colon(m: re.Match) -> str:
return _format_time(int(m.group(1)), int(m.group(2)))
def _rep_ordinal(m: re.Match) -> str:
return ordinal_to_ptbr(int(m.group(1)), feminine=(m.group(2) == "ª"))
def _rep_temp(m: re.Match) -> str:
val_str = m.group(1)
neg = val_str.startswith("-")
num = abs(int(val_str))
prefix = "menos " if neg else ""
if m.group(2):
return f"{prefix}{decimal_to_ptbr(str(num), m.group(2))} graus Celsius"
unit = "grau Celsius" if num == 1 else "graus Celsius"
return f"{prefix}{int_to_ptbr(num)} {unit}"
def _rep_unit(m: re.Match) -> str:
sing, plur, fem = _UNIT_NAMES[m.group(3)]
if m.group(2):
return f"{decimal_to_ptbr(m.group(1), m.group(2), feminine=fem)} {plur}"
val = int(m.group(1).replace(".", ""))
return f"{int_to_ptbr(val, feminine=fem)} {sing if val == 1 else plur}"
def normalize_ptbr_text(text: str) -> str:
"""Expande moedas, porcentagens, datas, horários, ordinais, números e abreviações PT-BR."""
s = unicodedata.normalize("NFC", text)
s = _CURRENCY_RE.sub(_rep_currency, s)
s = _TEMP_RE.sub(_rep_temp, s)
s = _PERCENT_RE.sub(_rep_percent, s)
s = _DATE_RE.sub(_rep_date, s)
s = _TIME_COLON_RE.sub(_rep_time_colon, s)
s = _TIME_H_RE.sub(_rep_time_h, s)
s = _ORDINAL_RE.sub(_rep_ordinal, s)
s = _UNIT_RE.sub(_rep_unit, s)
s = _THOUSANDS_RE.sub(
lambda m: decimal_to_ptbr(m.group(1), m.group(2)) if m.group(2) else int_to_ptbr(int(m.group(1).replace(".", ""))),
s,
)
s = _DECIMAL_RE.sub(lambda m: decimal_to_ptbr(m.group(1), m.group(2)), s)
s = _INT_RE.sub(lambda m: int_to_ptbr(int(m.group(1))), s)
for pattern, repl in _ABBREV_RULES:
s = pattern.sub(repl, s)
for pattern, repl in _LOANWORD_RULES:
s = pattern.sub(repl, s)
s = _ACRONYM_RE.sub(lambda m: _ACRONYM_MAP[m.group(0)], s)
for pattern, repl in _HOMOGRAPH_RULES:
s = pattern.sub(repl, s)
return re.sub(r"[ \t]{2,}", " ", s).strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347"""Brazilian Portuguese (PT-BR) front end: text -> phoneme tokens with a stress feature.
The same code runs during annotation, training-set preparation and inference,
so tokens can never drift between them.
* eSpeak NG (``pt-br``) is the default pronunciation source (``espeak``).
* A token is one eSpeak phoneme exactly as eSpeak segments it (``--sep``), for
example ``t``, ``ɐ̃``, ``ɐ̃ʊ̃`` or ``tʃ``. Every phone in ``PHONE_SET`` is also
present in ``facebook/wav2vec2-lv-60-espeak-cv-ft``'s vocabulary for CTC
forced alignment.
* Lexical stress is a parallel feature (0 none, 1 primary, 2 secondary), not a
token, so it never has to be given audio frames.
* Punctuation, word boundaries and the utterance edges are explicit tokens that
may last zero frames. They carry pauses when the recording has them.
"""
from dataclasses import dataclass
import hashlib
import json
import os
import re
import shutil
import subprocess
import unicodedata
FRONTEND_VERSION = 3
ESPEAK_VOICE = "pt-br"
SEPARATOR = "_"
FRONTENDS = ("espeak", "own")
FRONTEND_VARIABLE = "LUA_NOVA_FRONTEND"
_frontend = os.environ.get(FRONTEND_VARIABLE, "espeak")
if _frontend not in FRONTENDS:
raise ValueError(f"{FRONTEND_VARIABLE} must be one of {FRONTENDS}, not {_frontend!r}")
PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"
SPECIALS = (PAD, BOS, EOS, SP, UNK)
PUNCTUATION = (",", ".", "?", "!", ";", ":", '"', "'", "(", ")", "-", "—", "…")
CONSONANTS = (
"p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h",
"x", "ɣ", "m", "n", "ɲ", "ŋ", "l", "ʎ", "ɾ", "r", "ʁ", "j", "w", "tʃ", "dʒ", "ts",
)
VOWELS = (
"a", "ɐ", "æ", "e", "ɛ", "ə", "i", "ɪ", "y", "o", "ɔ", "u", "ʊ",
"aː", "eː", "iː", "oː", "uː",
"\u0250\u0303", "a\u0303", "e\u0303", "i\u0303", "o\u0303", "u\u0303", "\u0250\u0303\u028a\u0303",
"aɪ", "aʊ", "eɪ", "eʊ", "ɛɪ", "ɛʊ", "iʊ", "oɪ", "oʊ", "ɔɪ", "uɪ",
)
PHONES = CONSONANTS + VOWELS
# Append-only: changing the order or removing a symbol invalidates checkpoints.
SYMBOLS = SPECIALS + PUNCTUATION + PHONES
SYMBOLS_PTBR = list(SYMBOLS)
SYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}
PHONE_SET = frozenset(PHONES)
PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}
VOICELESS = frozenset(("p", "t", "k", "f", "θ", "s", "ʃ", "h", "x", "tʃ", "ts"))
VOWEL_SET = frozenset(VOWELS)
STRESS_MARKS = {"ˈ": 1, "ˌ": 2}
# eSpeak phonemes outside the inventory (foreign words, rare allophones, NFC nasals)
# map to the closest inventory phone(s). Anything else becomes <unk> and is reported.
FALLBACK = {
"g": ("ɡ",),
"\u00e3": ("\u0250\u0303",),
"\u1ebd": ("e\u0303",),
"\u0129": ("i\u0303",),
"\u00f5": ("o\u0303",),
"\u0169": ("u\u0303",),
"j\u0303": ("j",),
"w\u0303": ("w",),
"ɹ": ("ɾ",),
"ʔ": ("h",),
"ɻ": ("ɾ",),
"ç": ("ʃ",),
"ɬ": ("l",),
"ɫ": ("l",),
"dz": ("d", "z"),
"β": ("v",),
"ɑ": ("a",),
"ɑː": ("aː",),
"ɒ": ("ɔ",),
"ɑ\u0303": ("\u0250\u0303",),
"ɔ\u0303": ("o\u0303",),
"ɛ\u0303": ("e\u0303",),
"ʌ": ("ɐ",),
"ɚ": ("ə", "ɾ"),
"ᵻ": ("i",),
"ɜ": ("ɛ",),
"ɜː": ("ɛ",),
"ø": ("e",),
"øː": ("eː",),
"œ": ("ɛ",),
"ɛː": ("ɛ",),
"ɪː": ("iː",),
"ɔː": ("ɔ",),
"ʊː": ("uː",),
"yː": ("y",),
"əʊ": ("oʊ",),
"əl": ("ə", "l"),
"n̩": ("n",),
"l̩": ("l",),
"m̩": ("m",),
"iə": ("i", "ə"),
"aɪə": ("aɪ", "ə"),
"aʊɚ": ("aʊ", "ə", "ɾ"),
}
_QUOTES = str.maketrans({"‘": "'", "’": "'", "‚": "'", "‛": "'", "`": "'", "´": "'",
"“": '"', "”": '"', "„": '"', "‟": '"', "«": '"', "»": '"',
"–": "—", "―": "—", "[": "(", "{": "(", "]": ")", "}": ")"})
_PUNCTUATION_CHARS = frozenset(PUNCTUATION)
ABBREVIATIONS = {
"dr", "dra", "sr", "sra", "srta", "prof", "profa", "jr", "st", "sto", "sta",
"vs", "etc", "pág", "cap", "fig", "art", "inc", "ltda",
}
_LANGUAGE_TAG = re.compile(r"\((?:_?[a-z0-9]_?){2,3}(?:-(?:_?[a-z0-9]_?)+)*\)")
class NothingToPronounce(ValueError):
"""The text has no word, number or letter to say: only marks, emoji and the like."""
@dataclass(frozen=True)
class Phonemized:
symbols: tuple
ids: tuple
stress: tuple
unknown: tuple # eSpeak phonemes that had no inventory mapping
def __len__(self):
return len(self.ids)
def frontend():
"""Name of the program that produces the phonemes: ``"espeak"`` or ``"own"``."""
return _frontend
def set_frontend(name):
"""Select the phonemizer for this process. Tokens of the two front ends
must not be mixed: annotations and checkpoints record which one made them."""
global _frontend
if name not in FRONTENDS:
raise ValueError(f"front end must be one of {FRONTENDS}, not {name!r}")
_frontend = name
def _dizione():
try:
import dizione
except ImportError as error:
raise RuntimeError('the "own" front end needs the dizione package: pip install dizione') from error
if tuple(dizione.symbols.SYMBOLS) != SYMBOLS:
raise RuntimeError("dizione's symbol inventory differs from this model's")
return dizione
def frontend_identity():
if _frontend == "own":
phonemizer = _dizione()
return {"frontend_version": phonemizer.VERSION, "phonemizer": "dizione", "symbols": list(SYMBOLS)}
return {"frontend_version": FRONTEND_VERSION, "voice": ESPEAK_VOICE, "separator": SEPARATOR,
"symbols": list(SYMBOLS), "fallback": {key: list(value) for key, value in sorted(FALLBACK.items())}}
def frontend_runtime():
"""What an annotation run records about the exact program behind its
tokens: the eSpeak version, or the fingerprint of the phonemizer build."""
if _frontend == "own":
return {"phonemizer": _dizione().identity()["fingerprint"]}
return {"espeak_version": espeak_version()}
def frontend_fingerprint():
return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest()
def normalize_text(text):
text = unicodedata.normalize("NFKC", text).translate(_QUOTES)
text = re.sub(r"\.{3,}", "…", text)
text = re.sub(r"-{2,}|\s-\s", "—", text)
return re.sub(r"\s+", " ", text).strip()
def chunks(text):
"""Yield ``(is_punctuation, piece)``. Decimals, clock times, digit groups,
hyphenated words, contractions, title abbreviations and initialisms stay
inside the text piece for eSpeak; every other punctuation mark becomes its
own token."""
start = 0
for i, char in enumerate(text):
if char not in _PUNCTUATION_CHARS:
continue
previous = text[i-1] if i else ""
following = text[i+1] if i+1 < len(text) else ""
if char == "'" and previous.isalnum() and following.isalnum():
continue
if char == "-" and previous.isalpha() and following.isalpha():
continue
if char in ".,:" and previous.isdigit() and following.isdigit():
continue
if char == ".":
word = re.search(r"([^\W\d_]+)$", text[:i])
if word and word[1].lower() in ABBREVIATIONS:
continue
if previous.isalpha() and following.isalpha():
continue
if text[start:i].strip():
yield False, text[start:i].strip()
yield True, char
start = i+1
if text[start:].strip():
yield False, text[start:].strip()
def espeak_executable():
executable = shutil.which("espeak-ng")
if executable is None:
raise RuntimeError("Install espeak-ng and ensure it is on PATH before preprocessing/inference")
return executable
def espeak_version():
return subprocess.run(
[espeak_executable(), "--version"],
capture_output=True, text=True, encoding="utf-8", check=True, timeout=10,
).stdout.strip()
def espeak_words(piece):
"""Phonemize one text piece. Returns words as lists of ``(phone, stress)``.
The input must end with a newline: eSpeak NG 1.51 silently drops the last
character of unterminated standard input.
"""
result = subprocess.run(
[espeak_executable(), "-q", "--ipa", "--sep=" + SEPARATOR, "-v", ESPEAK_VOICE, "--stdin"],
input=piece.rstrip("\n") + "\n", text=True, encoding="utf-8", capture_output=True, check=True, timeout=30)
return parse_espeak(result.stdout)
def parse_espeak(output):
words = []
for word in _LANGUAGE_TAG.sub("", output).split():
units = []
for unit in word.split(SEPARATOR):
stress = 0
for mark, level in STRESS_MARKS.items():
if mark in unit:
stress = stress or level
unit = unit.replace(mark, "")
unit = "".join(c for c in unit if unicodedata.category(c) != "Cf" and c not in "()")
if unit:
units.append((unit, stress))
if units:
words.append(units)
return words
def canonical(phone):
"""Map an eSpeak phoneme to inventory phones; ``None`` when unknown."""
if phone in PHONE_SET:
return (phone,)
if phone in FALLBACK:
return FALLBACK[phone]
for candidate in (unicodedata.normalize("NFD", phone), phone.replace("ː", ""), unicodedata.normalize("NFD", phone).replace("ː", "")):
if candidate != phone and candidate in PHONE_SET:
return (candidate,)
if candidate != phone and candidate in FALLBACK:
return FALLBACK[candidate]
stripped = "".join(c for c in unicodedata.normalize("NFD", phone) if not unicodedata.combining(c))
for candidate in (stripped, stripped.replace("ː", ""), stripped + "ː"):
if candidate != phone and candidate in PHONE_SET:
return (candidate,)
if candidate != phone and candidate in FALLBACK:
return FALLBACK[candidate]
# Decompose novel compound diphthongs/affricates into base+combining units.
parts = []
for ch in phone.replace("ː", ""):
if unicodedata.combining(ch) and parts:
parts[-1] += ch
else:
parts.append(ch)
if len(parts) > 1:
resolved = []
for part in parts:
if part in PHONE_SET:
resolved.append(part)
elif part in FALLBACK:
resolved.extend(FALLBACK[part])
else:
return None
return tuple(resolved)
return None
def tokenize(pieces):
"""Build the token sequence from ``(is_punctuation, value)`` pieces where a
text piece's value is the parsed eSpeak word list. Pure function (testable
without eSpeak)."""
symbols, stress, unknown = [BOS], [0], []
for punctuation, value in pieces:
if punctuation:
if symbols[-1] != value: # collapse repeats such as "!!"
symbols.append(value)
stress.append(0)
continue
for word in value:
if symbols[-1] in PHONE_SET or symbols[-1] == UNK:
symbols.append(SP)
stress.append(0)
for phone, level in word:
mapped = canonical(phone)
if mapped is None:
unknown.append(phone)
mapped = (UNK,)
# A fallback may expand to several phones: stress goes to its first vowel.
carrier = next((i for i, item in enumerate(mapped) if item in VOWEL_SET), 0)
for index, item in enumerate(mapped):
symbols.append(item)
stress.append(level if index == carrier else 0)
symbols.append(EOS)
stress.append(0)
if not any(s in PHONE_SET or s == UNK for s in symbols):
raise NothingToPronounce("the text has nothing to pronounce")
return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown))
def phonemize(text):
if not isinstance(text, str) or not text.strip():
raise ValueError("text must not be empty")
if _frontend == "own":
return tokenize(_dizione().pieces(text))
pieces = []
for punctuation, piece in chunks(normalize_text(text)):
pieces.append((True, piece) if punctuation else (False, espeak_words(piece)))
return tokenize(pieces)
def phonemize_ptbr(text: str) -> tuple[list[int], list[int]]:
"""Return ``(ids, stress)`` lists for Brazilian Portuguese text."""
result = phonemize(text)
return list(result.ids), list(result.stress)
def is_phone(token_ids):
"""Boolean list/tensor helper: tokens that must be realised as audio."""
return [int(i) in PHONE_IDS for i in token_ids]12345678910111213141516171819202122232425262728293031"""Training pipelines for Lua Nova V1 (Stage 1, ProsodyFlow, CFM v5, Option A E2E, Option B Vocoder)."""
from .common import (
VALIDATION_SAMPLE_TEXTS,
atomic_save,
balanced_indices,
cfm_loss_step,
check_leakage,
cosine_lr,
export_cfm_checkpoint,
load_cfm_model,
masked_std,
precompute_bigvgan_mels,
update_ema,
validate_cfm,
)
__all__ = [
"VALIDATION_SAMPLE_TEXTS",
"atomic_save",
"balanced_indices",
"cfm_loss_step",
"check_leakage",
"cosine_lr",
"export_cfm_checkpoint",
"load_cfm_model",
"masked_std",
"precompute_bigvgan_mels",
"update_ema",
"validate_cfm",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269"""Train LuaNovaCFM in 24 kHz 100-band Slaney mel space for BigVGAN."""
from __future__ import annotations
import argparse
from collections import defaultdict
import copy
import json
from pathlib import Path
import time
import torch
from torch import nn
from ..config import CFMConfig, Config
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
from ..models.bigvgan import BigVGANMelExtractor
from ..models.cfm import LuaNovaCFM
from .common import (
MelDatasetView,
atomic_save,
balanced_indices,
cfm_loss_step,
check_leakage,
cosine_lr,
export_cfm_checkpoint,
precompute_bigvgan_mels,
update_ema,
validate_cfm,
)
_WARM_PREFIXES = (
"tokens.",
"stress.",
"voices.",
"encoder.",
"duration.",
"frame_voices.",
"frame_position.",
"prosody_stack.",
"prosody_head.",
"context_adapter.",
"frame_ctx_proj.",
"dur_flow.",
"prosody_flow.",
"acoustic_stack.",
"prosody_projection.",
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--train", type=Path, required=True)
parser.add_argument("--validation", type=Path, required=True)
parser.add_argument("--init-cfm", type=Path, default=None, help="Initial LuaNovaCFM checkpoint (ProsodyFlow or pretrained CFM)")
parser.add_argument("--init-frontend", type=Path, default=None, help="Optional Stage 1 checkpoint when starting without a CFM checkpoint")
parser.add_argument("--freeze-frontend", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--resume", type=Path, default=None)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--device", default="cuda")
parser.add_argument("--steps", type=int, default=25000)
parser.add_argument("--stop-after", type=int, default=None)
parser.add_argument("--batch-frames", type=int, default=6000)
parser.add_argument("--max-batch", type=int, default=24)
parser.add_argument("--lr", type=float, default=3e-4)
parser.add_argument("--min-lr", type=float, default=1.5e-5)
parser.add_argument("--warmup", type=int, default=500)
parser.add_argument("--ema-decay", type=float, default=0.999)
parser.add_argument("--prior-weight", type=float, default=0.8)
parser.add_argument("--delta-weight", type=float, default=1.0)
parser.add_argument("--freq-delta-weight", type=float, default=0.50)
parser.add_argument("--hf-boost", type=float, default=1.40)
parser.add_argument("--teacher-prob", type=float, default=0.35)
parser.add_argument("--f0-smooth-prob", type=float, default=0.15)
parser.add_argument("--save-every", type=int, default=5000)
parser.add_argument("--val-every", type=int, default=1000)
parser.add_argument("--log-every", type=int, default=100)
parser.add_argument("--seed", type=int, default=20261121)
args = parser.parse_args()
if args.init_cfm is None and args.init_frontend is None:
parser.error("provide --init-cfm or --init-frontend")
torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
src_ckpt = torch.load(args.init_cfm or args.init_frontend, map_location="cpu", weights_only=True)
if args.init_cfm is not None:
cfg_dict = dict(src_ckpt["cfm_config"])
else:
cfg_dict = {"base": dict(src_ckpt["config"]), "acoustic_from_frames": True, "use_energy_gate": True}
cfg_dict.update(
{
"flow_channels": 320,
"flow_layers": 8,
"flow_heads": 8,
"flow_feedforward": 1024,
"flow_kernel": 5,
"flow_dropout": 0.05,
"prior_sigma": 0.45,
"cfg_dropout": 0.10,
"default_pitch_range": 1.05,
"mel_space": "bigvgan_24k_100",
}
)
cfm_cfg = CFMConfig.from_dict(cfg_dict)
base_cfg = cfm_cfg.base
train_ds = AnnotatedDataset(args.train, base_cfg, voiced_vowels=True, cache=True)
val_ds = AnnotatedDataset(args.validation, base_cfg, voiced_vowels=True, cache=True)
check_leakage(train_ds, val_ds)
pool = list(range(len(train_ds)))
val_indices = balanced_indices(val_ds, len(val_ds))
print(f"Preloading train ({len(pool)}) and validation ({len(val_indices)}) ...", flush=True)
train_ds.preload(pool, workers=8)
val_ds.preload(val_indices, workers=4)
t_mel = time.perf_counter()
extractor = BigVGANMelExtractor().to(args.device).eval()
train_bg, bg_mean, bg_scale = precompute_bigvgan_mels(train_ds, pool, extractor, args.device, compute_stats=True)
val_bg, _, _ = precompute_bigvgan_mels(val_ds, val_indices, extractor, args.device, compute_stats=False)
del extractor
print(
f"Precomputed BigVGAN Slaney mels in {time.perf_counter() - t_mel:.2f}s | "
f"mean range=[{float(bg_mean.min()):.3f}, {float(bg_mean.max()):.3f}] "
f"scale range=[{float(bg_scale.min()):.3f}, {float(bg_scale.max()):.3f}]",
flush=True,
)
model = LuaNovaCFM(cfm_cfg).to(args.device)
loaded = []
if args.init_cfm is not None:
own = dict(model.state_dict())
for k, v in src_ckpt["model"].items():
if (args.freeze_frontend and k.startswith(_WARM_PREFIXES) or not args.freeze_frontend) and k in own and own[k].shape == v.shape:
if not (k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale")):
own[k] = v.to(own[k].device)
loaded.append(k)
model.load_state_dict(own, strict=True)
if not any(k == "vocoder.mel_mean" for k in loaded) or float(model.vocoder.mel_scale.std()) < 1e-6:
model.vocoder.set_mel_stats(bg_mean, bg_scale)
else:
s1_sd = src_ckpt.get("system", src_ckpt.get("model"))
loaded = model.load_frontend(s1_sd)
model.vocoder.set_mel_stats(bg_mean, bg_scale)
if str(src_ckpt.get("cfm_config", {}).get("mel_space")) != "bigvgan_24k_100":
model.vocoder.set_mel_stats(bg_mean, bg_scale)
model.freeze_frontend(args.freeze_frontend)
for p in model.vocoder.parameters():
p.requires_grad_(False)
del src_ckpt
ema_model = copy.deepcopy(model).eval()
for p in ema_model.parameters():
p.requires_grad_(False)
trainable = [p for p in model.parameters() if p.requires_grad]
trainable_prefixes = sorted({n.split(".")[0] for n, p in model.named_parameters() if p.requires_grad})
print(
f"CFM v5 initialized ({len(loaded)} tensors) | trainable prefixes={trainable_prefixes} | "
f"trainable params={sum(p.numel() for p in trainable):,} / {sum(p.numel() for p in model.parameters()):,}",
flush=True,
)
optimizer = torch.optim.AdamW(trainable, lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
step = 0
if args.resume is not None and args.resume.exists():
rs = torch.load(args.resume, map_location=args.device, weights_only=True)
model.load_state_dict(rs["model"], strict=True)
ema_model.load_state_dict(rs["ema_model"], strict=True)
optimizer.load_state_dict(rs["optimizer"])
sampler.generator.set_state(rs["sampler_rng"].cpu())
sampler.pending = list(rs["sampler_pending"])
step = int(rs["step"])
print(f"Resumed CFM from step {step}", flush=True)
train_view = MelDatasetView(train_ds, train_bg)
val_view = MelDatasetView(val_ds, val_bg)
args.output.mkdir(parents=True, exist_ok=True)
(args.output / "cfm_config.json").write_text(json.dumps(cfm_cfg.to_dict(), indent=2) + "\n", encoding="utf-8")
if step == 0:
v0 = validate_cfm(ema_model, val_view, val_indices, args.device, args.delta_weight, args.freq_delta_weight, args.hf_boost)
print(f"[step 0] {json.dumps(v0)}", flush=True)
target_stop = min(args.steps, args.stop_after) if args.stop_after is not None else args.steps
use_amp = str(args.device).startswith("cuda")
model.train()
win: dict[str, float] = defaultdict(float)
win_steps = 0
win_t = time.monotonic()
while step < target_stop:
lr = cosine_lr(step, args.warmup, args.steps, args.lr, min_lr=args.min_lr)
for pg in optimizer.param_groups:
pg["lr"] = lr
batch = collate([train_view[pool[i]] for i in sampler.next()], args.device)
optimizer.zero_grad(set_to_none=True)
with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=use_amp):
loss, m = cfm_loss_step(
model,
batch,
teacher_prob=args.teacher_prob,
prior_weight=args.prior_weight,
delta_weight=args.delta_weight,
freq_delta_weight=args.freq_delta_weight,
hf_boost=args.hf_boost,
f0_smooth_prob=args.f0_smooth_prob,
training=True,
)
loss_f = loss.float()
if not torch.isfinite(loss_f):
raise RuntimeError(f"Non-finite loss at step {step}: {loss_f}")
loss_f.backward()
grad_norm = float(nn.utils.clip_grad_norm_(trainable, 1.0))
optimizer.step()
update_ema(ema_model, model, args.ema_decay)
step += 1
for k, v in m.items():
win[k] += v
win["grad_norm"] += grad_norm
win_steps += 1
do_val = (step % args.val_every == 0) or (step == target_stop)
do_save = (step % args.save_every == 0) or (step == target_stop)
do_log = (step % args.log_every == 0) or do_val or do_save
if do_log:
if use_amp:
torch.cuda.synchronize()
dt = max(time.monotonic() - win_t, 1e-6)
rec = {k: round(v / win_steps, 5) for k, v in win.items()}
rec.update(step=step, lr=round(lr, 7), steps_per_s=round(win_steps / dt, 2))
if do_val:
val_m = validate_cfm(
ema_model, val_view, val_indices, args.device, args.delta_weight, args.freq_delta_weight, args.hf_boost
)
rec.update({k: round(val, 5) for k, val in val_m.items()})
with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as mf:
mf.write(json.dumps(rec) + "\n")
print(f"[step {step:05d}] {json.dumps(rec)}", flush=True)
win = defaultdict(float)
win_steps = 0
win_t = time.monotonic()
if do_save:
export_cfm_checkpoint(ema_model, args.output / "inference_v5_ema.pt", step, train_ds.annotation)
export_cfm_checkpoint(ema_model, args.output / f"inference_v5_step-{step:06d}.pt", step, train_ds.annotation)
atomic_save(
{
"step": step,
"model": model.state_dict(),
"ema_model": ema_model.state_dict(),
"optimizer": optimizer.state_dict(),
"sampler_rng": sampler.generator.get_state(),
"sampler_pending": sampler.pending,
},
args.output / "cfm_v5_last.pt",
)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474"""Option A: E2E fine-tuning of LuaNovaCFM v5 through frozen MIT BigVGAN and frozen NVIDIA pretrained MPD/MRD."""
from __future__ import annotations
import argparse
from collections import defaultdict
import copy
import json
import math
from pathlib import Path
import time
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
from ..models.bigvgan import BigVGANMelExtractor, _ensure_bigvgan_importable
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
from ..models.losses import SpectralLoss, masked_mean
from .common import (
MelDatasetView,
balanced_indices,
check_leakage,
cosine_lr,
export_cfm_checkpoint,
load_cfm_model,
precompute_bigvgan_mels,
update_ema,
)
def _unrolled_ode_sample(
model: LuaNovaCFM,
cond: torch.Tensor,
prior_mel: torch.Tensor,
frame_mask: torch.Tensor,
f0_feats: torch.Tensor | None,
n_steps: int,
cfg_scale: float,
temperature: float,
solver: str,
sway_coef: float,
use_checkpoint: bool = True,
noise_gate: torch.Tensor | None = None,
) -> torch.Tensor:
sigma = model.cfm_config.prior_sigma * temperature
eps = torch.randn_like(prior_mel)
noise = sigma * eps if noise_gate is None else sigma * noise_gate * eps
x = (prior_mel + noise) * frame_mask[..., None]
zero_cond = torch.zeros_like(cond)
zero_prior = torch.zeros_like(prior_mel)
zero_f0 = torch.zeros_like(f0_feats) if f0_feats is not None else None
def velocity(x_cur: torch.Tensor, t_val: float) -> torch.Tensor:
t_vec = torch.full((x_cur.shape[0],), t_val, device=x_cur.device, dtype=torch.float32)
v_c = model.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
if cfg_scale == 1.0:
return v_c
v_u = model.flow(x_cur, t_vec, zero_cond, zero_prior, frame_mask, f0_feats=zero_f0)
return v_u + cfg_scale * (v_c - v_u)
def one_step(x_in: torch.Tensor, t0_val: float, dt_val: float) -> torch.Tensor:
if solver == "midpoint":
v0 = velocity(x_in, t0_val)
x_mid = (x_in + 0.5 * dt_val * v0) * frame_mask[..., None]
v_mid = velocity(x_mid, t0_val + 0.5 * dt_val)
return (x_in + dt_val * v_mid) * frame_mask[..., None]
v0 = velocity(x_in, t0_val)
return (x_in + dt_val * v0) * frame_mask[..., None]
t_grid = model.sway_time_grid(n_steps, sway_coef)
for i in range(n_steps):
t0, t1 = t_grid[i], t_grid[i + 1]
dt_i = t1 - t0
if use_checkpoint and model.training and x.requires_grad:
x = checkpoint(lambda x_s, a=t0, d=dt_i: one_step(x_s, a, d), x, use_reentrant=False)
else:
x = one_step(x, t0, dt_i)
return x
def _lr_at(step: int, warmup: int, total_steps: int, base_lr: float, min_lr: float = 4e-6) -> float:
if step < warmup:
return base_lr * (step + 1) / max(warmup, 1)
prog = min(max((step - warmup) / max(total_steps - warmup, 1), 0.0), 1.0)
return min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * prog))
def option_a_micro_step(
model: LuaNovaCFM,
voc_net: nn.Module,
mpd: nn.Module,
mrd: nn.Module,
ext: BigVGANMelExtractor,
spectral: SpectralLoss,
feature_loss_fn,
generator_loss_fn,
batch: dict,
args,
use_bf16: bool,
) -> tuple[torch.Tensor, dict[str, float]]:
c = model.config
hop = int(c.hop)
with torch.no_grad():
hidden, tok_mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
p_tok_ctx, c_ctx_tok = model.encode_prosody_context(hidden, batch["tokens"], batch["stress"], tok_mask)
ac_f, pr_f, fmask, flen = model.expand_with_context(hidden, p_tok_ctx, c_ctx_tok, batch["durations"], tok_mask, batch["speakers"])
_, pred_pros, _ = model.sample_prosody(pr_f, fmask, seed=0)
if args.teacher_prob > 0.0:
teach = torch.rand(len(flen), device=flen.device) < args.teacher_prob
condition = torch.where(teach[:, None, None], batch["prosody"], model.hard_prosody(pred_pros))
else:
condition = model.hard_prosody(pred_pros)
if args.f0_smooth_prob > 0.0:
condition = smooth_f0_channel(condition, args.f0_smooth_prob)
base_h = ac_f if model.cfm_config.acoustic_from_frames else pr_f
f0_feats = f0_features(condition, fmask) if model.cfm_config.use_f0_harmonics else None
noise_gate = energy_noise_gate(condition, fmask) if model.cfm_config.use_energy_gate else None
x1 = ((batch["vocos_mel"] - model.vocoder.mel_mean) / model.vocoder.mel_scale) * fmask[..., None]
ch_w = torch.ones((1, 1, c.vocos_n_mels), device=x1.device, dtype=torch.float32)
ch_w[..., 60:] = args.hf_boost
ch_w = ch_w / ch_w.mean()
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
cond, prior_mel = model.condition_and_prior(base_h, condition, fmask)
mel_norm = _unrolled_ode_sample(
model, cond, prior_mel, fmask, f0_feats,
n_steps=args.ode_steps, cfg_scale=1.0, temperature=args.ode_temp,
solver="midpoint", sway_coef=args.sway_coef, use_checkpoint=True, noise_gate=noise_gate,
)
# Anchor CFM velocity on full sequence to preserve manifold alignment
t_anc = torch.sigmoid(torch.randn(x1.shape[0], device=x1.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
eps_anc = torch.randn_like(x1)
if noise_gate is not None:
eps_anc = eps_anc * noise_gate
x0_anc = (prior_mel.detach().float() + model.cfm_config.prior_sigma * eps_anc) * fmask[..., None]
xt_anc = ((1.0 - t_anc[:, None, None]) * x0_anc + t_anc[:, None, None] * x1) * fmask[..., None]
v_pred_anc = model.flow(xt_anc, t_anc, cond, prior_mel.detach(), fmask, f0_feats=f0_feats)
cfm_anchor = masked_mean(((v_pred_anc.float() - (x1 - x0_anc)).abs() * ch_w).mean(-1), fmask)
mel_f = mel_norm.float()
mel_l1 = masked_mean(((mel_f - x1).abs() * ch_w).mean(-1), fmask)
pair_mask = fmask[:, 1:] & fmask[:, :-1]
delta_l = masked_mean(((mel_f[:, 1:] - mel_f[:, :-1]) - (x1[:, 1:] - x1[:, :-1])).abs().mean(-1), pair_mask)
fdelta_l = masked_mean(((mel_f[..., 1:] - mel_f[..., :-1]) - (x1[..., 1:] - x1[..., :-1])).abs().mean(-1), fmask)
# Interior window crop -> frozen BigVGAN -> edge trim -> frozen STFT / Mel / MPD / MRD losses
b_sz = mel_f.shape[0]
crop_f = min(int(args.crop_frames), int(flen.min().item()))
starts = [
int(torch.randint(0, int(flen[i].item()) - crop_f + 1, (1,)).item()) if int(flen[i].item()) > crop_f else 0
for i in range(b_sz)
]
mel_crop = torch.stack([mel_f[i, s0 : s0 + crop_f] for i, s0 in enumerate(starts)], dim=0)
gt_crop = torch.stack([batch["wave"][i, s0 * hop : (s0 + crop_f) * hop] for i, s0 in enumerate(starts)], dim=0)[:, None, :]
phys_crop = (mel_crop * model.vocoder.mel_scale + model.vocoder.mel_mean).clamp(min=-11.512925)
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
pred_wav = voc_net(phys_crop.transpose(1, 2).contiguous())
trim = min(int(args.edge_trim), pred_wav.shape[-1] // 8)
pred_trim = pred_wav[:, :, trim:-trim] if trim > 0 else pred_wav
gt_trim = gt_crop[:, :, trim:-trim] if trim > 0 else gt_crop
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
_, y_df_g, fmap_f_r, fmap_f_g = mpd(gt_trim, pred_trim)
pred_32 = pred_trim.float()
gt_32 = gt_trim.float()
with torch.amp.autocast("cuda", enabled=False):
_, y_ds_g, fmap_s_r, fmap_s_g = mrd(gt_32, pred_32)
trim_len = torch.full((b_sz,), pred_32.shape[-1], device=x1.device, dtype=torch.long)
stft_l, _ = spectral(pred_32.squeeze(1), gt_32.squeeze(1), trim_len)
wmel_l = F.l1_loss(ext(pred_32.squeeze(1)), ext(gt_32.squeeze(1)))
fm_l = (
feature_loss_fn([[a.float() for a in l] for l in fmap_f_r], [[a.float() for a in l] for l in fmap_f_g])
+ feature_loss_fn(fmap_s_r, fmap_s_g)
)
adv_l = generator_loss_fn([t.float() for t in y_df_g])[0] + generator_loss_fn(y_ds_g)[0]
loss = (
args.w_cfm_anchor * cfm_anchor
+ args.w_mel * mel_l1
+ args.w_delta * delta_l
+ args.w_fdelta * fdelta_l
+ args.w_stft * stft_l
+ args.w_wmel * wmel_l
+ args.w_fm * fm_l
+ args.w_adv * adv_l
)
stats = {
"loss": float(loss.detach()),
"stft": float(stft_l.detach()),
"wmel": float(wmel_l.detach()),
"fm": float(fm_l.detach()),
"adv": float(adv_l.detach()),
"anc": float(cfm_anchor.detach()),
"mel": float(mel_l1.detach()),
"delta": float(delta_l.detach()),
}
return loss, stats
@torch.no_grad()
def validate_option_a(
ema_model: LuaNovaCFM,
voc_net: nn.Module,
ext: BigVGANMelExtractor,
spectral: SpectralLoss,
val_ds: AnnotatedDataset,
val_gt: dict[int, torch.Tensor],
val_indices: list[int],
args,
) -> dict[str, float]:
ema_model.eval()
stft_tot, wmel_tot, dt_tot, n = 0.0, 0.0, 0.0, 0
hop = int(ema_model.config.hop)
for idx in val_indices:
it = val_ds[idx]
gt_wav = it["wave"][None].to(device=args.device, dtype=torch.float32)
gt_m = val_gt[idx][None].to(device=args.device, dtype=torch.float32)
tok = it["tokens"][None].to(args.device)
st = it["stress"][None].to(args.device)
tl = torch.tensor([tok.shape[1]], device=args.device)
sp = torch.tensor([int(it["speaker"])], device=args.device)
dur = it["durations"][None].to(args.device)
h, m = ema_model.encode(tok, st, tl, sp)
pt, ct = ema_model.encode_prosody_context(h, tok, st, m)
af, pr_f, fm, fl = ema_model.expand_with_context(h, pt, ct, dur, m, sp)
_, pred_pros, _ = ema_model.sample_prosody(pr_f, fm, seed=0)
cond_p = ema_model.hard_prosody(pred_pros)
base_h = af if ema_model.cfm_config.acoustic_from_frames else pr_f
cond, prior_mel = ema_model.condition_and_prior(base_h, cond_p, fm)
f0f = f0_features(cond_p, fm) if ema_model.cfm_config.use_f0_harmonics else None
ng = energy_noise_gate(cond_p, fm) if ema_model.cfm_config.use_energy_gate else None
mel_norm = ema_model.sample_mel(
cond, prior_mel, fm, n_steps=args.ode_steps, cfg_scale=1.0,
temperature=args.ode_temp, solver="midpoint", seed=0,
f0_feats=f0f, noise_gate=ng, sway_coef=args.sway_coef,
)
phys = (mel_norm.float() * ema_model.vocoder.mel_scale + ema_model.vocoder.mel_mean).clamp(min=-11.512925)
pred_wav = voc_net(phys.transpose(1, 2).contiguous()).squeeze(1)[:, : int(fl[0]) * hop]
s_len = torch.tensor([pred_wav.shape[-1]], device=args.device, dtype=torch.long)
stft_l, _ = spectral(pred_wav, gt_wav, s_len)
rec_m = ext(pred_wav)
n_f = min(rec_m.shape[1], gt_m.shape[1])
wmel_l = F.l1_loss(rec_m[:, :n_f], gt_m[:, :n_f])
dt_mel = (rec_m[:, 1:n_f] - rec_m[:, : n_f - 1]).abs().mean()
stft_tot += float(stft_l)
wmel_tot += float(wmel_l)
dt_tot += float(dt_mel)
n += 1
return {
"val_stft": stft_tot / max(n, 1),
"val_wmel": wmel_tot / max(n, 1),
"val_dt_mel": dt_tot / max(n, 1),
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--train", type=Path, required=True)
parser.add_argument("--validation", type=Path, required=True)
parser.add_argument("--init-v5", type=Path, required=True)
parser.add_argument("--vocoder-id", default="nvidia/bigvgan_base_24khz_100band")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--device", default="cuda")
parser.add_argument("--steps", type=int, default=4000)
parser.add_argument("--batch-size", type=int, default=4)
parser.add_argument("--grad-accum", type=int, default=3)
parser.add_argument("--crop-frames", type=int, default=40)
parser.add_argument("--edge-trim", type=int, default=512)
parser.add_argument("--ode-steps", type=int, default=4)
parser.add_argument("--ode-temp", type=float, default=0.40)
parser.add_argument("--sway-coef", type=float, default=-0.5)
parser.add_argument("--lr", type=float, default=4e-5)
parser.add_argument("--min-lr", type=float, default=4e-6)
parser.add_argument("--warmup", type=int, default=200)
parser.add_argument("--ema-decay", type=float, default=0.995)
parser.add_argument("--teacher-prob", type=float, default=0.35)
parser.add_argument("--f0-smooth-prob", type=float, default=0.15)
parser.add_argument("--hf-boost", type=float, default=1.40)
parser.add_argument("--w-cfm-anchor", type=float, default=1.0)
parser.add_argument("--w-mel", type=float, default=0.5)
parser.add_argument("--w-delta", type=float, default=0.8)
parser.add_argument("--w-fdelta", type=float, default=0.4)
parser.add_argument("--w-stft", type=float, default=1.5)
parser.add_argument("--w-wmel", type=float, default=2.0)
parser.add_argument("--w-fm", type=float, default=0.08)
parser.add_argument("--w-adv", type=float, default=0.05)
parser.add_argument("--val-every", type=int, default=500)
parser.add_argument("--log-every", type=int, default=10)
parser.add_argument("--save-steps", nargs="+", type=int, default=[1500, 3000, 4000])
parser.add_argument("--seed", type=int, default=20261123)
args = parser.parse_args()
torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
_ensure_bigvgan_importable()
import bigvgan
from discriminators import MultiPeriodDiscriminator, MultiResolutionDiscriminator
from huggingface_hub import hf_hub_download
from loss import feature_loss, generator_loss
model = load_cfm_model(args.init_v5, args.device)
model.freeze_frontend(True)
for p in model.vocoder.parameters():
p.requires_grad_(False)
ema_model = copy.deepcopy(model).eval()
for p in ema_model.parameters():
p.requires_grad_(False)
trainable = [p for p in model.parameters() if p.requires_grad]
trainable_prefixes = sorted({n.split(".")[0] for n, p in model.named_parameters() if p.requires_grad})
voc_net = bigvgan.BigVGAN.from_pretrained(args.vocoder_id, use_cuda_kernel=False)
voc_net.remove_weight_norm()
voc_net = voc_net.eval().to(args.device)
for p in voc_net.parameters():
p.requires_grad_(False)
do_path = hf_hub_download(args.vocoder_id, "bigvgan_discriminator_optimizer.pt")
do_ckpt = torch.load(do_path, map_location="cpu", weights_only=True)
mpd = MultiPeriodDiscriminator(voc_net.h).to(args.device)
mrd = MultiResolutionDiscriminator(voc_net.h).to(args.device)
mpd.load_state_dict(do_ckpt["mpd"], strict=True)
mrd.load_state_dict(do_ckpt["mrd"], strict=True)
del do_ckpt
for mod in (mpd, mrd):
mod.eval()
for p in mod.parameters():
p.requires_grad_(False)
train_ds = AnnotatedDataset(args.train, model.config, voiced_vowels=True, cache=True)
val_ds = AnnotatedDataset(args.validation, model.config, voiced_vowels=True, cache=True)
check_leakage(train_ds, val_ds)
pool = [i for i in range(len(train_ds)) if train_ds.lengths[i] >= args.crop_frames]
val_indices = balanced_indices(val_ds, len(val_ds))
print(f"Preloading train ({len(pool)}) and validation ({len(val_indices)}) ...", flush=True)
train_ds.preload(pool, workers=8)
val_ds.preload(val_indices, workers=4)
ext = BigVGANMelExtractor().to(args.device).eval()
t_mel = time.perf_counter()
train_bg, _, _ = precompute_bigvgan_mels(train_ds, pool, ext, args.device, compute_stats=False)
val_bg, _, _ = precompute_bigvgan_mels(val_ds, val_indices, ext, args.device, compute_stats=False)
print(
f"Precomputed BigVGAN mels in {time.perf_counter() - t_mel:.2f}s | trainable={trainable_prefixes} "
f"({sum(p.numel() for p in trainable):,} params)",
flush=True,
)
spectral = SpectralLoss(
model.config.sample_rate,
resolutions=((256, 64), (512, 128), (1024, 256), (2048, 512)),
mel=(1024, 256, 80),
).to(args.device)
train_view = MelDatasetView(train_ds, train_bg)
sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_size * 500, args.batch_size, args.seed)
optimizer = torch.optim.AdamW(trainable, lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
is_cuda = torch.cuda.is_available() and str(args.device).startswith("cuda")
use_bf16 = is_cuda
grad_accum = max(int(args.grad_accum), 1)
args.output.mkdir(parents=True, exist_ok=True)
log_f = (args.output / "train.log").open("a", encoding="utf-8", buffering=1)
def emit(msg: str) -> None:
print(msg, flush=True)
log_f.write(msg + "\n")
log_f.flush()
if is_cuda:
torch.cuda.reset_peak_memory_stats(args.device)
v0 = validate_option_a(ema_model, voc_net, ext, spectral, val_ds, val_bg, val_indices, args)
emit(f"[step 0] {json.dumps(v0)}")
win = defaultdict(float)
win_n = 0
win_t = time.monotonic()
save_set = set(int(s) for s in args.save_steps) | {int(args.steps)}
try:
for step in range(args.steps):
lr = cosine_lr(step, args.warmup, args.steps, args.lr, min_lr=args.min_lr)
for pg in optimizer.param_groups:
pg["lr"] = lr
model.train()
optimizer.zero_grad(set_to_none=True)
acc = defaultdict(float)
for _micro in range(grad_accum):
batch_ids = [pool[i] for i in sampler.next()]
batch = collate([train_view[i] for i in batch_ids], args.device)
loss_mb, st_mb = option_a_micro_step(
model, voc_net, mpd, mrd, ext, spectral, feature_loss, generator_loss,
batch, args, use_bf16=use_bf16,
)
if not torch.isfinite(loss_mb):
raise RuntimeError(f"Non-finite loss at step {step}: {loss_mb}")
(loss_mb / grad_accum).backward()
for k, v in st_mb.items():
acc[k] += v / grad_accum
del batch, loss_mb
grad_norm = float(nn.utils.clip_grad_norm_(trainable, 1.0))
optimizer.step()
update_ema(ema_model, model, args.ema_decay)
cur = step + 1
for k, v in acc.items():
win[k] += v
win["grad_norm"] += grad_norm
win_n += 1
do_val = (cur % args.val_every == 0) or (cur == args.steps)
do_save = cur in save_set
do_log = (cur % args.log_every == 0) or (cur == 1) or do_val or do_save
if do_log:
if is_cuda:
torch.cuda.synchronize()
dt = max(time.monotonic() - win_t, 1e-6)
it_s = win_n / dt
eta_min = (args.steps - cur) / max(it_s, 1e-6) / 60.0
vram_gb = (torch.cuda.memory_allocated(args.device) / 1e9) if is_cuda else 0.0
vram_peak_gb = (torch.cuda.max_memory_allocated(args.device) / 1e9) if is_cuda else 0.0
rec = {k: round(v / win_n, 4) for k, v in win.items()}
rec.update(
step=cur,
lr=round(lr, 7),
it_s=round(it_s, 2),
eta_min=round(eta_min, 2),
vram_gb=round(vram_gb, 2),
vram_peak_gb=round(vram_peak_gb, 2),
)
if do_val:
val_m = validate_option_a(ema_model, voc_net, ext, spectral, val_ds, val_bg, val_indices, args)
rec.update({k: round(v, 5) for k, v in val_m.items()})
with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as mf:
mf.write(json.dumps(rec) + "\n")
mf.flush()
pct = 100.0 * cur / max(args.steps, 1)
msg = (
f"[step {cur:05d}/{args.steps:05d} | {pct:5.1f}%] "
f"loss={rec['loss']:.3f} stft={rec['stft']:.3f} wmel={rec['wmel']:.3f} "
f"fm={rec['fm']:.2f} adv={rec['adv']:.2f} anc={rec['anc']:.3f} | "
f"{rec['it_s']:.2f} it/s | ETA {rec['eta_min']:.1f}m | VRAM {rec['vram_gb']:.2f}/{rec['vram_peak_gb']:.2f} GB"
)
if do_val:
msg += f" | val_stft={rec['val_stft']:.5f} val_wmel={rec['val_wmel']:.5f} val_dt={rec['val_dt_mel']:.4f}"
emit(msg)
win = defaultdict(float)
win_n = 0
win_t = time.monotonic()
if do_save:
export_cfm_checkpoint(ema_model, args.output / f"inference_v5_e2e_step-{cur:06d}.pt", cur, train_ds.annotation)
export_cfm_checkpoint(ema_model, args.output / "inference_v5_e2e_ema.pt", cur, train_ds.annotation)
finally:
log_f.close()
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315"""Shared training utilities for Lua Nova V1."""
from __future__ import annotations
from collections import defaultdict
import json
import math
from pathlib import Path
import torch
from torch import nn
from ..config import CHECKPOINT_FORMAT, CFMConfig
from ..data.dataset import AnnotatedDataset, collate
from ..models.bigvgan import BigVGANMelExtractor
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
from ..models.losses import masked_mean
from ..text.phonemizer import frontend_fingerprint, frontend_identity
from ..utils.checkpoint import atomic_save
VALIDATION_SAMPLE_TEXTS = (
"Amanhã de manhã eu vou pôr o pão na mesa para os irmãos.",
"Eu almoço cedo quando o almoço está pronto no jogo.",
"Dia vinte e dois de março às quatorze horas custou duzentos reais.",
"Você tem certeza de que ele vem hoje à tarde?",
)
def masked_std(value: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""Standard deviation per row over valid masked positions, returning ``[B]``."""
count = mask.sum(1).clamp_min(1)
mean = (value * mask).sum(1) / count
return (((value - mean[:, None]).square() * mask).sum(1) / count + 1e-8).sqrt()
def balanced_indices(dataset: AnnotatedDataset, limit: int) -> list[int]:
"""Deterministic round-robin sample indices balanced across speakers."""
groups: dict[str, list[int]] = defaultdict(list)
for i, row in enumerate(dataset.rows):
groups[row["speaker"]].append(i)
limit = min(max(limit, len(groups)), len(dataset.rows))
selected: list[int] = []
for offset in range(limit):
for voice in sorted(groups):
if offset < len(groups[voice]):
selected.append(groups[voice][offset])
if len(selected) == limit:
return selected
return selected
def check_leakage(train: AnnotatedDataset, validation: AnnotatedDataset) -> None:
"""Ensure zero ID or text overlap between training and validation splits."""
ids = {r["id"] for r in train.rows}
texts: dict[str, list[str]] = defaultdict(list)
for row in train.rows:
texts[row["text_hash"]].append(row["id"])
collisions = []
for row in validation.rows:
if row["id"] in ids or row["text_hash"] in texts:
collisions.append(
{
"validation_id": row["id"],
"train_ids": texts.get(row["text_hash"], [])[:3],
"text": row.get("text", "")[:160],
}
)
if len(collisions) == 5:
break
if collisions:
raise ValueError("train/validation leakage detected: " + json.dumps(collisions, ensure_ascii=False))
def cosine_lr(step: int, warmup: int, total_steps: int, base_lr: float, min_lr: float) -> float:
"""Linear warmup followed by cosine decay down to ``min_lr``."""
if step < warmup:
return base_lr * (step + 1) / max(warmup, 1)
prog = min(max((step - warmup) / max(total_steps - warmup, 1), 0.0), 1.0)
return min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * prog))
def update_ema(ema_model: nn.Module, model: nn.Module, decay: float, on_cpu: bool = False) -> None:
"""Update exponential moving average parameters matching trainable flags on GPU or CPU."""
with torch.no_grad():
for p_ema, p in zip(ema_model.parameters(), model.parameters()):
if p.requires_grad:
src = p.detach().cpu() if on_cpu else p
p_ema.mul_(decay).add_(src, alpha=1.0 - decay)
def export_cfm_checkpoint(model: LuaNovaCFM, path: Path | str, step: int, annotation: str | None = None) -> None:
"""Save a portable LuaNovaCFM checkpoint containing config, frontend identity, and state_dict."""
atomic_save(
{
"format_version": CHECKPOINT_FORMAT,
"arch": "lua_nova_v1_cfm",
"cfm_config": model.cfm_config.to_dict(),
"step": int(step),
"frontend": {**frontend_identity(), "fingerprint": frontend_fingerprint()},
"annotation": annotation,
"model": {k: v.detach().cpu() for k, v in model.state_dict().items()},
},
path,
)
def load_cfm_model(
path: Path | str,
device: str = "cpu",
load_vocos: bool | None = None,
) -> LuaNovaCFM:
"""Load a LuaNovaCFM checkpoint (either full or stripped of legacy Vocos buffers)."""
state = torch.load(path, map_location="cpu", weights_only=True)
cfg = CFMConfig.from_dict(state["cfm_config"])
use_vocos = (cfg.mel_space == "vocos") if load_vocos is None else bool(load_vocos)
model = LuaNovaCFM(cfg, load_vocos=use_vocos)
sd = state["model"]
if not use_vocos:
# Filter unused legacy Vocos weights while keeping strict validation over all active tensors.
sd = {
k: v.float()
for k, v in sd.items()
if not (k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale"))
}
model.load_state_dict(sd, strict=True)
return model.to(device).eval()
class MelDatasetView:
"""In-memory view overriding ``vocos_mel`` with precomputed BigVGAN Slaney-100 mels."""
def __init__(self, ds: AnnotatedDataset, mels: dict[int, torch.Tensor]) -> None:
self.ds = ds
self.mels = mels
def __getitem__(self, idx: int) -> dict:
item = dict(self.ds[idx])
item["vocos_mel"] = self.mels[idx].float()
return item
@torch.no_grad()
def precompute_bigvgan_mels(
ds: AnnotatedDataset,
indices: list[int],
extractor: BigVGANMelExtractor,
device: str,
compute_stats: bool = False,
) -> tuple[dict[int, torch.Tensor], torch.Tensor | None, torch.Tensor | None]:
"""Extract unpadded 24 kHz 100-band Slaney log-mels in RAM without rewriting disk files."""
mels: dict[int, torch.Tensor] = {}
sum_1 = torch.zeros(extractor.n_mels, dtype=torch.float64, device=device)
sum_2 = torch.zeros(extractor.n_mels, dtype=torch.float64, device=device)
total_frames = 0
for idx in indices:
wav = ds[idx]["wave"].to(device=device, dtype=torch.float32)
mel = extractor(wav)[0]
if compute_stats:
mf64 = mel.double()
sum_1 += mf64.sum(dim=0)
sum_2 += mf64.square().sum(dim=0)
total_frames += int(mel.shape[0])
mels[idx] = mel.half().cpu()
if not compute_stats:
return mels, None, None
mean = (sum_1 / max(total_frames, 1)).float().cpu()
var = (sum_2 / max(total_frames, 1) - (sum_1 / max(total_frames, 1)).square()).clamp_min(1e-8)
scale = var.sqrt().float().clamp_min(1e-4).cpu()
return mels, mean, scale
def cfm_loss_step(
model: LuaNovaCFM,
batch: dict,
teacher_prob: float = 0.15,
prior_weight: float = 1.0,
delta_weight: float = 0.6,
freq_delta_weight: float = 0.35,
hf_boost: float = 1.35,
f0_smooth_prob: float = 0.0,
training: bool = True,
) -> tuple[torch.Tensor, dict]:
"""Compute prior-centered OT-CFM objective plus temporal and frequency derivative losses."""
c = model.config
cfg = model.cfm_config
with torch.no_grad() if model._frontend_frozen else torch.enable_grad():
hidden, token_mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
prosody_token_ctx, clause_ctx_tok = model.encode_prosody_context(
hidden, batch["tokens"], batch["stress"], token_mask
)
acoustic_frames, prosody_frames, frame_mask, lengths = model.expand_with_context(
hidden, prosody_token_ctx, clause_ctx_tok, batch["durations"], token_mask, batch["speakers"]
)
if teacher_prob >= 1.0 and cfg.acoustic_from_frames:
prosody_hidden = None
prediction = None
else:
prosody_hidden, prediction, _ = model.sample_prosody(prosody_frames, frame_mask, seed=0)
target_prosody = batch["prosody"]
if teacher_prob >= 1.0:
condition = target_prosody
elif training and teacher_prob > 0:
teacher = torch.rand(len(lengths), device=lengths.device) < teacher_prob
condition = torch.where(teacher[:, None, None], target_prosody, model.hard_prosody(prediction.detach()))
else:
condition = model.hard_prosody(prediction.detach())
if training and f0_smooth_prob > 0:
condition = smooth_f0_channel(condition, f0_smooth_prob)
base_h = acoustic_frames if cfg.acoustic_from_frames else prosody_hidden
cond, prior_mel = model.condition_and_prior(base_h, condition, frame_mask)
f0_feats = f0_features(condition, frame_mask) if cfg.use_f0_harmonics else None
gate = energy_noise_gate(condition, frame_mask) if cfg.use_energy_gate else 1.0
x1 = ((batch["vocos_mel"] - model.vocoder.mel_mean) / model.vocoder.mel_scale) * frame_mask[..., None]
if hf_boost != 1.0:
ch_w = torch.ones((1, 1, c.vocos_n_mels), device=x1.device, dtype=torch.float32)
ch_w[..., 60:] = hf_boost
ch_w = ch_w / ch_w.mean()
else:
ch_w = 1.0
prior_loss = masked_mean(((prior_mel - x1).abs() * ch_w).mean(-1), frame_mask)
b = x1.shape[0]
if training:
t = torch.sigmoid(torch.randn(b, device=x1.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
else:
t = torch.full((b,), 0.5, device=x1.device, dtype=torch.float32)
eps = torch.randn_like(x1)
x0 = (prior_mel.detach() + cfg.prior_sigma * gate * eps) * frame_mask[..., None]
t_view = t[:, None, None]
x_t = ((1.0 - t_view) * x0 + t_view * x1) * frame_mask[..., None]
v_target = (x1 - x0) * frame_mask[..., None]
if training and cfg.cfg_dropout > 0:
drop = (torch.rand(b, device=x1.device) < cfg.cfg_dropout)[:, None, None]
cond_in = torch.where(drop, torch.zeros_like(cond), cond)
prior_in = torch.where(drop, torch.zeros_like(prior_mel), prior_mel.detach())
f0_in = torch.where(drop, torch.zeros_like(f0_feats), f0_feats) if f0_feats is not None else None
else:
cond_in = cond
prior_in = prior_mel.detach()
f0_in = f0_feats
v_pred = model.flow(x_t, t, cond_in, prior_in, frame_mask, f0_feats=f0_in)
cfm_loss = masked_mean(((v_pred - v_target).abs() * ch_w).mean(-1), frame_mask)
x1_hat = x_t + (1.0 - t_view) * v_pred
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
t_weight = t[:, None]
delta_err = ((x1_hat[:, 1:] - x1_hat[:, :-1]) - (x1[:, 1:] - x1[:, :-1])).abs().mean(-1)
delta_loss = masked_mean(delta_err * t_weight, pair_mask)
if freq_delta_weight > 0:
f_err = ((x1_hat[..., 1:] - x1_hat[..., :-1]) - (x1[..., 1:] - x1[..., :-1])).abs().mean(-1)
freq_delta_loss = masked_mean(f_err * t_weight, frame_mask)
else:
freq_delta_loss = x1.new_zeros(())
loss = cfm_loss + prior_weight * prior_loss + delta_weight * delta_loss + freq_delta_weight * freq_delta_loss
metrics = {
"loss": float(loss.detach()),
"cfm": float(cfm_loss.detach()),
"prior": float(prior_loss.detach()),
"delta": float(delta_loss.detach()),
"f_delta": float(freq_delta_loss.detach()),
}
return loss, metrics
@torch.no_grad()
def validate_cfm(
model: LuaNovaCFM,
dataset,
indices: list[int],
device: str,
delta_weight: float = 0.6,
freq_delta_weight: float = 0.35,
hf_boost: float = 1.35,
) -> dict:
"""Evaluate OT-CFM losses in both predicted-prosody and teacher-forced modes."""
was_training = model.training
model.eval()
totals: dict[str, float] = defaultdict(float)
weight = 0
for start in range(0, len(indices), 8):
batch = collate([dataset[i] for i in indices[start : start + 8]], device)
sz = len(batch["frame_lengths"])
_, m = cfm_loss_step(
model,
batch,
teacher_prob=0.0,
delta_weight=delta_weight,
freq_delta_weight=freq_delta_weight,
hf_boost=hf_boost,
training=False,
)
for k, v in m.items():
totals[f"val_{k}"] += v * sz
_, m_gt = cfm_loss_step(
model,
batch,
teacher_prob=1.0,
delta_weight=delta_weight,
freq_delta_weight=freq_delta_weight,
hf_boost=hf_boost,
training=False,
)
for k, v in m_gt.items():
totals[f"val_gt_{k}"] += v * sz
weight += sz
if was_training:
model.train()
return {k: v / max(weight, 1) for k, v in totals.items()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376"""OT-CFM trajectory distillation (e.g. 8-step Sway Midpoint teacher -> 2-step Euler student)."""
from __future__ import annotations
import argparse
from collections import defaultdict
import copy
import json
import math
from pathlib import Path
import time
import torch
from torch import nn
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
from ..models.losses import masked_mean
from .common import (
balanced_indices,
check_leakage,
cosine_lr,
export_cfm_checkpoint,
load_cfm_model,
update_ema,
)
def make_channel_weights(n_mels: int, hf_boost: float, device: torch.device | str) -> torch.Tensor | float:
"""Upweight upper mel bands (bins 60..n_mels) when ``hf_boost != 1.0``."""
if hf_boost == 1.0:
return 1.0
ch_w = torch.ones((1, 1, n_mels), device=device, dtype=torch.float32)
ch_w[..., 60:] = float(hf_boost)
return ch_w / ch_w.mean()
def _teacher_velocity(
teacher: LuaNovaCFM,
x_cur: torch.Tensor,
t_val: float,
cond: torch.Tensor,
prior_mel: torch.Tensor,
frame_mask: torch.Tensor,
f0_feats: torch.Tensor | None,
cfg_scale: float,
) -> torch.Tensor:
t_vec = torch.full((x_cur.shape[0],), float(t_val), device=x_cur.device, dtype=torch.float32)
v_c = teacher.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
if cfg_scale == 1.0:
return v_c
v_u = teacher.flow(
x_cur,
t_vec,
torch.zeros_like(cond),
torch.zeros_like(prior_mel),
frame_mask,
f0_feats=torch.zeros_like(f0_feats) if f0_feats is not None else None,
)
return v_u + cfg_scale * (v_c - v_u)
def distill_loss_step(
teacher: LuaNovaCFM,
student: LuaNovaCFM,
batch: dict,
ch_w: torch.Tensor | float,
teacher_steps: int = 8,
teacher_sway: float = -0.5,
teacher_temp: float = 0.35,
teacher_cfg: float = 1.0,
teacher_solver: str = "midpoint",
student_steps: int = 2,
student_sway: float = 0.0,
teacher_prob: float = 0.35,
f0_smooth_prob: float = 0.15,
training: bool = True,
) -> tuple[torch.Tensor, dict[str, float]]:
"""Compute trajectory distillation loss matching student Euler ODE against the teacher ODE."""
dev_type = "cuda" if batch["tokens"].device.type == "cuda" else "cpu"
use_bf16 = dev_type == "cuda"
s_grid = student.sway_time_grid(student_steps, student_sway)
s_mid_idx = max(1, student_steps // 2)
s_mid_t = s_grid[s_mid_idx]
t_grid = teacher.sway_time_grid(teacher_steps, teacher_sway)
t_mid_idx = min(range(1, len(t_grid)), key=lambda idx: abs(t_grid[idx] - s_mid_t))
with torch.no_grad():
hidden, token_mask = teacher.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
prosody_token_ctx, clause_ctx_tok = teacher.encode_prosody_context(
hidden, batch["tokens"], batch["stress"], token_mask
)
acoustic_frames, prosody_frames, frame_mask, flen = teacher.expand_with_context(
hidden, prosody_token_ctx, clause_ctx_tok, batch["durations"], token_mask, batch["speakers"]
)
if teacher.cfm_config.acoustic_from_frames and teacher_prob >= 1.0:
prosody_hidden = None
pred_pros = None
else:
prosody_hidden, pred_pros, _ = teacher.sample_prosody(prosody_frames, frame_mask, seed=0)
if pred_pros is None or teacher_prob >= 1.0:
condition = batch["prosody"]
elif training and teacher_prob > 0.0:
teach = torch.rand(len(flen), device=flen.device) < teacher_prob
condition = torch.where(teach[:, None, None], batch["prosody"], teacher.hard_prosody(pred_pros))
else:
condition = teacher.hard_prosody(pred_pros)
if training and f0_smooth_prob > 0.0:
condition = smooth_f0_channel(condition, f0_smooth_prob)
base_h = acoustic_frames if teacher.cfm_config.acoustic_from_frames else prosody_hidden
f0_feats = f0_features(condition, frame_mask) if teacher.cfm_config.use_f0_harmonics else None
gate = energy_noise_gate(condition, frame_mask) if teacher.cfm_config.use_energy_gate else 1.0
with torch.amp.autocast(device_type=dev_type, dtype=torch.bfloat16, enabled=use_bf16):
cond, prior_mel = teacher.condition_and_prior(base_h, condition, frame_mask)
sigma = float(teacher.cfm_config.prior_sigma) * float(teacher_temp)
eps = torch.randn_like(prior_mel) if training else torch.zeros_like(prior_mel)
x0 = (prior_mel.float() + sigma * gate * eps) * frame_mask[..., None]
x_t = x0
x_t_mid = x0
for i in range(teacher_steps):
t0, t1 = t_grid[i], t_grid[i + 1]
dt_i = t1 - t0
if teacher_solver == "midpoint":
v0 = _teacher_velocity(teacher, x_t, t0, cond, prior_mel, frame_mask, f0_feats, teacher_cfg)
x_mid = (x_t + 0.5 * dt_i * v0) * frame_mask[..., None]
vm = _teacher_velocity(
teacher, x_mid, t0 + 0.5 * dt_i, cond, prior_mel, frame_mask, f0_feats, teacher_cfg
)
x_t = (x_t + dt_i * vm) * frame_mask[..., None]
else:
v0 = _teacher_velocity(teacher, x_t, t0, cond, prior_mel, frame_mask, f0_feats, teacher_cfg)
x_t = (x_t + dt_i * v0) * frame_mask[..., None]
if i + 1 == t_mid_idx:
x_t_mid = x_t
x_t_end = x_t
with torch.amp.autocast(device_type=dev_type, dtype=torch.bfloat16, enabled=use_bf16):
b = x0.shape[0]
x_s = x0
x_s_mid = x0
for i in range(student_steps):
t0, t1 = s_grid[i], s_grid[i + 1]
dt_i = t1 - t0
t_vec = torch.full((b,), t0, device=x0.device, dtype=torch.float32)
v_s = student.flow(x_s, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
x_s = (x_s + dt_i * v_s) * frame_mask[..., None]
if i + 1 == s_mid_idx:
x_s_mid = x_s
x_s_end = x_s
xs_end_f = x_s_end.float()
xt_end_f = x_t_end.float()
end_l1 = masked_mean(((xs_end_f - xt_end_f).abs() * ch_w).mean(-1), frame_mask)
mid_l1 = masked_mean(((x_s_mid.float() - x_t_mid.float()).abs() * ch_w).mean(-1), frame_mask)
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
dt_l1 = masked_mean(
(((xs_end_f[:, 1:] - xs_end_f[:, :-1]) - (xt_end_f[:, 1:] - xt_end_f[:, :-1])).abs()).mean(-1),
pair_mask,
)
df_l1 = masked_mean(
(((xs_end_f[..., 1:] - xs_end_f[..., :-1]) - (xt_end_f[..., 1:] - xt_end_f[..., :-1])).abs()).mean(-1),
frame_mask,
)
loss = end_l1 + 0.5 * mid_l1 + 0.7 * dt_l1 + 0.4 * df_l1
metrics = {
"loss": float(loss.detach()),
"end_l1": float(end_l1.detach()),
"mid_l1": float(mid_l1.detach()),
"dt_l1": float(dt_l1.detach()),
"df_l1": float(df_l1.detach()),
}
return loss, metrics
@torch.no_grad()
def validate_distill(
teacher: LuaNovaCFM,
student: LuaNovaCFM,
dataset: AnnotatedDataset,
indices: list[int],
device: str,
ch_w: torch.Tensor | float,
args: argparse.Namespace,
) -> dict[str, float]:
was_flow_training = student.flow.training
student.eval()
totals: dict[str, float] = defaultdict(float)
weight = 0
for start in range(0, len(indices), 8):
batch = collate([dataset[i] for i in indices[start : start + 8]], device)
sz = len(batch["frame_lengths"])
_, m = distill_loss_step(
teacher,
student,
batch,
ch_w,
teacher_steps=args.teacher_steps,
teacher_sway=args.teacher_sway,
teacher_temp=args.teacher_temp,
teacher_cfg=args.teacher_cfg,
teacher_solver=args.teacher_solver,
student_steps=args.student_steps,
student_sway=args.student_sway,
teacher_prob=args.teacher_prob,
f0_smooth_prob=0.0,
training=False,
)
for k, v in m.items():
totals[f"val_{k}"] += v * sz
weight += sz
if was_flow_training:
student.flow.train()
return {k: v / max(weight, 1) for k, v in totals.items()}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--train", type=Path, required=True)
parser.add_argument("--validation", type=Path, required=True)
parser.add_argument("--teacher", type=Path, required=True, help="Teacher CFM v5 checkpoint (.pt)")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--device", default="cuda")
parser.add_argument("--steps", type=int, default=12000)
parser.add_argument("--batch-frames", type=int, default=6000)
parser.add_argument("--max-batch", type=int, default=16)
parser.add_argument("--lr", type=float, default=1e-4)
parser.add_argument("--min-lr", type=float, default=5e-6)
parser.add_argument("--warmup", type=int, default=400)
parser.add_argument("--ema-decay", type=float, default=0.999)
parser.add_argument("--teacher-steps", type=int, default=8)
parser.add_argument("--teacher-sway", type=float, default=-0.5)
parser.add_argument("--teacher-temp", type=float, default=0.35)
parser.add_argument("--teacher-cfg", type=float, default=1.0)
parser.add_argument("--teacher-solver", default="midpoint", choices=["euler", "midpoint"])
parser.add_argument("--student-steps", type=int, default=2)
parser.add_argument("--student-sway", type=float, default=0.0)
parser.add_argument("--teacher-prob", type=float, default=0.35)
parser.add_argument("--hf-boost", type=float, default=1.40)
parser.add_argument("--f0-smooth-prob", type=float, default=0.15)
parser.add_argument("--save-every", type=int, default=3000)
parser.add_argument("--log-every", type=int, default=100)
parser.add_argument("--seed", type=int, default=20261121)
parser.add_argument("--max-seconds", type=float, default=3600.0)
args = parser.parse_args()
torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
teacher = load_cfm_model(args.teacher, device=args.device, load_vocos=False).eval()
for p in teacher.parameters():
p.requires_grad_(False)
student = copy.deepcopy(teacher)
for p in student.parameters():
p.requires_grad_(False)
for p in student.flow.parameters():
p.requires_grad_(True)
student.eval()
student.flow.train()
ema_model = copy.deepcopy(student).eval()
for p in ema_model.parameters():
p.requires_grad_(False)
trainable = list(student.flow.parameters())
optimizer = torch.optim.AdamW(trainable, lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
train_ds = AnnotatedDataset(args.train, student.config, voiced_vowels=True, cache=True)
val_ds = AnnotatedDataset(args.validation, student.config, voiced_vowels=True, cache=True)
check_leakage(train_ds, val_ds)
pool = list(range(len(train_ds)))
val_indices = balanced_indices(val_ds, min(32, len(val_ds)))
train_ds.preload(pool, workers=8)
val_ds.preload(val_indices, workers=4)
sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
ch_w = make_channel_weights(student.config.vocos_n_mels, args.hf_boost, args.device)
args.output.mkdir(parents=True, exist_ok=True)
log_file = (args.output / "train.log").open("a", encoding="utf-8", buffering=1)
metrics_path = args.output / "metrics.jsonl"
def log_record(rec: dict) -> None:
line = json.dumps(rec, ensure_ascii=False)
print(line, flush=True)
log_file.write(line + "\n")
log_file.flush()
with metrics_path.open("a", encoding="utf-8") as mf:
mf.write(line + "\n")
init_val = validate_distill(teacher, ema_model, val_ds, val_indices, args.device, ch_w, args)
log_record(
{
"step": 0,
"trainable_flow_params": sum(p.numel() for p in trainable),
"teacher_steps": args.teacher_steps,
"teacher_sway": args.teacher_sway,
"teacher_temp": args.teacher_temp,
"student_steps": args.student_steps,
"student_sway": args.student_sway,
**init_val,
}
)
t_start = time.monotonic()
t_win = time.monotonic()
win: dict[str, float] = defaultdict(float)
win_steps = 0
try:
for step in range(1, args.steps + 1):
lr = cosine_lr(step - 1, args.warmup, args.steps, args.lr, args.min_lr)
for g in optimizer.param_groups:
g["lr"] = lr
batch = collate([train_ds[pool[i]] for i in sampler.next()], args.device)
optimizer.zero_grad(set_to_none=True)
loss, m = distill_loss_step(
teacher,
student,
batch,
ch_w,
teacher_steps=args.teacher_steps,
teacher_sway=args.teacher_sway,
teacher_temp=args.teacher_temp,
teacher_cfg=args.teacher_cfg,
teacher_solver=args.teacher_solver,
student_steps=args.student_steps,
student_sway=args.student_sway,
teacher_prob=args.teacher_prob,
f0_smooth_prob=args.f0_smooth_prob,
training=True,
)
loss.backward()
grad_norm = float(nn.utils.clip_grad_norm_(trainable, 5.0))
optimizer.step()
update_ema(ema_model, student, args.ema_decay)
for k, v in m.items():
win[k] += v
win["grad_norm"] += grad_norm
win_steps += 1
elapsed = time.monotonic() - t_start
should_stop = step == args.steps or elapsed >= args.max_seconds
save = step % args.save_every == 0 or should_stop
if step % args.log_every == 0 or save:
if str(args.device).startswith("cuda"):
torch.cuda.synchronize()
dt = max(time.monotonic() - t_win, 1e-6)
rec: dict[str, object] = {k: v / win_steps for k, v in win.items()}
rec.update(step=step, lr=lr, steps_per_s=win_steps / dt, elapsed_s=elapsed)
if save:
rec.update(validate_distill(teacher, ema_model, val_ds, val_indices, args.device, ch_w, args))
export_cfm_checkpoint(
ema_model, args.output / "inference_v5_fast2_ema.pt", step, train_ds.annotation
)
export_cfm_checkpoint(
ema_model, args.output / f"inference_v5_fast2_step-{step:06d}.pt", step, train_ds.annotation
)
log_record(rec)
win = defaultdict(float)
win_steps = 0
t_win = time.monotonic()
if should_stop:
break
finally:
log_file.close()
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548"""Item 3 (Stage 3A): Contexto linguistico + DurationFlow + ProsodyFlow generativos."""
from __future__ import annotations
import argparse
from collections import defaultdict
import copy
import json
import math
from pathlib import Path
import time
import torch
from torch import nn
from torch.nn import functional as F
from ..config import CFMConfig, Config
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
from ..models.cfm import LuaNovaCFM, smooth_prosody_noise
from ..models.losses import masked_mean
from ..text.phonemizer import phonemize
from ..utils.audio import limit_peak
from .common import VALIDATION_SAMPLE_TEXTS, check_leakage, export_cfm_checkpoint, masked_std, update_ema
SEMITONES = 12.0 / math.log(2.0)
FROZEN_FOR_ITEM3 = (
"tokens",
"stress",
"voices",
"encoder",
"frame_voices",
"frame_position",
"prosody_projection",
"acoustic_stack",
"prior_head",
"flow",
"vocoder",
)
TRAINABLE_ITEM3 = (
"context_adapter",
"duration",
"dur_flow",
"frame_ctx_proj",
"prosody_stack",
"prosody_head",
"prosody_flow",
)
def set_item3_trainable(model: LuaNovaCFM) -> list[nn.Parameter]:
"""Congela encoder/acustico/vocoder e habilita apenas os modulos do Item 3."""
model._frontend_frozen = False
for p in model.parameters():
p.requires_grad_(False)
trainable: list[nn.Parameter] = []
for name in TRAINABLE_ITEM3:
mod = getattr(model, name, None)
if mod is None:
continue
for p in mod.parameters():
p.requires_grad_(True)
trainable.append(p)
return trainable
def set_item3_train_mode(model: LuaNovaCFM, training: bool = True) -> None:
model.eval()
if training:
for name in TRAINABLE_ITEM3:
mod = getattr(model, name, None)
if mod is not None:
mod.train()
def build_item3_model(
init_cfm_path: Path | None,
init_stage1_path: Path | None,
cfg_overrides: dict | None = None,
device: str = "cuda",
vocos_model=None,
) -> LuaNovaCFM:
"""Create LuaNovaCFM with Item 3 enabled from either a CFM checkpoint or Stage-1 weights."""
if init_cfm_path is None and init_stage1_path is None:
raise ValueError("at least one of init_cfm_path or init_stage1_path is required")
if init_cfm_path is not None:
cfm_ckpt = torch.load(init_cfm_path, map_location="cpu", weights_only=True)
cfg = CFMConfig.from_dict(cfm_ckpt["cfm_config"])
else:
s1_tmp = torch.load(init_stage1_path, map_location="cpu", weights_only=True)
cfg = CFMConfig(base=Config.from_dict(s1_tmp["config"]), acoustic_from_frames=True, mel_space="bigvgan_24k_100")
cfm_ckpt = None
cfg.use_ling_context = True
cfg.use_duration_flow = True
cfg.use_prosody_flow = True
cfg.use_energy_gate = True
if cfg_overrides:
for k, v in cfg_overrides.items():
if hasattr(cfg, k):
setattr(cfg, k, v)
model = LuaNovaCFM(cfg, vocos_model=vocos_model)
if cfm_ckpt is not None:
own = dict(model.state_dict())
for k, v in cfm_ckpt["model"].items():
if k in own and own[k].shape == v.shape:
own[k] = v
model.load_state_dict(own, strict=True)
if init_stage1_path is not None:
s1_ckpt = torch.load(init_stage1_path, map_location="cpu", weights_only=True)
s1_sd = s1_ckpt.get("system", s1_ckpt.get("model"))
if cfm_ckpt is None:
model.load_frontend(s1_sd)
else:
own = dict(model.state_dict())
pref = "model." if any(k.startswith("model.") for k in s1_sd) else ""
for k, v in s1_sd.items():
if pref and not k.startswith(pref):
continue
key = k[len(pref) :] if pref else k
if key.startswith(("duration.", "prosody_stack.", "prosody_head.")) and key in own and own[key].shape == v.shape:
own[key] = v
model.load_state_dict(own, strict=True)
return model.to(device)
def prosody_flow_loss_step(
model: LuaNovaCFM,
batch: dict,
frame_dropout: float = 0.15,
weights: dict[str, float] | None = None,
training: bool = True,
) -> tuple[torch.Tensor, dict[str, float]]:
w = {
"dur_prior": 2.0,
"pause_bce": 1.5,
"dur_cfm": 2.5,
"dur_total": 1.0,
"prior_f0": 2.0,
"prior_f0_dt": 3.0,
"voicing": 2.0,
"prior_eng": 1.5,
"prior_eng_dt": 1.0,
"pflow_f0": 3.5,
"pflow_eng": 1.5,
"pflow_f0_dt": 4.5,
"pflow_f0_d2": 1.5,
"pflow_eng_dt": 1.5,
"pflow_dist": 1.0,
}
if weights:
w.update(weights)
cfg = model.cfm_config
with torch.no_grad():
hidden, token_mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
prosody_token_ctx, clause_ctx_tok = model.encode_prosody_context(
hidden, batch["tokens"], batch["stress"], token_mask
)
# --- 1. Duration Prior + DurationFlow (OT-CFM sobre log1p(dur)) ---
gt_dur = batch["durations"]
present_mask = (gt_dur > 0) & token_mask
non_phone_mask = (~model.phone_tokens[batch["tokens"]]) & token_mask
raw_dur = model.duration(prosody_token_ctx, token_mask).float()
z1_gt = torch.log1p(gt_dur.float())
dur_prior_l1 = masked_mean((raw_dur[..., 0] - z1_gt).abs(), present_mask)
pause_bce = masked_mean(
F.binary_cross_entropy_with_logits(raw_dur[..., 1], (gt_dur > 0).float(), reduction="none"),
non_phone_mask,
)
b, l_len = batch["tokens"].shape
prior_z = raw_dur[..., 0].detach().clamp(0.0, math.log1p(400.0))
if training:
t_d = torch.sigmoid(torch.randn(b, device=hidden.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
eps_d = torch.randn((b, l_len, 1), device=hidden.device, dtype=torch.float32)
else:
t_d = torch.full((b,), 0.5, device=hidden.device, dtype=torch.float32)
eps_d = torch.zeros((b, l_len, 1), device=hidden.device, dtype=torch.float32)
z0_d = (prior_z[..., None] + cfg.dur_flow_sigma * eps_d) * token_mask[..., None].float()
z1_d = z1_gt[..., None]
td_view = t_d[:, None, None]
zt_d = ((1.0 - td_view) * z0_d + td_view * z1_d) * token_mask[..., None].float()
v_dur_pred = model.dur_flow(zt_d, t_d, prior_z[..., None], prosody_token_ctx, token_mask)
dur_cfm_l1 = masked_mean((v_dur_pred - (z1_d - z0_d)).abs().squeeze(-1), present_mask)
z1_d_hat = (zt_d + (1.0 - td_view) * v_dur_pred).squeeze(-1)
dur_hat_frames = (torch.exp(z1_d_hat.clamp(0.0, math.log1p(400.0))) - 1.0) * present_mask.float()
dur_gt_frames = gt_dur.float() * present_mask.float()
tot_rel = (dur_hat_frames.sum(dim=1) - dur_gt_frames.sum(dim=1)).abs() / dur_gt_frames.sum(dim=1).clamp_min(1.0)
dur_total_l1 = (tot_rel * t_d).mean()
# --- 2. Frame expansion + Prosody Prior + ProsodyFlow (OT-CFM com ruido correlacionado) ---
_, prosody_frames, frame_mask, _ = model.expand_with_context(
hidden, prosody_token_ctx, clause_ctx_tok, gt_dur, token_mask, batch["speakers"]
)
p_frames_in = F.dropout(prosody_frames, p=frame_dropout, training=True) if (training and frame_dropout > 0.0) else prosody_frames
prosody_hidden, prior_raw = model.predict_prosody(p_frames_in, frame_mask)
prior_raw = prior_raw.float()
gt_p = batch["prosody"].float()
trusted = batch["pitch_trusted"].float()
sung = frame_mask.float() * gt_p[..., 1] * trusted
pitch_w = frame_mask.float() * (trusted + 0.1 * (1.0 - trusted))
sung_pair = sung[:, 1:] * sung[:, :-1]
sung_tri = sung[:, 2:] * sung[:, 1:-1] * sung[:, :-2]
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
prior_f0_l1 = masked_mean((prior_raw[..., 0] - gt_p[..., 0]).abs(), pitch_w)
prior_f0_dt = masked_mean(((prior_raw[:, 1:, 0] - prior_raw[:, :-1, 0]) - (gt_p[:, 1:, 0] - gt_p[:, :-1, 0])).abs(), sung_pair)
voicing_bce = masked_mean(F.binary_cross_entropy_with_logits(prior_raw[..., 1], gt_p[..., 1], reduction="none"), frame_mask)
prior_eng_l1 = masked_mean((prior_raw[..., 2] - gt_p[..., 2]).abs(), frame_mask)
prior_eng_dt = masked_mean(((prior_raw[:, 1:, 2] - prior_raw[:, :-1, 2]) - (gt_p[:, 1:, 2] - gt_p[:, :-1, 2])).abs(), pair_mask)
prior_fe = torch.stack((prior_raw[..., 0], prior_raw[..., 2]), dim=-1).detach()
voicing_prob = torch.sigmoid(prior_raw[..., 1:2]).detach()
y1 = torch.stack((gt_p[..., 0], gt_p[..., 2]), dim=-1) * frame_mask[..., None].float()
t_len = prosody_frames.shape[1]
if training:
t_p = torch.sigmoid(torch.randn(b, device=hidden.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
eps_p = torch.randn((b, t_len, 2), device=hidden.device, dtype=torch.float32)
else:
t_p = torch.full((b,), 0.5, device=hidden.device, dtype=torch.float32)
eps_p = torch.zeros((b, t_len, 2), device=hidden.device, dtype=torch.float32)
eps_sm = smooth_prosody_noise(eps_p, frame_mask, model.prosody_noise_kernel)
y0 = (prior_fe + cfg.prosody_flow_sigma * eps_sm) * frame_mask[..., None].float()
tp_view = t_p[:, None, None]
y_t = ((1.0 - tp_view) * y0 + tp_view * y1) * frame_mask[..., None].float()
v_p_pred = model.prosody_flow(y_t, t_p, prior_fe, voicing_prob, prosody_hidden, frame_mask)
v_p_tgt = (y1 - y0) * frame_mask[..., None].float()
pflow_f0_l1 = masked_mean((v_p_pred[..., 0] - v_p_tgt[..., 0]).abs(), pitch_w)
pflow_eng_l1 = masked_mean((v_p_pred[..., 1] - v_p_tgt[..., 1]).abs(), frame_mask)
y1_hat = (y_t + (1.0 - tp_view) * v_p_pred) * frame_mask[..., None].float()
tp_w1 = t_p[:, None]
pflow_f0_dt = masked_mean(
((y1_hat[:, 1:, 0] - y1_hat[:, :-1, 0]) - (y1[:, 1:, 0] - y1[:, :-1, 0])).abs() * tp_w1,
sung_pair,
)
d2_p = y1_hat[:, 2:, 0] - 2.0 * y1_hat[:, 1:-1, 0] + y1_hat[:, :-2, 0]
d2_t = y1[:, 2:, 0] - 2.0 * y1[:, 1:-1, 0] + y1[:, :-2, 0]
pflow_f0_d2 = masked_mean((d2_p - d2_t).abs() * tp_w1, sung_tri)
pflow_eng_dt = masked_mean(
((y1_hat[:, 1:, 1] - y1_hat[:, :-1, 1]) - (y1[:, 1:, 1] - y1[:, :-1, 1])).abs() * tp_w1,
pair_mask,
)
# Distribuicao F0 por enunciado (std, P90-P10, caimento final) sem excursion_gain artificial
q_levels = torch.tensor([0.10, 0.90], device=hidden.device, dtype=torch.float32)
dist_errs = []
enough_dist = (sung.sum(1) >= 15) & (t_p > 0.35)
for i in range(b):
if not bool(enough_dist[i]):
continue
idx = (sung[i] > 0.5).nonzero(as_tuple=False).squeeze(-1)
vp = y1_hat[i, idx, 0]
vt = y1[i, idx, 0]
std_err = (vp.std() - vt.std()).abs()
qp = torch.quantile(vp, q_levels)
qt = torch.quantile(vt, q_levels)
span_err = ((qp[1] - qp[0]) - (qt[1] - qt[0])).abs()
k_tail = max(1, int(idx.numel()) // 5)
k_head = max(1, int(idx.numel()) // 2)
tail_err = ((vp[-k_tail:].mean() - vp[:k_head].mean()) - (vt[-k_tail:].mean() - vt[:k_head].mean())).abs()
dist_errs.append((std_err + 0.7 * span_err + 0.8 * tail_err) * t_p[i])
pflow_dist = torch.stack(dist_errs).mean() if dist_errs else y1_hat.new_zeros(())
terms = {
"dur_prior": dur_prior_l1,
"pause_bce": pause_bce,
"dur_cfm": dur_cfm_l1,
"dur_total": dur_total_l1,
"prior_f0": prior_f0_l1,
"prior_f0_dt": prior_f0_dt,
"voicing": voicing_bce,
"prior_eng": prior_eng_l1,
"prior_eng_dt": prior_eng_dt,
"pflow_f0": pflow_f0_l1,
"pflow_eng": pflow_eng_l1,
"pflow_f0_dt": pflow_f0_dt,
"pflow_f0_d2": pflow_f0_d2,
"pflow_eng_dt": pflow_eng_dt,
"pflow_dist": pflow_dist,
}
loss = sum(w[k] * v for k, v in terms.items())
metrics = {"loss": float(loss.detach()), **{k: float(v.detach()) for k, v in terms.items()}}
return loss, metrics
@torch.no_grad()
def evaluate_item3(
model: LuaNovaCFM,
dataset: AnnotatedDataset,
device: str,
dur_temp: float | None = None,
prosody_temp: float | None = None,
dur_steps: int | None = None,
prosody_steps: int | None = None,
) -> dict[str, float]:
"""Avalia DurationFlow e ProsodyFlow em free-running na validacao/teste inteiros."""
model.eval()
dur_ph_mae, dur_all_mae, tot_len_err = [], [], []
f0_mae, f0_delta_mae, jit_pred, jit_gt = [], [], [], []
std_pred, std_gt, span95_pred, span95_gt, tail_pred, tail_gt = [], [], [], [], [], []
q_tail_p, q_tail_g, d_tail_p, d_tail_g = [], [], [], []
eng_mae, v_acc = [], []
sp_tp = sp_fp = sp_fn = 0
q95 = torch.tensor([0.05, 0.95], device=device, dtype=torch.float32)
for i, row in enumerate(dataset.rows):
batch = collate([dataset[i]], device)
hidden, mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
p_tok_ctx, clause_ctx = model.encode_prosody_context(hidden, batch["tokens"], batch["stress"], mask)
pred_dur, _ = model.sample_durations(
p_tok_ctx, mask, batch["tokens"], speed=1.0, seed=0, temperature=dur_temp, steps=dur_steps
)
pd = pred_dur[0]
gd = batch["durations"][0]
tok = batch["tokens"][0]
is_ph = model.phone_tokens[tok]
dur_ph_mae.append(float((pd[is_ph] - gd[is_ph]).abs().float().mean()))
dur_all_mae.append(float((pd - gd).abs().float().mean()))
tot_len_err.append(abs(int(pd.sum()) - int(gd.sum())) / max(int(gd.sum()), 1) * 100.0)
pause_tok = ~is_ph & mask[0]
sp_tp += int(((pd > 0) & (gd > 0) & pause_tok).sum())
sp_fp += int(((pd > 0) & (gd == 0) & pause_tok).sum())
sp_fn += int(((pd == 0) & (gd > 0) & pause_tok).sum())
_, p_frames, fmask, _ = model.expand_with_context(
hidden, p_tok_ctx, clause_ctx, batch["durations"], mask, batch["speakers"]
)
_, pred_p, _ = model.sample_prosody(p_frames, fmask, seed=0, temperature=prosody_temp, steps=prosody_steps)
gp = batch["prosody"][0].float()
tr = batch["pitch_trusted"][0] > 0.5
vp = pred_p[0, :, 0].float()
vt = gp[:, 0]
sung = (gp[:, 1] > 0.5) & tr
if int(sung.sum()) >= 15:
f0_mae.append(SEMITONES * float((vp[sung] - vt[sung]).abs().mean()))
pair = sung[1:] & sung[:-1]
if bool(pair.any()):
dp = (vp[1:] - vp[:-1])[pair]
dt = (vt[1:] - vt[:-1])[pair]
f0_delta_mae.append(SEMITONES * float((dp - dt).abs().mean()))
jit_pred.append(SEMITONES * float(dp.abs().mean()))
jit_gt.append(SEMITONES * float(dt.abs().mean()))
pv, tv = vp[sung], vt[sung]
std_pred.append(SEMITONES * float(pv.std()))
std_gt.append(SEMITONES * float(tv.std()))
qp = torch.quantile(pv, q95)
qt = torch.quantile(tv, q95)
span95_pred.append(SEMITONES * float(qp[1] - qp[0]))
span95_gt.append(SEMITONES * float(qt[1] - qt[0]))
kt, kh = max(1, int(pv.numel()) // 5), max(1, int(pv.numel()) // 2)
tp = SEMITONES * float(pv[-kt:].mean() - pv[:kh].mean())
tg = SEMITONES * float(tv[-kt:].mean() - tv[:kh].mean())
tail_pred.append(tp)
tail_gt.append(tg)
if "?" in row["text"]:
q_tail_p.append(tp)
q_tail_g.append(tg)
else:
d_tail_p.append(tp)
d_tail_g.append(tg)
eng_mae.append(float((pred_p[0, :, 2] - gp[:, 2]).abs().mean()))
v_acc.append(float(((pred_p[0, :, 1] > 0) == (gp[:, 1] > 0.5)).float().mean()))
pause_f1 = 2 * sp_tp / max(2 * sp_tp + sp_fp + sp_fn, 1)
return {
"val_dur_ph_mae": sum(dur_ph_mae) / len(dur_ph_mae),
"val_dur_all_mae": sum(dur_all_mae) / len(dur_all_mae),
"val_tot_len_err_pct": sum(tot_len_err) / len(tot_len_err),
"val_pause_f1": pause_f1,
"val_f0_mae_st": sum(f0_mae) / max(len(f0_mae), 1),
"val_f0_delta_mae_st": sum(f0_delta_mae) / max(len(f0_delta_mae), 1),
"val_f0_jit_pred": sum(jit_pred) / max(len(jit_pred), 1),
"val_f0_jit_gt": sum(jit_gt) / max(len(jit_gt), 1),
"val_f0_std_pred": sum(std_pred) / max(len(std_pred), 1),
"val_f0_std_gt": sum(std_gt) / max(len(std_gt), 1),
"val_span95_pred": sum(span95_pred) / max(len(span95_pred), 1),
"val_span95_gt": sum(span95_gt) / max(len(span95_gt), 1),
"val_tail_pred": sum(tail_pred) / max(len(tail_pred), 1),
"val_tail_gt": sum(tail_gt) / max(len(tail_gt), 1),
"val_q_tail_pred": sum(q_tail_p) / max(len(q_tail_p), 1),
"val_q_tail_gt": sum(q_tail_g) / max(len(q_tail_g), 1),
"val_decl_tail_pred": sum(d_tail_p) / max(len(d_tail_p), 1),
"val_decl_tail_gt": sum(d_tail_g) / max(len(d_tail_g), 1),
"val_voicing_acc": sum(v_acc) / len(v_acc),
"val_eng_mae": sum(eng_mae) / len(eng_mae),
}
@torch.no_grad()
def save_item3_samples(model: LuaNovaCFM, out_dir: Path, step: int) -> None:
if getattr(model.vocoder, "vocos", None) is None:
return
import soundfile as sf
model.eval()
device = next(model.parameters()).device
sample_dir = out_dir / "samples" / f"step-{step:08d}"
sample_dir.mkdir(parents=True, exist_ok=True)
for idx, text in enumerate(VALIDATION_SAMPLE_TEXTS, 1):
ph = phonemize(text)
tok = torch.tensor([ph.ids], device=device)
st = torch.tensor([ph.stress], device=device)
ln = torch.tensor([len(ph)], device=device)
sp = torch.tensor([0], device=device)
wav, wav_len, _ = model.synthesize(
tok, st, ln, sp, seed=0, n_steps=4, cfg_scale=1.0, temperature=0.85, solver="midpoint"
)
w = limit_peak(wav[0, : int(wav_len[0])].cpu())
sf.write(sample_dir / f"sample_{idx:02d}.wav", w.numpy(), model.config.sample_rate, subtype="PCM_16")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--train", type=Path, required=True)
parser.add_argument("--validation", type=Path, required=True)
parser.add_argument("--init-cfm", type=Path, default=None, help="Optional LuaNovaCFM checkpoint to initialize from")
parser.add_argument("--init-stage1", type=Path, default=None, help="Stage 1 checkpoint for encoder, duration, and prosody")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--device", default="cuda")
parser.add_argument("--steps", type=int, default=12000)
parser.add_argument("--batch-frames", type=int, default=9000)
parser.add_argument("--max-batch", type=int, default=32)
parser.add_argument("--learning-rate", type=float, default=2e-4)
parser.add_argument("--warmup", type=int, default=600)
parser.add_argument("--ema-decay", type=float, default=0.997)
parser.add_argument("--frame-dropout", type=float, default=0.15)
parser.add_argument("--dur-temp", type=float, default=0.50)
parser.add_argument("--prosody-temp", type=float, default=0.75)
parser.add_argument("--log-every", type=int, default=100)
parser.add_argument("--eval-every", type=int, default=2000)
parser.add_argument("--save-every", type=int, default=3000)
parser.add_argument("--sample-every", type=int, default=3000)
parser.add_argument("--seed", type=int, default=20261120)
parser.add_argument("--max-seconds", type=float, default=2400)
args = parser.parse_args()
torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
model = build_item3_model(
args.init_cfm,
args.init_stage1,
cfg_overrides={"dur_flow_temp": args.dur_temp, "prosody_flow_temp": args.prosody_temp},
device=args.device,
)
trainable = set_item3_trainable(model)
ema_model = copy.deepcopy(model).eval()
for p in ema_model.parameters():
p.requires_grad_(False)
train_ds = AnnotatedDataset(args.train, model.config, voiced_vowels=True)
val_ds = AnnotatedDataset(args.validation, model.config, voiced_vowels=True)
check_leakage(train_ds, val_ds)
pool = list(range(len(train_ds)))
train_ds.preload(pool)
val_ds.preload(list(range(len(val_ds))))
args.output.mkdir(parents=True, exist_ok=True)
(args.output / "cfm_config.json").write_text(json.dumps(model.cfm_config.to_dict(), indent=2) + "\n", encoding="utf-8")
init_eval = evaluate_item3(ema_model, val_ds, args.device)
print(
json.dumps(
{
"step": 0,
"total_parameters": sum(p.numel() for p in model.parameters()),
"trainable_item3_params": sum(p.numel() for p in trainable),
**init_eval,
}
),
flush=True,
)
optimizer = torch.optim.AdamW(trainable, lr=args.learning_rate, betas=(0.9, 0.98), weight_decay=0.01)
sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
def lr_at(s: int) -> float:
if s < args.warmup:
return args.learning_rate * (s + 1) / max(args.warmup, 1)
prog = (s - args.warmup) / max(args.steps - args.warmup, 1)
return args.learning_rate * (0.08 + 0.92 * 0.5 * (1.0 + math.cos(math.pi * min(prog, 1.0))))
win = defaultdict(float)
win_steps = 0
t_start = time.monotonic()
t_win = time.monotonic()
set_item3_train_mode(model, True)
for step in range(1, args.steps + 1):
lr = lr_at(step - 1)
for g in optimizer.param_groups:
g["lr"] = lr
batch = collate([train_ds[pool[i]] for i in sampler.next()], args.device)
optimizer.zero_grad(set_to_none=True)
loss, metrics = prosody_flow_loss_step(model, batch, frame_dropout=args.frame_dropout, training=True)
loss.backward()
grad_norm = float(nn.utils.clip_grad_norm_(trainable, 5.0))
optimizer.step()
update_ema(ema_model, model, args.ema_decay)
for k, v in metrics.items():
win[k] += v
win["grad_norm"] += grad_norm
win_steps += 1
elapsed = time.monotonic() - t_start
should_stop = step == args.steps or elapsed >= args.max_seconds
is_eval = step % args.eval_every == 0 or should_stop
is_save = step % args.save_every == 0 or should_stop
if step % args.log_every == 0 or is_eval or is_save:
if str(args.device).startswith("cuda"):
torch.cuda.synchronize()
dt = max(time.monotonic() - t_win, 1e-6)
rec = {k: v / win_steps for k, v in win.items()}
rec.update(step=step, lr=lr, steps_per_s=win_steps / dt, elapsed_s=elapsed)
if is_eval:
rec.update(evaluate_item3(ema_model, val_ds, args.device))
if is_save:
export_cfm_checkpoint(ema_model, args.output / "inference_prosody_flow.pt", step, train_ds.annotation)
export_cfm_checkpoint(
ema_model, args.output / f"inference_prosody_flow-step-{step:08d}.pt", step, train_ds.annotation
)
with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as f:
f.write(json.dumps(rec) + "\n")
print(json.dumps(rec), flush=True)
win = defaultdict(float)
win_steps = 0
t_win = time.monotonic()
set_item3_train_mode(model, True)
if args.sample_every > 0 and (step % args.sample_every == 0 or should_stop):
save_item3_samples(ema_model, args.output, step)
set_item3_train_mode(model, True)
if should_stop:
break
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583"""From-scratch training on validated durations. Running this starts paid compute.
There is no learned aligner and no alignment loss: token durations come from
the annotation layer and must cover the acoustic frames exactly. The waveform
discriminators and the auxiliary mel head are training-only. No model or data
downloads and no infrastructure management happen here.
"""
import argparse
from collections import defaultdict
import json
import math
import os
from pathlib import Path
import time
import torch
from torch import nn
from torch.nn import functional as F
from ..config import CHECKPOINT_FORMAT, Config
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
from ..models.frontend import LuaNovaBase
from ..models.losses import Discriminators, SpectralLoss, discriminator_loss, generator_gan_loss, masked_mean
from ..text.phonemizer import frontend_fingerprint, frontend_identity, phonemize
from ..utils.audio import limit_peak
from ..utils.checkpoint import atomic_save
WEIGHTS = {"duration": 1.0, "pause": 1.0, "pitch": 2.0, "pitch_spread": 2.0, "voicing": 1.0, "energy": 1.0,
"mel_head": 2.0, "mel_delta": 5.0, "stft": 2.0, "mel": 10.0}
SEMITONES = 12 / math.log(2)
VALIDATION_SAMPLE_TEXTS = (
"Amanhã de manhã eu vou pôr o pão na mesa para os irmãos.",
"Eu almoço cedo quando o almoço está pronto no jogo.",
"Dia vinte e dois de março às quatorze horas custou duzentos reais.",
"Você tem certeza de que ele vem hoje à tarde?",
)
def save_validation_samples(model, output_dir, step):
import soundfile as sf
was_training = model.training
model.eval()
device = next(model.parameters()).device
sample_dir = Path(output_dir) / "samples" / f"step-{step:08d}"
sample_dir.mkdir(parents=True, exist_ok=True)
try:
with torch.no_grad():
for idx, text in enumerate(VALIDATION_SAMPLE_TEXTS, 1):
ph = phonemize(text)
tok = torch.tensor([ph.ids], device=device)
st = torch.tensor([ph.stress], device=device)
ln = torch.tensor([len(ph)], device=device)
sp = torch.tensor([0], device=device)
wave, lengths, _ = model.synthesize(tok, st, ln, sp, seed=0)
w = limit_peak(wave[0, : int(lengths[0])].cpu())
sf.write(sample_dir / f"sample_{idx:02d}.wav", w.numpy(), model.config.sample_rate, subtype="PCM_16")
finally:
if was_training:
model.train()
def masked_std(value, mask):
"""Standard deviation per row over the masked positions, [B]."""
count = mask.sum(1).clamp_min(1)
mean = (value * mask).sum(1) / count
return (((value - mean[:, None]).square() * mask).sum(1) / count + 1e-8).sqrt()
LINGUISTIC_MODULES = (
"tokens", "stress", "voices", "encoder", "duration",
"frame_voices", "frame_position", "prosody_stack", "prosody_head",
)
class TrainingSystem(nn.Module):
def __init__(self, config, waveform_loss=True, freeze_vocoder=False, vocos_checkpointing=False,
freeze_linguistic=False):
super().__init__()
self.model = LuaNovaBase(config)
self.mel_head = nn.Linear(config.channels, config.n_mels) if config.vocoder_type == "source_filter" else None
self.spectral = SpectralLoss(config.sample_rate)
self.waveform_loss = waveform_loss
self.vocos_checkpointing = vocos_checkpointing
self.freeze_linguistic = freeze_linguistic
if config.vocoder_type == "vocos" and freeze_vocoder:
self.model.vocoder.freeze_vocoder(True)
if freeze_linguistic:
for name in LINGUISTIC_MODULES:
mod = getattr(self.model, name)
for p in mod.parameters():
p.requires_grad_(False)
mod.eval()
def train(self, mode=True):
super().train(mode)
if self.freeze_linguistic:
for name in LINGUISTIC_MODULES:
getattr(self.model, name).eval()
return self
def objective(self, batch, teacher_probability, weights=WEIGHTS, random_phase=True):
"""Loss on full utterances. Returns ``(loss, terms, auxiliary)``.
``teacher_probability`` is the per-utterance chance that the acoustic
decoder is conditioned on recorded pitch/voicing/energy; otherwise it
gets the model's own (detached) predictions, exactly as at inference.
The oscillator always follows the recorded pitch here, because the
waveform target does.
"""
m, c = self.model, self.model.config
hidden, token_mask = m.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
output = m.duration(hidden, token_mask).float()
# Length is learned only where a token has frames; whether a pause-capable
# token has any is a separate yes/no target.
present = batch["durations"] > 0
duration = masked_mean((output[..., 0] - torch.log1p(batch["durations"].float())).square(), token_mask & present)
pausable = token_mask & ~m.phone_tokens[batch["tokens"]]
pause = masked_mean(F.binary_cross_entropy_with_logits(output[..., 1], present.float(), reduction="none"), pausable)
frames, frame_mask, lengths = m.expand(hidden, batch["durations"], token_mask, batch["speakers"])
if not torch.equal(lengths, batch["frame_lengths"]):
raise ValueError("durations do not sum to the acoustic frame count")
prosody_hidden, prediction = m.predict_prosody(frames, frame_mask)
prediction, target = prediction.float(), batch["prosody"]
trusted = batch["pitch_trusted"]
# Recorded pitch counts fully; interpolated stretches only keep the curve continuous.
pitch = masked_mean((prediction[..., 0] - target[..., 0]).abs(), frame_mask * (trusted + 0.1 * (1 - trusted)))
# An absolute-error fit alone predicts a flatter contour than people speak
# (about three quarters of the recorded spread on held-out text). Match each
# utterance's pitch spread as well, the classic global-variance correction.
sung = frame_mask * target[..., 1] * trusted
enough = (sung.sum(1) >= 10).float()
predicted_spread, recorded_spread = masked_std(prediction[..., 0], sung), masked_std(target[..., 0], sung)
pitch_spread = masked_mean((predicted_spread - recorded_spread).abs(), enough)
voicing = masked_mean(F.binary_cross_entropy_with_logits(prediction[..., 1], target[..., 1], reduction="none"), frame_mask)
energy = masked_mean((prediction[..., 2] - target[..., 2]).abs(), frame_mask)
teacher = torch.rand(len(lengths), device=lengths.device) < teacher_probability
condition = torch.where(teacher[:, None, None], target, m.hard_prosody(prediction.detach()))
acoustic = m.decode(prosody_hidden, condition.to(prosody_hidden.dtype), frame_mask)
if c.vocoder_type == "vocos":
mel_norm = m.vocoder.predict_mel(acoustic, frame_mask)
mel_target = (batch["vocos_mel"] - m.vocoder.mel_mean) / m.vocoder.mel_scale
mel_pred = masked_mean((mel_norm.float() - mel_target).abs().mean(-1), frame_mask)
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
mel_delta = masked_mean(
((mel_norm[:, 1:] - mel_norm[:, :-1]) - (mel_target[:, 1:] - mel_target[:, :-1])).abs().mean(-1),
pair_mask,
)
if self.waveform_loss:
wave = m.vocoder.decode_mel(mel_norm, lengths, checkpointing=self.vocos_checkpointing)
stft, mel = self.spectral(wave, batch["wave"], lengths * c.hop)
mel_head = mel_pred
reconstruction = weights["stft"] * stft + weights["mel"] * mel
else:
wave = None
stft = mel_pred.new_zeros(())
mel = mel_pred
mel_head = mel_pred.new_zeros(())
reconstruction = None
terms = dict(duration=duration, pause=pause, pitch=pitch, pitch_spread=pitch_spread, voicing=voicing,
energy=energy, mel_head=mel_head, mel_delta=mel_delta, stft=stft, mel=mel)
else:
mel_target = (batch["mel"] - c.mel_mean) / c.mel_scale
mel_head = masked_mean((self.mel_head(acoustic).float() - mel_target).abs().mean(-1), frame_mask)
phase = 2 * math.pi * torch.rand(len(lengths), device=lengths.device) if random_phase else None
wave = m.vocoder(acoustic, m.frequency(target[..., 0]), lengths, phase=phase)
stft, mel = self.spectral(wave, batch["wave"], lengths * c.hop)
reconstruction = weights["stft"] * stft + weights["mel"] * mel
terms = dict(duration=duration, pause=pause, pitch=pitch, pitch_spread=pitch_spread, voicing=voicing,
energy=energy, mel_head=mel_head, stft=stft, mel=mel)
loss = sum(weights[name] * value for name, value in terms.items())
with torch.no_grad():
voiced = sung
predicted = m.predict_durations(hidden, token_mask, batch["tokens"])
predicted_frames = predicted.sum(1)
pause_frames = (batch["durations"] * pausable).sum().clamp_min(1)
terms.update(
base_loss=loss.detach(), teacher_fraction=teacher.float().mean(),
pitch_error_semitones=SEMITONES * masked_mean((prediction[..., 0] - target[..., 0]).abs(), voiced),
pitch_spread_ratio=masked_mean(predicted_spread / recorded_spread.clamp_min(1e-3), enough),
voicing_accuracy=masked_mean(((prediction[..., 1] > 0) == target[..., 1].bool()).float(), frame_mask),
pause_accuracy=masked_mean(((output[..., 1] > 0) == present).float(), pausable),
pause_length_ratio=(predicted * pausable).sum() / pause_frames,
duration_length_ratio=(predicted_frames / lengths).mean(),
duration_length_error=((predicted_frames - lengths).abs() / lengths).mean())
return loss, terms, {"wave": wave, "reconstruction": reconstruction}
def crops(fake, real, lengths, size, count):
"""Aligned random windows [B*count, size] from generated and recorded audio,
plus the sample indices they cover ([B, count*size])."""
size = min(size, int(lengths.min()))
start = (torch.rand(len(lengths), count, device=fake.device) * (lengths[:, None] - size + 1)).long()
index = (start[..., None] + torch.arange(size, device=fake.device)).flatten(1)
return fake.gather(1, index).view(-1, size), real.gather(1, index).view(-1, size), index
def learning_rate(step, base, warmup, half_life, start=0):
"""Linear warm-up from ``start`` (0, or the step a run was branched at),
then halving every ``half_life`` steps."""
return base * min(1.0, (step - start + 1) / max(warmup, 1)) * 0.5 ** (step / half_life)
def teacher_probability(step, hold, ramp, final):
"""1 while the prosody predictor is still poor, then down to ``final``."""
return 1.0 if step < hold else max(final, 1.0 - (1.0 - final) * (step - hold) / max(ramp, 1))
def optimize_step(system, critics, optimizer, critic_optimizer, batch, step, recipe):
weights = recipe["weights"]
start = (recipe.get("branched_from") or {}).get("step", 0)
for group in optimizer.param_groups:
group["lr"] = learning_rate(step, recipe["learning_rate"], recipe["warmup"], recipe["lr_half_life"], start)
for group in critic_optimizer.param_groups:
group["lr"] = learning_rate(step, recipe["learning_rate"], 1, recipe["lr_half_life"], start)
optimizer.zero_grad(set_to_none=True)
probability = teacher_probability(step, recipe["teacher_hold"], recipe["teacher_ramp"], recipe["teacher_final"])
loss, metrics, auxiliary = system.objective(batch, probability, weights)
if step >= recipe["gan_start"]:
wave = auxiliary["wave"]
fake, real, index = crops(wave, batch["wave"], batch["frame_lengths"] * system.model.config.hop, recipe["crop_samples"], recipe["crops"])
critic_optimizer.zero_grad(set_to_none=True)
d_loss = discriminator_loss(critics(real), critics(fake.detach()))
d_loss.backward()
nn.utils.clip_grad_norm_(critics.parameters(), 10, error_if_nonfinite=True)
critic_optimizer.step()
critics.requires_grad_(False)
try:
with torch.no_grad():
real_features = critics(real)
adversarial, matching = generator_gan_loss(real_features, critics(fake))
gan = adversarial + recipe["feature_matching"] * matching
# Fixed weights cannot balance these terms: measured at the waveform, the
# adversarial gradient was under 1% of the spectral one, i.e. switched off.
# Scale the GAN term so that, inside the windows the critics saw, its
# gradient is ``gan_ratio`` times the reconstruction gradient.
reconstruction_gradient = torch.autograd.grad(auxiliary["reconstruction"], wave, retain_graph=True)[0].gather(1, index)
gan_gradient = torch.autograd.grad(gan, wave, retain_graph=True)[0].gather(1, index)
ramp = min(1.0, (step - recipe["gan_start"] + 1) / max(recipe["gan_ramp"], 1))
scale = (recipe["gan_ratio"] * ramp * reconstruction_gradient.norm() / gan_gradient.norm().clamp_min(1e-12))
scale = scale.clamp(max=recipe["gan_scale_max"]).detach()
loss = loss + scale * gan
metrics.update(discriminator=d_loss, adversarial=adversarial, feature_matching=matching, gan_scale=scale)
loss.backward()
finally:
critics.requires_grad_(True)
else:
loss.backward()
grad = nn.utils.clip_grad_norm_(system.parameters(), recipe["grad_clip"], error_if_nonfinite=True)
optimizer.step()
return {**{k: float(v.detach()) for k, v in metrics.items()}, "loss": float(loss.detach()), "grad_norm": float(grad),
"frames": int(batch["frame_lengths"].sum()), "utterances": len(batch["frame_lengths"])}
def export_model(model, path, step, annotation=None):
atomic_save({"format_version": CHECKPOINT_FORMAT, "config": model.config.to_dict(), "step": step,
"frontend": {**frontend_identity(), "fingerprint": frontend_fingerprint()}, "annotation": annotation,
"model": {k: v.detach().cpu() for k, v in model.state_dict().items()}}, path)
def load_compatible(module, state):
"""Load weights for a branched run. A tensor that grew (same rank, every
dimension at least as large) keeps the old values in its leading block and
its fresh initialisation elsewhere. Returns what was not an exact copy."""
current = module.state_dict()
report = {"grown": [], "new": [], "dropped": sorted(set(state) - set(current))}
for name, tensor in current.items():
if name not in state:
report["new"].append(name)
elif state[name].shape == tensor.shape:
current[name] = state[name]
elif state[name].ndim == tensor.ndim and all(a <= b for a, b in zip(state[name].shape, tensor.shape)):
merged = tensor.clone()
merged[tuple(slice(0, size) for size in state[name].shape)] = state[name]
current[name] = merged
report["grown"].append(name)
else:
raise ValueError(f"cannot branch: {name} changed shape from {tuple(state[name].shape)} to {tuple(tensor.shape)}")
module.load_state_dict(current)
return report
def balanced_indices(dataset, limit):
"""Stable round-robin over voices, independent of manifest order."""
groups = defaultdict(list)
for i, row in enumerate(dataset.rows):
groups[row["speaker"]].append(i)
limit = min(max(limit, len(groups)), len(dataset.rows))
selected = []
for offset in range(limit):
for voice in sorted(groups):
if offset < len(groups[voice]):
selected.append(groups[voice][offset])
if len(selected) == limit:
return selected
return selected
def check_leakage(train, validation):
ids = {r["id"] for r in train.rows}
texts = defaultdict(list)
for row in train.rows:
texts[row["text_hash"]].append(row["id"])
collisions = []
for row in validation.rows:
if row["id"] in ids or row["text_hash"] in texts:
collisions.append({"validation_id": row["id"], "train_ids": texts.get(row["text_hash"], [])[:3], "text": row.get("text", "")[:160]})
if len(collisions) == 5:
break
if collisions:
raise ValueError("train/validation leakage; split by sentence/text_id across BOTH voices. Examples: " + json.dumps(collisions, ensure_ascii=False))
@torch.no_grad()
def validate(system, dataset, indices, device, weights=WEIGHTS, batch_size=8):
"""Held-out metrics on a fixed balanced subset.
``teacher_forced`` conditions the decoder on recorded prosody, ``predicted``
on the model's own; both use recorded durations and pitch for the oscillator
so the spectra are comparable with the recording. Durations, pauses, pitch
and voicing errors are those of the free-running predictors. This is a
training monitor; pronunciation is judged separately with ASR and by listening.
"""
system.eval()
order = sorted(indices, key=lambda i: dataset.lengths[i])
totals, weight = defaultdict(float), 0
for start in range(0, len(order), batch_size):
batch = collate([dataset[i] for i in order[start:start + batch_size]], device)
size = len(batch["frame_lengths"])
for name, probability in (("teacher_forced", 1.0), ("predicted", 0.0)):
_, metrics, _ = system.objective(batch, probability, weights, random_phase=False)
totals[f"validation_{name}_mel"] += float(metrics["mel"]) * size
totals[f"validation_{name}_stft"] += float(metrics["stft"]) * size
for key in ("duration", "pause_accuracy", "pause_length_ratio", "pitch_error_semitones", "pitch_spread_ratio", "voicing_accuracy",
"duration_length_ratio", "duration_length_error"):
totals["validation_" + key] += float(metrics[key]) * size
weight += size
system.train()
return {key: value / weight for key, value in totals.items()}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--train", type=Path, required=True, help="Annotation manifest (train.jsonl)")
parser.add_argument("--validation", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--config", type=Path)
parser.add_argument("--device", default="cuda")
parser.add_argument("--steps", type=int, default=100000)
parser.add_argument("--batch-frames", type=int, default=9000, help="Padded acoustic frames per batch")
parser.add_argument("--max-batch", type=int, default=32)
parser.add_argument("--learning-rate", type=float, default=3e-4)
parser.add_argument("--warmup", type=int, default=1000)
parser.add_argument("--lr-half-life", type=float, default=100000)
parser.add_argument("--grad-clip", type=float, default=10.0)
parser.add_argument("--weights", type=json.loads, default={}, help="JSON overrides for the loss weights, e.g. '{\"mel\": 5}'")
parser.add_argument("--gan-start", type=int, default=8000)
parser.add_argument("--gan-ratio", type=float, default=0.7, help="Adversarial gradient as a fraction of the reconstruction gradient at the waveform")
parser.add_argument("--gan-ramp", type=int, default=3000, help="Steps over which the adversarial term fades in while the critics warm up")
parser.add_argument("--feature-matching", type=float, default=30.0, help="Feature-matching weight inside the adversarial term")
parser.add_argument("--gan-scale-max", type=float, default=2000.0)
parser.add_argument("--crop-samples", type=int, default=8192)
parser.add_argument("--crops", type=int, default=2, help="Discriminator windows per utterance")
parser.add_argument("--teacher-hold", type=int, default=3000, help="Steps with recorded prosody conditioning only")
parser.add_argument("--teacher-ramp", type=int, default=7000)
parser.add_argument("--teacher-final", type=float, default=0.0, help="Share of utterances still conditioned on recorded prosody "
"after the ramp (0 = the decoder sees only what it gets at inference)")
parser.add_argument("--subset", type=int, help="Train on the first N utterances (balanced by voice): memorisation check")
parser.add_argument("--validation-size", type=int, default=32)
parser.add_argument("--save-every", type=int, default=1000)
parser.add_argument("--keep-every", type=int, default=10000, help="Keep a numbered checkpoint at this interval and at the GAN boundary")
parser.add_argument("--sample-every", type=int, default=5000, help="Generate validation audio samples every N steps (0 to disable)")
parser.add_argument("--log-every", type=int, default=10)
parser.add_argument("--seed", type=int, default=20261113)
parser.add_argument("--max-seconds", type=float, default=3600, help="Wall-time cap per invocation; save and exit at a step boundary")
parser.add_argument("--deadline-file", type=Path, help="Budget JSON with an absolute 'deadline'; training saves and exits before it")
parser.add_argument("--deadline-margin", type=float, default=300)
parser.add_argument("--resume", type=Path, help="Continue the same run exactly (same recipe, data and configuration)")
parser.add_argument("--init-from", type=Path, help="Start a NEW run from another run's checkpoint with a changed recipe: "
"weights, step counter and already-trained critics are taken over; the data order starts fresh")
parser.add_argument("--new-data", action="store_true", help="With --init-from: the checkpoint comes from a different annotation "
"run or front end (same symbol inventory)")
parser.add_argument("--stop-file", type=Path, help="Save and exit after a step when this file appears")
parser.add_argument("--recorded-voicing", action="store_true", help="Use the pitch tracker's voicing as it is, "
"without marking vowel frames voiced")
parser.add_argument("--no-preload", action="store_true", help="Load feature files lazily instead of before the first step")
parser.add_argument("--vocoder", choices=("source_filter", "vocos"), default=None, help="Vocoder architecture")
parser.add_argument("--vocos-stats", type=Path, default=None, help="JSON with Vocos per-channel mel mean and scale")
parser.add_argument("--freeze-vocoder", action="store_true", help="Keep pretrained Vocos weights frozen")
parser.add_argument("--freeze-linguistic", action="store_true",
help="Freeze encoder, duration and prosody predictors (refine only acoustic stack + vocoder)")
parser.add_argument("--no-waveform-loss", action="store_true", help="Skip waveform decode and STFT loss (mel-only Stage 1)")
parser.add_argument("--vocos-checkpointing", action="store_true", help="Gradient checkpoint Vocos ConvNeXt blocks")
args = parser.parse_args()
if min(args.steps, args.batch_frames, args.max_batch, args.save_every, args.keep_every, args.log_every, args.crops, args.gan_ramp) < 1:
parser.error("steps, batch limits and intervals must be positive")
if args.max_seconds <= 0 or args.learning_rate <= 0 or args.lr_half_life <= 0 or not 0 <= args.teacher_final <= 1:
parser.error("time cap, learning rate and half life must be positive; teacher_final in [0, 1]")
if set(args.weights) - set(WEIGHTS) or min(args.gan_ratio, args.feature_matching, args.gan_scale_max) < 0:
parser.error(f"--weights may only override {sorted(WEIGHTS)}; GAN settings must be non-negative")
if args.resume and args.init_from:
parser.error("--init-from starts a new run; --resume continues one")
if args.no_waveform_loss and args.gan_start < args.steps:
parser.error("--no-waveform-loss requires --gan-start >= --steps")
# The budget file is re-read while training so a deliberate extension (or cut) takes effect.
budget = {"deadline": math.inf, "checked": time.time()}
if args.deadline_file:
budget["deadline"] = float(json.loads(args.deadline_file.read_text())["deadline"]) - args.deadline_margin
def deadline():
if args.deadline_file and time.time() - budget["checked"] > 30:
budget["checked"] = time.time()
try:
budget["deadline"] = float(json.loads(args.deadline_file.read_text())["deadline"]) - args.deadline_margin
except (OSError, ValueError, KeyError):
pass # keep the last valid deadline while the file is being rewritten
return budget["deadline"]
if time.time() >= deadline():
raise SystemExit("the cloud budget deadline has passed (or is too close); not starting")
if args.config:
c = Config.from_dict(json.loads(args.config.read_text()))
elif args.vocoder is not None:
c = Config(vocoder_type=args.vocoder)
elif args.resume or args.init_from:
ckpt_state = torch.load(args.resume or args.init_from, map_location="cpu", weights_only=True)
c = Config.from_dict(ckpt_state["config"])
del ckpt_state
else:
c = Config()
torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
train = AnnotatedDataset(args.train, c, voiced_vowels=not args.recorded_voicing)
validation = AnnotatedDataset(args.validation, c, voiced_vowels=not args.recorded_voicing)
check_leakage(train, validation)
if train.annotation != validation.annotation:
raise ValueError("train and validation manifests come from different annotation runs")
if args.output.exists() and any(args.output.iterdir()) and not args.resume:
raise FileExistsError("output directory is not empty; use --resume or a new directory")
pool = balanced_indices(train, args.subset) if args.subset else list(range(len(train)))
validation_indices = balanced_indices(validation, args.validation_size)
if not args.no_preload:
train.preload(pool)
validation.preload(validation_indices)
system = TrainingSystem(
c,
waveform_loss=not args.no_waveform_loss,
freeze_vocoder=args.freeze_vocoder,
vocos_checkpointing=args.vocos_checkpointing,
freeze_linguistic=args.freeze_linguistic,
).to(args.device)
if c.vocoder_type == "vocos" and args.vocos_stats:
stats = json.loads(args.vocos_stats.read_text(encoding="utf-8"))
system.model.vocoder.set_mel_stats(stats["mean"], stats["scale"])
critics = Discriminators().to(args.device)
count = sum(p.numel() for p in system.model.parameters())
budget_limit = 25_000_000 if c.vocoder_type == "vocos" else 5_000_000
if count > budget_limit:
raise ValueError(f"inference parameter budget exceeded: {count:,}")
trainable_params = [p for p in system.parameters() if p.requires_grad] if args.freeze_linguistic else list(system.parameters())
optimizer = torch.optim.AdamW(trainable_params, lr=args.learning_rate, betas=(0.8, 0.99), weight_decay=0.01)
critic_optimizer = torch.optim.AdamW(critics.parameters(), lr=args.learning_rate, betas=(0.8, 0.99), weight_decay=0.0)
sampler = BucketSampler([train.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
fingerprints = [train.fingerprint, validation.fingerprint]
recipe = {key: getattr(args, key) for key in ("batch_frames", "max_batch", "learning_rate", "warmup", "lr_half_life", "grad_clip",
"gan_start", "gan_ratio", "gan_ramp", "feature_matching", "gan_scale_max",
"crop_samples", "crops", "teacher_hold", "teacher_ramp", "teacher_final",
"subset", "validation_size", "seed")}
recipe["voiced_vowel_targets"] = not args.recorded_voicing
recipe["vocoder_type"] = c.vocoder_type
recipe["freeze_vocoder"] = bool(args.freeze_vocoder)
recipe["freeze_linguistic"] = bool(args.freeze_linguistic)
recipe["waveform_loss"] = not args.no_waveform_loss
recipe["weights"] = {**WEIGHTS, **{key: float(value) for key, value in args.weights.items()}}
recipe["branched_from"] = None
step = 0
def compatible(state, what, same_data=True):
if state.get("format_version") != CHECKPOINT_FORMAT:
raise ValueError(f"checkpoint predates phoneme tokens and supervised durations (format < 4); it cannot be {what}")
if same_data and (state["frontend"] != frontend_fingerprint() or state["annotation"] != train.annotation):
raise ValueError("checkpoint was trained with a different front end or annotation run "
"(branch with --init-from and --new-data to fine-tune on new annotations)")
if state["config"] != c.to_dict():
raise ValueError("checkpoint was trained with a different model configuration")
if args.resume:
state = torch.load(args.resume, map_location=args.device, weights_only=True)
compatible(state, "resumed")
recipe["branched_from"] = state["recipe"].get("branched_from")
if state["datasets"] != fingerprints or state["recipe"] != recipe:
raise ValueError("resume recipe or dataset mismatch (use --init-from to branch a new run with a changed recipe)")
system.load_state_dict(state["system"])
critics.load_state_dict(state["critics"])
optimizer.load_state_dict(state["optimizer"])
critic_optimizer.load_state_dict(state["critic_optimizer"])
sampler.load_state(state["sampler"])
torch.set_rng_state(state["torch_rng"].cpu())
if str(args.device).startswith("cuda") and state["cuda_rng"] is not None:
torch.cuda.set_rng_state_all([x.cpu() for x in state["cuda_rng"]])
step = state["step"]
elif args.init_from:
state = torch.load(args.init_from, map_location=args.device, weights_only=True)
# The symbol inventory is fixed (vocabulary size is part of the configuration),
# so a checkpoint can be fine-tuned on another annotation run or front end.
compatible(state, "branched", same_data=not args.new_data)
step = state["step"]
loaded = load_compatible(system, state["system"])
# Critics that have already been trained are taken over, otherwise a branch
# in the adversarial phase would hand full-strength gradients from untrained
# critics to the generator. Optimizer moments are kept when no tensor changed.
loaded["critics"] = step > state["recipe"]["gan_start"]
if loaded["critics"]:
critics.load_state_dict(state["critics"])
critic_optimizer.load_state_dict(state["critic_optimizer"])
loaded["optimizer"] = (
not loaded["grown"] and not loaded["new"] and not loaded["dropped"]
and not args.freeze_linguistic
)
if loaded["optimizer"]:
optimizer.load_state_dict(state["optimizer"])
recipe["branched_from"] = {"step": step, "recipe": state["recipe"], "datasets": state["datasets"], "loaded": loaded}
if args.new_data:
recipe["branched_from"].update(frontend=state["frontend"], annotation=state["annotation"])
if step >= args.steps:
raise ValueError("checkpoint already reached requested total steps")
args.output.mkdir(parents=True, exist_ok=True)
(args.output / "config.json").write_text(json.dumps(c.to_dict(), indent=2) + "\n")
(args.output / "recipe.json").write_text(json.dumps({**recipe, "annotation": train.annotation, "frontend": frontend_fingerprint(),
"train_utterances": len(pool), "datasets": fingerprints}, indent=2) + "\n")
mel_head_params = sum(p.numel() for p in system.mel_head.parameters()) if system.mel_head is not None else 0
print(json.dumps({"inference_parameters": count, "training_only_parameters": mel_head_params
+ sum(p.numel() for p in critics.parameters()), "train_utterances": len(pool), "start_step": step,
"branched": bool(args.init_from), "resumed": bool(args.resume)}), flush=True)
start = time.monotonic()
system.train()
def snapshot():
return {"format_version": CHECKPOINT_FORMAT, "config": c.to_dict(), "frontend": frontend_fingerprint(), "annotation": train.annotation,
"step": step, "datasets": fingerprints, "recipe": recipe, "system": system.state_dict(), "critics": critics.state_dict(),
"optimizer": optimizer.state_dict(), "critic_optimizer": critic_optimizer.state_dict(), "sampler": sampler.state(),
"torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state_all() if str(args.device).startswith("cuda") else None}
if step == args.gan_start and not args.resume:
atomic_save(snapshot(), args.output / f"step-{step:08d}.pt")
window, window_steps, window_start = defaultdict(float), 0, time.monotonic()
while step < args.steps:
batch = collate([train[pool[i]] for i in sampler.next()], args.device)
metrics = optimize_step(system, critics, optimizer, critic_optimizer, batch, step, recipe)
step += 1
for key, value in metrics.items():
window[key] += value
window_steps += 1
elapsed = time.monotonic() - start
should_stop = (elapsed >= args.max_seconds or step == args.steps or time.time() >= deadline()
or (args.stop_file is not None and args.stop_file.exists()))
retain = step == args.gan_start or step % args.keep_every == 0
save = step % args.save_every == 0 or should_stop or retain
if step % args.log_every == 0 or save:
if str(args.device).startswith("cuda"):
torch.cuda.synchronize()
seconds = time.monotonic() - window_start
record = {key: (value if key in ("frames", "utterances") else value / window_steps) for key, value in window.items()}
record.update(step=step, elapsed_seconds=elapsed, steps_per_second=window_steps / max(seconds, 1e-9),
audio_seconds_per_second=window["frames"] * c.hop / c.sample_rate / max(seconds, 1e-9),
learning_rate=optimizer.param_groups[0]["lr"])
if save:
record.update(validate(system, validation, validation_indices, args.device, recipe["weights"]))
state = snapshot()
atomic_save(state, args.output / "last.pt")
export_model(system.model, args.output / "inference.pt", step, train.annotation)
if retain:
atomic_save(state, args.output / f"step-{step:08d}.pt")
with (args.output / "metrics.jsonl").open("a") as stream:
stream.write(json.dumps(record) + "\n")
print(json.dumps(record), flush=True)
window, window_steps, window_start = defaultdict(float), 0, time.monotonic()
if args.sample_every > 0 and (step % args.sample_every == 0 or step == args.steps):
save_validation_samples(system.model, args.output, step)
if should_stop:
break
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464"""Anti-forgetting fine-tuning of MIT BigVGAN (base or v1 Large) on F1 real + CFM v5 predicted mels."""
from __future__ import annotations
import argparse
from collections import defaultdict
import copy
import json
import math
from pathlib import Path
import time
import torch
from torch import nn
from torch.nn import functional as F
from ..data.dataset import AnnotatedDataset, collate
from ..models.bigvgan import BigVGANMelExtractor, _ensure_bigvgan_importable
from ..models.cfm import energy_noise_gate, f0_features
from .common import atomic_save, balanced_indices, check_leakage, load_cfm_model, update_ema
@torch.inference_mode()
def precompute_gt_and_cfm_mels(
ds: AnnotatedDataset,
indices: list[int],
cfm,
extractor: BigVGANMelExtractor,
device: str,
seed: int = 0,
cfm_steps: int = 8,
cfm_temp: float = 0.35,
sway_coef: float = -0.5,
) -> tuple[dict[int, torch.Tensor], dict[int, torch.Tensor]]:
"""Precompute exact ``gt_mel`` and ``CFM v5`` predicted ``cfm_mel`` (``all_gt``) in RAM."""
gt_mels: dict[int, torch.Tensor] = {}
cfm_mels: dict[int, torch.Tensor] = {}
for idx in indices:
wav = ds[idx]["wave"].to(device=device, dtype=torch.float32)
gt_mels[idx] = extractor(wav)[0].half().cpu()
sorted_idx = sorted(indices, key=lambda i: ds.lengths[i])
use_amp = str(device).startswith("cuda")
for start in range(0, len(sorted_idx), 16):
chunk = sorted_idx[start : start + 16]
batch = collate([ds[i] for i in chunk], device)
with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=use_amp):
h, m = cfm.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
pt, ct = cfm.encode_prosody_context(h, batch["tokens"], batch["stress"], m)
af, _, fm, fl = cfm.expand_with_context(h, pt, ct, batch["durations"], m, batch["speakers"])
hp = cfm.hard_prosody(batch["prosody"])
cond, prior = cfm.condition_and_prior(af, hp, fm)
f0f = f0_features(hp, fm) if cfm.cfm_config.use_f0_harmonics else None
ng = energy_noise_gate(hp, fm) if cfm.cfm_config.use_energy_gate else None
mel_norm = cfm.sample_mel(
cond, prior, fm, n_steps=cfm_steps, cfg_scale=1.0, temperature=cfm_temp,
solver="midpoint", seed=seed, f0_feats=f0f, noise_gate=ng, sway_coef=sway_coef,
)
phys = (mel_norm.float() * cfm.vocoder.mel_scale + cfm.vocoder.mel_mean).clamp(min=-11.512925)
for b_i, ds_i in enumerate(chunk):
cfm_mels[ds_i] = phys[b_i, : int(fl[b_i])].half().cpu()
return gt_mels, cfm_mels
def sample_ft_crops(
ds: AnnotatedDataset,
indices: list[int],
gt_mels: dict[int, torch.Tensor],
cfm_mels: dict[int, torch.Tensor],
batch_size: int,
crop_frames: int,
cfm_prob: float,
hop: int,
rng: torch.Generator,
device: str,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Sample aligned ``[B, 100, crop_frames]`` mel crops (gt/cfm mix) and ``[B, 1, crop_frames*hop]`` real wave."""
eligible = [i for i in indices if ds.lengths[i] >= crop_frames]
pick = torch.randint(len(eligible), (batch_size,), generator=rng).tolist()
mels = torch.zeros((batch_size, 100, crop_frames), dtype=torch.float32)
waves = torch.zeros((batch_size, 1, crop_frames * hop), dtype=torch.float32)
use_cfm = torch.rand((batch_size,), generator=rng).tolist()
for b, e_idx in enumerate(pick):
ds_i = eligible[e_idx]
t_tot = int(gt_mels[ds_i].shape[0])
s0 = int(torch.randint(0, t_tot - crop_frames + 1, (1,), generator=rng).item())
src = cfm_mels[ds_i] if use_cfm[b] < cfm_prob else gt_mels[ds_i]
mels[b] = src[s0 : s0 + crop_frames].float().transpose(0, 1)
waves[b, 0] = ds[ds_i]["wave"][s0 * hop : (s0 + crop_frames) * hop]
return mels.to(device), waves.to(device)
def _update_ema(ema_gen: nn.Module, gen: nn.Module, decay: float, on_cpu: bool) -> None:
if not on_cpu:
update_ema(ema_gen, gen, decay)
return
with torch.no_grad():
for p_ema, p in zip(ema_gen.parameters(), gen.parameters()):
if p.requires_grad:
p_ema.mul_(decay).add_(p.detach().cpu(), alpha=1.0 - decay)
@torch.no_grad()
def validate_bigvgan(
gen,
ext: BigVGANMelExtractor,
ds: AnnotatedDataset,
indices: list[int],
gt_mels: dict[int, torch.Tensor],
cfm_mels: dict[int, torch.Tensor],
device: str,
ema_on_cpu: bool = False,
) -> dict[str, float]:
was_training = gen.training
if ema_on_cpu:
gen.to(device)
gen.eval()
gt_tot, cfm_tot, n = 0.0, 0.0, 0
try:
for idx in indices:
gt_m = gt_mels[idx][None].to(device=device, dtype=torch.float32)
t_len = int(gt_m.shape[1])
cfm_m = cfm_mels[idx][None].to(device=device, dtype=torch.float32)
w_from_gt = gen(gt_m.transpose(1, 2)).squeeze(1)[:, : t_len * 256]
w_from_cfm = gen(cfm_m.transpose(1, 2)).squeeze(1)[:, : t_len * 256]
gt_tot += float(F.l1_loss(ext(w_from_gt), gt_m))
cfm_tot += float(F.l1_loss(ext(w_from_cfm), gt_m))
n += 1
finally:
if was_training:
gen.train()
if ema_on_cpu:
gen.to("cpu")
if str(device).startswith("cuda") and torch.cuda.is_available():
torch.cuda.empty_cache()
return {"val_gt_mel_l1": gt_tot / max(n, 1), "val_cfm_mel_l1": cfm_tot / max(n, 1)}
def _lr_g_at(step: int, disc_warmup: int, warmup_g: int, total_steps: int, lr_g: float, min_lr_g: float) -> float:
if step < disc_warmup:
return 0.0
gs = step - disc_warmup
g_tot = max(total_steps - disc_warmup, 1)
if gs < warmup_g:
return lr_g * (gs + 1) / max(warmup_g, 1)
prog = min(max((gs - warmup_g) / max(g_tot - warmup_g, 1), 0.0), 1.0)
return min_lr_g + 0.5 * (lr_g - min_lr_g) * (1.0 + math.cos(math.pi * prog))
def _lr_d_at(step: int, disc_warmup: int, total_steps: int, lr_d: float, lr_d_post: float, min_lr_d: float) -> float:
if step < disc_warmup:
return lr_d
prog = min(max((step - disc_warmup) / max(total_steps - disc_warmup, 1), 0.0), 1.0)
return min_lr_d + 0.5 * (lr_d_post - min_lr_d) * (1.0 + math.cos(math.pi * prog))
def _save_bigvgan_ckpt(gen, model_id: str, step: int, path: Path) -> None:
atomic_save(
{
"format": "bigvgan_ft_v1",
"model_id": model_id,
"step": int(step),
"weight_norm_removed": False,
"h": dict(gen.h),
"state_dict": {k: v.detach().cpu() for k, v in gen.state_dict().items()},
},
path,
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--train", type=Path, required=True)
parser.add_argument("--validation", type=Path, required=True)
parser.add_argument("--cfm-ckpt", type=Path, required=True)
parser.add_argument("--model-id", default="nvidia/bigvgan_base_24khz_100band")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--device", default="cuda")
parser.add_argument("--steps", type=int, default=3500)
parser.add_argument("--disc-warmup", type=int, default=500)
parser.add_argument("--batch-size", type=int, default=6)
parser.add_argument("--grad-accum", type=int, default=2)
parser.add_argument("--crop-frames", type=int, default=32)
parser.add_argument("--cfm-prob", type=float, default=0.50)
parser.add_argument("--bf16", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--lr-g", type=float, default=2e-5)
parser.add_argument("--min-lr-g", type=float, default=2e-6)
parser.add_argument("--warmup-g", type=int, default=300)
parser.add_argument("--lr-d", type=float, default=1e-4)
parser.add_argument("--lr-d-post", type=float, default=5e-5)
parser.add_argument("--min-lr-d", type=float, default=5e-6)
parser.add_argument("--ema-decay", type=float, default=0.995)
parser.add_argument("--val-every", type=int, default=500)
parser.add_argument("--log-every", type=int, default=10)
parser.add_argument("--save-steps", nargs="+", type=int, default=[2000, 3500])
parser.add_argument("--pretrained-disc", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--cfm-steps", type=int, default=8)
parser.add_argument("--cfm-temp", type=float, default=0.35)
parser.add_argument("--sway-coef", type=float, default=-0.5)
parser.add_argument("--ema-on-cpu", action=argparse.BooleanOptionalAction, default=False)
parser.add_argument("--seed", type=int, default=20261122)
args = parser.parse_args()
torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
_ensure_bigvgan_importable()
import bigvgan
from discriminators import MultiPeriodDiscriminator, MultiResolutionDiscriminator
from loss import discriminator_loss, feature_loss, generator_loss
cfm = load_cfm_model(args.cfm_ckpt, args.device)
train_ds = AnnotatedDataset(args.train, cfm.config, voiced_vowels=True, cache=True)
val_ds = AnnotatedDataset(args.validation, cfm.config, voiced_vowels=True, cache=True)
check_leakage(train_ds, val_ds)
pool = [i for i in range(len(train_ds)) if train_ds.lengths[i] >= args.crop_frames]
val_indices = balanced_indices(val_ds, len(val_ds))
print(f"Preloading train ({len(pool)}) and validation ({len(val_indices)}) ...", flush=True)
train_ds.preload(pool, workers=8)
val_ds.preload(val_indices, workers=4)
ext = BigVGANMelExtractor().to(args.device).eval()
t0_pre = time.perf_counter()
train_gt, train_cfm = precompute_gt_and_cfm_mels(
train_ds, pool, cfm, ext, args.device, seed=0,
cfm_steps=args.cfm_steps, cfm_temp=args.cfm_temp, sway_coef=args.sway_coef,
)
val_gt, val_cfm = precompute_gt_and_cfm_mels(
val_ds, val_indices, cfm, ext, args.device, seed=0,
cfm_steps=args.cfm_steps, cfm_temp=args.cfm_temp, sway_coef=args.sway_coef,
)
del cfm
torch.cuda.empty_cache()
print(
f"Precomputed paired GT + CFM mels (s={args.cfm_steps}, T={args.cfm_temp}, sway={args.sway_coef}) in {time.perf_counter() - t0_pre:.1f}s",
flush=True,
)
gen = bigvgan.BigVGAN.from_pretrained(args.model_id, use_cuda_kernel=False).to(args.device)
ema_device = "cpu" if args.ema_on_cpu else args.device
ema_gen = bigvgan.BigVGAN(gen.h, use_cuda_kernel=False).to(ema_device)
ema_gen.load_state_dict({k: v.detach().to(ema_device).clone() for k, v in gen.state_dict().items()}, strict=True)
ema_gen.eval()
for p in ema_gen.parameters():
p.requires_grad_(False)
mpd = MultiPeriodDiscriminator(gen.h).to(args.device)
mrd = MultiResolutionDiscriminator(gen.h).to(args.device)
disc_msg = "Discriminators initialized randomly"
if args.pretrained_disc:
from huggingface_hub import hf_hub_download
do_path = hf_hub_download(args.model_id, "bigvgan_discriminator_optimizer.pt")
do_ckpt = torch.load(do_path, map_location="cpu", weights_only=True)
mpd.load_state_dict(do_ckpt["mpd"], strict=True)
mrd.load_state_dict(do_ckpt["mrd"], strict=True)
disc_msg = f"Loaded pretrained NVIDIA MPD/MRD from {args.model_id} (steps={do_ckpt.get('steps')})"
del do_ckpt
disc_params = list(mpd.parameters()) + list(mrd.parameters())
for p in gen.parameters():
p.requires_grad_(False)
opt_g = torch.optim.AdamW(list(gen.parameters()), lr=args.lr_g, betas=(0.8, 0.99), weight_decay=0.0)
opt_d = torch.optim.AdamW(disc_params, lr=args.lr_d, betas=(0.8, 0.99), weight_decay=0.0)
args.output.mkdir(parents=True, exist_ok=True)
log_f = (args.output / "train.log").open("a", encoding="utf-8", buffering=1)
def emit(msg: str) -> None:
print(msg, flush=True)
log_f.write(msg + "\n")
log_f.flush()
emit(f"{disc_msg} | ema_on_cpu={args.ema_on_cpu}")
is_cuda = torch.cuda.is_available() and str(args.device).startswith("cuda")
use_bf16 = bool(args.bf16 and is_cuda)
grad_accum = max(int(args.grad_accum), 1)
if is_cuda:
torch.cuda.reset_peak_memory_stats(args.device)
v0 = validate_bigvgan(ema_gen, ext, val_ds, val_indices, val_gt, val_cfm, args.device, ema_on_cpu=args.ema_on_cpu)
emit(f"[step 0] {json.dumps(v0)}")
rng = torch.Generator().manual_seed(args.seed + 31)
hop = int(gen.h.hop_size)
win = defaultdict(float)
win_n = 0
win_t = time.monotonic()
save_set = set(int(s) for s in args.save_steps) | {int(args.steps)}
try:
for step in range(args.steps):
if step == args.disc_warmup:
for p in gen.parameters():
p.requires_grad_(True)
if is_cuda:
torch.cuda.reset_peak_memory_stats(args.device)
emit(f"[step {step}] Generator unfrozen (lr_g -> {args.lr_g}, bf16={use_bf16}, bs={args.batch_size}x{grad_accum})")
lr_d = _lr_d_at(step, args.disc_warmup, args.steps, args.lr_d, args.lr_d_post, args.min_lr_d)
for pg in opt_d.param_groups:
pg["lr"] = lr_d
lr_g = _lr_g_at(step, args.disc_warmup, args.warmup_g, args.steps, args.lr_g, args.min_lr_g)
for pg in opt_g.param_groups:
pg["lr"] = lr_g
opt_d.zero_grad(set_to_none=True)
if step >= args.disc_warmup:
opt_g.zero_grad(set_to_none=True)
acc_loss_d = 0.0
acc_loss_g = 0.0
acc_mel = 0.0
acc_fm = 0.0
acc_adv = 0.0
for _micro in range(grad_accum):
mel_crop, y = sample_ft_crops(
train_ds, pool, train_gt, train_cfm, args.batch_size, args.crop_frames, args.cfm_prob, hop, rng, args.device
)
# Forward generator
if step < args.disc_warmup:
gen.eval()
with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
y_g_hat = gen(mel_crop)
else:
gen.train()
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
y_g_hat = gen(mel_crop)
y_g_det_bf = y_g_hat.detach()
y_g_det_32 = y_g_det_bf.float()
y_32 = y.float()
# Discriminator micro-step
mpd.train()
mrd.train()
for p in disc_params:
p.requires_grad_(True)
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
y_df_r, y_df_g, _, _ = mpd(y, y_g_det_bf)
with torch.amp.autocast("cuda", enabled=False):
loss_df, _, _ = discriminator_loss([t.float() for t in y_df_r], [t.float() for t in y_df_g])
y_ds_r, y_ds_g, _, _ = mrd(y_32, y_g_det_32)
loss_ds, _, _ = discriminator_loss(y_ds_r, y_ds_g)
loss_d_mb = loss_df + loss_ds
if not torch.isfinite(loss_d_mb):
raise RuntimeError(f"Non-finite loss_d at step {step}: {loss_d_mb}")
(loss_d_mb / grad_accum).backward()
acc_loss_d += float(loss_d_mb.detach()) / grad_accum
del y_df_r, y_df_g, y_ds_r, y_ds_g, y_g_det_bf, y_g_det_32
# Generator micro-step after disc warmup
if step >= args.disc_warmup:
for p in disc_params:
p.requires_grad_(False)
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
y_df_r, y_df_g, fmap_f_r, fmap_f_g = mpd(y, y_g_hat)
y_g_hat_32 = y_g_hat.float()
with torch.amp.autocast("cuda", enabled=False):
y_ds_r, y_ds_g, fmap_s_r, fmap_s_g = mrd(y_32, y_g_hat_32)
loss_mel_mb = F.l1_loss(ext(y_g_hat_32.squeeze(1)), ext(y_32.squeeze(1))) * 45.0
loss_fm_mb = (
feature_loss([[a.float() for a in l] for l in fmap_f_r], [[a.float() for a in l] for l in fmap_f_g])
+ feature_loss(fmap_s_r, fmap_s_g)
)
loss_gen_mb = generator_loss([t.float() for t in y_df_g])[0] + generator_loss(y_ds_g)[0]
loss_g_mb = loss_gen_mb + loss_fm_mb + loss_mel_mb
if not torch.isfinite(loss_g_mb):
raise RuntimeError(f"Non-finite loss_g at step {step}: {loss_g_mb}")
(loss_g_mb / grad_accum).backward()
acc_loss_g += float(loss_g_mb.detach()) / grad_accum
acc_mel += float(loss_mel_mb.detach()) / grad_accum
acc_fm += float(loss_fm_mb.detach()) / grad_accum
acc_adv += float(loss_gen_mb.detach()) / grad_accum
del y_g_hat_32, y_df_r, y_df_g, fmap_f_r, fmap_f_g, y_ds_r, y_ds_g, fmap_s_r, fmap_s_g
else:
with torch.no_grad(), torch.amp.autocast("cuda", enabled=False):
loss_mel_mb = F.l1_loss(ext(y_g_hat.float().squeeze(1)), ext(y_32.squeeze(1))) * 45.0
acc_mel += float(loss_mel_mb.detach()) / grad_accum
acc_loss_g += float(loss_mel_mb.detach()) / grad_accum
del y_g_hat, mel_crop, y, y_32
for p in disc_params:
p.requires_grad_(True)
nn.utils.clip_grad_norm_(disc_params, 1.0)
opt_d.step()
if step >= args.disc_warmup:
grad_g = float(nn.utils.clip_grad_norm_(gen.parameters(), 1.0))
opt_g.step()
_update_ema(ema_gen, gen, args.ema_decay, args.ema_on_cpu)
else:
grad_g = 0.0
cur = step + 1
win["loss_g"] += acc_loss_g
win["loss_d"] += acc_loss_d
win["mel"] += acc_mel
win["fm"] += acc_fm
win["adv"] += acc_adv
win["grad_g"] += grad_g
win_n += 1
do_val = (cur % args.val_every == 0) or (cur == args.steps)
do_save = cur in save_set
do_log = (cur % args.log_every == 0) or (cur == args.disc_warmup + 1) or do_val or do_save
if do_log:
if is_cuda:
torch.cuda.synchronize()
dt = max(time.monotonic() - win_t, 1e-6)
it_s = win_n / dt
eta_min = (args.steps - cur) / max(it_s, 1e-6) / 60.0
vram_gb = (torch.cuda.memory_allocated(args.device) / 1e9) if is_cuda else 0.0
vram_peak_gb = (torch.cuda.max_memory_allocated(args.device) / 1e9) if is_cuda else 0.0
rec = {k: round(v / win_n, 4) for k, v in win.items()}
rec.update(
step=cur,
lr_g=round(lr_g, 7),
lr_d=round(lr_d, 7),
it_s=round(it_s, 2),
eta_min=round(eta_min, 2),
vram_gb=round(vram_gb, 2),
vram_peak_gb=round(vram_peak_gb, 2),
)
if do_val:
rec.update(
{
k: round(v, 5)
for k, v in validate_bigvgan(
ema_gen, ext, val_ds, val_indices, val_gt, val_cfm, args.device, ema_on_cpu=args.ema_on_cpu
).items()
}
)
with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as mf:
mf.write(json.dumps(rec) + "\n")
mf.flush()
pct = 100.0 * cur / max(args.steps, 1)
msg = (
f"[step {cur:05d}/{args.steps:05d} | {pct:5.1f}%] "
f"loss_g={rec['loss_g']:.3f} mel={rec['mel']:.3f} fm={rec['fm']:.3f} adv={rec['adv']:.3f} loss_d={rec['loss_d']:.3f} | "
f"{rec['it_s']:.2f} it/s | ETA {rec['eta_min']:.1f}m | VRAM {rec['vram_gb']:.2f}/{rec['vram_peak_gb']:.2f} GB"
)
if do_val:
msg += f" | val_gt={rec['val_gt_mel_l1']:.5f} val_cfm={rec['val_cfm_mel_l1']:.5f}"
emit(msg)
win = defaultdict(float)
win_n = 0
win_t = time.monotonic()
if do_save:
_save_bigvgan_ckpt(ema_gen, args.model_id, cur, args.output / f"bigvgan_ft_step-{cur:06d}.pt")
_save_bigvgan_ckpt(ema_gen, args.model_id, cur, args.output / "bigvgan_ft_ema.pt")
finally:
log_f.close()
if __name__ == "__main__":
main()12345678910111213141516171819202122232425262728293031"""Shared audio and checkpoint utilities."""
from .audio import (
DEFAULT_FADE_MS,
DEFAULT_TARGET_RMS_DB,
PEAK,
finished,
limit_peak,
pcm16,
postprocess_audio,
sentences,
shorter,
split_clauses,
)
from .checkpoint import atomic_save, soup_checkpoints, strip_legacy_vocoder
__all__ = [
"DEFAULT_FADE_MS",
"DEFAULT_TARGET_RMS_DB",
"PEAK",
"atomic_save",
"finished",
"limit_peak",
"pcm16",
"postprocess_audio",
"sentences",
"shorter",
"soup_checkpoints",
"split_clauses",
"strip_legacy_vocoder",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""Audio post-processing, PCM16 conversion, and text segmentation helpers."""
from __future__ import annotations
import math
import re
import numpy as np
import torch
PEAK = 0.99
DEFAULT_TARGET_RMS_DB = -14.5
DEFAULT_FADE_MS = 5.0
_SPACE = re.compile(r"[\s\ufeff]+")
_SENTENCE_END = re.compile(r"""(?:(?<=[.!?…])|(?<=[.!?…]["')\]]))\s+(?=["'(\[]?[A-ZÀ-Ý0-9])""")
_NOT_AN_END = re.compile(
r"(?:\b(?:mr|mrs|ms|dr|dra|sr|sra|srta|prof|profa|jr|st|sto|sta|vs|etc|no|inc|ltd|ltda|co|pág|cap|fig|art|e\.g|i\.e|a\.m|p\.m)|\b[A-ZÀ-Ý])\.$",
re.IGNORECASE,
)
_CLAUSE_END = re.compile(r"(?<=[,;:—])\s+")
_TEXT_END = re.compile(r"[\s\ufeff]+$")
_CLOSING = "\"'”’)]»"
def pcm16(wave: np.ndarray | torch.Tensor) -> tuple[np.ndarray, float]:
"""Scale samples into [-1, 1] when peak > 1.0 and return ``(samples, attenuation_db)``."""
arr = wave.detach().cpu().numpy() if isinstance(wave, torch.Tensor) else wave
arr = np.asarray(arr, dtype=np.float64)
peak = float(np.abs(arr).max()) if arr.size else 0.0
if peak <= 1.0:
return arr, 0.0
return arr / peak, round(20.0 * float(np.log10(peak)), 2)
def limit_peak(wave: torch.Tensor, peak: float = PEAK) -> torch.Tensor:
"""Scale ``wave`` down as a whole only when its peak amplitude exceeds ``peak``."""
loudest = float(wave.abs().max()) if wave.numel() else 0.0
return wave * (peak / loudest) if loudest > peak else wave
def _postprocess_numpy(
arr: np.ndarray,
sample_rate: int,
target_rms_db: float | None,
peak: float | None,
fade_ms: float,
) -> np.ndarray:
if not arr.size:
return arr
out = np.asarray(arr, dtype=np.float32)
if target_rms_db is not None:
loudest = float(np.abs(out).max())
if loudest > 1e-7:
frame_len = max(1, int(round(sample_rate * 0.02)))
usable = (out.size // frame_len) * frame_len
if usable >= frame_len:
f_rms = np.sqrt((out[:usable].reshape(-1, frame_len) ** 2).mean(axis=1))
active = f_rms[f_rms > loudest * (10.0 ** (-35.0 / 20.0))]
rms = float(np.sqrt((active ** 2).mean())) if active.size else float(np.sqrt((out ** 2).mean()))
else:
rms = float(np.sqrt((out ** 2).mean()))
target_rms = 10.0 ** (float(target_rms_db) / 20.0)
gain = max(0.25, min(4.0, target_rms / max(rms, 1e-8)))
out = out * np.float32(gain)
if fade_ms and fade_ms > 0:
n = min(int(round(sample_rate * fade_ms / 1000.0)), out.size // 2)
if n > 1:
out = out.copy()
ramp = (0.5 * (1.0 - np.cos(np.linspace(0.0, math.pi, n, dtype=np.float32)))).astype(np.float32)
out[:n] *= ramp
out[-n:] *= ramp[::-1]
if peak is not None:
loudest = float(np.abs(out).max())
if loudest > peak:
out = out * np.float32(peak / loudest)
return out
def postprocess_audio(
wave: np.ndarray | torch.Tensor,
sample_rate: int = 24000,
target_rms_db: float | None = DEFAULT_TARGET_RMS_DB,
peak: float | None = PEAK,
fade_ms: float = DEFAULT_FADE_MS,
) -> np.ndarray | torch.Tensor:
"""Normalize active-speech RMS, apply short cosine edge fades, and limit peaks."""
if isinstance(wave, torch.Tensor):
if not wave.numel():
return wave
processed = _postprocess_numpy(wave.detach().cpu().numpy(), sample_rate, target_rms_db, peak, fade_ms)
return torch.from_numpy(processed).to(device=wave.device, dtype=wave.dtype)
return _postprocess_numpy(np.asarray(wave, dtype=np.float32), sample_rate, target_rms_db, peak, fade_ms)
def sentences(text: str) -> list[str]:
"""Split text into natural sentences without breaking on common abbreviations."""
parts, current = [], ""
for piece in _SENTENCE_END.split(_SPACE.sub(" ", text).strip()):
current = f"{current} {piece}" if current else piece
if not _NOT_AN_END.search(current):
parts.append(current)
current = ""
if current:
parts.append(current)
return [part for part in parts if any(ch.isalnum() for ch in part)]
def finished(text: str) -> str:
"""Append a final period when text ends without terminal or clause punctuation."""
body = _TEXT_END.sub("", text)
if not body:
return text
last = _SPACE.split(body)[-1]
if any(ch.isalnum() for ch in last):
marked = last.rstrip(_CLOSING)[-1:] in tuple(".!?…,;:")
else:
marked = any(ch in ".!?…" for ch in last) or last in (",", ";", ":")
return text if marked else body + "."
def shorter(text: str) -> list[str]:
"""Split an overly long sentence on clause punctuation, or at its middle word."""
pieces = _CLAUSE_END.split(text)
if len(pieces) > 1:
return pieces
words = text.split(" ")
if len(words) < 2:
return []
half = (len(words) + 1) // 2
return [" ".join(words[:half]), " ".join(words[half:])]
def split_clauses(text: str) -> list[str]:
"""Split text into sentences and clause-level chunks with terminal punctuation."""
chunks: list[str] = []
for sent in sentences(text):
for clause in _CLAUSE_END.split(finished(sent)):
clean = clause.strip()
if clean:
chunks.append(clean)
return chunks or ([text.strip()] if text.strip() else [])12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Checkpoint I/O, weight-soup interpolation, and lightweight inference stripping."""
from __future__ import annotations
import os
from pathlib import Path
import torch
def atomic_save(value: object, path: Path | str) -> None:
"""Write a torch object safely using a temporary sibling file and atomic replace."""
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
temporary = target.with_suffix(target.suffix + ".tmp")
torch.save(value, temporary)
os.replace(temporary, target)
def soup_checkpoints(
ckpt_a: Path | str,
ckpt_b: Path | str,
out_path: Path | str,
alpha: float = 0.5,
) -> Path:
"""Interpolate ``(1 - alpha) * a + alpha * b`` across all floating-point ``model`` weights."""
a = torch.load(ckpt_a, map_location="cpu", weights_only=True)
b = torch.load(ckpt_b, map_location="cpu", weights_only=True)
sd_a, sd_b = a["model"], b["model"]
if set(sd_a.keys()) != set(sd_b.keys()):
raise ValueError("checkpoints do not have identical model keys for souping")
w_a = 1.0 - float(alpha)
w_b = float(alpha)
merged = {}
for k in sd_a:
ta, tb = sd_a[k], sd_b[k]
if torch.is_floating_point(ta):
merged[k] = (w_a * ta.float() + w_b * tb.float()).to(ta.dtype)
else:
merged[k] = ta.clone()
out = dict(a)
out["model"] = merged
out["soup"] = {"alpha": float(alpha), "source_a": Path(ckpt_a).name, "source_b": Path(ckpt_b).name}
atomic_save(out, out_path)
return Path(out_path)
def strip_legacy_vocoder(
ckpt_path: Path | str,
out_path: Path | str,
fp16: bool = False,
) -> Path:
"""Strip unused legacy Vocos weights from a BigVGAN-space CFM checkpoint for distribution."""
state = torch.load(ckpt_path, map_location="cpu", weights_only=True)
sd = state["model"]
cleaned = {}
for k, v in sd.items():
if k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale"):
continue
cleaned[k] = v.half() if (fp16 and torch.is_floating_point(v)) else v.clone()
out = dict(state)
out["model"] = cleaned
out["stripped_legacy_vocoder"] = True
atomic_save(out, out_path)
return Path(out_path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Unit tests for CFMConfig, LuaNovaCFM, Sway Sampling, BigVGAN mel extractor, and checkpoint helpers."""
from __future__ import annotations
from pathlib import Path
import tempfile
import unittest
import torch
from lua_nova_v1.config import CFMConfig, Config
from lua_nova_v1.models import BigVGANMelExtractor, MelStatsHead, LuaNovaCFM
from lua_nova_v1.training.common import export_cfm_checkpoint, load_cfm_model
from lua_nova_v1.utils.checkpoint import soup_checkpoints, strip_legacy_vocoder
class ModelTests(unittest.TestCase):
def _tiny_cfg(self) -> CFMConfig:
base = Config(
channels=32,
heads=2,
feedforward=64,
encoder_layers=1,
prosody_layers=1,
acoustic_layers=1,
predictor_channels=16,
vocos_n_mels=100,
)
return CFMConfig(
base=base,
flow_channels=32,
flow_layers=2,
flow_heads=2,
flow_feedforward=64,
flow_kernel=3,
use_acoustic_prior=True,
use_f0_harmonics=True,
acoustic_from_frames=True,
use_energy_gate=True,
use_ling_context=True,
use_duration_flow=True,
use_prosody_flow=True,
prosody_context_layers=1,
dur_flow_channels=16,
dur_flow_layers=1,
dur_flow_heads=2,
dur_flow_feedforward=32,
prosody_flow_channels=16,
prosody_flow_layers=1,
prosody_flow_heads=2,
prosody_flow_feedforward=32,
mel_space="bigvgan_24k_100",
)
def test_mel_stats_head_requires_no_external_vocos(self) -> None:
model = LuaNovaCFM(self._tiny_cfg())
self.assertIsInstance(model.vocoder, MelStatsHead)
self.assertIsNone(model.vocoder.vocos)
def test_sway_schedule_and_parity(self) -> None:
uniform = LuaNovaCFM.sway_time_grid(8, sway_coef=0.0)
self.assertEqual(uniform, [i / 8 for i in range(9)])
swayed = LuaNovaCFM.sway_time_grid(8, sway_coef=-0.5)
self.assertAlmostEqual(swayed[0], 0.0, places=6)
self.assertAlmostEqual(swayed[-1], 1.0, places=6)
self.assertTrue(all(a < b for a, b in zip(swayed[:-1], swayed[1:])))
self.assertLess(swayed[4], 0.5)
model = LuaNovaCFM(self._tiny_cfg()).eval()
cond = torch.randn(1, 12, 32)
prior = torch.randn(1, 12, 100)
fmask = torch.ones(1, 12, dtype=torch.bool)
f0_f = torch.randn(1, 12, 12)
m1 = model.sample_mel(cond, prior, fmask, n_steps=4, cfg_scale=1.0, temperature=0.35, seed=7, f0_feats=f0_f, sway_coef=0.0)
m2 = model.sample_mel(cond, prior, fmask, n_steps=4, cfg_scale=1.0, temperature=0.35, seed=7, f0_feats=f0_f, sway_coef=-0.5)
self.assertEqual(m1.shape, (1, 12, 100))
self.assertTrue(torch.isfinite(m1).all() and torch.isfinite(m2).all())
def test_bigvgan_mel_extractor_shapes_and_finiteness(self) -> None:
ext = BigVGANMelExtractor().eval()
wave = torch.randn(2, 256 * 20) * 0.1
mel = ext(wave)
self.assertEqual(mel.shape, (2, 20, 100))
self.assertTrue(torch.isfinite(mel).all())
mel_1d = ext(wave[0])
self.assertTrue(torch.allclose(mel[0], mel_1d[0], atol=1e-5))
def test_checkpoint_strip_soup_and_load_roundtrip(self) -> None:
m_a = LuaNovaCFM(self._tiny_cfg()).eval()
m_b = LuaNovaCFM(self._tiny_cfg()).eval()
with tempfile.TemporaryDirectory() as tmp:
p_a = Path(tmp) / "a.pt"
p_b = Path(tmp) / "b.pt"
p_soup = Path(tmp) / "soup.pt"
p_strip = Path(tmp) / "stripped.pt"
export_cfm_checkpoint(m_a, p_a, step=10)
export_cfm_checkpoint(m_b, p_b, step=20)
soup_checkpoints(p_a, p_b, p_soup, alpha=0.5)
strip_legacy_vocoder(p_soup, p_strip, fp16=True)
loaded = load_cfm_model(p_strip, device="cpu")
for k in m_a.state_dict():
if not (k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale")):
expected = 0.5 * m_a.state_dict()[k] + 0.5 * m_b.state_dict()[k]
if torch.is_floating_point(expected):
self.assertLess((loaded.state_dict()[k] - expected).abs().max().item(), 1e-2)
if __name__ == "__main__":
unittest.main().gitattributes+9
README.md+196
checkpoints/bigvgan_base_optB_2k.ptAdded+3
checkpoints/cfm_v5_fast2.ptAdded+3
checkpoints/cfm_v5_soup50.ptAdded+3
code/.gitignoreAdded+37
code/LICENSEAdded+202
code/README.mdAdded+208
code/THIRD_PARTY_NOTICES.mdAdded+14
code/docs/ARCHITECTURE.mdAdded+38
code/docs/FINE_TUNING.mdAdded+139
code/docs/OPTIMIZATION.mdAdded+113
code/docs/TRAINING_FROM_SCRATCH.mdAdded+137
code/pyproject.tomlAdded+60
code/src/lua_nova_v1/__init__.pyAdded+26
code/src/lua_nova_v1/config.pyAdded+199
code/src/lua_nova_v1/data/__init__.pyAdded+15
code/src/lua_nova_v1/data/aligner.pyAdded+301
code/src/lua_nova_v1/data/annotate.pyAdded+324
code/src/lua_nova_v1/data/dataset.pyAdded+179
code/src/lua_nova_v1/data/journal.pyAdded+73
code/src/lua_nova_v1/data/prepare.pyAdded+212
code/src/lua_nova_v1/data/refine.pyAdded+152
code/src/lua_nova_v1/export/__init__.pyAdded+30
code/src/lua_nova_v1/export/onnx_export.pyAdded+526
code/src/lua_nova_v1/inference/__init__.pyAdded+7
code/src/lua_nova_v1/inference/cli.pyAdded+131
code/src/lua_nova_v1/inference/onnx_engine.pyAdded+170
code/src/lua_nova_v1/inference/streaming.pyAdded+96
code/src/lua_nova_v1/inference/synthesizer.pyAdded+209
code/src/lua_nova_v1/models/__init__.pyAdded+39
code/src/lua_nova_v1/models/bigvgan.pyAdded+135
code/src/lua_nova_v1/models/cfm.pyAdded+900
code/src/lua_nova_v1/models/frontend.pyAdded+474
code/src/lua_nova_v1/models/losses.pyAdded+130
code/src/lua_nova_v1/text/__init__.pyAdded+69
code/src/lua_nova_v1/text/normalizer.pyAdded+343
code/src/lua_nova_v1/text/phonemizer.pyAdded+347
code/src/lua_nova_v1/training/__init__.pyAdded+31
code/src/lua_nova_v1/training/cfm.pyAdded+269
code/src/lua_nova_v1/training/cfm_e2e.pyAdded+474
code/src/lua_nova_v1/training/common.pyAdded+315
code/src/lua_nova_v1/training/distill.pyAdded+376
code/src/lua_nova_v1/training/prosody_flow.pyAdded+548
code/src/lua_nova_v1/training/stage1.pyAdded+583
code/src/lua_nova_v1/training/vocoder_ft.pyAdded+464
code/src/lua_nova_v1/utils/__init__.pyAdded+31
code/src/lua_nova_v1/utils/audio.pyAdded+141
code/src/lua_nova_v1/utils/checkpoint.pyAdded+67
code/tests/test_model.pyAdded+109