diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..8933229c3e6a8c72e60340c93a6fb57395b0581a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +samples/stress_cot_00.wav filter=lfs diff=lfs merge=lfs -text +samples/stress_emo_00.wav filter=lfs diff=lfs merge=lfs -text +samples/stress_est_00.wav filter=lfs diff=lfs merge=lfs -text +samples/test_01_gen.wav filter=lfs diff=lfs merge=lfs -text +samples/test_01_ref.wav filter=lfs diff=lfs merge=lfs -text +samples/test_02_gen.wav filter=lfs diff=lfs merge=lfs -text +samples/test_02_ref.wav filter=lfs diff=lfs merge=lfs -text +samples/test_03_gen.wav filter=lfs diff=lfs merge=lfs -text +samples/test_03_ref.wav filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 154df8298fab5ecf322016157858e08cd1bccbe1..da0a93fcd71b46a6bcccc1b8b9ab544d4f8ab258 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,199 @@ --- +language: +- pt license: apache-2.0 +library_name: pytorch +pipeline_tag: text-to-speech +tags: +- text-to-speech +- tts +- brazilian-portuguese +- pt-br +- flow-matching +- bigvgan +- onnx +- single-speaker +datasets: +- 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 o +dataset [`oProfM/LuaNovaDataset`](https://huggingface.co/datasets/oProfM/LuaNovaDataset) com a arquitetura +Lua 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ápido + +Requer Python 3.11/3.12, [`uv`](https://docs.astral.sh/uv/) e `espeak-ng` no `PATH`. + +```bash +git clone https://huggingface.co/oProfM/LuaNovaV1 +cd LuaNovaV1/code +uv sync # + "uv sync --extra onnx" para ONNX Runtime +``` + +```python +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", # 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): + +```python +from lua_nova_v1 import OnnxSynthesizer +ox = 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`. + +## Dados + +Fonte: `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 preservar + frases 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). + +## Treinamento + +Hardware (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 o +fine-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 foi + retomada 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ção + +Juízes do `tts-eval` (UTMOS22-strong, SCOREQ, DNSMOS P.835, Whisper-small para WER/CER, ECAPA para similaridade +de 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 e +DNSMOS. 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ência + +5 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**. diff --git a/checkpoints/bigvgan_base_optB_2k.pt b/checkpoints/bigvgan_base_optB_2k.pt new file mode 100644 index 0000000000000000000000000000000000000000..4850b531a87a5131a40075df6f790c3ea9b38f0f --- /dev/null +++ b/checkpoints/bigvgan_base_optB_2k.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db0fe65486dd98892b282bb5c07c02f18e43bdb946dd1a58134dcd7206ff53ea +size 56285259 diff --git a/checkpoints/cfm_v5_fast2.pt b/checkpoints/cfm_v5_fast2.pt new file mode 100644 index 0000000000000000000000000000000000000000..0b5dfa3d0d92ce6241edda72a62967ebde05460b --- /dev/null +++ b/checkpoints/cfm_v5_fast2.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89431d10d153160fa54b41f3a6a2db7dbe917ea9ce959a5e4ad2a772b6406885 +size 87242383 diff --git a/checkpoints/cfm_v5_soup50.pt b/checkpoints/cfm_v5_soup50.pt new file mode 100644 index 0000000000000000000000000000000000000000..5b6c8a299b987697fc2977d847bd3399e7129b0d --- /dev/null +++ b/checkpoints/cfm_v5_soup50.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce6297351ce0e8b5535e77f8be61b7f946aa07895c76cf4c1166442416df734b +size 87243013 diff --git a/code/.gitignore b/code/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d1ba0a0df9ef4d4762702acd5e5bd08f71b0a174 --- /dev/null +++ b/code/.gitignore @@ -0,0 +1,37 @@ +# 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.db diff --git a/code/LICENSE b/code/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..75b52484ea471f882c29e02693b4f02dba175b5e --- /dev/null +++ b/code/LICENSE @@ -0,0 +1,202 @@ + + 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. diff --git a/code/README.md b/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4d78565c945eb6d34370e9212798b254ecb03900 --- /dev/null +++ b/code/README.md @@ -0,0 +1,208 @@ +# 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). diff --git a/code/THIRD_PARTY_NOTICES.md b/code/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000000000000000000000000000000000000..cd54327fcbca797b9e5061076f10b8c8516cb6bf --- /dev/null +++ b/code/THIRD_PARTY_NOTICES.md @@ -0,0 +1,14 @@ +# 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. diff --git a/code/docs/ARCHITECTURE.md b/code/docs/ARCHITECTURE.md new file mode 100644 index 0000000000000000000000000000000000000000..04dff69881723d19e53c96a9f42ae8d98ea34b28 --- /dev/null +++ b/code/docs/ARCHITECTURE.md @@ -0,0 +1,38 @@ +# 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 `` 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. diff --git a/code/docs/FINE_TUNING.md b/code/docs/FINE_TUNING.md new file mode 100644 index 0000000000000000000000000000000000000000..1be1023a87d10e82f200f8923c2d0944f274fbb7 --- /dev/null +++ b/code/docs/FINE_TUNING.md @@ -0,0 +1,139 @@ +# 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 +``` diff --git a/code/docs/OPTIMIZATION.md b/code/docs/OPTIMIZATION.md new file mode 100644 index 0000000000000000000000000000000000000000..d74421947e875c6a6bc90afd63c1b0f48b31ac61 --- /dev/null +++ b/code/docs/OPTIMIZATION.md @@ -0,0 +1,113 @@ +# 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 `.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. diff --git a/code/docs/TRAINING_FROM_SCRATCH.md b/code/docs/TRAINING_FROM_SCRATCH.md new file mode 100644 index 0000000000000000000000000000000000000000..1a46c5cc683c031a8e1b605d1da50801aa579589 --- /dev/null +++ b/code/docs/TRAINING_FROM_SCRATCH.md @@ -0,0 +1,137 @@ +# 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`. diff --git a/code/pyproject.toml b/code/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..43ffb52658c094723449b595770c423c8ea70e4b --- /dev/null +++ b/code/pyproject.toml @@ -0,0 +1,60 @@ +[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 = true diff --git a/code/src/lua_nova_v1/__init__.py b/code/src/lua_nova_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7720cce2aaf8cd97bc8bfda38b43560d9a6781bd --- /dev/null +++ b/code/src/lua_nova_v1/__init__.py @@ -0,0 +1,26 @@ +"""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", +] diff --git a/code/src/lua_nova_v1/config.py b/code/src/lua_nova_v1/config.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb392a41894bbe12818d862d03ed361b7776b18 --- /dev/null +++ b/code/src/lua_nova_v1/config.py @@ -0,0 +1,199 @@ +"""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) diff --git a/code/src/lua_nova_v1/data/__init__.py b/code/src/lua_nova_v1/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..09e700518e9914495a1ec35b0e34c38bce52b5bf --- /dev/null +++ b/code/src/lua_nova_v1/data/__init__.py @@ -0,0 +1,15 @@ +"""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", +] diff --git a/code/src/lua_nova_v1/data/aligner.py b/code/src/lua_nova_v1/data/aligner.py new file mode 100644 index 0000000000000000000000000000000000000000..2aa33956f6211e3f71d05b1d3b84db26ffc57bd0 --- /dev/null +++ b/code/src/lua_nova_v1/data/aligner.py @@ -0,0 +1,301 @@ +"""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: ""} + + +@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(), qc diff --git a/code/src/lua_nova_v1/data/annotate.py b/code/src/lua_nova_v1/data/annotate.py new file mode 100644 index 0000000000000000000000000000000000000000..8d00c8be893288ffae84db29098715a5177cff24 --- /dev/null +++ b/code/src/lua_nova_v1/data/annotate.py @@ -0,0 +1,324 @@ +"""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 .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-") + 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() diff --git a/code/src/lua_nova_v1/data/dataset.py b/code/src/lua_nova_v1/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ee968f277b1199ff890833502350148beae27379 --- /dev/null +++ b/code/src/lua_nova_v1/data/dataset.py @@ -0,0 +1,179 @@ +"""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"]] diff --git a/code/src/lua_nova_v1/data/journal.py b/code/src/lua_nova_v1/data/journal.py new file mode 100644 index 0000000000000000000000000000000000000000..10fe0aeaaf58207f7cad7da1041e82c9c5fd7834 --- /dev/null +++ b/code/src/lua_nova_v1/data/journal.py @@ -0,0 +1,73 @@ +"""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) diff --git a/code/src/lua_nova_v1/data/prepare.py b/code/src/lua_nova_v1/data/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..7351d8e2ad052e28e8119d39ef3291bb7a326396 --- /dev/null +++ b/code/src/lua_nova_v1/data/prepare.py @@ -0,0 +1,212 @@ +"""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() diff --git a/code/src/lua_nova_v1/data/refine.py b/code/src/lua_nova_v1/data/refine.py new file mode 100644 index 0000000000000000000000000000000000000000..d689d5a717ce23c9ef9101fad2aeff2ec04e1f1e --- /dev/null +++ b/code/src/lua_nova_v1/data/refine.py @@ -0,0 +1,152 @@ +"""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 == "" 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 results diff --git a/code/src/lua_nova_v1/export/__init__.py b/code/src/lua_nova_v1/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9f473b7c50f40a6abc522d8493f703ca12b8b56 --- /dev/null +++ b/code/src/lua_nova_v1/export/__init__.py @@ -0,0 +1,30 @@ +"""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", +] diff --git a/code/src/lua_nova_v1/export/onnx_export.py b/code/src/lua_nova_v1/export/onnx_export.py new file mode 100644 index 0000000000000000000000000000000000000000..7766fe5cc863c256a4f9be4c10843b493493187b --- /dev/null +++ b/code/src/lua_nova_v1/export/onnx_export.py @@ -0,0 +1,526 @@ +"""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() diff --git a/code/src/lua_nova_v1/inference/__init__.py b/code/src/lua_nova_v1/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..54893c9c5162f3e71617a92c7c3ccd52cd5b3a87 --- /dev/null +++ b/code/src/lua_nova_v1/inference/__init__.py @@ -0,0 +1,7 @@ +"""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"] diff --git a/code/src/lua_nova_v1/inference/cli.py b/code/src/lua_nova_v1/inference/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..bdee325240beda3a01dcd9ce33d1639599706ccb --- /dev/null +++ b/code/src/lua_nova_v1/inference/cli.py @@ -0,0 +1,131 @@ +"""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() diff --git a/code/src/lua_nova_v1/inference/onnx_engine.py b/code/src/lua_nova_v1/inference/onnx_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..9d33d5f71fd4f912fb608f305d8ce7a74b7102e9 --- /dev/null +++ b/code/src/lua_nova_v1/inference/onnx_engine.py @@ -0,0 +1,170 @@ +"""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_path diff --git a/code/src/lua_nova_v1/inference/streaming.py b/code/src/lua_nova_v1/inference/streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..b82c873b6bebae45b352659eaf11848974f3e486 --- /dev/null +++ b/code/src/lua_nova_v1/inference/streaming.py @@ -0,0 +1,96 @@ +"""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 = end diff --git a/code/src/lua_nova_v1/inference/synthesizer.py b/code/src/lua_nova_v1/inference/synthesizer.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f575cc70a93c785002ad80acc2427bc555213b --- /dev/null +++ b/code/src/lua_nova_v1/inference/synthesizer.py @@ -0,0 +1,209 @@ +"""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_path diff --git a/code/src/lua_nova_v1/models/__init__.py b/code/src/lua_nova_v1/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d83b8ba3e34f8341d3e468c03b7b26f9b4c1541 --- /dev/null +++ b/code/src/lua_nova_v1/models/__init__.py @@ -0,0 +1,39 @@ +"""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", +] diff --git a/code/src/lua_nova_v1/models/bigvgan.py b/code/src/lua_nova_v1/models/bigvgan.py new file mode 100644 index 0000000000000000000000000000000000000000..c4846f579c05112ba6af918449451e24ba88747d --- /dev/null +++ b/code/src/lua_nova_v1/models/bigvgan.py @@ -0,0 +1,135 @@ +"""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 wav diff --git a/code/src/lua_nova_v1/models/cfm.py b/code/src/lua_nova_v1/models/cfm.py new file mode 100644 index 0000000000000000000000000000000000000000..3e25151a07ab926d67bf8104ae1d998343d19a87 --- /dev/null +++ b/code/src/lua_nova_v1/models/cfm.py @@ -0,0 +1,900 @@ +"""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[""] +_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, details diff --git a/code/src/lua_nova_v1/models/frontend.py b/code/src/lua_nova_v1/models/frontend.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee1b0f8bace7fa2d5386e2944eb7414cecbe94d --- /dev/null +++ b/code/src/lua_nova_v1/models/frontend.py @@ -0,0 +1,474 @@ +"""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} diff --git a/code/src/lua_nova_v1/models/losses.py b/code/src/lua_nova_v1/models/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..119f7a0014d3a605019db53be93cd54904d060af --- /dev/null +++ b/code/src/lua_nova_v1/models/losses.py @@ -0,0 +1,130 @@ +import 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, matching diff --git a/code/src/lua_nova_v1/text/__init__.py b/code/src/lua_nova_v1/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5026b60d7413be2638cbad51255fa1bc207d09ca --- /dev/null +++ b/code/src/lua_nova_v1/text/__init__.py @@ -0,0 +1,69 @@ +"""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", +] diff --git a/code/src/lua_nova_v1/text/normalizer.py b/code/src/lua_nova_v1/text/normalizer.py new file mode 100644 index 0000000000000000000000000000000000000000..4e281598a523770e38be07c925077860997b6bee --- /dev/null +++ b/code/src/lua_nova_v1/text/normalizer.py @@ -0,0 +1,343 @@ +"""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"(? 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() diff --git a/code/src/lua_nova_v1/text/phonemizer.py b/code/src/lua_nova_v1/text/phonemizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e30a721d6b85805180ad6239ce26ffa383828477 --- /dev/null +++ b/code/src/lua_nova_v1/text/phonemizer.py @@ -0,0 +1,347 @@ +"""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 = "", "", "", "", "" +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 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] diff --git a/code/src/lua_nova_v1/training/__init__.py b/code/src/lua_nova_v1/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2b55347dc764b1b5e53fd0a49587419441e6e6 --- /dev/null +++ b/code/src/lua_nova_v1/training/__init__.py @@ -0,0 +1,31 @@ +"""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", +] diff --git a/code/src/lua_nova_v1/training/cfm.py b/code/src/lua_nova_v1/training/cfm.py new file mode 100644 index 0000000000000000000000000000000000000000..b0beda623a66c180f44888282557822285e2ac12 --- /dev/null +++ b/code/src/lua_nova_v1/training/cfm.py @@ -0,0 +1,269 @@ +"""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() diff --git a/code/src/lua_nova_v1/training/cfm_e2e.py b/code/src/lua_nova_v1/training/cfm_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3751232f5d1babf827bf4694f584bcddcb25f0 --- /dev/null +++ b/code/src/lua_nova_v1/training/cfm_e2e.py @@ -0,0 +1,474 @@ +"""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() diff --git a/code/src/lua_nova_v1/training/common.py b/code/src/lua_nova_v1/training/common.py new file mode 100644 index 0000000000000000000000000000000000000000..9a4cf8b03ab08857819a565168b18488cb6e010d --- /dev/null +++ b/code/src/lua_nova_v1/training/common.py @@ -0,0 +1,315 @@ +"""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()} diff --git a/code/src/lua_nova_v1/training/distill.py b/code/src/lua_nova_v1/training/distill.py new file mode 100644 index 0000000000000000000000000000000000000000..476c1437b40bda678dc9a4063c94204ca5116ddc --- /dev/null +++ b/code/src/lua_nova_v1/training/distill.py @@ -0,0 +1,376 @@ +"""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() diff --git a/code/src/lua_nova_v1/training/prosody_flow.py b/code/src/lua_nova_v1/training/prosody_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..3e5b6779b2e048f310d662398bfa63030bbb7e49 --- /dev/null +++ b/code/src/lua_nova_v1/training/prosody_flow.py @@ -0,0 +1,548 @@ +"""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() diff --git a/code/src/lua_nova_v1/training/stage1.py b/code/src/lua_nova_v1/training/stage1.py new file mode 100644 index 0000000000000000000000000000000000000000..79bc4db3615121ef6e137c57f5698e5a2ffd4c31 --- /dev/null +++ b/code/src/lua_nova_v1/training/stage1.py @@ -0,0 +1,583 @@ +"""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() diff --git a/code/src/lua_nova_v1/training/vocoder_ft.py b/code/src/lua_nova_v1/training/vocoder_ft.py new file mode 100644 index 0000000000000000000000000000000000000000..ae28216f95d3e7bfe53b654298814d8f5693f202 --- /dev/null +++ b/code/src/lua_nova_v1/training/vocoder_ft.py @@ -0,0 +1,464 @@ +"""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() diff --git a/code/src/lua_nova_v1/utils/__init__.py b/code/src/lua_nova_v1/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e7c61bed26b9290b8f32e48bc22da9d8a45064b --- /dev/null +++ b/code/src/lua_nova_v1/utils/__init__.py @@ -0,0 +1,31 @@ +"""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", +] diff --git a/code/src/lua_nova_v1/utils/audio.py b/code/src/lua_nova_v1/utils/audio.py new file mode 100644 index 0000000000000000000000000000000000000000..59858787408c56cb3ed4c10f0d8d2514de636bb9 --- /dev/null +++ b/code/src/lua_nova_v1/utils/audio.py @@ -0,0 +1,141 @@ +"""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 []) diff --git a/code/src/lua_nova_v1/utils/checkpoint.py b/code/src/lua_nova_v1/utils/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c82ed4602b801204d66b2e04eaad45783db0e7 --- /dev/null +++ b/code/src/lua_nova_v1/utils/checkpoint.py @@ -0,0 +1,67 @@ +"""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) diff --git a/code/tests/test_model.py b/code/tests/test_model.py new file mode 100644 index 0000000000000000000000000000000000000000..626b046fff32a70564b6d32a0d9ad3baf80ec883 --- /dev/null +++ b/code/tests/test_model.py @@ -0,0 +1,109 @@ +"""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() diff --git a/code/tests/test_onnx_and_streaming.py b/code/tests/test_onnx_and_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..4c330599c6821834eb55662f5c13938d38b9ace5 --- /dev/null +++ b/code/tests/test_onnx_and_streaming.py @@ -0,0 +1,240 @@ +"""Unit tests for ONNX export parity, chunked vocoder streaming, and OT-CFM distillation.""" +from __future__ import annotations + +import copy +from pathlib import Path +import tempfile +import unittest + +import numpy as np +import torch + +from lua_nova_v1.config import CFMConfig, Config +from lua_nova_v1.export import ( + ExportableCFMAcoustic, + example_cfm_inputs, + export_bigvgan_onnx, + export_cfm_onnx, + verify_bigvgan_onnx, + verify_cfm_onnx, +) +from lua_nova_v1.inference import OnnxSynthesizer +from lua_nova_v1.inference.streaming import stream_vocoder_chunks +from lua_nova_v1.models import BigVGANVocoderWrapper, LuaNovaCFM +from lua_nova_v1.models.bigvgan import _ensure_bigvgan_importable +from lua_nova_v1.training.distill import distill_loss_step, make_channel_weights + + +def _tiny_v5_cfg() -> 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", + ) + + +class OnnxAndStreamingTests(unittest.TestCase): + def test_cfm_onnx_export_and_parity_euler2_and_sway8(self) -> None: + model = LuaNovaCFM(_tiny_v5_cfg()).eval() + # Deterministic math check between predict_physical_mel and ExportableCFMAcoustic. + inp = example_cfm_inputs("Dia vinte e dois de março, vamos testar!") + wrapper_det = ExportableCFMAcoustic( + model, n_steps=4, solver="midpoint", sway_coef=-0.5, temperature=0.0, dur_temp=0.0, prosody_temp=0.0 + ).eval() + with torch.no_grad(): + mel_ref, flen_ref, _ = model.predict_physical_mel( + inp[0], + inp[1], + torch.tensor([inp[0].shape[1]]), + inp[2], + speed=float(inp[3].item()), + pitch_shift=float(inp[4].item()), + pitch_range=float(inp[5].item()), + n_steps=4, + cfg_scale=1.0, + temperature=0.0, + solver="midpoint", + sway_coef=-0.5, + dur_temp=0.0, + prosody_temp=0.0, + ) + mel_wrap, flen_wrap = wrapper_det(*inp) + self.assertEqual(int(flen_ref.item()), int(flen_wrap.item())) + self.assertLess((mel_ref - mel_wrap).abs().max().item(), 1e-4) + + with tempfile.TemporaryDirectory() as tmp: + onnx_euler2 = Path(tmp) / "cfm_euler2.onnx" + export_cfm_onnx(model, onnx_euler2, n_steps=2, solver="euler", sway_coef=0.0, temperature=0.35, seed=0) + self.assertTrue(onnx_euler2.with_suffix(".meta.json").is_file()) + for probe_text in ("Oi!", "Olá, tudo bem com você hoje?", "Dia vinte e dois de março vamos ao mercado."): + parity2 = verify_cfm_onnx( + model, + onnx_euler2, + n_steps=2, + solver="euler", + sway_coef=0.0, + temperature=0.35, + seed=0, + text=probe_text, + ) + self.assertEqual(parity2["frames_match"], 1.0) + self.assertLess(parity2["max_abs_diff"], 1e-4) + + onnx_sway8 = Path(tmp) / "cfm_sway8.onnx" + export_cfm_onnx(model, onnx_sway8, n_steps=8, solver="midpoint", sway_coef=-0.5, temperature=0.35, seed=0) + parity8 = verify_cfm_onnx( + model, onnx_sway8, n_steps=8, solver="midpoint", sway_coef=-0.5, temperature=0.35, seed=0 + ) + self.assertEqual(parity8["frames_match"], 1.0) + self.assertLess(parity8["max_abs_diff"], 1e-4) + + def test_stream_vocoder_chunks_exact_length_and_smooth_boundary(self) -> None: + hop = 256 + total_frames = 90 + mel = np.zeros((total_frames, 100), dtype=np.float32) + mel[:, 0] = np.arange(total_frames, dtype=np.float32) + + def _smooth_dummy_vocoder(mel_slice: np.ndarray) -> np.ndarray: + n_frames = int(mel_slice.shape[0]) + f0 = float(mel_slice[0, 0]) + t = np.arange(n_frames * hop, dtype=np.float32) / float(hop) + f0 + return 0.5 * np.sin(2.0 * np.pi * 0.25 * t) + + chunks = list( + stream_vocoder_chunks( + _smooth_dummy_vocoder, + mel, + hop=hop, + chunk_frames=32, + context_frames=8, + fade_frames=4, + ) + ) + self.assertGreater(len(chunks), 1) + stitched = np.concatenate(chunks, axis=0) + self.assertEqual(stitched.shape, (total_frames * hop,)) + self.assertTrue(np.isfinite(stitched).all()) + + full = _smooth_dummy_vocoder(mel) + self.assertLess(float(np.abs(stitched - full).max()), 1e-5) + + def test_distill_loss_step_updates_only_student_flow(self) -> None: + teacher = LuaNovaCFM(_tiny_v5_cfg()).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() + + batch = { + "tokens": torch.tensor([[1, 5, 6, 7, 2], [1, 8, 9, 2, 0]], dtype=torch.long), + "stress": torch.tensor([[0, 1, 0, 0, 0], [0, 0, 1, 0, 0]], dtype=torch.long), + "token_lengths": torch.tensor([5, 4], dtype=torch.long), + "durations": torch.tensor([[2, 4, 5, 3, 2], [2, 5, 4, 2, 0]], dtype=torch.long), + "frame_lengths": torch.tensor([16, 13], dtype=torch.long), + "speakers": torch.tensor([0, 0], dtype=torch.long), + "prosody": torch.randn(2, 16, 3), + } + ch_w = make_channel_weights(100, 1.4, "cpu") + loss, metrics = distill_loss_step( + teacher, + student, + batch, + ch_w, + teacher_steps=4, + teacher_sway=-0.5, + teacher_temp=0.35, + student_steps=2, + training=True, + ) + self.assertTrue(torch.isfinite(loss)) + self.assertIn("end_l1", metrics) + loss.backward() + self.assertTrue(any(p.grad is not None for p in student.flow.parameters())) + self.assertTrue(all(p.grad is None for p in student.encoder.parameters())) + + def test_bigvgan_onnx_export_and_onnx_synthesizer_stream(self) -> None: + _ensure_bigvgan_importable() + import bigvgan + from env import AttrDict + + h = { + "num_mels": 100, + "hop_size": 256, + "sampling_rate": 24000, + "upsample_initial_channel": 64, + "upsample_rates": [8, 8, 2, 2], + "upsample_kernel_sizes": [16, 16, 4, 4], + "resblock": "1", + "resblock_kernel_sizes": [3], + "resblock_dilation_sizes": [[1, 3]], + "activation": "snakebeta", + "snake_logscale": True, + "use_bias_at_final": True, + "use_tanh_at_final": True, + } + cfm = LuaNovaCFM(_tiny_v5_cfg()).eval() + net = bigvgan.BigVGAN(AttrDict(h), use_cuda_kernel=False).eval() + with tempfile.TemporaryDirectory() as tmp: + voc_ckpt = Path(tmp) / "tiny_bigvgan.pt" + torch.save({"h": h, "state_dict": net.state_dict(), "weight_norm_removed": False}, voc_ckpt) + voc_wrapper = BigVGANVocoderWrapper(ckpt_path=voc_ckpt, device="cpu") + + voc_onnx = Path(tmp) / "tiny_bigvgan.onnx" + export_bigvgan_onnx(voc_wrapper, voc_onnx, dummy_frames=8) + parity = verify_bigvgan_onnx(voc_wrapper, voc_onnx, test_frames=13) + self.assertEqual(int(parity["samples"]), 13 * 256) + self.assertLess(parity["max_abs_diff"], 1e-4) + + cfm_onnx = Path(tmp) / "tiny_cfm2.onnx" + export_cfm_onnx(cfm, cfm_onnx, n_steps=2, solver="euler", sway_coef=0.0, temperature=0.35, seed=0) + + ox = OnnxSynthesizer(cfm_onnx, voc_onnx, threads=2) + full_wav = ox.speak("Olá, tudo bem?", normalize=True, postprocess=True) + self.assertEqual(full_wav.dtype, np.float32) + self.assertTrue(np.isfinite(full_wav).all()) + self.assertGreater(full_wav.size, 256) + + chunks = list(ox.speak_stream("Olá! Vamos testar o streaming agora.", chunk_frames=12, context_frames=4, fade_frames=2)) + self.assertGreater(len(chunks), 1) + streamed = np.concatenate(chunks, axis=0) + self.assertTrue(np.isfinite(streamed).all()) + self.assertGreater(streamed.size, 256) + + +if __name__ == "__main__": + unittest.main() diff --git a/code/tests/test_synthesizer.py b/code/tests/test_synthesizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e776fc70c11b1391bce185abe6d19f66ba73eee0 --- /dev/null +++ b/code/tests/test_synthesizer.py @@ -0,0 +1,73 @@ +"""End-to-end synthetic tests for Synthesizer and audio post-processing.""" +from __future__ import annotations + +from pathlib import Path +import tempfile +import types +import unittest +from unittest.mock import patch + +import numpy as np +import soundfile as sf +import torch + +from lua_nova_v1.config import CFMConfig, Config +from lua_nova_v1.inference import Synthesizer +from lua_nova_v1.models import LuaNovaCFM +from lua_nova_v1.text.phonemizer import Phonemized, SYMBOL_TO_ID + + +class _DummyVocoder(torch.nn.Module): + def decode_raw_mel(self, phys_mel: torch.Tensor, lengths: torch.Tensor | None = None) -> torch.Tensor: + b, t, _ = phys_mel.shape + out = torch.sin(torch.linspace(0.0, 20.0, t * 256, device=phys_mel.device))[None].expand(b, -1) * 0.25 + return out.contiguous() + + +class SynthesizerTests(unittest.TestCase): + def test_synthesizer_speak_and_save_wav(self) -> None: + base = Config( + channels=32, + heads=2, + feedforward=64, + encoder_layers=1, + prosody_layers=1, + acoustic_layers=1, + predictor_channels=16, + vocos_n_mels=100, + ) + cfg = CFMConfig( + base=base, + flow_channels=32, + flow_layers=1, + flow_heads=2, + flow_feedforward=64, + flow_kernel=3, + mel_space="bigvgan_24k_100", + ) + cfm = LuaNovaCFM(cfg).eval() + synth = Synthesizer(cfm=cfm, vocoder=_DummyVocoder(), device="cpu") # type: ignore[arg-type] + + fake_ph = Phonemized( + symbols=("", "o", "l", "a", ""), + ids=tuple(SYMBOL_TO_ID[s] for s in ("", "o", "l", "a", "")), + stress=(0, 0, 0, 1, 0), + unknown=(), + ) + with patch("lua_nova_v1.inference.synthesizer.phonemize", return_value=fake_ph): + wav = synth.speak("Dia 22/03 custou R$ 10,00. Vamos testar?", n_steps=2, sway_coef=-0.5) + self.assertEqual(wav.dtype, np.float32) + self.assertGreater(len(wav), 256) + self.assertTrue(np.isfinite(wav).all()) + self.assertGreater(float(np.abs(wav).max()), 0.05) + + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "out.wav" + synth.save_wav(out, wav) + read_wav, sr = sf.read(out, dtype="float32") + self.assertEqual(sr, 24000) + self.assertEqual(len(read_wav), len(wav)) + + +if __name__ == "__main__": + unittest.main() diff --git a/code/tests/test_text.py b/code/tests/test_text.py new file mode 100644 index 0000000000000000000000000000000000000000..219d53d2d5b1fca87b31bcce66f34b0b10906e8a --- /dev/null +++ b/code/tests/test_text.py @@ -0,0 +1,52 @@ +"""Tests for PT-BR text normalization, segmentation, and phonetic tokenization.""" +from __future__ import annotations + +import shutil +import unittest + +from lua_nova_v1.text import normalize_ptbr_text, phonemize +from lua_nova_v1.text.phonemizer import SYMBOL_TO_ID, chunks, tokenize +from lua_nova_v1.utils.audio import finished, sentences, shorter + + +class TextPipelineTests(unittest.TestCase): + def test_ptbr_normalizer_formats_common_expressions(self) -> None: + raw = "Dia 22/03 às 14h30 custou R$ 45,90." + norm = normalize_ptbr_text(raw) + self.assertIn("vinte e dois de março", norm) + self.assertIn("quatorze horas e trinta minutos", norm) + self.assertIn("quarenta e cinco reais e noventa centavos", norm) + + def test_segmentation_handles_abbreviations_and_clauses(self) -> None: + text = "Dr. Silva chegou cedo, tomou café; depois saiu." + sents = sentences(text) + self.assertEqual(len(sents), 1) + self.assertEqual(finished("Olá"), "Olá.") + self.assertEqual(finished("Tudo bem?"), "Tudo bem?") + parts = shorter("um, dois, três") + self.assertEqual(len(parts), 3) + + def test_pure_tokenizer_maps_specials_and_stress(self) -> None: + ph = tokenize([(False, [[("k", 0), ("a", 1), ("z", 0), ("ɐ", 0)]]), (True, "?")]) + self.assertEqual(ph.symbols[0], "") + self.assertEqual(ph.symbols[-1], "") + self.assertIn("?", ph.symbols) + self.assertEqual(ph.ids[0], SYMBOL_TO_ID[""]) + self.assertIn(1, ph.stress) + self.assertEqual(ph.unknown, ()) + + def test_chunks_preserve_abbreviations_and_decimals(self) -> None: + out = list(chunks("Dr. Silva pagou 3.14 reais, e saiu!")) + text_pieces = [val for is_p, val in out if not is_p] + self.assertIn("Dr. Silva pagou 3.14 reais", text_pieces) + + @unittest.skipUnless(shutil.which("espeak-ng") is not None, "espeak-ng binary not on PATH") + def test_espeak_phonemizer_smoke(self) -> None: + ph = phonemize("Olá, mundo!") + self.assertGreater(len(ph), 4) + self.assertEqual(ph.symbols[0], "") + self.assertEqual(ph.symbols[-1], "") + + +if __name__ == "__main__": + unittest.main() diff --git a/code/third_party/bigvgan/LICENSE b/code/third_party/bigvgan/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6016317a8d20a1d7c01bdd34451b424bf212e8c7 --- /dev/null +++ b/code/third_party/bigvgan/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 NVIDIA CORPORATION. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/code/third_party/bigvgan/activations.py b/code/third_party/bigvgan/activations.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e83fcdef46300f5d5bff1f0dbf71f58f3b1186 --- /dev/null +++ b/code/third_party/bigvgan/activations.py @@ -0,0 +1,126 @@ +# Implementation adapted from https://github.com/EdwardDixon/snake under the MIT license. +# LICENSE is in incl_licenses directory. + +import torch +from torch import nn, sin, pow +from torch.nn import Parameter + + +class Snake(nn.Module): + """ + Implementation of a sine-based periodic activation function + Shape: + - Input: (B, C, T) + - Output: (B, C, T), same shape as the input + Parameters: + - alpha - trainable parameter + References: + - This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda: + https://arxiv.org/abs/2006.08195 + Examples: + >>> a1 = snake(256) + >>> x = torch.randn(256) + >>> x = a1(x) + """ + + def __init__( + self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False + ): + """ + Initialization. + INPUT: + - in_features: shape of the input + - alpha: trainable parameter + alpha is initialized to 1 by default, higher values = higher-frequency. + alpha will be trained along with the rest of your model. + """ + super(Snake, self).__init__() + self.in_features = in_features + + # Initialize alpha + self.alpha_logscale = alpha_logscale + if self.alpha_logscale: # Log scale alphas initialized to zeros + self.alpha = Parameter(torch.zeros(in_features) * alpha) + else: # Linear scale alphas initialized to ones + self.alpha = Parameter(torch.ones(in_features) * alpha) + + self.alpha.requires_grad = alpha_trainable + + self.no_div_by_zero = 0.000000001 + + def forward(self, x): + """ + Forward pass of the function. + Applies the function to the input elementwise. + Snake ∶= x + 1/a * sin^2 (xa) + """ + alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # Line up with x to [B, C, T] + if self.alpha_logscale: + alpha = torch.exp(alpha) + x = x + (1.0 / (alpha + self.no_div_by_zero)) * pow(sin(x * alpha), 2) + + return x + + +class SnakeBeta(nn.Module): + """ + A modified Snake function which uses separate parameters for the magnitude of the periodic components + Shape: + - Input: (B, C, T) + - Output: (B, C, T), same shape as the input + Parameters: + - alpha - trainable parameter that controls frequency + - beta - trainable parameter that controls magnitude + References: + - This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda: + https://arxiv.org/abs/2006.08195 + Examples: + >>> a1 = snakebeta(256) + >>> x = torch.randn(256) + >>> x = a1(x) + """ + + def __init__( + self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False + ): + """ + Initialization. + INPUT: + - in_features: shape of the input + - alpha - trainable parameter that controls frequency + - beta - trainable parameter that controls magnitude + alpha is initialized to 1 by default, higher values = higher-frequency. + beta is initialized to 1 by default, higher values = higher-magnitude. + alpha will be trained along with the rest of your model. + """ + super(SnakeBeta, self).__init__() + self.in_features = in_features + + # Initialize alpha + self.alpha_logscale = alpha_logscale + if self.alpha_logscale: # Log scale alphas initialized to zeros + self.alpha = Parameter(torch.zeros(in_features) * alpha) + self.beta = Parameter(torch.zeros(in_features) * alpha) + else: # Linear scale alphas initialized to ones + self.alpha = Parameter(torch.ones(in_features) * alpha) + self.beta = Parameter(torch.ones(in_features) * alpha) + + self.alpha.requires_grad = alpha_trainable + self.beta.requires_grad = alpha_trainable + + self.no_div_by_zero = 0.000000001 + + def forward(self, x): + """ + Forward pass of the function. + Applies the function to the input elementwise. + SnakeBeta ∶= x + 1/b * sin^2 (xa) + """ + alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # Line up with x to [B, C, T] + beta = self.beta.unsqueeze(0).unsqueeze(-1) + if self.alpha_logscale: + alpha = torch.exp(alpha) + beta = torch.exp(beta) + x = x + (1.0 / (beta + self.no_div_by_zero)) * pow(sin(x * alpha), 2) + + return x diff --git a/code/third_party/bigvgan/alias_free_activation/cuda/__init__.py b/code/third_party/bigvgan/alias_free_activation/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/third_party/bigvgan/alias_free_activation/cuda/activation1d.py b/code/third_party/bigvgan/alias_free_activation/cuda/activation1d.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0d313cb265170943fb7cb16742b031038f7859 --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/cuda/activation1d.py @@ -0,0 +1,77 @@ +# Copyright (c) 2024 NVIDIA CORPORATION. +# Licensed under the MIT license. + +import torch +import torch.nn as nn +from alias_free_activation.torch.resample import UpSample1d, DownSample1d + +# load fused CUDA kernel: this enables importing anti_alias_activation_cuda +from alias_free_activation.cuda import load + +anti_alias_activation_cuda = load.load() + + +class FusedAntiAliasActivation(torch.autograd.Function): + """ + Assumes filter size 12, replication padding on upsampling/downsampling, and logscale alpha/beta parameters as inputs. + The hyperparameters are hard-coded in the kernel to maximize speed. + NOTE: The fused kenrel is incorrect for Activation1d with different hyperparameters. + """ + + @staticmethod + def forward(ctx, inputs, up_ftr, down_ftr, alpha, beta): + activation_results = anti_alias_activation_cuda.forward( + inputs, up_ftr, down_ftr, alpha, beta + ) + + return activation_results + + @staticmethod + def backward(ctx, output_grads): + raise NotImplementedError + return output_grads, None, None + + +class Activation1d(nn.Module): + def __init__( + self, + activation, + up_ratio: int = 2, + down_ratio: int = 2, + up_kernel_size: int = 12, + down_kernel_size: int = 12, + fused: bool = True, + ): + super().__init__() + self.up_ratio = up_ratio + self.down_ratio = down_ratio + self.act = activation + self.upsample = UpSample1d(up_ratio, up_kernel_size) + self.downsample = DownSample1d(down_ratio, down_kernel_size) + + self.fused = fused # Whether to use fused CUDA kernel or not + + def forward(self, x): + if not self.fused: + x = self.upsample(x) + x = self.act(x) + x = self.downsample(x) + return x + else: + if self.act.__class__.__name__ == "Snake": + beta = self.act.alpha.data # Snake uses same params for alpha and beta + else: + beta = ( + self.act.beta.data + ) # Snakebeta uses different params for alpha and beta + alpha = self.act.alpha.data + if ( + not self.act.alpha_logscale + ): # Exp baked into cuda kernel, cancel it out with a log + alpha = torch.log(alpha) + beta = torch.log(beta) + + x = FusedAntiAliasActivation.apply( + x, self.upsample.filter, self.downsample.lowpass.filter, alpha, beta + ) + return x diff --git a/code/third_party/bigvgan/alias_free_activation/cuda/anti_alias_activation.cpp b/code/third_party/bigvgan/alias_free_activation/cuda/anti_alias_activation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..94fd90da386e66ce12a64ef243e4d125926dfd2a --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/cuda/anti_alias_activation.cpp @@ -0,0 +1,23 @@ +/* coding=utf-8 + * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + * + * 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. + */ + + #include + +extern "C" torch::Tensor fwd_cuda(torch::Tensor const &input, torch::Tensor const &up_filter, torch::Tensor const &down_filter, torch::Tensor const &alpha, torch::Tensor const &beta); + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", &fwd_cuda, "Anti-Alias Activation forward (CUDA)"); +} \ No newline at end of file diff --git a/code/third_party/bigvgan/alias_free_activation/cuda/anti_alias_activation_cuda.cu b/code/third_party/bigvgan/alias_free_activation/cuda/anti_alias_activation_cuda.cu new file mode 100644 index 0000000000000000000000000000000000000000..7ee97492984a92c753f2357f03e7c04252060824 --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/cuda/anti_alias_activation_cuda.cu @@ -0,0 +1,246 @@ +/* coding=utf-8 + * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "type_shim.h" +#include +#include +#include +#include +#include + +namespace +{ + // Hard-coded hyperparameters + // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and + constexpr int ELEMENTS_PER_LDG_STG = 1; //(WARP_ITERATIONS < 4) ? 1 : 4; + constexpr int BUFFER_SIZE = 32; + constexpr int FILTER_SIZE = 12; + constexpr int HALF_FILTER_SIZE = 6; + constexpr int UPSAMPLE_REPLICATION_PAD = 5; // 5 on each side, matching torch impl + constexpr int DOWNSAMPLE_REPLICATION_PAD_LEFT = 5; // matching torch impl + constexpr int DOWNSAMPLE_REPLICATION_PAD_RIGHT = 6; // matching torch impl + + template + __global__ void anti_alias_activation_forward( + output_t *dst, + const input_t *src, + const input_t *up_ftr, + const input_t *down_ftr, + const input_t *alpha, + const input_t *beta, + int batch_size, + int channels, + int seq_len) + { + // Up and downsample filters + input_t up_filter[FILTER_SIZE]; + input_t down_filter[FILTER_SIZE]; + + // Load data from global memory including extra indices reserved for replication paddings + input_t elements[2 * FILTER_SIZE + 2 * BUFFER_SIZE + 2 * UPSAMPLE_REPLICATION_PAD] = {0}; + input_t intermediates[2 * FILTER_SIZE + 2 * BUFFER_SIZE + DOWNSAMPLE_REPLICATION_PAD_LEFT + DOWNSAMPLE_REPLICATION_PAD_RIGHT] = {0}; + + // Output stores downsampled output before writing to dst + output_t output[BUFFER_SIZE]; + + // blockDim/threadIdx = (128, 1, 1) + // gridDim/blockIdx = (seq_blocks, channels, batches) + int block_offset = (blockIdx.x * 128 * BUFFER_SIZE + seq_len * (blockIdx.y + gridDim.y * blockIdx.z)); + int local_offset = threadIdx.x * BUFFER_SIZE; + int seq_offset = blockIdx.x * 128 * BUFFER_SIZE + local_offset; + + // intermediate have double the seq_len + int intermediate_local_offset = threadIdx.x * BUFFER_SIZE * 2; + int intermediate_seq_offset = blockIdx.x * 128 * BUFFER_SIZE * 2 + intermediate_local_offset; + + // Get values needed for replication padding before moving pointer + const input_t *right_most_pntr = src + (seq_len * (blockIdx.y + gridDim.y * blockIdx.z)); + input_t seq_left_most_value = right_most_pntr[0]; + input_t seq_right_most_value = right_most_pntr[seq_len - 1]; + + // Move src and dst pointers + src += block_offset + local_offset; + dst += block_offset + local_offset; + + // Alpha and beta values for snake activatons. Applies exp by default + alpha = alpha + blockIdx.y; + input_t alpha_val = expf(alpha[0]); + beta = beta + blockIdx.y; + input_t beta_val = expf(beta[0]); + + #pragma unroll + for (int it = 0; it < FILTER_SIZE; it += 1) + { + up_filter[it] = up_ftr[it]; + down_filter[it] = down_ftr[it]; + } + + // Apply replication padding for upsampling, matching torch impl + #pragma unroll + for (int it = -HALF_FILTER_SIZE; it < BUFFER_SIZE + HALF_FILTER_SIZE; it += 1) + { + int element_index = seq_offset + it; // index for element + if ((element_index < 0) && (element_index >= -UPSAMPLE_REPLICATION_PAD)) + { + elements[2 * (HALF_FILTER_SIZE + it)] = 2 * seq_left_most_value; + } + if ((element_index >= seq_len) && (element_index < seq_len + UPSAMPLE_REPLICATION_PAD)) + { + elements[2 * (HALF_FILTER_SIZE + it)] = 2 * seq_right_most_value; + } + if ((element_index >= 0) && (element_index < seq_len)) + { + elements[2 * (HALF_FILTER_SIZE + it)] = 2 * src[it]; + } + } + + // Apply upsampling strided convolution and write to intermediates. It reserves DOWNSAMPLE_REPLICATION_PAD_LEFT for replication padding of the downsampilng conv later + #pragma unroll + for (int it = 0; it < (2 * BUFFER_SIZE + 2 * FILTER_SIZE); it += 1) + { + input_t acc = 0.0; + int element_index = intermediate_seq_offset + it; // index for intermediate + #pragma unroll + for (int f_idx = 0; f_idx < FILTER_SIZE; f_idx += 1) + { + if ((element_index + f_idx) >= 0) + { + acc += up_filter[f_idx] * elements[it + f_idx]; + } + } + intermediates[it + DOWNSAMPLE_REPLICATION_PAD_LEFT] = acc; + } + + // Apply activation function. It reserves DOWNSAMPLE_REPLICATION_PAD_LEFT and DOWNSAMPLE_REPLICATION_PAD_RIGHT for replication padding of the downsampilng conv later + double no_div_by_zero = 0.000000001; + #pragma unroll + for (int it = 0; it < 2 * BUFFER_SIZE + 2 * FILTER_SIZE; it += 1) + { + intermediates[it + DOWNSAMPLE_REPLICATION_PAD_LEFT] += (1.0 / (beta_val + no_div_by_zero)) * sinf(intermediates[it + DOWNSAMPLE_REPLICATION_PAD_LEFT] * alpha_val) * sinf(intermediates[it + DOWNSAMPLE_REPLICATION_PAD_LEFT] * alpha_val); + } + + // Apply replication padding before downsampling conv from intermediates + #pragma unroll + for (int it = 0; it < DOWNSAMPLE_REPLICATION_PAD_LEFT; it += 1) + { + intermediates[it] = intermediates[DOWNSAMPLE_REPLICATION_PAD_LEFT]; + } + #pragma unroll + for (int it = DOWNSAMPLE_REPLICATION_PAD_LEFT + 2 * BUFFER_SIZE + 2 * FILTER_SIZE; it < DOWNSAMPLE_REPLICATION_PAD_LEFT + 2 * BUFFER_SIZE + 2 * FILTER_SIZE + DOWNSAMPLE_REPLICATION_PAD_RIGHT; it += 1) + { + intermediates[it] = intermediates[DOWNSAMPLE_REPLICATION_PAD_LEFT + 2 * BUFFER_SIZE + 2 * FILTER_SIZE - 1]; + } + + // Apply downsample strided convolution (assuming stride=2) from intermediates + #pragma unroll + for (int it = 0; it < BUFFER_SIZE; it += 1) + { + input_t acc = 0.0; + #pragma unroll + for (int f_idx = 0; f_idx < FILTER_SIZE; f_idx += 1) + { + // Add constant DOWNSAMPLE_REPLICATION_PAD_RIGHT to match torch implementation + acc += down_filter[f_idx] * intermediates[it * 2 + f_idx + DOWNSAMPLE_REPLICATION_PAD_RIGHT]; + } + output[it] = acc; + } + + // Write output to dst + #pragma unroll + for (int it = 0; it < BUFFER_SIZE; it += ELEMENTS_PER_LDG_STG) + { + int element_index = seq_offset + it; + if (element_index < seq_len) + { + dst[it] = output[it]; + } + } + + } + + template + void dispatch_anti_alias_activation_forward( + output_t *dst, + const input_t *src, + const input_t *up_ftr, + const input_t *down_ftr, + const input_t *alpha, + const input_t *beta, + int batch_size, + int channels, + int seq_len) + { + if (seq_len == 0) + { + return; + } + else + { + // Use 128 threads per block to maximimize gpu utilization + constexpr int threads_per_block = 128; + constexpr int seq_len_per_block = 4096; + int blocks_per_seq_len = (seq_len + seq_len_per_block - 1) / seq_len_per_block; + dim3 blocks(blocks_per_seq_len, channels, batch_size); + dim3 threads(threads_per_block, 1, 1); + + anti_alias_activation_forward + <<>>(dst, src, up_ftr, down_ftr, alpha, beta, batch_size, channels, seq_len); + } + } +} + +extern "C" torch::Tensor fwd_cuda(torch::Tensor const &input, torch::Tensor const &up_filter, torch::Tensor const &down_filter, torch::Tensor const &alpha, torch::Tensor const &beta) +{ + // Input is a 3d tensor with dimensions [batches, channels, seq_len] + const int batches = input.size(0); + const int channels = input.size(1); + const int seq_len = input.size(2); + + // Output + auto act_options = input.options().requires_grad(false); + + torch::Tensor anti_alias_activation_results = + torch::empty({batches, channels, seq_len}, act_options); + + void *input_ptr = static_cast(input.data_ptr()); + void *up_filter_ptr = static_cast(up_filter.data_ptr()); + void *down_filter_ptr = static_cast(down_filter.data_ptr()); + void *alpha_ptr = static_cast(alpha.data_ptr()); + void *beta_ptr = static_cast(beta.data_ptr()); + void *anti_alias_activation_results_ptr = static_cast(anti_alias_activation_results.data_ptr()); + + DISPATCH_FLOAT_HALF_AND_BFLOAT( + input.scalar_type(), + "dispatch anti alias activation_forward", + dispatch_anti_alias_activation_forward( + reinterpret_cast(anti_alias_activation_results_ptr), + reinterpret_cast(input_ptr), + reinterpret_cast(up_filter_ptr), + reinterpret_cast(down_filter_ptr), + reinterpret_cast(alpha_ptr), + reinterpret_cast(beta_ptr), + batches, + channels, + seq_len);); + return anti_alias_activation_results; +} \ No newline at end of file diff --git a/code/third_party/bigvgan/alias_free_activation/cuda/compat.h b/code/third_party/bigvgan/alias_free_activation/cuda/compat.h new file mode 100644 index 0000000000000000000000000000000000000000..0f93af5700470e7f6066af7dbe56aced98ea32d9 --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/cuda/compat.h @@ -0,0 +1,29 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * 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. + */ + +/*This code is copied fron NVIDIA apex: + * https://github.com/NVIDIA/apex + * with minor changes. */ + +#ifndef TORCH_CHECK +#define TORCH_CHECK AT_CHECK +#endif + +#ifdef VERSION_GE_1_3 +#define DATA_PTR data_ptr +#else +#define DATA_PTR data +#endif diff --git a/code/third_party/bigvgan/alias_free_activation/cuda/load.py b/code/third_party/bigvgan/alias_free_activation/cuda/load.py new file mode 100644 index 0000000000000000000000000000000000000000..82afde3d73dda72b06af28a622fdab1954825a28 --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/cuda/load.py @@ -0,0 +1,86 @@ +# Copyright (c) 2024 NVIDIA CORPORATION. +# Licensed under the MIT license. + +import os +import pathlib +import subprocess + +from torch.utils import cpp_extension + +""" +Setting this param to a list has a problem of generating different compilation commands (with diferent order of architectures) and leading to recompilation of fused kernels. +Set it to empty stringo avoid recompilation and assign arch flags explicity in extra_cuda_cflags below +""" +os.environ["TORCH_CUDA_ARCH_LIST"] = "" + + +def load(): + # Check if cuda 11 is installed for compute capability 8.0 + cc_flag = [] + _, bare_metal_major, _ = _get_cuda_bare_metal_version(cpp_extension.CUDA_HOME) + if int(bare_metal_major) >= 11: + cc_flag.append("-gencode") + cc_flag.append("arch=compute_80,code=sm_80") + + # Build path + srcpath = pathlib.Path(__file__).parent.absolute() + buildpath = srcpath / "build" + _create_build_dir(buildpath) + + # Helper function to build the kernels. + def _cpp_extention_load_helper(name, sources, extra_cuda_flags): + return cpp_extension.load( + name=name, + sources=sources, + build_directory=buildpath, + extra_cflags=[ + "-O3", + ], + extra_cuda_cflags=[ + "-O3", + "-gencode", + "arch=compute_70,code=sm_70", + "--use_fast_math", + ] + + extra_cuda_flags + + cc_flag, + verbose=True, + ) + + extra_cuda_flags = [ + "-U__CUDA_NO_HALF_OPERATORS__", + "-U__CUDA_NO_HALF_CONVERSIONS__", + "--expt-relaxed-constexpr", + "--expt-extended-lambda", + ] + + sources = [ + srcpath / "anti_alias_activation.cpp", + srcpath / "anti_alias_activation_cuda.cu", + ] + anti_alias_activation_cuda = _cpp_extention_load_helper( + "anti_alias_activation_cuda", sources, extra_cuda_flags + ) + + return anti_alias_activation_cuda + + +def _get_cuda_bare_metal_version(cuda_dir): + raw_output = subprocess.check_output( + [cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True + ) + output = raw_output.split() + release_idx = output.index("release") + 1 + release = output[release_idx].split(".") + bare_metal_major = release[0] + bare_metal_minor = release[1][0] + + return raw_output, bare_metal_major, bare_metal_minor + + +def _create_build_dir(buildpath): + try: + os.mkdir(buildpath) + except OSError: + if not os.path.isdir(buildpath): + print(f"Creation of the build directory {buildpath} failed") diff --git a/code/third_party/bigvgan/alias_free_activation/cuda/type_shim.h b/code/third_party/bigvgan/alias_free_activation/cuda/type_shim.h new file mode 100644 index 0000000000000000000000000000000000000000..4328d0369a5fb8730cdf236d9f267453f4201d84 --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/cuda/type_shim.h @@ -0,0 +1,92 @@ +/* coding=utf-8 + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * 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. + */ + +#include +#include "compat.h" + +#define DISPATCH_FLOAT_HALF_AND_BFLOAT(TYPE, NAME, ...) \ + switch (TYPE) \ + { \ + case at::ScalarType::Float: \ + { \ + using scalar_t = float; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::Half: \ + { \ + using scalar_t = at::Half; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::BFloat16: \ + { \ + using scalar_t = at::BFloat16; \ + __VA_ARGS__; \ + break; \ + } \ + default: \ + AT_ERROR(#NAME, " not implemented for '", toString(TYPE), "'"); \ + } + +#define DISPATCH_FLOAT_HALF_AND_BFLOAT_INOUT_TYPES(TYPEIN, TYPEOUT, NAME, ...) \ + switch (TYPEIN) \ + { \ + case at::ScalarType::Float: \ + { \ + using scalar_t_in = float; \ + switch (TYPEOUT) \ + { \ + case at::ScalarType::Float: \ + { \ + using scalar_t_out = float; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::Half: \ + { \ + using scalar_t_out = at::Half; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::BFloat16: \ + { \ + using scalar_t_out = at::BFloat16; \ + __VA_ARGS__; \ + break; \ + } \ + default: \ + AT_ERROR(#NAME, " not implemented for '", toString(TYPEOUT), "'"); \ + } \ + break; \ + } \ + case at::ScalarType::Half: \ + { \ + using scalar_t_in = at::Half; \ + using scalar_t_out = at::Half; \ + __VA_ARGS__; \ + break; \ + } \ + case at::ScalarType::BFloat16: \ + { \ + using scalar_t_in = at::BFloat16; \ + using scalar_t_out = at::BFloat16; \ + __VA_ARGS__; \ + break; \ + } \ + default: \ + AT_ERROR(#NAME, " not implemented for '", toString(TYPEIN), "'"); \ + } diff --git a/code/third_party/bigvgan/alias_free_activation/torch/__init__.py b/code/third_party/bigvgan/alias_free_activation/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb0ad84ef184dcb15464c8ca827ae1c284f8990 --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/torch/__init__.py @@ -0,0 +1,6 @@ +# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0 +# LICENSE is in incl_licenses directory. + +from .filter import * +from .resample import * +from .act import * diff --git a/code/third_party/bigvgan/alias_free_activation/torch/act.py b/code/third_party/bigvgan/alias_free_activation/torch/act.py new file mode 100644 index 0000000000000000000000000000000000000000..421a1cdd470e462b263c50db4d82bad2d0fe552e --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/torch/act.py @@ -0,0 +1,30 @@ +# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0 +# LICENSE is in incl_licenses directory. + +import torch.nn as nn +from alias_free_activation.torch.resample import UpSample1d, DownSample1d + + +class Activation1d(nn.Module): + def __init__( + self, + activation, + up_ratio: int = 2, + down_ratio: int = 2, + up_kernel_size: int = 12, + down_kernel_size: int = 12, + ): + super().__init__() + self.up_ratio = up_ratio + self.down_ratio = down_ratio + self.act = activation + self.upsample = UpSample1d(up_ratio, up_kernel_size) + self.downsample = DownSample1d(down_ratio, down_kernel_size) + + # x: [B,C,T] + def forward(self, x): + x = self.upsample(x) + x = self.act(x) + x = self.downsample(x) + + return x diff --git a/code/third_party/bigvgan/alias_free_activation/torch/filter.py b/code/third_party/bigvgan/alias_free_activation/torch/filter.py new file mode 100644 index 0000000000000000000000000000000000000000..81a4a9a7cefb457f8880f54385335180fbd43f1b --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/torch/filter.py @@ -0,0 +1,101 @@ +# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0 +# LICENSE is in incl_licenses directory. + +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + +if "sinc" in dir(torch): + sinc = torch.sinc +else: + # This code is adopted from adefossez's julius.core.sinc under the MIT License + # https://adefossez.github.io/julius/julius/core.html + # LICENSE is in incl_licenses directory. + def sinc(x: torch.Tensor): + """ + Implementation of sinc, i.e. sin(pi * x) / (pi * x) + __Warning__: Different to julius.sinc, the input is multiplied by `pi`! + """ + return torch.where( + x == 0, + torch.tensor(1.0, device=x.device, dtype=x.dtype), + torch.sin(math.pi * x) / math.pi / x, + ) + + +# This code is adopted from adefossez's julius.lowpass.LowPassFilters under the MIT License +# https://adefossez.github.io/julius/julius/lowpass.html +# LICENSE is in incl_licenses directory. +def kaiser_sinc_filter1d( + cutoff, half_width, kernel_size +): # return filter [1,1,kernel_size] + even = kernel_size % 2 == 0 + half_size = kernel_size // 2 + + # For kaiser window + delta_f = 4 * half_width + A = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95 + if A > 50.0: + beta = 0.1102 * (A - 8.7) + elif A >= 21.0: + beta = 0.5842 * (A - 21) ** 0.4 + 0.07886 * (A - 21.0) + else: + beta = 0.0 + window = torch.kaiser_window(kernel_size, beta=beta, periodic=False) + + # ratio = 0.5/cutoff -> 2 * cutoff = 1 / ratio + if even: + time = torch.arange(-half_size, half_size) + 0.5 + else: + time = torch.arange(kernel_size) - half_size + if cutoff == 0: + filter_ = torch.zeros_like(time) + else: + filter_ = 2 * cutoff * window * sinc(2 * cutoff * time) + """ + Normalize filter to have sum = 1, otherwise we will have a small leakage of the constant component in the input signal. + """ + filter_ /= filter_.sum() + filter = filter_.view(1, 1, kernel_size) + + return filter + + +class LowPassFilter1d(nn.Module): + def __init__( + self, + cutoff=0.5, + half_width=0.6, + stride: int = 1, + padding: bool = True, + padding_mode: str = "replicate", + kernel_size: int = 12, + ): + """ + kernel_size should be even number for stylegan3 setup, in this implementation, odd number is also possible. + """ + super().__init__() + if cutoff < -0.0: + raise ValueError("Minimum cutoff must be larger than zero.") + if cutoff > 0.5: + raise ValueError("A cutoff above 0.5 does not make sense.") + self.kernel_size = kernel_size + self.even = kernel_size % 2 == 0 + self.pad_left = kernel_size // 2 - int(self.even) + self.pad_right = kernel_size // 2 + self.stride = stride + self.padding = padding + self.padding_mode = padding_mode + filter = kaiser_sinc_filter1d(cutoff, half_width, kernel_size) + self.register_buffer("filter", filter) + + # Input [B, C, T] + def forward(self, x): + _, C, _ = x.shape + + if self.padding: + x = F.pad(x, (self.pad_left, self.pad_right), mode=self.padding_mode) + out = F.conv1d(x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C) + + return out diff --git a/code/third_party/bigvgan/alias_free_activation/torch/resample.py b/code/third_party/bigvgan/alias_free_activation/torch/resample.py new file mode 100644 index 0000000000000000000000000000000000000000..c2cf40e9a24da7da3b707659cec274860102a11f --- /dev/null +++ b/code/third_party/bigvgan/alias_free_activation/torch/resample.py @@ -0,0 +1,58 @@ +# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0 +# LICENSE is in incl_licenses directory. + +import torch.nn as nn +from torch.nn import functional as F +from alias_free_activation.torch.filter import LowPassFilter1d +from alias_free_activation.torch.filter import kaiser_sinc_filter1d + + +class UpSample1d(nn.Module): + def __init__(self, ratio=2, kernel_size=None): + super().__init__() + self.ratio = ratio + self.kernel_size = ( + int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size + ) + self.stride = ratio + self.pad = self.kernel_size // ratio - 1 + self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2 + self.pad_right = ( + self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2 + ) + filter = kaiser_sinc_filter1d( + cutoff=0.5 / ratio, half_width=0.6 / ratio, kernel_size=self.kernel_size + ) + self.register_buffer("filter", filter) + + # x: [B, C, T] + def forward(self, x): + _, C, _ = x.shape + + x = F.pad(x, (self.pad, self.pad), mode="replicate") + x = self.ratio * F.conv_transpose1d( + x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C + ) + x = x[..., self.pad_left : -self.pad_right] + + return x + + +class DownSample1d(nn.Module): + def __init__(self, ratio=2, kernel_size=None): + super().__init__() + self.ratio = ratio + self.kernel_size = ( + int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size + ) + self.lowpass = LowPassFilter1d( + cutoff=0.5 / ratio, + half_width=0.6 / ratio, + stride=ratio, + kernel_size=self.kernel_size, + ) + + def forward(self, x): + xx = self.lowpass(x) + + return xx diff --git a/code/third_party/bigvgan/bigvgan.py b/code/third_party/bigvgan/bigvgan.py new file mode 100644 index 0000000000000000000000000000000000000000..40407c3ca142bf7e069aba066486cfe1b3ab9016 --- /dev/null +++ b/code/third_party/bigvgan/bigvgan.py @@ -0,0 +1,493 @@ +# Copyright (c) 2024 NVIDIA CORPORATION. +# Licensed under the MIT license. + +# Adapted from https://github.com/jik876/hifi-gan under the MIT license. +# LICENSE is in incl_licenses directory. + +import os +import json +from pathlib import Path +from typing import Optional, Union, Dict + +import torch +import torch.nn as nn +from torch.nn import Conv1d, ConvTranspose1d +from torch.nn.utils import weight_norm, remove_weight_norm + +import activations +from utils import init_weights, get_padding +from alias_free_activation.torch.act import Activation1d as TorchActivation1d +from env import AttrDict + +from huggingface_hub import PyTorchModelHubMixin, hf_hub_download + + +def load_hparams_from_json(path) -> AttrDict: + with open(path) as f: + data = f.read() + return AttrDict(json.loads(data)) + + +class AMPBlock1(torch.nn.Module): + """ + AMPBlock applies Snake / SnakeBeta activation functions with trainable parameters that control periodicity, defined for each layer. + AMPBlock1 has additional self.convs2 that contains additional Conv1d layers with a fixed dilation=1 followed by each layer in self.convs1 + + Args: + h (AttrDict): Hyperparameters. + channels (int): Number of convolution channels. + kernel_size (int): Size of the convolution kernel. Default is 3. + dilation (tuple): Dilation rates for the convolutions. Each dilation layer has two convolutions. Default is (1, 3, 5). + activation (str): Activation function type. Should be either 'snake' or 'snakebeta'. Default is None. + """ + + def __init__( + self, + h: AttrDict, + channels: int, + kernel_size: int = 3, + dilation: tuple = (1, 3, 5), + activation: str = None, + ): + super().__init__() + + self.h = h + + self.convs1 = nn.ModuleList( + [ + weight_norm( + Conv1d( + channels, + channels, + kernel_size, + stride=1, + dilation=d, + padding=get_padding(kernel_size, d), + ) + ) + for d in dilation + ] + ) + self.convs1.apply(init_weights) + + self.convs2 = nn.ModuleList( + [ + weight_norm( + Conv1d( + channels, + channels, + kernel_size, + stride=1, + dilation=1, + padding=get_padding(kernel_size, 1), + ) + ) + for _ in range(len(dilation)) + ] + ) + self.convs2.apply(init_weights) + + self.num_layers = len(self.convs1) + len( + self.convs2 + ) # Total number of conv layers + + # Select which Activation1d, lazy-load cuda version to ensure backward compatibility + if self.h.get("use_cuda_kernel", False): + from alias_free_activation.cuda.activation1d import ( + Activation1d as CudaActivation1d, + ) + + Activation1d = CudaActivation1d + else: + Activation1d = TorchActivation1d + + # Activation functions + if activation == "snake": + self.activations = nn.ModuleList( + [ + Activation1d( + activation=activations.Snake( + channels, alpha_logscale=h.snake_logscale + ) + ) + for _ in range(self.num_layers) + ] + ) + elif activation == "snakebeta": + self.activations = nn.ModuleList( + [ + Activation1d( + activation=activations.SnakeBeta( + channels, alpha_logscale=h.snake_logscale + ) + ) + for _ in range(self.num_layers) + ] + ) + else: + raise NotImplementedError( + "activation incorrectly specified. check the config file and look for 'activation'." + ) + + def forward(self, x): + acts1, acts2 = self.activations[::2], self.activations[1::2] + for c1, c2, a1, a2 in zip(self.convs1, self.convs2, acts1, acts2): + xt = a1(x) + xt = c1(xt) + xt = a2(xt) + xt = c2(xt) + x = xt + x + + return x + + def remove_weight_norm(self): + for l in self.convs1: + remove_weight_norm(l) + for l in self.convs2: + remove_weight_norm(l) + + +class AMPBlock2(torch.nn.Module): + """ + AMPBlock applies Snake / SnakeBeta activation functions with trainable parameters that control periodicity, defined for each layer. + Unlike AMPBlock1, AMPBlock2 does not contain extra Conv1d layers with fixed dilation=1 + + Args: + h (AttrDict): Hyperparameters. + channels (int): Number of convolution channels. + kernel_size (int): Size of the convolution kernel. Default is 3. + dilation (tuple): Dilation rates for the convolutions. Each dilation layer has two convolutions. Default is (1, 3, 5). + activation (str): Activation function type. Should be either 'snake' or 'snakebeta'. Default is None. + """ + + def __init__( + self, + h: AttrDict, + channels: int, + kernel_size: int = 3, + dilation: tuple = (1, 3, 5), + activation: str = None, + ): + super().__init__() + + self.h = h + + self.convs = nn.ModuleList( + [ + weight_norm( + Conv1d( + channels, + channels, + kernel_size, + stride=1, + dilation=d, + padding=get_padding(kernel_size, d), + ) + ) + for d in dilation + ] + ) + self.convs.apply(init_weights) + + self.num_layers = len(self.convs) # Total number of conv layers + + # Select which Activation1d, lazy-load cuda version to ensure backward compatibility + if self.h.get("use_cuda_kernel", False): + from alias_free_activation.cuda.activation1d import ( + Activation1d as CudaActivation1d, + ) + + Activation1d = CudaActivation1d + else: + Activation1d = TorchActivation1d + + # Activation functions + if activation == "snake": + self.activations = nn.ModuleList( + [ + Activation1d( + activation=activations.Snake( + channels, alpha_logscale=h.snake_logscale + ) + ) + for _ in range(self.num_layers) + ] + ) + elif activation == "snakebeta": + self.activations = nn.ModuleList( + [ + Activation1d( + activation=activations.SnakeBeta( + channels, alpha_logscale=h.snake_logscale + ) + ) + for _ in range(self.num_layers) + ] + ) + else: + raise NotImplementedError( + "activation incorrectly specified. check the config file and look for 'activation'." + ) + + def forward(self, x): + for c, a in zip(self.convs, self.activations): + xt = a(x) + xt = c(xt) + x = xt + x + return x + + def remove_weight_norm(self): + for l in self.convs: + remove_weight_norm(l) + + +class BigVGAN( + torch.nn.Module, + PyTorchModelHubMixin, + library_name="bigvgan", + repo_url="https://github.com/NVIDIA/BigVGAN", + docs_url="https://github.com/NVIDIA/BigVGAN/blob/main/README.md", + pipeline_tag="audio-to-audio", + license="mit", + tags=["neural-vocoder", "audio-generation", "arxiv:2206.04658"], +): + """ + BigVGAN is a neural vocoder model that applies anti-aliased periodic activation for residual blocks (resblocks). + New in BigVGAN-v2: it can optionally use optimized CUDA kernels for AMP (anti-aliased multi-periodicity) blocks. + + Args: + h (AttrDict): Hyperparameters. + use_cuda_kernel (bool): If set to True, loads optimized CUDA kernels for AMP. This should be used for inference only, as training is not supported with CUDA kernels. + + Note: + - The `use_cuda_kernel` parameter should be used for inference only, as training with CUDA kernels is not supported. + - Ensure that the activation function is correctly specified in the hyperparameters (h.activation). + """ + + def __init__(self, h: AttrDict, use_cuda_kernel: bool = False): + super().__init__() + self.h = h + self.h["use_cuda_kernel"] = use_cuda_kernel + + # Select which Activation1d, lazy-load cuda version to ensure backward compatibility + if self.h.get("use_cuda_kernel", False): + from alias_free_activation.cuda.activation1d import ( + Activation1d as CudaActivation1d, + ) + + Activation1d = CudaActivation1d + else: + Activation1d = TorchActivation1d + + self.num_kernels = len(h.resblock_kernel_sizes) + self.num_upsamples = len(h.upsample_rates) + + # Pre-conv + self.conv_pre = weight_norm( + Conv1d(h.num_mels, h.upsample_initial_channel, 7, 1, padding=3) + ) + + # Define which AMPBlock to use. BigVGAN uses AMPBlock1 as default + if h.resblock == "1": + resblock_class = AMPBlock1 + elif h.resblock == "2": + resblock_class = AMPBlock2 + else: + raise ValueError( + f"Incorrect resblock class specified in hyperparameters. Got {h.resblock}" + ) + + # Transposed conv-based upsamplers. does not apply anti-aliasing + self.ups = nn.ModuleList() + for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)): + self.ups.append( + nn.ModuleList( + [ + weight_norm( + ConvTranspose1d( + h.upsample_initial_channel // (2**i), + h.upsample_initial_channel // (2 ** (i + 1)), + k, + u, + padding=(k - u) // 2, + ) + ) + ] + ) + ) + + # Residual blocks using anti-aliased multi-periodicity composition modules (AMP) + self.resblocks = nn.ModuleList() + for i in range(len(self.ups)): + ch = h.upsample_initial_channel // (2 ** (i + 1)) + for j, (k, d) in enumerate( + zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes) + ): + self.resblocks.append( + resblock_class(h, ch, k, d, activation=h.activation) + ) + + # Post-conv + activation_post = ( + activations.Snake(ch, alpha_logscale=h.snake_logscale) + if h.activation == "snake" + else ( + activations.SnakeBeta(ch, alpha_logscale=h.snake_logscale) + if h.activation == "snakebeta" + else None + ) + ) + if activation_post is None: + raise NotImplementedError( + "activation incorrectly specified. check the config file and look for 'activation'." + ) + + self.activation_post = Activation1d(activation=activation_post) + + # Whether to use bias for the final conv_post. Default to True for backward compatibility + self.use_bias_at_final = h.get("use_bias_at_final", True) + self.conv_post = weight_norm( + Conv1d(ch, 1, 7, 1, padding=3, bias=self.use_bias_at_final) + ) + + # Weight initialization + for i in range(len(self.ups)): + self.ups[i].apply(init_weights) + self.conv_post.apply(init_weights) + + # Final tanh activation. Defaults to True for backward compatibility + self.use_tanh_at_final = h.get("use_tanh_at_final", True) + + def forward(self, x): + # Pre-conv + x = self.conv_pre(x) + + for i in range(self.num_upsamples): + # Upsampling + for i_up in range(len(self.ups[i])): + x = self.ups[i][i_up](x) + # AMP blocks + xs = None + for j in range(self.num_kernels): + if xs is None: + xs = self.resblocks[i * self.num_kernels + j](x) + else: + xs += self.resblocks[i * self.num_kernels + j](x) + x = xs / self.num_kernels + + # Post-conv + x = self.activation_post(x) + x = self.conv_post(x) + # Final tanh activation + if self.use_tanh_at_final: + x = torch.tanh(x) + else: + x = torch.clamp(x, min=-1.0, max=1.0) # Bound the output to [-1, 1] + + return x + + def remove_weight_norm(self): + try: + print("Removing weight norm...") + for l in self.ups: + for l_i in l: + remove_weight_norm(l_i) + for l in self.resblocks: + l.remove_weight_norm() + remove_weight_norm(self.conv_pre) + remove_weight_norm(self.conv_post) + except ValueError: + print("[INFO] Model already removed weight norm. Skipping!") + pass + + # Additional methods for huggingface_hub support + def _save_pretrained(self, save_directory: Path) -> None: + """Save weights and config.json from a Pytorch model to a local directory.""" + + model_path = save_directory / "bigvgan_generator.pt" + torch.save({"generator": self.state_dict()}, model_path) + + config_path = save_directory / "config.json" + with open(config_path, "w") as config_file: + json.dump(self.h, config_file, indent=4) + + @classmethod + def _from_pretrained( + cls, + *, + model_id: str, + revision: str, + cache_dir: str, + force_download: bool, + proxies: Optional[Dict], + resume_download: bool, + local_files_only: bool, + token: Union[str, bool, None], + map_location: str = "cpu", # Additional argument + strict: bool = False, # Additional argument + use_cuda_kernel: bool = False, + **model_kwargs, + ): + """Load Pytorch pretrained weights and return the loaded model.""" + + # Download and load hyperparameters (h) used by BigVGAN + if os.path.isdir(model_id): + print("Loading config.json from local directory") + config_file = os.path.join(model_id, "config.json") + else: + config_file = hf_hub_download( + repo_id=model_id, + filename="config.json", + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + proxies=proxies, + resume_download=resume_download, + token=token, + local_files_only=local_files_only, + ) + h = load_hparams_from_json(config_file) + + # instantiate BigVGAN using h + if use_cuda_kernel: + print( + f"[WARNING] You have specified use_cuda_kernel=True during BigVGAN.from_pretrained(). Only inference is supported (training is not implemented)!" + ) + print( + f"[WARNING] You need nvcc and ninja installed in your system that matches your PyTorch build is using to build the kernel. If not, the model will fail to initialize or generate incorrect waveform!" + ) + print( + f"[WARNING] For detail, see the official GitHub repository: https://github.com/NVIDIA/BigVGAN?tab=readme-ov-file#using-custom-cuda-kernel-for-synthesis" + ) + model = cls(h, use_cuda_kernel=use_cuda_kernel) + + # Download and load pretrained generator weight + if os.path.isdir(model_id): + print("Loading weights from local directory") + model_file = os.path.join(model_id, "bigvgan_generator.pt") + else: + print(f"Loading weights from {model_id}") + model_file = hf_hub_download( + repo_id=model_id, + filename="bigvgan_generator.pt", + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + proxies=proxies, + resume_download=resume_download, + token=token, + local_files_only=local_files_only, + ) + + checkpoint_dict = torch.load(model_file, map_location=map_location) + + try: + model.load_state_dict(checkpoint_dict["generator"]) + except RuntimeError: + print( + f"[INFO] the pretrained checkpoint does not contain weight norm. Loading the checkpoint after removing weight norm!" + ) + model.remove_weight_norm() + model.load_state_dict(checkpoint_dict["generator"]) + + return model diff --git a/code/third_party/bigvgan/discriminators.py b/code/third_party/bigvgan/discriminators.py new file mode 100644 index 0000000000000000000000000000000000000000..197f6ff77e8040e1aad8ce1ffe7c871653dbb0d8 --- /dev/null +++ b/code/third_party/bigvgan/discriminators.py @@ -0,0 +1,651 @@ +# Copyright (c) 2024 NVIDIA CORPORATION. +# Licensed under the MIT license. + +# Adapted from https://github.com/jik876/hifi-gan under the MIT license. +# LICENSE is in incl_licenses directory. + + +import torch +import torch.nn.functional as F +import torch.nn as nn +from torch.nn import Conv2d +from torch.nn.utils import weight_norm, spectral_norm +from torchaudio.transforms import Spectrogram, Resample + +from env import AttrDict +from utils import get_padding +import typing +from typing import Optional, List, Union, Dict, Tuple + + +class DiscriminatorP(torch.nn.Module): + def __init__( + self, + h: AttrDict, + period: List[int], + kernel_size: int = 5, + stride: int = 3, + use_spectral_norm: bool = False, + ): + super().__init__() + self.period = period + self.d_mult = h.discriminator_channel_mult + norm_f = weight_norm if not use_spectral_norm else spectral_norm + + self.convs = nn.ModuleList( + [ + norm_f( + Conv2d( + 1, + int(32 * self.d_mult), + (kernel_size, 1), + (stride, 1), + padding=(get_padding(5, 1), 0), + ) + ), + norm_f( + Conv2d( + int(32 * self.d_mult), + int(128 * self.d_mult), + (kernel_size, 1), + (stride, 1), + padding=(get_padding(5, 1), 0), + ) + ), + norm_f( + Conv2d( + int(128 * self.d_mult), + int(512 * self.d_mult), + (kernel_size, 1), + (stride, 1), + padding=(get_padding(5, 1), 0), + ) + ), + norm_f( + Conv2d( + int(512 * self.d_mult), + int(1024 * self.d_mult), + (kernel_size, 1), + (stride, 1), + padding=(get_padding(5, 1), 0), + ) + ), + norm_f( + Conv2d( + int(1024 * self.d_mult), + int(1024 * self.d_mult), + (kernel_size, 1), + 1, + padding=(2, 0), + ) + ), + ] + ) + self.conv_post = norm_f( + Conv2d(int(1024 * self.d_mult), 1, (3, 1), 1, padding=(1, 0)) + ) + + def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: + fmap = [] + + # 1d to 2d + b, c, t = x.shape + if t % self.period != 0: # pad first + n_pad = self.period - (t % self.period) + x = F.pad(x, (0, n_pad), "reflect") + t = t + n_pad + x = x.view(b, c, t // self.period, self.period) + + for l in self.convs: + x = l(x) + x = F.leaky_relu(x, 0.1) + fmap.append(x) + x = self.conv_post(x) + fmap.append(x) + x = torch.flatten(x, 1, -1) + + return x, fmap + + +class MultiPeriodDiscriminator(torch.nn.Module): + def __init__(self, h: AttrDict): + super().__init__() + self.mpd_reshapes = h.mpd_reshapes + print(f"mpd_reshapes: {self.mpd_reshapes}") + self.discriminators = nn.ModuleList( + [ + DiscriminatorP(h, rs, use_spectral_norm=h.use_spectral_norm) + for rs in self.mpd_reshapes + ] + ) + + def forward(self, y: torch.Tensor, y_hat: torch.Tensor) -> Tuple[ + List[torch.Tensor], + List[torch.Tensor], + List[List[torch.Tensor]], + List[List[torch.Tensor]], + ]: + y_d_rs = [] + y_d_gs = [] + fmap_rs = [] + fmap_gs = [] + for i, d in enumerate(self.discriminators): + y_d_r, fmap_r = d(y) + y_d_g, fmap_g = d(y_hat) + y_d_rs.append(y_d_r) + fmap_rs.append(fmap_r) + y_d_gs.append(y_d_g) + fmap_gs.append(fmap_g) + + return y_d_rs, y_d_gs, fmap_rs, fmap_gs + + +class DiscriminatorR(nn.Module): + def __init__(self, cfg: AttrDict, resolution: List[List[int]]): + super().__init__() + + self.resolution = resolution + assert ( + len(self.resolution) == 3 + ), f"MRD layer requires list with len=3, got {self.resolution}" + self.lrelu_slope = 0.1 + + norm_f = weight_norm if cfg.use_spectral_norm == False else spectral_norm + if hasattr(cfg, "mrd_use_spectral_norm"): + print( + f"[INFO] overriding MRD use_spectral_norm as {cfg.mrd_use_spectral_norm}" + ) + norm_f = ( + weight_norm if cfg.mrd_use_spectral_norm == False else spectral_norm + ) + self.d_mult = cfg.discriminator_channel_mult + if hasattr(cfg, "mrd_channel_mult"): + print(f"[INFO] overriding mrd channel multiplier as {cfg.mrd_channel_mult}") + self.d_mult = cfg.mrd_channel_mult + + self.convs = nn.ModuleList( + [ + norm_f(nn.Conv2d(1, int(32 * self.d_mult), (3, 9), padding=(1, 4))), + norm_f( + nn.Conv2d( + int(32 * self.d_mult), + int(32 * self.d_mult), + (3, 9), + stride=(1, 2), + padding=(1, 4), + ) + ), + norm_f( + nn.Conv2d( + int(32 * self.d_mult), + int(32 * self.d_mult), + (3, 9), + stride=(1, 2), + padding=(1, 4), + ) + ), + norm_f( + nn.Conv2d( + int(32 * self.d_mult), + int(32 * self.d_mult), + (3, 9), + stride=(1, 2), + padding=(1, 4), + ) + ), + norm_f( + nn.Conv2d( + int(32 * self.d_mult), + int(32 * self.d_mult), + (3, 3), + padding=(1, 1), + ) + ), + ] + ) + self.conv_post = norm_f( + nn.Conv2d(int(32 * self.d_mult), 1, (3, 3), padding=(1, 1)) + ) + + def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: + fmap = [] + + x = self.spectrogram(x) + x = x.unsqueeze(1) + for l in self.convs: + x = l(x) + x = F.leaky_relu(x, self.lrelu_slope) + fmap.append(x) + x = self.conv_post(x) + fmap.append(x) + x = torch.flatten(x, 1, -1) + + return x, fmap + + def spectrogram(self, x: torch.Tensor) -> torch.Tensor: + n_fft, hop_length, win_length = self.resolution + x = F.pad( + x, + (int((n_fft - hop_length) / 2), int((n_fft - hop_length) / 2)), + mode="reflect", + ) + x = x.squeeze(1) + x = torch.stft( + x, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + center=False, + return_complex=True, + ) + x = torch.view_as_real(x) # [B, F, TT, 2] + mag = torch.norm(x, p=2, dim=-1) # [B, F, TT] + + return mag + + +class MultiResolutionDiscriminator(nn.Module): + def __init__(self, cfg, debug=False): + super().__init__() + self.resolutions = cfg.resolutions + assert ( + len(self.resolutions) == 3 + ), f"MRD requires list of list with len=3, each element having a list with len=3. Got {self.resolutions}" + self.discriminators = nn.ModuleList( + [DiscriminatorR(cfg, resolution) for resolution in self.resolutions] + ) + + def forward(self, y: torch.Tensor, y_hat: torch.Tensor) -> Tuple[ + List[torch.Tensor], + List[torch.Tensor], + List[List[torch.Tensor]], + List[List[torch.Tensor]], + ]: + y_d_rs = [] + y_d_gs = [] + fmap_rs = [] + fmap_gs = [] + + for i, d in enumerate(self.discriminators): + y_d_r, fmap_r = d(x=y) + y_d_g, fmap_g = d(x=y_hat) + y_d_rs.append(y_d_r) + fmap_rs.append(fmap_r) + y_d_gs.append(y_d_g) + fmap_gs.append(fmap_g) + + return y_d_rs, y_d_gs, fmap_rs, fmap_gs + + +# Method based on descript-audio-codec: https://github.com/descriptinc/descript-audio-codec +# Modified code adapted from https://github.com/gemelo-ai/vocos under the MIT license. +# LICENSE is in incl_licenses directory. +class DiscriminatorB(nn.Module): + def __init__( + self, + window_length: int, + channels: int = 32, + hop_factor: float = 0.25, + bands: Tuple[Tuple[float, float], ...] = ( + (0.0, 0.1), + (0.1, 0.25), + (0.25, 0.5), + (0.5, 0.75), + (0.75, 1.0), + ), + ): + super().__init__() + self.window_length = window_length + self.hop_factor = hop_factor + self.spec_fn = Spectrogram( + n_fft=window_length, + hop_length=int(window_length * hop_factor), + win_length=window_length, + power=None, + ) + n_fft = window_length // 2 + 1 + bands = [(int(b[0] * n_fft), int(b[1] * n_fft)) for b in bands] + self.bands = bands + convs = lambda: nn.ModuleList( + [ + weight_norm(nn.Conv2d(2, channels, (3, 9), (1, 1), padding=(1, 4))), + weight_norm( + nn.Conv2d(channels, channels, (3, 9), (1, 2), padding=(1, 4)) + ), + weight_norm( + nn.Conv2d(channels, channels, (3, 9), (1, 2), padding=(1, 4)) + ), + weight_norm( + nn.Conv2d(channels, channels, (3, 9), (1, 2), padding=(1, 4)) + ), + weight_norm( + nn.Conv2d(channels, channels, (3, 3), (1, 1), padding=(1, 1)) + ), + ] + ) + self.band_convs = nn.ModuleList([convs() for _ in range(len(self.bands))]) + + self.conv_post = weight_norm( + nn.Conv2d(channels, 1, (3, 3), (1, 1), padding=(1, 1)) + ) + + def spectrogram(self, x: torch.Tensor) -> List[torch.Tensor]: + # Remove DC offset + x = x - x.mean(dim=-1, keepdims=True) + # Peak normalize the volume of input audio + x = 0.8 * x / (x.abs().max(dim=-1, keepdim=True)[0] + 1e-9) + x = self.spec_fn(x) + x = torch.view_as_real(x) + x = x.permute(0, 3, 2, 1) # [B, F, T, C] -> [B, C, T, F] + # Split into bands + x_bands = [x[..., b[0] : b[1]] for b in self.bands] + return x_bands + + def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: + x_bands = self.spectrogram(x.squeeze(1)) + fmap = [] + x = [] + + for band, stack in zip(x_bands, self.band_convs): + for i, layer in enumerate(stack): + band = layer(band) + band = torch.nn.functional.leaky_relu(band, 0.1) + if i > 0: + fmap.append(band) + x.append(band) + + x = torch.cat(x, dim=-1) + x = self.conv_post(x) + fmap.append(x) + + return x, fmap + + +# Method based on descript-audio-codec: https://github.com/descriptinc/descript-audio-codec +# Modified code adapted from https://github.com/gemelo-ai/vocos under the MIT license. +# LICENSE is in incl_licenses directory. +class MultiBandDiscriminator(nn.Module): + def __init__( + self, + h, + ): + """ + Multi-band multi-scale STFT discriminator, with the architecture based on https://github.com/descriptinc/descript-audio-codec. + and the modified code adapted from https://github.com/gemelo-ai/vocos. + """ + super().__init__() + # fft_sizes (list[int]): Tuple of window lengths for FFT. Defaults to [2048, 1024, 512] if not set in h. + self.fft_sizes = h.get("mbd_fft_sizes", [2048, 1024, 512]) + self.discriminators = nn.ModuleList( + [DiscriminatorB(window_length=w) for w in self.fft_sizes] + ) + + def forward(self, y: torch.Tensor, y_hat: torch.Tensor) -> Tuple[ + List[torch.Tensor], + List[torch.Tensor], + List[List[torch.Tensor]], + List[List[torch.Tensor]], + ]: + + y_d_rs = [] + y_d_gs = [] + fmap_rs = [] + fmap_gs = [] + + for d in self.discriminators: + y_d_r, fmap_r = d(x=y) + y_d_g, fmap_g = d(x=y_hat) + y_d_rs.append(y_d_r) + fmap_rs.append(fmap_r) + y_d_gs.append(y_d_g) + fmap_gs.append(fmap_g) + + return y_d_rs, y_d_gs, fmap_rs, fmap_gs + + +# Adapted from https://github.com/open-mmlab/Amphion/blob/main/models/vocoders/gan/discriminator/mssbcqtd.py under the MIT license. +# LICENSE is in incl_licenses directory. +class DiscriminatorCQT(nn.Module): + def __init__(self, cfg: AttrDict, hop_length: int, n_octaves:int, bins_per_octave: int): + super().__init__() + self.cfg = cfg + + self.filters = cfg["cqtd_filters"] + self.max_filters = cfg["cqtd_max_filters"] + self.filters_scale = cfg["cqtd_filters_scale"] + self.kernel_size = (3, 9) + self.dilations = cfg["cqtd_dilations"] + self.stride = (1, 2) + + self.in_channels = cfg["cqtd_in_channels"] + self.out_channels = cfg["cqtd_out_channels"] + self.fs = cfg["sampling_rate"] + self.hop_length = hop_length + self.n_octaves = n_octaves + self.bins_per_octave = bins_per_octave + + # Lazy-load + from nnAudio import features + + self.cqt_transform = features.cqt.CQT2010v2( + sr=self.fs * 2, + hop_length=self.hop_length, + n_bins=self.bins_per_octave * self.n_octaves, + bins_per_octave=self.bins_per_octave, + output_format="Complex", + pad_mode="constant", + ) + + self.conv_pres = nn.ModuleList() + for _ in range(self.n_octaves): + self.conv_pres.append( + nn.Conv2d( + self.in_channels * 2, + self.in_channels * 2, + kernel_size=self.kernel_size, + padding=self.get_2d_padding(self.kernel_size), + ) + ) + + self.convs = nn.ModuleList() + + self.convs.append( + nn.Conv2d( + self.in_channels * 2, + self.filters, + kernel_size=self.kernel_size, + padding=self.get_2d_padding(self.kernel_size), + ) + ) + + in_chs = min(self.filters_scale * self.filters, self.max_filters) + for i, dilation in enumerate(self.dilations): + out_chs = min( + (self.filters_scale ** (i + 1)) * self.filters, self.max_filters + ) + self.convs.append( + weight_norm( + nn.Conv2d( + in_chs, + out_chs, + kernel_size=self.kernel_size, + stride=self.stride, + dilation=(dilation, 1), + padding=self.get_2d_padding(self.kernel_size, (dilation, 1)), + ) + ) + ) + in_chs = out_chs + out_chs = min( + (self.filters_scale ** (len(self.dilations) + 1)) * self.filters, + self.max_filters, + ) + self.convs.append( + weight_norm( + nn.Conv2d( + in_chs, + out_chs, + kernel_size=(self.kernel_size[0], self.kernel_size[0]), + padding=self.get_2d_padding( + (self.kernel_size[0], self.kernel_size[0]) + ), + ) + ) + ) + + self.conv_post = weight_norm( + nn.Conv2d( + out_chs, + self.out_channels, + kernel_size=(self.kernel_size[0], self.kernel_size[0]), + padding=self.get_2d_padding((self.kernel_size[0], self.kernel_size[0])), + ) + ) + + self.activation = torch.nn.LeakyReLU(negative_slope=0.1) + self.resample = Resample(orig_freq=self.fs, new_freq=self.fs * 2) + + self.cqtd_normalize_volume = self.cfg.get("cqtd_normalize_volume", False) + if self.cqtd_normalize_volume: + print( + f"[INFO] cqtd_normalize_volume set to True. Will apply DC offset removal & peak volume normalization in CQTD!" + ) + + def get_2d_padding( + self, + kernel_size: typing.Tuple[int, int], + dilation: typing.Tuple[int, int] = (1, 1), + ): + return ( + ((kernel_size[0] - 1) * dilation[0]) // 2, + ((kernel_size[1] - 1) * dilation[1]) // 2, + ) + + def forward(self, x: torch.tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: + fmap = [] + + if self.cqtd_normalize_volume: + # Remove DC offset + x = x - x.mean(dim=-1, keepdims=True) + # Peak normalize the volume of input audio + x = 0.8 * x / (x.abs().max(dim=-1, keepdim=True)[0] + 1e-9) + + x = self.resample(x) + + z = self.cqt_transform(x) + + z_amplitude = z[:, :, :, 0].unsqueeze(1) + z_phase = z[:, :, :, 1].unsqueeze(1) + + z = torch.cat([z_amplitude, z_phase], dim=1) + z = torch.permute(z, (0, 1, 3, 2)) # [B, C, W, T] -> [B, C, T, W] + + latent_z = [] + for i in range(self.n_octaves): + latent_z.append( + self.conv_pres[i]( + z[ + :, + :, + :, + i * self.bins_per_octave : (i + 1) * self.bins_per_octave, + ] + ) + ) + latent_z = torch.cat(latent_z, dim=-1) + + for i, l in enumerate(self.convs): + latent_z = l(latent_z) + + latent_z = self.activation(latent_z) + fmap.append(latent_z) + + latent_z = self.conv_post(latent_z) + + return latent_z, fmap + + +class MultiScaleSubbandCQTDiscriminator(nn.Module): + def __init__(self, cfg: AttrDict): + super().__init__() + + self.cfg = cfg + # Using get with defaults + self.cfg["cqtd_filters"] = self.cfg.get("cqtd_filters", 32) + self.cfg["cqtd_max_filters"] = self.cfg.get("cqtd_max_filters", 1024) + self.cfg["cqtd_filters_scale"] = self.cfg.get("cqtd_filters_scale", 1) + self.cfg["cqtd_dilations"] = self.cfg.get("cqtd_dilations", [1, 2, 4]) + self.cfg["cqtd_in_channels"] = self.cfg.get("cqtd_in_channels", 1) + self.cfg["cqtd_out_channels"] = self.cfg.get("cqtd_out_channels", 1) + # Multi-scale params to loop over + self.cfg["cqtd_hop_lengths"] = self.cfg.get("cqtd_hop_lengths", [512, 256, 256]) + self.cfg["cqtd_n_octaves"] = self.cfg.get("cqtd_n_octaves", [9, 9, 9]) + self.cfg["cqtd_bins_per_octaves"] = self.cfg.get( + "cqtd_bins_per_octaves", [24, 36, 48] + ) + + self.discriminators = nn.ModuleList( + [ + DiscriminatorCQT( + self.cfg, + hop_length=self.cfg["cqtd_hop_lengths"][i], + n_octaves=self.cfg["cqtd_n_octaves"][i], + bins_per_octave=self.cfg["cqtd_bins_per_octaves"][i], + ) + for i in range(len(self.cfg["cqtd_hop_lengths"])) + ] + ) + + def forward(self, y: torch.Tensor, y_hat: torch.Tensor) -> Tuple[ + List[torch.Tensor], + List[torch.Tensor], + List[List[torch.Tensor]], + List[List[torch.Tensor]], + ]: + + y_d_rs = [] + y_d_gs = [] + fmap_rs = [] + fmap_gs = [] + + for disc in self.discriminators: + y_d_r, fmap_r = disc(y) + y_d_g, fmap_g = disc(y_hat) + y_d_rs.append(y_d_r) + fmap_rs.append(fmap_r) + y_d_gs.append(y_d_g) + fmap_gs.append(fmap_g) + + return y_d_rs, y_d_gs, fmap_rs, fmap_gs + + +class CombinedDiscriminator(nn.Module): + """ + Wrapper of chaining multiple discrimiantor architectures. + Example: combine mbd and cqtd as a single class + """ + + def __init__(self, list_discriminator: List[nn.Module]): + super().__init__() + self.discrimiantor = nn.ModuleList(list_discriminator) + + def forward(self, y: torch.Tensor, y_hat: torch.Tensor) -> Tuple[ + List[torch.Tensor], + List[torch.Tensor], + List[List[torch.Tensor]], + List[List[torch.Tensor]], + ]: + + y_d_rs = [] + y_d_gs = [] + fmap_rs = [] + fmap_gs = [] + + for disc in self.discrimiantor: + y_d_r, y_d_g, fmap_r, fmap_g = disc(y, y_hat) + y_d_rs.extend(y_d_r) + fmap_rs.extend(fmap_r) + y_d_gs.extend(y_d_g) + fmap_gs.extend(fmap_g) + + return y_d_rs, y_d_gs, fmap_rs, fmap_gs diff --git a/code/third_party/bigvgan/env.py b/code/third_party/bigvgan/env.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc6c9a6b460f13b59761bebf69c43bd6a6ecf1d --- /dev/null +++ b/code/third_party/bigvgan/env.py @@ -0,0 +1,18 @@ +# Adapted from https://github.com/jik876/hifi-gan under the MIT license. +# LICENSE is in incl_licenses directory. + +import os +import shutil + + +class AttrDict(dict): + def __init__(self, *args, **kwargs): + super(AttrDict, self).__init__(*args, **kwargs) + self.__dict__ = self + + +def build_env(config, config_name, path): + t_path = os.path.join(path, config_name) + if config != t_path: + os.makedirs(path, exist_ok=True) + shutil.copyfile(config, os.path.join(path, config_name)) diff --git a/code/third_party/bigvgan/loss.py b/code/third_party/bigvgan/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..3fdfba26c66bd05566c4ba7946d2f1163eed2067 --- /dev/null +++ b/code/third_party/bigvgan/loss.py @@ -0,0 +1,254 @@ +# Copyright (c) 2024 NVIDIA CORPORATION. +# Licensed under the MIT license. + +# Adapted from https://github.com/jik876/hifi-gan under the MIT license. +# LICENSE is in incl_licenses directory. + + +import torch +import torch.nn.functional as F +import torch.nn as nn +from librosa.filters import mel as librosa_mel_fn +from scipy import signal + +import typing +from typing import Optional, List, Union, Dict, Tuple +from collections import namedtuple +import math +import functools + + +# Adapted from https://github.com/descriptinc/descript-audio-codec/blob/main/dac/nn/loss.py under the MIT license. +# LICENSE is in incl_licenses directory. +class MultiScaleMelSpectrogramLoss(nn.Module): + """Compute distance between mel spectrograms. Can be used + in a multi-scale way. + + Parameters + ---------- + n_mels : List[int] + Number of mels per STFT, by default [5, 10, 20, 40, 80, 160, 320], + window_lengths : List[int], optional + Length of each window of each STFT, by default [32, 64, 128, 256, 512, 1024, 2048] + loss_fn : typing.Callable, optional + How to compare each loss, by default nn.L1Loss() + clamp_eps : float, optional + Clamp on the log magnitude, below, by default 1e-5 + mag_weight : float, optional + Weight of raw magnitude portion of loss, by default 0.0 (no ampliciation on mag part) + log_weight : float, optional + Weight of log magnitude portion of loss, by default 1.0 + pow : float, optional + Power to raise magnitude to before taking log, by default 1.0 + weight : float, optional + Weight of this loss, by default 1.0 + match_stride : bool, optional + Whether to match the stride of convolutional layers, by default False + + Implementation copied from: https://github.com/descriptinc/lyrebird-audiotools/blob/961786aa1a9d628cca0c0486e5885a457fe70c1a/audiotools/metrics/spectral.py + Additional code copied and modified from https://github.com/descriptinc/audiotools/blob/master/audiotools/core/audio_signal.py + """ + + def __init__( + self, + sampling_rate: int, + n_mels: List[int] = [5, 10, 20, 40, 80, 160, 320], + window_lengths: List[int] = [32, 64, 128, 256, 512, 1024, 2048], + loss_fn: typing.Callable = nn.L1Loss(), + clamp_eps: float = 1e-5, + mag_weight: float = 0.0, + log_weight: float = 1.0, + pow: float = 1.0, + weight: float = 1.0, + match_stride: bool = False, + mel_fmin: List[float] = [0, 0, 0, 0, 0, 0, 0], + mel_fmax: List[float] = [None, None, None, None, None, None, None], + window_type: str = "hann", + ): + super().__init__() + self.sampling_rate = sampling_rate + + STFTParams = namedtuple( + "STFTParams", + ["window_length", "hop_length", "window_type", "match_stride"], + ) + + self.stft_params = [ + STFTParams( + window_length=w, + hop_length=w // 4, + match_stride=match_stride, + window_type=window_type, + ) + for w in window_lengths + ] + self.n_mels = n_mels + self.loss_fn = loss_fn + self.clamp_eps = clamp_eps + self.log_weight = log_weight + self.mag_weight = mag_weight + self.weight = weight + self.mel_fmin = mel_fmin + self.mel_fmax = mel_fmax + self.pow = pow + + @staticmethod + @functools.lru_cache(None) + def get_window( + window_type, + window_length, + ): + return signal.get_window(window_type, window_length) + + @staticmethod + @functools.lru_cache(None) + def get_mel_filters(sr, n_fft, n_mels, fmin, fmax): + return librosa_mel_fn(sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax) + + def mel_spectrogram( + self, + wav, + n_mels, + fmin, + fmax, + window_length, + hop_length, + match_stride, + window_type, + ): + """ + Mirrors AudioSignal.mel_spectrogram used by BigVGAN-v2 training from: + https://github.com/descriptinc/audiotools/blob/master/audiotools/core/audio_signal.py + """ + B, C, T = wav.shape + + if match_stride: + assert ( + hop_length == window_length // 4 + ), "For match_stride, hop must equal n_fft // 4" + right_pad = math.ceil(T / hop_length) * hop_length - T + pad = (window_length - hop_length) // 2 + else: + right_pad = 0 + pad = 0 + + wav = torch.nn.functional.pad(wav, (pad, pad + right_pad), mode="reflect") + + window = self.get_window(window_type, window_length) + window = torch.from_numpy(window).to(wav.device).float() + + stft = torch.stft( + wav.reshape(-1, T), + n_fft=window_length, + hop_length=hop_length, + window=window, + return_complex=True, + center=True, + ) + _, nf, nt = stft.shape + stft = stft.reshape(B, C, nf, nt) + if match_stride: + """ + Drop first two and last two frames, which are added, because of padding. Now num_frames * hop_length = num_samples. + """ + stft = stft[..., 2:-2] + magnitude = torch.abs(stft) + + nf = magnitude.shape[2] + mel_basis = self.get_mel_filters( + self.sampling_rate, 2 * (nf - 1), n_mels, fmin, fmax + ) + mel_basis = torch.from_numpy(mel_basis).to(wav.device) + mel_spectrogram = magnitude.transpose(2, -1) @ mel_basis.T + mel_spectrogram = mel_spectrogram.transpose(-1, 2) + + return mel_spectrogram + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """Computes mel loss between an estimate and a reference + signal. + + Parameters + ---------- + x : torch.Tensor + Estimate signal + y : torch.Tensor + Reference signal + + Returns + ------- + torch.Tensor + Mel loss. + """ + + loss = 0.0 + for n_mels, fmin, fmax, s in zip( + self.n_mels, self.mel_fmin, self.mel_fmax, self.stft_params + ): + kwargs = { + "n_mels": n_mels, + "fmin": fmin, + "fmax": fmax, + "window_length": s.window_length, + "hop_length": s.hop_length, + "match_stride": s.match_stride, + "window_type": s.window_type, + } + + x_mels = self.mel_spectrogram(x, **kwargs) + y_mels = self.mel_spectrogram(y, **kwargs) + x_logmels = torch.log( + x_mels.clamp(min=self.clamp_eps).pow(self.pow) + ) / torch.log(torch.tensor(10.0)) + y_logmels = torch.log( + y_mels.clamp(min=self.clamp_eps).pow(self.pow) + ) / torch.log(torch.tensor(10.0)) + + loss += self.log_weight * self.loss_fn(x_logmels, y_logmels) + loss += self.mag_weight * self.loss_fn(x_logmels, y_logmels) + + return loss + + +# Loss functions +def feature_loss( + fmap_r: List[List[torch.Tensor]], fmap_g: List[List[torch.Tensor]] +) -> torch.Tensor: + + loss = 0 + for dr, dg in zip(fmap_r, fmap_g): + for rl, gl in zip(dr, dg): + loss += torch.mean(torch.abs(rl - gl)) + + return loss * 2 # This equates to lambda=2.0 for the feature matching loss + + +def discriminator_loss( + disc_real_outputs: List[torch.Tensor], disc_generated_outputs: List[torch.Tensor] +) -> Tuple[torch.Tensor, List[torch.Tensor], List[torch.Tensor]]: + + loss = 0 + r_losses = [] + g_losses = [] + for dr, dg in zip(disc_real_outputs, disc_generated_outputs): + r_loss = torch.mean((1 - dr) ** 2) + g_loss = torch.mean(dg**2) + loss += r_loss + g_loss + r_losses.append(r_loss.item()) + g_losses.append(g_loss.item()) + + return loss, r_losses, g_losses + + +def generator_loss( + disc_outputs: List[torch.Tensor], +) -> Tuple[torch.Tensor, List[torch.Tensor]]: + + loss = 0 + gen_losses = [] + for dg in disc_outputs: + l = torch.mean((1 - dg) ** 2) + gen_losses.append(l) + loss += l + + return loss, gen_losses diff --git a/code/third_party/bigvgan/meldataset.py b/code/third_party/bigvgan/meldataset.py new file mode 100644 index 0000000000000000000000000000000000000000..9661bb2f5e04835f09b1d6e318e3360094d187b4 --- /dev/null +++ b/code/third_party/bigvgan/meldataset.py @@ -0,0 +1,396 @@ +# Copyright (c) 2024 NVIDIA CORPORATION. +# Licensed under the MIT license. + +# Adapted from https://github.com/jik876/hifi-gan under the MIT license. +# LICENSE is in incl_licenses directory. + +import math +import os +import random +import torch +import torch.utils.data +import numpy as np +import librosa +from librosa.filters import mel as librosa_mel_fn +import pathlib +from tqdm import tqdm +from typing import List, Tuple, Optional +from env import AttrDict + +MAX_WAV_VALUE = 32767.0 # NOTE: 32768.0 -1 to prevent int16 overflow (results in popping sound in corner cases) + + +def dynamic_range_compression(x, C=1, clip_val=1e-5): + return np.log(np.clip(x, a_min=clip_val, a_max=None) * C) + + +def dynamic_range_decompression(x, C=1): + return np.exp(x) / C + + +def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): + return torch.log(torch.clamp(x, min=clip_val) * C) + + +def dynamic_range_decompression_torch(x, C=1): + return torch.exp(x) / C + + +def spectral_normalize_torch(magnitudes): + return dynamic_range_compression_torch(magnitudes) + + +def spectral_de_normalize_torch(magnitudes): + return dynamic_range_decompression_torch(magnitudes) + + +mel_basis_cache = {} +hann_window_cache = {} + + +def mel_spectrogram( + y: torch.Tensor, + n_fft: int, + num_mels: int, + sampling_rate: int, + hop_size: int, + win_size: int, + fmin: int, + fmax: int = None, + center: bool = False, +) -> torch.Tensor: + """ + Calculate the mel spectrogram of an input signal. + This function uses slaney norm for the librosa mel filterbank (using librosa.filters.mel) and uses Hann window for STFT (using torch.stft). + + Args: + y (torch.Tensor): Input signal. + n_fft (int): FFT size. + num_mels (int): Number of mel bins. + sampling_rate (int): Sampling rate of the input signal. + hop_size (int): Hop size for STFT. + win_size (int): Window size for STFT. + fmin (int): Minimum frequency for mel filterbank. + fmax (int): Maximum frequency for mel filterbank. If None, defaults to half the sampling rate (fmax = sr / 2.0) inside librosa_mel_fn + center (bool): Whether to pad the input to center the frames. Default is False. + + Returns: + torch.Tensor: Mel spectrogram. + """ + if torch.min(y) < -1.0: + print(f"[WARNING] Min value of input waveform signal is {torch.min(y)}") + if torch.max(y) > 1.0: + print(f"[WARNING] Max value of input waveform signal is {torch.max(y)}") + + device = y.device + key = f"{n_fft}_{num_mels}_{sampling_rate}_{hop_size}_{win_size}_{fmin}_{fmax}_{device}" + + if key not in mel_basis_cache: + mel = librosa_mel_fn( + sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax + ) + mel_basis_cache[key] = torch.from_numpy(mel).float().to(device) + hann_window_cache[key] = torch.hann_window(win_size).to(device) + + mel_basis = mel_basis_cache[key] + hann_window = hann_window_cache[key] + + padding = (n_fft - hop_size) // 2 + y = torch.nn.functional.pad( + y.unsqueeze(1), (padding, padding), mode="reflect" + ).squeeze(1) + + spec = torch.stft( + y, + n_fft, + hop_length=hop_size, + win_length=win_size, + window=hann_window, + center=center, + pad_mode="reflect", + normalized=False, + onesided=True, + return_complex=True, + ) + spec = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9) + + mel_spec = torch.matmul(mel_basis, spec) + mel_spec = spectral_normalize_torch(mel_spec) + + return mel_spec + + +def get_mel_spectrogram(wav, h): + """ + Generate mel spectrogram from a waveform using given hyperparameters. + + Args: + wav (torch.Tensor): Input waveform. + h: Hyperparameters object with attributes n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax. + + Returns: + torch.Tensor: Mel spectrogram. + """ + return mel_spectrogram( + wav, + h.n_fft, + h.num_mels, + h.sampling_rate, + h.hop_size, + h.win_size, + h.fmin, + h.fmax, + ) + + +def get_dataset_filelist(a): + training_files = [] + validation_files = [] + list_unseen_validation_files = [] + + with open(a.input_training_file, "r", encoding="utf-8") as fi: + training_files = [ + os.path.join(a.input_wavs_dir, x.split("|")[0] + ".wav") + for x in fi.read().split("\n") + if len(x) > 0 + ] + print(f"first training file: {training_files[0]}") + + with open(a.input_validation_file, "r", encoding="utf-8") as fi: + validation_files = [ + os.path.join(a.input_wavs_dir, x.split("|")[0] + ".wav") + for x in fi.read().split("\n") + if len(x) > 0 + ] + print(f"first validation file: {validation_files[0]}") + + for i in range(len(a.list_input_unseen_validation_file)): + with open(a.list_input_unseen_validation_file[i], "r", encoding="utf-8") as fi: + unseen_validation_files = [ + os.path.join(a.list_input_unseen_wavs_dir[i], x.split("|")[0] + ".wav") + for x in fi.read().split("\n") + if len(x) > 0 + ] + print( + f"first unseen {i}th validation fileset: {unseen_validation_files[0]}" + ) + list_unseen_validation_files.append(unseen_validation_files) + + return training_files, validation_files, list_unseen_validation_files + + +class MelDataset(torch.utils.data.Dataset): + def __init__( + self, + training_files: List[str], + hparams: AttrDict, + segment_size: int, + n_fft: int, + num_mels: int, + hop_size: int, + win_size: int, + sampling_rate: int, + fmin: int, + fmax: Optional[int], + split: bool = True, + shuffle: bool = True, + device: str = None, + fmax_loss: Optional[int] = None, + fine_tuning: bool = False, + base_mels_path: str = None, + is_seen: bool = True, + ): + self.audio_files = training_files + random.seed(1234) + if shuffle: + random.shuffle(self.audio_files) + self.hparams = hparams + self.is_seen = is_seen + if self.is_seen: + self.name = pathlib.Path(self.audio_files[0]).parts[0] + else: + self.name = "-".join(pathlib.Path(self.audio_files[0]).parts[:2]).strip("/") + + self.segment_size = segment_size + self.sampling_rate = sampling_rate + self.split = split + self.n_fft = n_fft + self.num_mels = num_mels + self.hop_size = hop_size + self.win_size = win_size + self.fmin = fmin + self.fmax = fmax + self.fmax_loss = fmax_loss + self.device = device + self.fine_tuning = fine_tuning + self.base_mels_path = base_mels_path + + print("[INFO] checking dataset integrity...") + for i in tqdm(range(len(self.audio_files))): + assert os.path.exists( + self.audio_files[i] + ), f"{self.audio_files[i]} not found" + + def __getitem__( + self, index: int + ) -> Tuple[torch.Tensor, torch.Tensor, str, torch.Tensor]: + try: + filename = self.audio_files[index] + + # Use librosa.load that ensures loading waveform into mono with [-1, 1] float values + # Audio is ndarray with shape [T_time]. Disable auto-resampling here to minimize overhead + # The on-the-fly resampling during training will be done only for the obtained random chunk + audio, source_sampling_rate = librosa.load(filename, sr=None, mono=True) + + # Main logic that uses pair for training BigVGAN + if not self.fine_tuning: + if self.split: # Training step + # Obtain randomized audio chunk + if source_sampling_rate != self.sampling_rate: + # Adjust segment size to crop if the source sr is different + target_segment_size = math.ceil( + self.segment_size + * (source_sampling_rate / self.sampling_rate) + ) + else: + target_segment_size = self.segment_size + + # Compute upper bound index for the random chunk + random_chunk_upper_bound = max( + 0, audio.shape[0] - target_segment_size + ) + + # Crop or pad audio to obtain random chunk with target_segment_size + if audio.shape[0] >= target_segment_size: + audio_start = random.randint(0, random_chunk_upper_bound) + audio = audio[audio_start : audio_start + target_segment_size] + else: + audio = np.pad( + audio, + (0, target_segment_size - audio.shape[0]), + mode="constant", + ) + + # Resample audio chunk to self.sampling rate + if source_sampling_rate != self.sampling_rate: + audio = librosa.resample( + audio, + orig_sr=source_sampling_rate, + target_sr=self.sampling_rate, + ) + if audio.shape[0] > self.segment_size: + # trim last elements to match self.segment_size (e.g., 16385 for 44khz downsampled to 24khz -> 16384) + audio = audio[: self.segment_size] + + else: # Validation step + # Resample full audio clip to target sampling rate + if source_sampling_rate != self.sampling_rate: + audio = librosa.resample( + audio, + orig_sr=source_sampling_rate, + target_sr=self.sampling_rate, + ) + # Trim last elements to match audio length to self.hop_size * n for evaluation + if (audio.shape[0] % self.hop_size) != 0: + audio = audio[: -(audio.shape[0] % self.hop_size)] + + # BigVGAN is trained using volume-normalized waveform + audio = librosa.util.normalize(audio) * 0.95 + + # Cast ndarray to torch tensor + audio = torch.FloatTensor(audio) + audio = audio.unsqueeze(0) # [B(1), self.segment_size] + + # Compute mel spectrogram corresponding to audio + mel = mel_spectrogram( + audio, + self.n_fft, + self.num_mels, + self.sampling_rate, + self.hop_size, + self.win_size, + self.fmin, + self.fmax, + center=False, + ) # [B(1), self.num_mels, self.segment_size // self.hop_size] + + # Fine-tuning logic that uses pre-computed mel. Example: Using TTS model-generated mel as input + else: + # For fine-tuning, assert that the waveform is in the defined sampling_rate + # Fine-tuning won't support on-the-fly resampling to be fool-proof (the dataset should have been prepared properly) + assert ( + source_sampling_rate == self.sampling_rate + ), f"For fine_tuning, waveform must be in the spcified sampling rate {self.sampling_rate}, got {source_sampling_rate}" + + # Cast ndarray to torch tensor + audio = torch.FloatTensor(audio) + audio = audio.unsqueeze(0) # [B(1), T_time] + + # Load pre-computed mel from disk + mel = np.load( + os.path.join( + self.base_mels_path, + os.path.splitext(os.path.split(filename)[-1])[0] + ".npy", + ) + ) + mel = torch.from_numpy(mel) + + if len(mel.shape) < 3: + mel = mel.unsqueeze(0) # ensure [B, C, T] + + if self.split: + frames_per_seg = math.ceil(self.segment_size / self.hop_size) + + if audio.size(1) >= self.segment_size: + mel_start = random.randint(0, mel.size(2) - frames_per_seg - 1) + mel = mel[:, :, mel_start : mel_start + frames_per_seg] + audio = audio[ + :, + mel_start + * self.hop_size : (mel_start + frames_per_seg) + * self.hop_size, + ] + + # Pad pre-computed mel and audio to match length to ensuring fine-tuning without error. + # NOTE: this may introduce a single-frame misalignment of the + # To remove possible misalignment, it is recommended to prepare the pair where the audio length is the integer multiple of self.hop_size + mel = torch.nn.functional.pad( + mel, (0, frames_per_seg - mel.size(2)), "constant" + ) + audio = torch.nn.functional.pad( + audio, (0, self.segment_size - audio.size(1)), "constant" + ) + + # Compute mel_loss used by spectral regression objective. Uses self.fmax_loss instead (usually None) + mel_loss = mel_spectrogram( + audio, + self.n_fft, + self.num_mels, + self.sampling_rate, + self.hop_size, + self.win_size, + self.fmin, + self.fmax_loss, + center=False, + ) # [B(1), self.num_mels, self.segment_size // self.hop_size] + + # Shape sanity checks + assert ( + audio.shape[1] == mel.shape[2] * self.hop_size + and audio.shape[1] == mel_loss.shape[2] * self.hop_size + ), f"Audio length must be mel frame length * hop_size. Got audio shape {audio.shape} mel shape {mel.shape} mel_loss shape {mel_loss.shape}" + + return (mel.squeeze(), audio.squeeze(0), filename, mel_loss.squeeze()) + + # If it encounters error during loading the data, skip this sample and load random other sample to the batch + except Exception as e: + if self.fine_tuning: + raise e # Terminate training if it is fine-tuning. The dataset should have been prepared properly. + else: + print( + f"[WARNING] Failed to load waveform, skipping! filename: {filename} Error: {e}" + ) + return self[random.randrange(len(self))] + + def __len__(self): + return len(self.audio_files) diff --git a/code/third_party/bigvgan/utils.py b/code/third_party/bigvgan/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fc64ae591d7ec40e69146e626a7570414495d243 --- /dev/null +++ b/code/third_party/bigvgan/utils.py @@ -0,0 +1,99 @@ +# Adapted from https://github.com/jik876/hifi-gan under the MIT license. +# LICENSE is in incl_licenses directory. + +import glob +import os +import matplotlib +import torch +from torch.nn.utils import weight_norm + +matplotlib.use("Agg") +import matplotlib.pylab as plt +from meldataset import MAX_WAV_VALUE +from scipy.io.wavfile import write + + +def plot_spectrogram(spectrogram): + fig, ax = plt.subplots(figsize=(10, 2)) + im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none") + plt.colorbar(im, ax=ax) + + fig.canvas.draw() + plt.close() + + return fig + + +def plot_spectrogram_clipped(spectrogram, clip_max=2.0): + fig, ax = plt.subplots(figsize=(10, 2)) + im = ax.imshow( + spectrogram, + aspect="auto", + origin="lower", + interpolation="none", + vmin=1e-6, + vmax=clip_max, + ) + plt.colorbar(im, ax=ax) + + fig.canvas.draw() + plt.close() + + return fig + + +def init_weights(m, mean=0.0, std=0.01): + classname = m.__class__.__name__ + if classname.find("Conv") != -1: + m.weight.data.normal_(mean, std) + + +def apply_weight_norm(m): + classname = m.__class__.__name__ + if classname.find("Conv") != -1: + weight_norm(m) + + +def get_padding(kernel_size, dilation=1): + return int((kernel_size * dilation - dilation) / 2) + + +def load_checkpoint(filepath, device): + assert os.path.isfile(filepath) + print(f"Loading '{filepath}'") + checkpoint_dict = torch.load(filepath, map_location=device) + print("Complete.") + return checkpoint_dict + + +def save_checkpoint(filepath, obj): + print(f"Saving checkpoint to {filepath}") + torch.save(obj, filepath) + print("Complete.") + + +def scan_checkpoint(cp_dir, prefix, renamed_file=None): + # Fallback to original scanning logic first + pattern = os.path.join(cp_dir, prefix + "????????") + cp_list = glob.glob(pattern) + + if len(cp_list) > 0: + last_checkpoint_path = sorted(cp_list)[-1] + print(f"[INFO] Resuming from checkpoint: '{last_checkpoint_path}'") + return last_checkpoint_path + + # If no pattern-based checkpoints are found, check for renamed file + if renamed_file: + renamed_path = os.path.join(cp_dir, renamed_file) + if os.path.isfile(renamed_path): + print(f"[INFO] Resuming from renamed checkpoint: '{renamed_file}'") + return renamed_path + + return None + + +def save_audio(audio, path, sr): + # wav: torch with 1d shape + audio = audio * MAX_WAV_VALUE + audio = audio.cpu().numpy().astype("int16") + write(path, sr, audio) diff --git a/eval/latency.json b/eval/latency.json new file mode 100644 index 0000000000000000000000000000000000000000..ad919da7c84fd5d1cc99d81f1e1a6a5f6370006c --- /dev/null +++ b/eval/latency.json @@ -0,0 +1,51 @@ +{ + "cpu_threads": 6, + "texts": [ + "Olá! Tudo bem com você? Hoje vamos testar a síntese de voz em português.", + "O relatório foi entregue às 14h30, e a reunião ficou para amanhã de manhã.", + "Você tem certeza de que o modelo já fala perguntas com naturalidade?", + "Precisamos comprar pão, leite, café e frutas antes de voltar para casa.", + "A destilação reduziu a geração para apenas dois passos, mantendo a qualidade." + ], + "pytorch_cuda_fast2": { + "avg_latency_ms": 592.8, + "rtf_speed_x": 9.28, + "audio_sec_total": 27.51 + }, + "pytorch_cpu_fast2": { + "avg_latency_ms": 2545.5, + "rtf_speed_x": 2.22, + "audio_sec_total": 28.24 + }, + "pytorch_cpu_fast2_stream24": { + "avg_latency_ms": 2667.7, + "rtf_speed_x": 2.12, + "audio_sec_total": 28.24, + "avg_ttfa_ms": 540.4 + }, + "pytorch_cuda_soup50_8p": { + "avg_latency_ms": 639.6, + "rtf_speed_x": 8.6, + "audio_sec_total": 27.51 + }, + "pytorch_cpu_soup50_8p": { + "avg_latency_ms": 3032.5, + "rtf_speed_x": 1.86, + "audio_sec_total": 28.24 + }, + "onnx_cpu_fast2": { + "avg_latency_ms": 3535.4, + "rtf_speed_x": 1.6, + "audio_sec_total": 28.23 + }, + "onnx_cpu_fast2_stream24": { + "avg_latency_ms": 5028.9, + "rtf_speed_x": 1.12, + "audio_sec_total": 28.23, + "avg_ttfa_ms": 627.1 + }, + "onnx_sizes_mib": { + "bigvgan_base_ft.onnx": 54.7, + "cfm_v5_fast2.onnx": 86.3 + } +} \ No newline at end of file diff --git a/eval/scores.json b/eval/scores.json new file mode 100644 index 0000000000000000000000000000000000000000..57d0f184bb639a3d14650d101afde04472264140 --- /dev/null +++ b/eval/scores.json @@ -0,0 +1,3712 @@ +{ + "reference/test": { + "summary": { + "utmos22_mean": 3.7012, + "scoreq_mean": 3.9353, + "dns_ovr": 3.1259, + "wer": 0.0086, + "cer": 0.0019, + "speaker_sim": 0.8708, + "n": 57 + }, + "items": [ + { + "id": "006251", + "utmos22_mean": 3.6973, + "utmos22_p10": 3.6973, + "scoreq_mean": 4.3516, + "scoreq_p10": 4.3516, + "dns_p808": 3.2566, + "dns_sig": 3.2828, + "dns_bak": 3.8303, + "dns_ovr": 2.9739, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Vai ter pavê na mesa?", + "speaker_sim": 0.7721 + }, + { + "id": "008569", + "utmos22_mean": 4.091, + "utmos22_p10": 4.091, + "scoreq_mean": 4.2073, + "scoreq_p10": 4.2073, + "dns_p808": 3.1833, + "dns_sig": 3.0813, + "dns_bak": 3.78, + "dns_ovr": 2.6944, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Não quero ir sozinho.", + "speaker_sim": 0.7558 + }, + { + "id": "002227", + "utmos22_mean": 3.7497, + "utmos22_p10": 3.7497, + "scoreq_mean": 4.0065, + "scoreq_p10": 4.0065, + "dns_p808": 3.2698, + "dns_sig": 3.5904, + "dns_bak": 4.1604, + "dns_ovr": 3.3538, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A guitarra está desafinada.", + "speaker_sim": 0.8679 + }, + { + "id": "010144", + "utmos22_mean": 3.6323, + "utmos22_p10": 3.6323, + "scoreq_mean": 3.8108, + "scoreq_p10": 3.8108, + "dns_p808": 3.3412, + "dns_sig": 3.1861, + "dns_bak": 4.1782, + "dns_ovr": 3.003, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ele estava tenso com a prova.", + "speaker_sim": 0.7919 + }, + { + "id": "002156", + "utmos22_mean": 3.5851, + "utmos22_p10": 3.5851, + "scoreq_mean": 3.667, + "scoreq_p10": 3.667, + "dns_p808": 3.4599, + "dns_sig": 3.3344, + "dns_bak": 3.9684, + "dns_ovr": 3.0279, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que personagem interessante.", + "speaker_sim": 0.8823 + }, + { + "id": "005535", + "utmos22_mean": 3.7769, + "utmos22_p10": 3.7769, + "scoreq_mean": 3.9162, + "scoreq_p10": 3.9162, + "dns_p808": 3.4984, + "dns_sig": 3.192, + "dns_bak": 3.9905, + "dns_ovr": 2.9511, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você sabe fazer arroz doce?", + "speaker_sim": 0.7429 + }, + { + "id": "009128", + "utmos22_mean": 3.9107, + "utmos22_p10": 3.9107, + "scoreq_mean": 4.1856, + "scoreq_p10": 4.1856, + "dns_p808": 3.2332, + "dns_sig": 3.3735, + "dns_bak": 4.1282, + "dns_ovr": 3.1129, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A luz batia no rosto.", + "speaker_sim": 0.7865 + }, + { + "id": "001356", + "utmos22_mean": 3.6158, + "utmos22_p10": 3.6158, + "scoreq_mean": 3.6663, + "scoreq_p10": 3.6663, + "dns_p808": 3.3586, + "dns_sig": 2.755, + "dns_bak": 3.9852, + "dns_ovr": 2.5737, + "wer": 0.2, + "cer": 0.0417, + "asr_text": "Dá pra guardar alguma coisa?", + "speaker_sim": 0.8254 + }, + { + "id": "004982", + "utmos22_mean": 3.6322, + "utmos22_p10": 3.6322, + "scoreq_mean": 4.2014, + "scoreq_p10": 4.2014, + "dns_p808": 3.203, + "dns_sig": 3.419, + "dns_bak": 4.1413, + "dns_ovr": 3.1851, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Coentro estraga a comida toda.", + "speaker_sim": 0.8406 + }, + { + "id": "008746", + "utmos22_mean": 3.8012, + "utmos22_p10": 3.8012, + "scoreq_mean": 4.119, + "scoreq_p10": 4.119, + "dns_p808": 3.4004, + "dns_sig": 3.3656, + "dns_bak": 4.0902, + "dns_ovr": 3.1106, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que doideira esse tempo relativo.", + "speaker_sim": 0.8184 + }, + { + "id": "000788", + "utmos22_mean": 3.5529, + "utmos22_p10": 3.5529, + "scoreq_mean": 3.7874, + "scoreq_p10": 3.7874, + "dns_p808": 3.253, + "dns_sig": 3.0207, + "dns_bak": 3.7841, + "dns_ovr": 2.7095, + "wer": 0.2, + "cer": 0.0435, + "asr_text": "E use azeite para fritar tudo.", + "speaker_sim": 0.7466 + }, + { + "id": "005176", + "utmos22_mean": 3.7332, + "utmos22_p10": 3.7332, + "scoreq_mean": 4.0055, + "scoreq_p10": 4.0055, + "dns_p808": 3.3301, + "dns_sig": 3.3056, + "dns_bak": 4.0207, + "dns_ovr": 3.0478, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A floresta parecia não ter fim.", + "speaker_sim": 0.8628 + }, + { + "id": "009887", + "utmos22_mean": 3.6665, + "utmos22_p10": 3.6665, + "scoreq_mean": 4.0631, + "scoreq_p10": 4.0631, + "dns_p808": 3.6619, + "dns_sig": 3.0372, + "dns_bak": 3.8416, + "dns_ovr": 2.7396, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A indústria nasceu na Inglaterra Antiga.", + "speaker_sim": 0.8672 + }, + { + "id": "003791", + "utmos22_mean": 3.7381, + "utmos22_p10": 3.7381, + "scoreq_mean": 4.0403, + "scoreq_p10": 4.0403, + "dns_p808": 3.348, + "dns_sig": 3.3584, + "dns_bak": 4.0225, + "dns_ovr": 3.0791, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Precisamos de mais toalhas limpas.", + "speaker_sim": 0.8378 + }, + { + "id": "005794", + "utmos22_mean": 3.7736, + "utmos22_p10": 3.7736, + "scoreq_mean": 3.9261, + "scoreq_p10": 3.9261, + "dns_p808": 3.4031, + "dns_sig": 3.423, + "dns_bak": 4.0166, + "dns_ovr": 3.1402, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A Idade Média teve muitos castelos.", + "speaker_sim": 0.883 + }, + { + "id": "004271", + "utmos22_mean": 3.7048, + "utmos22_p10": 3.7048, + "scoreq_mean": 4.2267, + "scoreq_p10": 4.2267, + "dns_p808": 3.6674, + "dns_sig": 3.3057, + "dns_bak": 4.11, + "dns_ovr": 3.0728, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ela é uma pessoa decidida.", + "speaker_sim": 0.7953 + }, + { + "id": "002030", + "utmos22_mean": 3.7279, + "utmos22_p10": 3.7279, + "scoreq_mean": 4.0422, + "scoreq_p10": 4.0422, + "dns_p808": 3.6636, + "dns_sig": 3.563, + "dns_bak": 4.1613, + "dns_ovr": 3.3409, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quem aqui acha que eu vou conseguir passar desse nível logo?", + "speaker_sim": 0.8472 + }, + { + "id": "000476", + "utmos22_mean": 3.7296, + "utmos22_p10": 3.7296, + "scoreq_mean": 4.0661, + "scoreq_p10": 4.0661, + "dns_p808": 3.7542, + "dns_sig": 3.3439, + "dns_bak": 4.1332, + "dns_ovr": 3.1168, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Tem um cinema antigo que ainda exibe filmes clássicos.", + "speaker_sim": 0.8345 + }, + { + "id": "010092", + "utmos22_mean": 3.7835, + "utmos22_p10": 3.7835, + "scoreq_mean": 4.1122, + "scoreq_p10": 4.1122, + "dns_p808": 3.6403, + "dns_sig": 3.4133, + "dns_bak": 4.0439, + "dns_ovr": 3.1604, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu vou deixar um recado com a sua irmã sobre o horário.", + "speaker_sim": 0.8244 + }, + { + "id": "004474", + "utmos22_mean": 3.8434, + "utmos22_p10": 3.8434, + "scoreq_mean": 4.0389, + "scoreq_p10": 4.0389, + "dns_p808": 3.6393, + "dns_sig": 3.3843, + "dns_bak": 4.0701, + "dns_ovr": 3.1539, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você sabia que o núcleo da terra é quente como sol?", + "speaker_sim": 0.8758 + }, + { + "id": "010456", + "utmos22_mean": 3.6317, + "utmos22_p10": 3.6317, + "scoreq_mean": 4.1128, + "scoreq_p10": 4.1128, + "dns_p808": 3.8015, + "dns_sig": 3.3884, + "dns_bak": 3.8744, + "dns_ovr": 3.0367, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu passei a noite inteira tentando resolver esse bug no código.", + "speaker_sim": 0.9064 + }, + { + "id": "002930", + "utmos22_mean": 3.7745, + "utmos22_p10": 3.7745, + "scoreq_mean": 3.8743, + "scoreq_p10": 3.8743, + "dns_p808": 3.5182, + "dns_sig": 3.4934, + "dns_bak": 3.6777, + "dns_ovr": 2.9527, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu amo a sensação de fechar os olhos e começar a sonhar.", + "speaker_sim": 0.9017 + }, + { + "id": "007758", + "utmos22_mean": 3.8741, + "utmos22_p10": 3.8741, + "scoreq_mean": 4.0957, + "scoreq_p10": 4.0957, + "dns_p808": 3.7172, + "dns_sig": 3.7142, + "dns_bak": 4.2271, + "dns_ovr": 3.5197, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O gato dormia tranquilamente em cima do sofá da sala.", + "speaker_sim": 0.8989 + }, + { + "id": "008302", + "utmos22_mean": 3.7932, + "utmos22_p10": 3.7932, + "scoreq_mean": 3.8637, + "scoreq_p10": 3.8637, + "dns_p808": 3.5051, + "dns_sig": 3.1667, + "dns_bak": 2.8349, + "dns_ovr": 2.3515, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Olha só, a Lua iluminou todo o jardim com esse brilho.", + "speaker_sim": 0.8682 + }, + { + "id": "003146", + "utmos22_mean": 3.6317, + "utmos22_p10": 3.6317, + "scoreq_mean": 4.0878, + "scoreq_p10": 4.0878, + "dns_p808": 3.6501, + "dns_sig": 3.3622, + "dns_bak": 4.1205, + "dns_ovr": 3.1453, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu vou trocar a música da live para animar mais o ambiente.", + "speaker_sim": 0.8882 + }, + { + "id": "006905", + "utmos22_mean": 3.7571, + "utmos22_p10": 3.7571, + "scoreq_mean": 3.7651, + "scoreq_p10": 3.7651, + "dns_p808": 3.7608, + "dns_sig": 3.2725, + "dns_bak": 3.9501, + "dns_ovr": 2.986, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você já sabe onde vai passar a ceia de Natal deste ano?", + "speaker_sim": 0.8679 + }, + { + "id": "009498", + "utmos22_mean": 3.3702, + "utmos22_p10": 3.3702, + "scoreq_mean": 3.7461, + "scoreq_p10": 3.7461, + "dns_p808": 3.9573, + "dns_sig": 3.6196, + "dns_bak": 4.2293, + "dns_ovr": 3.4322, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Aquela televisão antiga precisava de um tapa para funcionar bem.", + "speaker_sim": 0.9075 + }, + { + "id": "000664", + "utmos22_mean": 3.5885, + "utmos22_p10": 3.5885, + "scoreq_mean": 3.8846, + "scoreq_p10": 3.8846, + "dns_p808": 3.6711, + "dns_sig": 3.2986, + "dns_bak": 3.8479, + "dns_ovr": 3.0051, + "wer": 0.0909, + "cer": 0.0222, + "asr_text": "Você já montou a lista de tudo o que precisa fazer amanhã?", + "speaker_sim": 0.9021 + }, + { + "id": "003728", + "utmos22_mean": 3.551, + "utmos22_p10": 3.551, + "scoreq_mean": 4.0965, + "scoreq_p10": 4.0965, + "dns_p808": 3.5653, + "dns_sig": 3.4768, + "dns_bak": 4.0999, + "dns_ovr": 3.2373, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Onde eu baixo o driver de vídeo para o meu computador novo.", + "speaker_sim": 0.8513 + }, + { + "id": "007273", + "utmos22_mean": 3.5976, + "utmos22_p10": 3.5976, + "scoreq_mean": 3.6847, + "scoreq_p10": 3.6847, + "dns_p808": 3.5846, + "dns_sig": 3.508, + "dns_bak": 4.1677, + "dns_ovr": 3.2948, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Não suporto quando a comida chega fria no restaurante caro.", + "speaker_sim": 0.8722 + }, + { + "id": "010313", + "utmos22_mean": 3.7082, + "utmos22_p10": 3.7082, + "scoreq_mean": 3.965, + "scoreq_p10": 3.965, + "dns_p808": 3.4763, + "dns_sig": 3.4981, + "dns_bak": 4.0159, + "dns_ovr": 3.2131, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O café da manhã do hotel tinha frutas frescas e pão quente.", + "speaker_sim": 0.8779 + }, + { + "id": "003210", + "utmos22_mean": 3.7492, + "utmos22_p10": 3.7492, + "scoreq_mean": 4.134, + "scoreq_p10": 4.134, + "dns_p808": 3.6454, + "dns_sig": 3.3937, + "dns_bak": 3.9939, + "dns_ovr": 3.1082, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você já planejou como vai investir o seu dinheiro no futuro.", + "speaker_sim": 0.872 + }, + { + "id": "006836", + "utmos22_mean": 3.8061, + "utmos22_p10": 3.8061, + "scoreq_mean": 4.0007, + "scoreq_p10": 4.0007, + "dns_p808": 3.4225, + "dns_sig": 3.4849, + "dns_bak": 4.1405, + "dns_ovr": 3.2638, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você prefere assistir cinema no shopping ou em casa mesmo?", + "speaker_sim": 0.9092 + }, + { + "id": "010791", + "utmos22_mean": 3.8402, + "utmos22_p10": 3.8402, + "scoreq_mean": 4.3442, + "scoreq_p10": 4.3442, + "dns_p808": 3.6077, + "dns_sig": 3.5448, + "dns_bak": 4.1813, + "dns_ovr": 3.3264, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A internet mudou completamente a forma como a gente se comunica.", + "speaker_sim": 0.8392 + }, + { + "id": "007790", + "utmos22_mean": 3.6119, + "utmos22_p10": 3.6119, + "scoreq_mean": 3.9753, + "scoreq_p10": 3.9753, + "dns_p808": 3.9299, + "dns_sig": 3.5972, + "dns_bak": 4.1592, + "dns_ovr": 3.3615, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Por gentileza, prepare um sanduíche simples para o meu café da manhã.", + "speaker_sim": 0.9137 + }, + { + "id": "003372", + "utmos22_mean": 3.6896, + "utmos22_p10": 3.6896, + "scoreq_mean": 3.9422, + "scoreq_p10": 3.9422, + "dns_p808": 3.2911, + "dns_sig": 3.6048, + "dns_bak": 4.1212, + "dns_ovr": 3.3708, + "wer": 0.0, + "cer": 0.0, + "asr_text": "As barracas de comida da festa junina são as melhores partes.", + "speaker_sim": 0.8701 + }, + { + "id": "010543", + "utmos22_mean": 3.8552, + "utmos22_p10": 3.8552, + "scoreq_mean": 3.9752, + "scoreq_p10": 3.9752, + "dns_p808": 3.549, + "dns_sig": 3.3686, + "dns_bak": 3.7664, + "dns_ovr": 2.9537, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nada substitui o sabor de um café fresquinho logo pela manhã.", + "speaker_sim": 0.8987 + }, + { + "id": "001601", + "utmos22_mean": 3.6279, + "utmos22_p10": 3.6279, + "scoreq_mean": 3.954, + "scoreq_p10": 3.954, + "dns_p808": 3.6967, + "dns_sig": 3.6508, + "dns_bak": 4.0922, + "dns_ovr": 3.389, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Onde será que aquele nosso amigo de infância anda morando agora?", + "speaker_sim": 0.9123 + }, + { + "id": "004761", + "utmos22_mean": 3.6151, + "utmos22_p10": 3.6151, + "scoreq_mean": 3.8995, + "scoreq_p10": 3.8995, + "dns_p808": 3.4543, + "dns_sig": 3.4879, + "dns_bak": 4.1543, + "dns_ovr": 3.2617, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A tinta branca escorreu pela parede enquanto eu pintava o teto.", + "speaker_sim": 0.9023 + }, + { + "id": "009510", + "utmos22_mean": 3.6537, + "utmos22_p10": 3.6537, + "scoreq_mean": 3.8585, + "scoreq_p10": 3.8585, + "dns_p808": 3.5024, + "dns_sig": 3.508, + "dns_bak": 4.0875, + "dns_ovr": 3.2503, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você pode trazer os balões coloridos para a festa de aniversário.", + "speaker_sim": 0.8707 + }, + { + "id": "005027", + "utmos22_mean": 3.7208, + "utmos22_p10": 3.7208, + "scoreq_mean": 3.8341, + "scoreq_p10": 3.8341, + "dns_p808": 3.8112, + "dns_sig": 3.487, + "dns_bak": 4.1555, + "dns_ovr": 3.272, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Vovó, por favor, me ensine a fazer aquele doce de leite.", + "speaker_sim": 0.866 + }, + { + "id": "005858", + "utmos22_mean": 3.7762, + "utmos22_p10": 3.7762, + "scoreq_mean": 4.0588, + "scoreq_p10": 4.0588, + "dns_p808": 3.6788, + "dns_sig": 3.484, + "dns_bak": 4.11, + "dns_ovr": 3.2499, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O artesanato com recicláveis é uma ótima forma de ajudar natureza.", + "speaker_sim": 0.9207 + }, + { + "id": "003719", + "utmos22_mean": 3.641, + "utmos22_p10": 3.641, + "scoreq_mean": 3.6336, + "scoreq_p10": 3.6336, + "dns_p808": 3.8976, + "dns_sig": 3.107, + "dns_bak": 3.9798, + "dns_ovr": 2.8707, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O caminho para a montanha era cheio de curvas e árvores verdes.", + "speaker_sim": 0.8887 + }, + { + "id": "003590", + "utmos22_mean": 3.8022, + "utmos22_p10": 3.8022, + "scoreq_mean": 4.1167, + "scoreq_p10": 4.1167, + "dns_p808": 3.5894, + "dns_sig": 3.4567, + "dns_bak": 3.9403, + "dns_ovr": 3.1298, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você lembra de quando a gente passava a noite inteira acordado conversando?", + "speaker_sim": 0.9176 + }, + { + "id": "004697", + "utmos22_mean": 3.7372, + "utmos22_p10": 3.7372, + "scoreq_mean": 3.7134, + "scoreq_p10": 3.7134, + "dns_p808": 3.7721, + "dns_sig": 3.5164, + "dns_bak": 4.1742, + "dns_ovr": 3.3125, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A gente colecionava figurinhas repetidas e trocava no recreio da escola.", + "speaker_sim": 0.9341 + }, + { + "id": "007703", + "utmos22_mean": 3.867, + "utmos22_p10": 3.867, + "scoreq_mean": 3.9047, + "scoreq_p10": 3.9047, + "dns_p808": 3.8858, + "dns_sig": 3.5539, + "dns_bak": 4.205, + "dns_ovr": 3.3558, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O sorriso dele iluminava qualquer ambiente, não importa onde estivéssemos nós.", + "speaker_sim": 0.9152 + }, + { + "id": "001055", + "utmos22_mean": 3.554, + "utmos22_p10": 3.554, + "scoreq_mean": 3.6407, + "scoreq_p10": 3.6407, + "dns_p808": 3.7929, + "dns_sig": 3.3306, + "dns_bak": 3.8591, + "dns_ovr": 3.0334, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Meus filhos estão crescendo rápido demais, eu nem consigo acreditar nisso.", + "speaker_sim": 0.9161 + }, + { + "id": "005025", + "utmos22_mean": 3.5607, + "utmos22_p10": 3.5607, + "scoreq_mean": 3.6401, + "scoreq_p10": 3.6401, + "dns_p808": 3.8826, + "dns_sig": 3.2447, + "dns_bak": 3.9667, + "dns_ovr": 2.9953, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O restaurante italiano tem uma decoração rústica com muitas luzes amarelas.", + "speaker_sim": 0.9101 + }, + { + "id": "000311", + "utmos22_mean": 3.5364, + "utmos22_p10": 3.5364, + "scoreq_mean": 3.2763, + "scoreq_p10": 3.2763, + "dns_p808": 3.9688, + "dns_sig": 3.494, + "dns_bak": 4.1427, + "dns_ovr": 3.2686, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O riso dos meus filhos preenche todos os cômodos da casa e traz uma alegria que não acaba.", + "speaker_sim": 0.8799 + }, + { + "id": "006727", + "utmos22_mean": 3.7092, + "utmos22_p10": 3.7092, + "scoreq_mean": 4.123, + "scoreq_p10": 4.123, + "dns_p808": 3.8839, + "dns_sig": 3.5931, + "dns_bak": 4.1978, + "dns_ovr": 3.3906, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu sempre lembro do cheiro da comida da minha avó e sinto uma paz enorme no meu coração agora.", + "speaker_sim": 0.9353 + }, + { + "id": "010438", + "utmos22_mean": 3.5559, + "utmos22_p10": 3.5559, + "scoreq_mean": 3.5956, + "scoreq_p10": 3.5956, + "dns_p808": 3.743, + "dns_sig": 3.3195, + "dns_bak": 3.8705, + "dns_ovr": 2.9258, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Gente, me perdoa, eu me perdi no caminho e não consegui achar o endereço certo do restaurante.", + "speaker_sim": 0.8495 + }, + { + "id": "001260", + "utmos22_mean": 3.7363, + "utmos22_p10": 3.7363, + "scoreq_mean": 3.8546, + "scoreq_p10": 3.8546, + "dns_p808": 3.9727, + "dns_sig": 3.5587, + "dns_bak": 3.8992, + "dns_ovr": 3.1762, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Aquela cena de luta foi coreografada com tanta precisão que parecia uma dança sincronizada e violenta.", + "speaker_sim": 0.9309 + }, + { + "id": "008515", + "utmos22_mean": 3.7809, + "utmos22_p10": 3.7809, + "scoreq_mean": 3.921, + "scoreq_p10": 3.921, + "dns_p808": 4.0361, + "dns_sig": 3.3651, + "dns_bak": 4.1072, + "dns_ovr": 3.1413, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Gente, quem fez esse quentão maravilhoso? Eu estou sentindo o calorzinho subir e ficando muito feliz agora!", + "speaker_sim": 0.8936 + }, + { + "id": "002356", + "utmos22_mean": 3.8838, + "utmos22_p10": 3.8838, + "scoreq_mean": 4.0491, + "scoreq_p10": 4.0491, + "dns_p808": 3.8726, + "dns_sig": 3.4806, + "dns_bak": 4.1933, + "dns_ovr": 3.2623, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quem aí concorda que esse personagem é o mais apelão de todos, ou eu estou ficando louca sozinha?", + "speaker_sim": 0.914 + }, + { + "id": "005566", + "utmos22_mean": 3.3989, + "utmos22_p10": 3.3989, + "scoreq_mean": 3.7685, + "scoreq_p10": 3.7685, + "dns_p808": 3.9078, + "dns_sig": 3.3734, + "dns_bak": 4.0073, + "dns_ovr": 3.0834, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O meio de campo distribuiu a bola com precisão, criando a chance perfeita para o centroavante marcar gol.", + "speaker_sim": 0.9375 + }, + { + "id": "007600", + "utmos22_mean": 3.6741, + "utmos22_p10": 3.6741, + "scoreq_mean": 3.6396, + "scoreq_p10": 3.6396, + "dns_p808": 3.9708, + "dns_sig": 3.5112, + "dns_bak": 4.2019, + "dns_ovr": 3.3141, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nós passamos a tarde inteira discutindo qual era a melhor temporada daquela série de ficção científica antiga.", + "speaker_sim": 0.9266 + }, + { + "id": "003245", + "utmos22_mean": 3.5639, + "utmos22_p10": 3.5639, + "scoreq_mean": 3.8403, + "scoreq_p10": 3.8403, + "dns_p808": 4.0327, + "dns_sig": 3.5964, + "dns_bak": 4.1877, + "dns_ovr": 3.3846, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Caramba, você realmente conseguiu transformar esse pedaço de madeira velha em um porta-jóias maravilhoso e super elegante.", + "speaker_sim": 0.9107 + } + ] + }, + "fast2/test": { + "summary": { + "utmos22_mean": 3.6904, + "scoreq_mean": 4.025, + "dns_ovr": 3.2602, + "wer": 0.0157, + "cer": 0.0048, + "speaker_sim": 0.8851, + "n": 57 + }, + "items": [ + { + "id": "006251", + "utmos22_mean": 3.8919, + "utmos22_p10": 3.8919, + "scoreq_mean": 4.3705, + "scoreq_p10": 4.3705, + "dns_p808": 3.6016, + "dns_sig": 3.4533, + "dns_bak": 4.1638, + "dns_ovr": 3.2684, + "wer": 0.4, + "cer": 0.125, + "asr_text": "Vai ter pra ver na mesa.", + "speaker_sim": 0.6956 + }, + { + "id": "008569", + "utmos22_mean": 4.0183, + "utmos22_p10": 4.0183, + "scoreq_mean": 3.9994, + "scoreq_p10": 3.9994, + "dns_p808": 3.6206, + "dns_sig": 3.3853, + "dns_bak": 4.1152, + "dns_ovr": 3.1495, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Não quero ir sozinho.", + "speaker_sim": 0.832 + }, + { + "id": "002227", + "utmos22_mean": 3.6656, + "utmos22_p10": 3.6656, + "scoreq_mean": 4.0207, + "scoreq_p10": 4.0207, + "dns_p808": 3.6965, + "dns_sig": 3.5827, + "dns_bak": 4.2129, + "dns_ovr": 3.3975, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A guitarra está desafinada.", + "speaker_sim": 0.8022 + }, + { + "id": "010144", + "utmos22_mean": 3.7826, + "utmos22_p10": 3.7826, + "scoreq_mean": 3.8867, + "scoreq_p10": 3.8867, + "dns_p808": 3.6996, + "dns_sig": 3.1362, + "dns_bak": 4.1636, + "dns_ovr": 2.9739, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ele estava tenso com a prova.", + "speaker_sim": 0.7675 + }, + { + "id": "002156", + "utmos22_mean": 3.7313, + "utmos22_p10": 3.7313, + "scoreq_mean": 4.1191, + "scoreq_p10": 4.1191, + "dns_p808": 3.788, + "dns_sig": 3.5669, + "dns_bak": 4.1887, + "dns_ovr": 3.3707, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que personagem interessante.", + "speaker_sim": 0.891 + }, + { + "id": "005535", + "utmos22_mean": 3.9387, + "utmos22_p10": 3.9387, + "scoreq_mean": 4.1816, + "scoreq_p10": 4.1816, + "dns_p808": 3.8609, + "dns_sig": 3.5252, + "dns_bak": 4.1909, + "dns_ovr": 3.3183, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você sabe fazer arroz doce?", + "speaker_sim": 0.7498 + }, + { + "id": "009128", + "utmos22_mean": 3.8856, + "utmos22_p10": 3.8856, + "scoreq_mean": 4.1787, + "scoreq_p10": 4.1787, + "dns_p808": 3.8127, + "dns_sig": 3.3746, + "dns_bak": 4.2101, + "dns_ovr": 3.1998, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A luz batia no rosto.", + "speaker_sim": 0.7756 + }, + { + "id": "001356", + "utmos22_mean": 3.4592, + "utmos22_p10": 3.4592, + "scoreq_mean": 4.1951, + "scoreq_p10": 4.1951, + "dns_p808": 3.7127, + "dns_sig": 3.2353, + "dns_bak": 4.1933, + "dns_ovr": 3.0704, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Dá para guardar alguma coisa?", + "speaker_sim": 0.7757 + }, + { + "id": "004982", + "utmos22_mean": 3.3295, + "utmos22_p10": 3.3295, + "scoreq_mean": 3.9071, + "scoreq_p10": 3.9071, + "dns_p808": 3.674, + "dns_sig": 3.4827, + "dns_bak": 4.2294, + "dns_ovr": 3.3017, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Coentro estraga a comida toda.", + "speaker_sim": 0.8076 + }, + { + "id": "008746", + "utmos22_mean": 3.9954, + "utmos22_p10": 3.9954, + "scoreq_mean": 4.1752, + "scoreq_p10": 4.1752, + "dns_p808": 3.6736, + "dns_sig": 3.2161, + "dns_bak": 3.9563, + "dns_ovr": 2.9363, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que doideira esse tempo relativo.", + "speaker_sim": 0.8807 + }, + { + "id": "000788", + "utmos22_mean": 3.7791, + "utmos22_p10": 3.7791, + "scoreq_mean": 3.9638, + "scoreq_p10": 3.9638, + "dns_p808": 3.8544, + "dns_sig": 3.4342, + "dns_bak": 4.231, + "dns_ovr": 3.2564, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Use azeite para fritar tudo.", + "speaker_sim": 0.7833 + }, + { + "id": "005176", + "utmos22_mean": 3.5403, + "utmos22_p10": 3.5403, + "scoreq_mean": 4.0804, + "scoreq_p10": 4.0804, + "dns_p808": 3.7289, + "dns_sig": 3.7029, + "dns_bak": 4.2908, + "dns_ovr": 3.5203, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A floresta parecia não ter fim.", + "speaker_sim": 0.8224 + }, + { + "id": "009887", + "utmos22_mean": 3.3095, + "utmos22_p10": 3.3095, + "scoreq_mean": 4.1468, + "scoreq_p10": 4.1468, + "dns_p808": 4.0713, + "dns_sig": 3.5246, + "dns_bak": 4.1673, + "dns_ovr": 3.3107, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A indústria nasceu na Inglaterra Antiga.", + "speaker_sim": 0.8926 + }, + { + "id": "003791", + "utmos22_mean": 3.2928, + "utmos22_p10": 3.2928, + "scoreq_mean": 4.1005, + "scoreq_p10": 4.1005, + "dns_p808": 4.1341, + "dns_sig": 3.05, + "dns_bak": 4.0733, + "dns_ovr": 2.8477, + "wer": 0.2, + "cer": 0.069, + "asr_text": "Precisamos de mais toalhas lintas.", + "speaker_sim": 0.8778 + }, + { + "id": "005794", + "utmos22_mean": 3.8964, + "utmos22_p10": 3.8964, + "scoreq_mean": 4.1346, + "scoreq_p10": 4.1346, + "dns_p808": 3.9282, + "dns_sig": 3.5658, + "dns_bak": 4.1941, + "dns_ovr": 3.3651, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A Idade Média teve muitos castelos.", + "speaker_sim": 0.9025 + }, + { + "id": "004271", + "utmos22_mean": 3.8126, + "utmos22_p10": 3.8126, + "scoreq_mean": 4.1213, + "scoreq_p10": 4.1213, + "dns_p808": 4.0589, + "dns_sig": 3.3053, + "dns_bak": 4.1405, + "dns_ovr": 3.1157, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ela é uma pessoa decidida.", + "speaker_sim": 0.8639 + }, + { + "id": "002030", + "utmos22_mean": 4.1298, + "utmos22_p10": 4.1298, + "scoreq_mean": 4.501, + "scoreq_p10": 4.501, + "dns_p808": 3.8556, + "dns_sig": 3.5593, + "dns_bak": 4.1366, + "dns_ovr": 3.3135, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quem aqui acha que eu vou conseguir passar desse nível logo?", + "speaker_sim": 0.8883 + }, + { + "id": "000476", + "utmos22_mean": 3.9948, + "utmos22_p10": 3.9948, + "scoreq_mean": 4.006, + "scoreq_p10": 4.006, + "dns_p808": 3.8946, + "dns_sig": 3.416, + "dns_bak": 3.7167, + "dns_ovr": 3.0016, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Tem um cinema antigo que ainda exibe filmes clássicos.", + "speaker_sim": 0.9035 + }, + { + "id": "010092", + "utmos22_mean": 3.8034, + "utmos22_p10": 3.8034, + "scoreq_mean": 4.1013, + "scoreq_p10": 4.1013, + "dns_p808": 3.9923, + "dns_sig": 3.666, + "dns_bak": 4.2644, + "dns_ovr": 3.4651, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu vou deixar um recado com a sua irmã sobre o horário.", + "speaker_sim": 0.8855 + }, + { + "id": "004474", + "utmos22_mean": 3.4566, + "utmos22_p10": 3.4566, + "scoreq_mean": 3.9021, + "scoreq_p10": 3.9021, + "dns_p808": 3.8043, + "dns_sig": 3.4638, + "dns_bak": 4.1727, + "dns_ovr": 3.2498, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você sabia que o núcleo da terra é quente como sol?", + "speaker_sim": 0.9076 + }, + { + "id": "010456", + "utmos22_mean": 3.7623, + "utmos22_p10": 3.7623, + "scoreq_mean": 4.31, + "scoreq_p10": 4.31, + "dns_p808": 4.0555, + "dns_sig": 3.4111, + "dns_bak": 4.0951, + "dns_ovr": 3.1656, + "wer": 0.0909, + "cer": 0.0577, + "asr_text": "Eu passei a noite inteira tentando resolver esse burro no código.", + "speaker_sim": 0.9323 + }, + { + "id": "002930", + "utmos22_mean": 3.7669, + "utmos22_p10": 3.7669, + "scoreq_mean": 4.2477, + "scoreq_p10": 4.2477, + "dns_p808": 3.9334, + "dns_sig": 3.6324, + "dns_bak": 3.8424, + "dns_ovr": 3.1809, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu amo a sensação de fechar os olhos e começar a sonhar.", + "speaker_sim": 0.912 + }, + { + "id": "007758", + "utmos22_mean": 3.6538, + "utmos22_p10": 3.6538, + "scoreq_mean": 4.1971, + "scoreq_p10": 4.1971, + "dns_p808": 4.0412, + "dns_sig": 3.6113, + "dns_bak": 4.2104, + "dns_ovr": 3.4122, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O gato dormia tranquilamente em cima do sofá da sala.", + "speaker_sim": 0.9004 + }, + { + "id": "008302", + "utmos22_mean": 3.1378, + "utmos22_p10": 3.1378, + "scoreq_mean": 3.9647, + "scoreq_p10": 3.9647, + "dns_p808": 3.9473, + "dns_sig": 3.1974, + "dns_bak": 3.8403, + "dns_ovr": 2.8492, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Olha só, a Lua iluminou todo o jardim com esse brilho.", + "speaker_sim": 0.8804 + }, + { + "id": "003146", + "utmos22_mean": 3.5223, + "utmos22_p10": 3.5223, + "scoreq_mean": 3.9807, + "scoreq_p10": 3.9807, + "dns_p808": 4.0739, + "dns_sig": 3.5357, + "dns_bak": 4.1975, + "dns_ovr": 3.3522, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu vou trocar a música da live para animar mais o ambiente.", + "speaker_sim": 0.9208 + }, + { + "id": "006905", + "utmos22_mean": 3.7629, + "utmos22_p10": 3.7629, + "scoreq_mean": 4.0556, + "scoreq_p10": 4.0556, + "dns_p808": 4.074, + "dns_sig": 3.5414, + "dns_bak": 4.1735, + "dns_ovr": 3.3363, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você já sabe onde vai passar a ceia de Natal deste ano.", + "speaker_sim": 0.8904 + }, + { + "id": "009498", + "utmos22_mean": 3.5333, + "utmos22_p10": 3.5333, + "scoreq_mean": 3.8684, + "scoreq_p10": 3.8684, + "dns_p808": 3.942, + "dns_sig": 3.6639, + "dns_bak": 4.2421, + "dns_ovr": 3.4721, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Aquela televisão antiga precisava de um tapa para funcionar bem.", + "speaker_sim": 0.9294 + }, + { + "id": "000664", + "utmos22_mean": 3.6798, + "utmos22_p10": 3.6798, + "scoreq_mean": 4.1107, + "scoreq_p10": 4.1107, + "dns_p808": 3.6985, + "dns_sig": 3.1485, + "dns_bak": 4.0879, + "dns_ovr": 2.9499, + "wer": 0.0909, + "cer": 0.0222, + "asr_text": "Você já montou a lista de tudo o que precisa fazer amanhã?", + "speaker_sim": 0.9164 + }, + { + "id": "003728", + "utmos22_mean": 3.0253, + "utmos22_p10": 3.0253, + "scoreq_mean": 3.9495, + "scoreq_p10": 3.9495, + "dns_p808": 3.8122, + "dns_sig": 3.4967, + "dns_bak": 4.1804, + "dns_ovr": 3.2886, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Onde eu baixo o driver de vídeo para o meu computador novo.", + "speaker_sim": 0.8933 + }, + { + "id": "007273", + "utmos22_mean": 3.7239, + "utmos22_p10": 3.7239, + "scoreq_mean": 3.8848, + "scoreq_p10": 3.8848, + "dns_p808": 3.7955, + "dns_sig": 3.4418, + "dns_bak": 4.188, + "dns_ovr": 3.249, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Não suporto quando a comida chega fria no restaurante caro.", + "speaker_sim": 0.9056 + }, + { + "id": "010313", + "utmos22_mean": 3.785, + "utmos22_p10": 3.785, + "scoreq_mean": 4.0485, + "scoreq_p10": 4.0485, + "dns_p808": 3.8151, + "dns_sig": 3.6243, + "dns_bak": 4.1346, + "dns_ovr": 3.3729, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O café da manhã do hotel tinha frutas frescas e pão quente.", + "speaker_sim": 0.9104 + }, + { + "id": "003210", + "utmos22_mean": 3.7011, + "utmos22_p10": 3.7011, + "scoreq_mean": 4.0955, + "scoreq_p10": 4.0955, + "dns_p808": 3.7683, + "dns_sig": 3.2851, + "dns_bak": 4.0769, + "dns_ovr": 3.063, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você já planejou como vai investir o seu dinheiro no futuro?", + "speaker_sim": 0.8724 + }, + { + "id": "006836", + "utmos22_mean": 3.6705, + "utmos22_p10": 3.6705, + "scoreq_mean": 3.9675, + "scoreq_p10": 3.9675, + "dns_p808": 3.8018, + "dns_sig": 3.5218, + "dns_bak": 4.152, + "dns_ovr": 3.3046, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você prefere assistir cinema no shopping ou em casa mesmo?", + "speaker_sim": 0.9163 + }, + { + "id": "010791", + "utmos22_mean": 3.6093, + "utmos22_p10": 3.6093, + "scoreq_mean": 4.2442, + "scoreq_p10": 4.2442, + "dns_p808": 4.1588, + "dns_sig": 3.5682, + "dns_bak": 4.1504, + "dns_ovr": 3.3225, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A internet mudou completamente a forma como a gente se comunica.", + "speaker_sim": 0.8179 + }, + { + "id": "007790", + "utmos22_mean": 3.9114, + "utmos22_p10": 3.9114, + "scoreq_mean": 4.0205, + "scoreq_p10": 4.0205, + "dns_p808": 3.933, + "dns_sig": 3.6597, + "dns_bak": 4.1902, + "dns_ovr": 3.4601, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Por gentileza, prepare um sanduíche simples para o meu café da manhã.", + "speaker_sim": 0.9266 + }, + { + "id": "003372", + "utmos22_mean": 4.0135, + "utmos22_p10": 4.0135, + "scoreq_mean": 4.1154, + "scoreq_p10": 4.1154, + "dns_p808": 4.0461, + "dns_sig": 3.5744, + "dns_bak": 4.2072, + "dns_ovr": 3.3715, + "wer": 0.0, + "cer": 0.0, + "asr_text": "As barracas de comida da festa junina são as melhores partes.", + "speaker_sim": 0.9362 + }, + { + "id": "010543", + "utmos22_mean": 3.8336, + "utmos22_p10": 3.8336, + "scoreq_mean": 4.072, + "scoreq_p10": 4.072, + "dns_p808": 3.9473, + "dns_sig": 3.6076, + "dns_bak": 4.0982, + "dns_ovr": 3.3193, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nada substitui o sabor de um café fresquinho logo pela manhã.", + "speaker_sim": 0.9259 + }, + { + "id": "001601", + "utmos22_mean": 3.8827, + "utmos22_p10": 3.8827, + "scoreq_mean": 4.2878, + "scoreq_p10": 4.2878, + "dns_p808": 3.9777, + "dns_sig": 3.6162, + "dns_bak": 4.1666, + "dns_ovr": 3.3809, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Onde será que aquele nosso amigo de infância anda morando agora?", + "speaker_sim": 0.915 + }, + { + "id": "004761", + "utmos22_mean": 3.7731, + "utmos22_p10": 3.7731, + "scoreq_mean": 4.0745, + "scoreq_p10": 4.0745, + "dns_p808": 3.6593, + "dns_sig": 3.4071, + "dns_bak": 4.1804, + "dns_ovr": 3.2013, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A tinta branca escorreu pela parede enquanto eu pintava o teto.", + "speaker_sim": 0.8776 + }, + { + "id": "009510", + "utmos22_mean": 3.7716, + "utmos22_p10": 3.7716, + "scoreq_mean": 3.7731, + "scoreq_p10": 3.7731, + "dns_p808": 3.7026, + "dns_sig": 3.532, + "dns_bak": 4.1973, + "dns_ovr": 3.3263, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você pode trazer os balões coloridos para a festa de aniversário.", + "speaker_sim": 0.903 + }, + { + "id": "005027", + "utmos22_mean": 3.8376, + "utmos22_p10": 3.8376, + "scoreq_mean": 4.012, + "scoreq_p10": 4.012, + "dns_p808": 4.0241, + "dns_sig": 3.4403, + "dns_bak": 4.198, + "dns_ovr": 3.2464, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Vovó, por favor, me ensine a fazer aquele doce de leite.", + "speaker_sim": 0.897 + }, + { + "id": "005858", + "utmos22_mean": 3.857, + "utmos22_p10": 3.857, + "scoreq_mean": 3.9988, + "scoreq_p10": 3.9988, + "dns_p808": 3.9399, + "dns_sig": 3.6385, + "dns_bak": 4.2374, + "dns_ovr": 3.4282, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O artesanato com recicláveis é uma ótima forma de ajudar natureza.", + "speaker_sim": 0.9224 + }, + { + "id": "003719", + "utmos22_mean": 3.1359, + "utmos22_p10": 3.1359, + "scoreq_mean": 3.4452, + "scoreq_p10": 3.4452, + "dns_p808": 3.8697, + "dns_sig": 3.1729, + "dns_bak": 4.0547, + "dns_ovr": 2.9792, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O caminho para a montanha era cheio de curvas e árvores verdes.", + "speaker_sim": 0.8773 + }, + { + "id": "003590", + "utmos22_mean": 4.0492, + "utmos22_p10": 4.0492, + "scoreq_mean": 4.1124, + "scoreq_p10": 4.1124, + "dns_p808": 4.0143, + "dns_sig": 3.5452, + "dns_bak": 4.1963, + "dns_ovr": 3.3322, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você lembra de quando a gente passava a noite inteira acordado conversando?", + "speaker_sim": 0.9195 + }, + { + "id": "004697", + "utmos22_mean": 3.524, + "utmos22_p10": 3.524, + "scoreq_mean": 3.8643, + "scoreq_p10": 3.8643, + "dns_p808": 3.8564, + "dns_sig": 3.6193, + "dns_bak": 4.2399, + "dns_ovr": 3.4298, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A gente colecionava figurinhas repetidas e trocava no recreio da escola.", + "speaker_sim": 0.9357 + }, + { + "id": "007703", + "utmos22_mean": 3.9505, + "utmos22_p10": 3.9505, + "scoreq_mean": 3.96, + "scoreq_p10": 3.96, + "dns_p808": 4.0894, + "dns_sig": 3.4208, + "dns_bak": 4.213, + "dns_ovr": 3.2425, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O sorriso dele iluminava qualquer ambiente, não importa onde estivéssemos nós.", + "speaker_sim": 0.9193 + }, + { + "id": "001055", + "utmos22_mean": 3.699, + "utmos22_p10": 3.699, + "scoreq_mean": 3.8782, + "scoreq_p10": 3.8782, + "dns_p808": 4.1753, + "dns_sig": 3.5371, + "dns_bak": 4.1849, + "dns_ovr": 3.3321, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Meus filhos estão crescendo rápido demais, eu nem consigo acreditar nisso.", + "speaker_sim": 0.9092 + }, + { + "id": "005025", + "utmos22_mean": 3.5563, + "utmos22_p10": 3.5563, + "scoreq_mean": 3.8951, + "scoreq_p10": 3.8951, + "dns_p808": 4.1369, + "dns_sig": 3.5298, + "dns_bak": 4.1329, + "dns_ovr": 3.31, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O restaurante italiano tem uma decoração rústica com muitas luzes amarelas.", + "speaker_sim": 0.9337 + }, + { + "id": "000311", + "utmos22_mean": 3.4158, + "utmos22_p10": 3.4158, + "scoreq_mean": 3.674, + "scoreq_p10": 3.674, + "dns_p808": 4.1155, + "dns_sig": 3.6017, + "dns_bak": 4.2107, + "dns_ovr": 3.3883, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O riso dos meus filhos preenche todos os cômodos da casa e traz uma alegria que não acaba.", + "speaker_sim": 0.9001 + }, + { + "id": "006727", + "utmos22_mean": 3.7276, + "utmos22_p10": 3.7276, + "scoreq_mean": 4.1533, + "scoreq_p10": 4.1533, + "dns_p808": 4.0565, + "dns_sig": 3.368, + "dns_bak": 4.1029, + "dns_ovr": 3.1196, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu sempre lembro do cheiro da comida da minha avó e sinto uma paz enorme no meu coração agora.", + "speaker_sim": 0.9332 + }, + { + "id": "010438", + "utmos22_mean": 3.6823, + "utmos22_p10": 3.6823, + "scoreq_mean": 3.6248, + "scoreq_p10": 3.6248, + "dns_p808": 4.0409, + "dns_sig": 3.4565, + "dns_bak": 4.1582, + "dns_ovr": 3.2585, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Gente, me perdoa. Eu me perdi no caminho e não consegui achar o endereço certo do restaurante.", + "speaker_sim": 0.9498 + }, + { + "id": "001260", + "utmos22_mean": 3.6926, + "utmos22_p10": 3.6926, + "scoreq_mean": 3.8995, + "scoreq_p10": 3.8995, + "dns_p808": 4.0556, + "dns_sig": 3.5945, + "dns_bak": 4.1892, + "dns_ovr": 3.3797, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Aquela cena de luta foi coreografada com tanta precisão que parecia uma dança sincronizada e violenta.", + "speaker_sim": 0.9238 + }, + { + "id": "008515", + "utmos22_mean": 3.9125, + "utmos22_p10": 3.9125, + "scoreq_mean": 3.9568, + "scoreq_p10": 3.9568, + "dns_p808": 3.947, + "dns_sig": 3.4965, + "dns_bak": 4.1664, + "dns_ovr": 3.2883, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Gente, quem fez esse quentão maravilhoso, eu estou sentindo o calorzinho subir e ficando muito feliz agora.", + "speaker_sim": 0.9127 + }, + { + "id": "002356", + "utmos22_mean": 3.792, + "utmos22_p10": 3.792, + "scoreq_mean": 4.057, + "scoreq_p10": 4.057, + "dns_p808": 3.8944, + "dns_sig": 3.5698, + "dns_bak": 4.219, + "dns_ovr": 3.3686, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quem aí concorda que esse personagem é o mais apelão de todos, ou eu estou ficando louca sozinha?", + "speaker_sim": 0.9214 + }, + { + "id": "005566", + "utmos22_mean": 3.3649, + "utmos22_p10": 3.3649, + "scoreq_mean": 4.037, + "scoreq_p10": 4.037, + "dns_p808": 3.9614, + "dns_sig": 3.4492, + "dns_bak": 4.1858, + "dns_ovr": 3.2495, + "wer": 0.1111, + "cer": 0.0, + "asr_text": "O meio de campo distribuiu a bola com precisão, criando a chance perfeita para o centro-avante marcar gol.", + "speaker_sim": 0.9207 + }, + { + "id": "007600", + "utmos22_mean": 3.6318, + "utmos22_p10": 3.6318, + "scoreq_mean": 3.7889, + "scoreq_p10": 3.7889, + "dns_p808": 4.1218, + "dns_sig": 3.6033, + "dns_bak": 4.1529, + "dns_ovr": 3.3662, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nós passamos a tarde inteira discutindo qual era a melhor temporada daquela série de ficção científica antiga.", + "speaker_sim": 0.9495 + }, + { + "id": "003245", + "utmos22_mean": 3.2886, + "utmos22_p10": 3.2886, + "scoreq_mean": 3.7071, + "scoreq_p10": 3.7071, + "dns_p808": 4.0957, + "dns_sig": 3.5057, + "dns_bak": 4.1678, + "dns_ovr": 3.3036, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Caramba, você realmente conseguiu transformar esse pedaço de madeira velha em um porta-joias maravilhoso e super elegante.", + "speaker_sim": 0.9385 + } + ] + }, + "fast2/stress_ptbr": { + "summary": { + "utmos22_mean": 3.5904, + "scoreq_mean": 3.8611, + "dns_ovr": 3.348, + "wer": 0.0426, + "cer": 0.0111, + "speaker_sim": 0.9078, + "n": 36 + }, + "items": [ + { + "id": "cot_00", + "utmos22_mean": 3.2977, + "utmos22_p10": 3.2977, + "scoreq_mean": 3.7885, + "scoreq_p10": 3.7885, + "dns_p808": 3.7933, + "dns_sig": 3.4977, + "dns_bak": 4.1755, + "dns_ovr": 3.3076, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Amanhã de manhã, eu vou pôr o pão na mesa para os irmãos.", + "speaker_sim": 0.8705 + }, + { + "id": "cot_01", + "utmos22_mean": 3.8806, + "utmos22_p10": 3.8806, + "scoreq_mean": 4.0548, + "scoreq_p10": 4.0548, + "dns_p808": 3.8053, + "dns_sig": 3.4883, + "dns_bak": 4.1459, + "dns_ovr": 3.2787, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Depois que a tempestade passou, o ar da serra ficou fresco e limpo.", + "speaker_sim": 0.9059 + }, + { + "id": "cot_02", + "utmos22_mean": 3.1022, + "utmos22_p10": 3.1022, + "scoreq_mean": 3.6754, + "scoreq_p10": 3.6754, + "dns_p808": 3.7371, + "dns_sig": 3.5639, + "dns_bak": 4.1791, + "dns_ovr": 3.3444, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O café brasileiro é reconhecido no mundo inteiro pelo aroma marcante.", + "speaker_sim": 0.9285 + }, + { + "id": "cot_03", + "utmos22_mean": 3.9028, + "utmos22_p10": 3.9028, + "scoreq_mean": 3.9852, + "scoreq_p10": 3.9852, + "dns_p808": 3.9799, + "dns_sig": 3.5631, + "dns_bak": 4.2172, + "dns_ovr": 3.3582, + "wer": 0.0833, + "cer": 0.0164, + "asr_text": "Ela caminhou 10 km pelo parque e voltou para a casa bem disposta.", + "speaker_sim": 0.9041 + }, + { + "id": "cot_04", + "utmos22_mean": 3.4801, + "utmos22_p10": 3.4801, + "scoreq_mean": 3.6491, + "scoreq_p10": 3.6491, + "dns_p808": 3.8553, + "dns_sig": 3.3992, + "dns_bak": 4.194, + "dns_ovr": 3.2167, + "wer": 0.1429, + "cer": 0.0597, + "asr_text": "Estudaram um pouco todos os dias atrás resultados melhores do que correr na véspera.", + "speaker_sim": 0.9162 + }, + { + "id": "cot_05", + "utmos22_mean": 3.1691, + "utmos22_p10": 3.1691, + "scoreq_mean": 3.7005, + "scoreq_p10": 3.7005, + "dns_p808": 4.079, + "dns_sig": 3.7047, + "dns_bak": 4.2796, + "dns_ovr": 3.5222, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Acordei tarde hoje e acabei perdendo a hora do café da manhã na cozinha.", + "speaker_sim": 0.9038 + }, + { + "id": "prg_00", + "utmos22_mean": 3.615, + "utmos22_p10": 3.615, + "scoreq_mean": 3.8126, + "scoreq_p10": 3.8126, + "dns_p808": 3.7444, + "dns_sig": 3.5577, + "dns_bak": 4.1713, + "dns_ovr": 3.3537, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você tem certeza de que ele vem hoje a tarde?", + "speaker_sim": 0.8291 + }, + { + "id": "prg_01", + "utmos22_mean": 3.776, + "utmos22_p10": 3.776, + "scoreq_mean": 4.263, + "scoreq_p10": 4.263, + "dns_p808": 3.952, + "dns_sig": 3.4241, + "dns_bak": 4.1474, + "dns_ovr": 3.209, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quantas pessoas confirmaram presença na reunião de sexta-feira?", + "speaker_sim": 0.9013 + }, + { + "id": "prg_02", + "utmos22_mean": 3.6326, + "utmos22_p10": 3.6326, + "scoreq_mean": 4.1506, + "scoreq_p10": 4.1506, + "dns_p808": 3.9109, + "dns_sig": 3.5404, + "dns_bak": 4.2125, + "dns_ovr": 3.3504, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Onde você guardou as chaves do carro que estavam em cima da estante?", + "speaker_sim": 0.8971 + }, + { + "id": "prg_03", + "utmos22_mean": 3.5273, + "utmos22_p10": 3.5273, + "scoreq_mean": 3.7175, + "scoreq_p10": 3.7175, + "dns_p808": 3.9448, + "dns_sig": 3.6678, + "dns_bak": 4.2634, + "dns_ovr": 3.4868, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Será que conseguimos terminar essa tarefa antes do final do expediente?", + "speaker_sim": 0.9323 + }, + { + "id": "prg_04", + "utmos22_mean": 3.4559, + "utmos22_p10": 3.4559, + "scoreq_mean": 4.0646, + "scoreq_p10": 4.0646, + "dns_p808": 3.9413, + "dns_sig": 3.6521, + "dns_bak": 4.2243, + "dns_ovr": 3.4706, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você já almoçou ou ainda está com muita fome?", + "speaker_sim": 0.8988 + }, + { + "id": "prg_05", + "utmos22_mean": 3.8433, + "utmos22_p10": 3.8433, + "scoreq_mean": 4.267, + "scoreq_p10": 4.267, + "dns_p808": 3.822, + "dns_sig": 3.6063, + "dns_bak": 4.2368, + "dns_ovr": 3.4324, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Como você consegue acordar tão cedo todos os dias sem despertador?", + "speaker_sim": 0.901 + }, + { + "id": "emo_00", + "utmos22_mean": 3.4045, + "utmos22_p10": 3.4045, + "scoreq_mean": 3.767, + "scoreq_p10": 3.767, + "dns_p808": 3.9651, + "dns_sig": 3.5074, + "dns_bak": 4.1499, + "dns_ovr": 3.2929, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que notícia maravilhosa receber a aprovação logo na primeira tentativa!", + "speaker_sim": 0.9199 + }, + { + "id": "emo_01", + "utmos22_mean": 3.6685, + "utmos22_p10": 3.6685, + "scoreq_mean": 3.9596, + "scoreq_p10": 3.9596, + "dns_p808": 3.8704, + "dns_sig": 3.5373, + "dns_bak": 4.2519, + "dns_ovr": 3.3721, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nossa, isso ficou muito mais bonito e natural do que eu imaginava.", + "speaker_sim": 0.9133 + }, + { + "id": "emo_02", + "utmos22_mean": 3.717, + "utmos22_p10": 3.717, + "scoreq_mean": 3.8585, + "scoreq_p10": 3.8585, + "dns_p808": 3.8052, + "dns_sig": 3.6111, + "dns_bak": 4.2084, + "dns_ovr": 3.3935, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ufa, que alívio gigantesco. Achei mesmo que tinha perdido todo o trabalho.", + "speaker_sim": 0.8775 + }, + { + "id": "emo_03", + "utmos22_mean": 3.8972, + "utmos22_p10": 3.8972, + "scoreq_mean": 4.1336, + "scoreq_p10": 4.1336, + "dns_p808": 3.9938, + "dns_sig": 3.5902, + "dns_bak": 4.1063, + "dns_ovr": 3.3049, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que susto terrível, eu quase caí da cadeira com aquele barulho repentino.", + "speaker_sim": 0.8877 + }, + { + "id": "emo_04", + "utmos22_mean": 4.0043, + "utmos22_p10": 4.0043, + "scoreq_mean": 4.276, + "scoreq_p10": 4.276, + "dns_p808": 3.9845, + "dns_sig": 3.5872, + "dns_bak": 4.2116, + "dns_ovr": 3.3754, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ai, que saudade de você, fazia meses que a gente não conversava assim.", + "speaker_sim": 0.903 + }, + { + "id": "emo_05", + "utmos22_mean": 3.7024, + "utmos22_p10": 3.7024, + "scoreq_mean": 3.6238, + "scoreq_p10": 3.6238, + "dns_p808": 4.0171, + "dns_sig": 3.4974, + "dns_bak": 4.2149, + "dns_ovr": 3.3114, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Muito obrigado pela paciência, pelo cuidado e pela ajuda durante todo este experimento.", + "speaker_sim": 0.9222 + }, + { + "id": "nrm_00", + "utmos22_mean": 3.4072, + "utmos22_p10": 3.4072, + "scoreq_mean": 3.6026, + "scoreq_p10": 3.6026, + "dns_p808": 4.1827, + "dns_sig": 3.6161, + "dns_bak": 4.2461, + "dns_ovr": 3.4256, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Dia 22 de março às 14 horas e 30 minutos custou 40 e 5 reais e 90 centavos à vista você prefere parcelar em três vezes", + "speaker_sim": 0.9304 + }, + { + "id": "nrm_01", + "utmos22_mean": 3.7835, + "utmos22_p10": 3.7835, + "scoreq_mean": 3.6493, + "scoreq_p10": 3.6493, + "dns_p808": 3.9253, + "dns_sig": 3.5, + "dns_bak": 4.0686, + "dns_ovr": 3.2111, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A taxa de juros caiu 0,5% no último trimestre segundo os dados do IBGE.", + "speaker_sim": 0.9063 + }, + { + "id": "nrm_02", + "utmos22_mean": 3.2667, + "utmos22_p10": 3.2667, + "scoreq_mean": 3.6021, + "scoreq_p10": 3.6021, + "dns_p808": 3.9885, + "dns_sig": 3.3721, + "dns_bak": 4.0093, + "dns_ovr": 3.0908, + "wer": 0.1053, + "cer": 0.1304, + "asr_text": "A temperatura máxima amanhã deve chegar a 30°C e 2°C perto das 15 horas na região central.", + "speaker_sim": 0.9372 + }, + { + "id": "nrm_03", + "utmos22_mean": 3.6361, + "utmos22_p10": 3.6361, + "scoreq_mean": 3.8278, + "scoreq_p10": 3.8278, + "dns_p808": 4.1809, + "dns_sig": 3.4408, + "dns_bak": 4.148, + "dns_ovr": 3.2103, + "wer": 0.4706, + "cer": 0.0278, + "asr_text": "O sistema processa mais de 1.500 requisições via P e em C, P, U ou G, P, U sem falhar.", + "speaker_sim": 0.9046 + }, + { + "id": "nrm_04", + "utmos22_mean": 2.9762, + "utmos22_p10": 2.9762, + "scoreq_mean": 3.5914, + "scoreq_p10": 3.5914, + "dns_p808": 3.8782, + "dns_sig": 3.6403, + "dns_bak": 4.1861, + "dns_ovr": 3.4118, + "wer": 0.375, + "cer": 0.0847, + "asr_text": "O novo modelo Onix em CL, e gera um arquivo avilimpo a partir de texto jeson.", + "speaker_sim": 0.8987 + }, + { + "id": "nrm_05", + "utmos22_mean": 3.8655, + "utmos22_p10": 3.8655, + "scoreq_mean": 4.0554, + "scoreq_p10": 4.0554, + "dns_p808": 4.034, + "dns_sig": 3.4428, + "dns_bak": 4.0991, + "dns_ovr": 3.2212, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Na sede da empresa, eu sempre almoço cedo e começo o projeto novo com sede de aprender.", + "speaker_sim": 0.924 + }, + { + "id": "est_00", + "utmos22_mean": 3.8252, + "utmos22_p10": 3.8252, + "scoreq_mean": 3.928, + "scoreq_p10": 3.928, + "dns_p808": 3.7651, + "dns_sig": 3.5942, + "dns_bak": 4.236, + "dns_ovr": 3.401, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Instalei o script em Python no Windows e conectei o fone via Bluetooth sem erro.", + "speaker_sim": 0.8727 + }, + { + "id": "est_01", + "utmos22_mean": 3.4268, + "utmos22_p10": 3.4268, + "scoreq_mean": 4.0601, + "scoreq_p10": 4.0601, + "dns_p808": 3.8902, + "dns_sig": 3.6111, + "dns_bak": 4.2224, + "dns_ovr": 3.3836, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quando o Wi-Fi caiu durante o vídeo no YouTube, mandei uma mensagem no WhatsApp.", + "speaker_sim": 0.9146 + }, + { + "id": "est_02", + "utmos22_mean": 3.173, + "utmos22_p10": 3.173, + "scoreq_mean": 3.5948, + "scoreq_p10": 3.5948, + "dns_p808": 4.0166, + "dns_sig": 3.5404, + "dns_bak": 4.1903, + "dns_ovr": 3.3199, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O computador travou justo na hora de salvar o projeto pesado no editor de áudio.", + "speaker_sim": 0.8947 + }, + { + "id": "est_03", + "utmos22_mean": 3.6458, + "utmos22_p10": 3.6458, + "scoreq_mean": 4.159, + "scoreq_p10": 4.159, + "dns_p808": 4.1613, + "dns_sig": 3.5461, + "dns_bak": 4.1351, + "dns_ovr": 3.2937, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Reiniciei o roteador da sala e a conexão de internet voltou rapidamente ao normal.", + "speaker_sim": 0.8994 + }, + { + "id": "est_04", + "utmos22_mean": 3.3645, + "utmos22_p10": 3.3645, + "scoreq_mean": 3.6643, + "scoreq_p10": 3.6643, + "dns_p808": 3.9227, + "dns_sig": 3.5913, + "dns_bak": 4.226, + "dns_ovr": 3.3861, + "wer": 0.1538, + "cer": 0.0286, + "asr_text": "Esse framework aberto combina síntese rápida em CPU com exportação direta para o AVI.", + "speaker_sim": 0.9241 + }, + { + "id": "est_05", + "utmos22_mean": 3.7683, + "utmos22_p10": 3.7683, + "scoreq_mean": 4.0192, + "scoreq_p10": 4.0192, + "dns_p808": 3.7624, + "dns_sig": 3.5955, + "dns_bak": 4.181, + "dns_ovr": 3.3829, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Baixei a atualização mais recente do aplicativo, mas o servidor demorou para responder.", + "speaker_sim": 0.9383 + }, + { + "id": "fol_00", + "utmos22_mean": 3.6993, + "utmos22_p10": 3.6993, + "scoreq_mean": 3.9559, + "scoreq_p10": 3.9559, + "dns_p808": 4.0433, + "dns_sig": 3.661, + "dns_bak": 4.2615, + "dns_ovr": 3.4797, + "wer": 0.0435, + "cer": 0.0089, + "asr_text": "Depois que a tempestade passou pela serra silenciosa, o ar da manhã ficou fresco e limpo, trazendo o sossego para toda a cidade adormecida.", + "speaker_sim": 0.9394 + }, + { + "id": "fol_01", + "utmos22_mean": 3.7083, + "utmos22_p10": 3.7083, + "scoreq_mean": 3.7698, + "scoreq_p10": 3.7698, + "dns_p808": 4.1517, + "dns_sig": 3.5513, + "dns_bak": 4.163, + "dns_ovr": 3.3052, + "wer": 0.0556, + "cer": 0.0167, + "asr_text": "Os seis cientistas analisaram os sinais acústicos sucessivos com bastante precisão, buscando eliminar qualquer axiado ou zumbido sintético.", + "speaker_sim": 0.9036 + }, + { + "id": "fol_02", + "utmos22_mean": 3.3198, + "utmos22_p10": 3.3198, + "scoreq_mean": 3.5699, + "scoreq_p10": 3.5699, + "dns_p808": 4.0718, + "dns_sig": 3.6492, + "dns_bak": 4.2331, + "dns_ovr": 3.4479, + "wer": 0.0476, + "cer": 0.0087, + "asr_text": "Sempre que as crianças atravessam a praça ensolarada no fim da tarde, os pássaros sobrevoum as árvores próximas fazendo bastante barulho.", + "speaker_sim": 0.9278 + }, + { + "id": "fol_03", + "utmos22_mean": 3.6993, + "utmos22_p10": 3.6993, + "scoreq_mean": 3.6315, + "scoreq_p10": 3.6315, + "dns_p808": 3.9892, + "dns_sig": 3.5515, + "dns_bak": 4.19, + "dns_ovr": 3.3468, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nossos sistemas de síntese precisam soar suaves nas sibilantes, expressivos nas perguntas curtas e firmes nas afirmações extensas.", + "speaker_sim": 0.9033 + }, + { + "id": "fol_04", + "utmos22_mean": 3.7482, + "utmos22_p10": 3.7482, + "scoreq_mean": 3.7653, + "scoreq_p10": 3.7653, + "dns_p808": 4.2075, + "dns_sig": 3.62, + "dns_bak": 4.2334, + "dns_ovr": 3.4389, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Se você escutar com atenção cada sílaba pronunciada em sequência rápida, perceberá imediatamente se a voz respira com naturalidade.", + "speaker_sim": 0.9247 + }, + { + "id": "fol_05", + "utmos22_mean": 3.8657, + "utmos22_p10": 3.8657, + "scoreq_mean": 3.8044, + "scoreq_p10": 3.8044, + "dns_p808": 4.0545, + "dns_sig": 3.592, + "dns_bak": 4.1939, + "dns_ovr": 3.3894, + "wer": 0.0556, + "cer": 0.0185, + "asr_text": "Durante toda a sessão experimental de sexta-feira, revisamos seis relatórios extensos sobre qualidade sonora, prosódia e edição.", + "speaker_sim": 0.9259 + } + ] + }, + "soup50_8p/test": { + "summary": { + "utmos22_mean": 3.6998, + "scoreq_mean": 4.0147, + "dns_ovr": 3.2546, + "wer": 0.0157, + "cer": 0.0048, + "speaker_sim": 0.8851, + "n": 57 + }, + "items": [ + { + "id": "006251", + "utmos22_mean": 3.9976, + "utmos22_p10": 3.9976, + "scoreq_mean": 4.2583, + "scoreq_p10": 4.2583, + "dns_p808": 3.6158, + "dns_sig": 3.4662, + "dns_bak": 4.1588, + "dns_ovr": 3.2776, + "wer": 0.4, + "cer": 0.125, + "asr_text": "Vai ter pra ver na mesa.", + "speaker_sim": 0.6856 + }, + { + "id": "008569", + "utmos22_mean": 4.1036, + "utmos22_p10": 4.1036, + "scoreq_mean": 3.95, + "scoreq_p10": 3.95, + "dns_p808": 3.5758, + "dns_sig": 3.3487, + "dns_bak": 4.124, + "dns_ovr": 3.1232, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Não quero ir sozinho.", + "speaker_sim": 0.836 + }, + { + "id": "002227", + "utmos22_mean": 3.9928, + "utmos22_p10": 3.9928, + "scoreq_mean": 3.973, + "scoreq_p10": 3.973, + "dns_p808": 3.7707, + "dns_sig": 3.6221, + "dns_bak": 4.2168, + "dns_ovr": 3.4325, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A guitarra está desafinada.", + "speaker_sim": 0.8096 + }, + { + "id": "010144", + "utmos22_mean": 3.7105, + "utmos22_p10": 3.7105, + "scoreq_mean": 3.8257, + "scoreq_p10": 3.8257, + "dns_p808": 3.7432, + "dns_sig": 3.1108, + "dns_bak": 4.1574, + "dns_ovr": 2.9481, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ele estava tenso com a prova.", + "speaker_sim": 0.7737 + }, + { + "id": "002156", + "utmos22_mean": 3.8447, + "utmos22_p10": 3.8447, + "scoreq_mean": 4.1328, + "scoreq_p10": 4.1328, + "dns_p808": 3.8191, + "dns_sig": 3.5666, + "dns_bak": 4.1965, + "dns_ovr": 3.3759, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que personagem interessante.", + "speaker_sim": 0.8892 + }, + { + "id": "005535", + "utmos22_mean": 4.0209, + "utmos22_p10": 4.0209, + "scoreq_mean": 4.2592, + "scoreq_p10": 4.2592, + "dns_p808": 3.8392, + "dns_sig": 3.5231, + "dns_bak": 4.1933, + "dns_ovr": 3.3221, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você sabe fazer arroz doce?", + "speaker_sim": 0.7548 + }, + { + "id": "009128", + "utmos22_mean": 3.98, + "utmos22_p10": 3.98, + "scoreq_mean": 4.1918, + "scoreq_p10": 4.1918, + "dns_p808": 3.8083, + "dns_sig": 3.4086, + "dns_bak": 4.212, + "dns_ovr": 3.2265, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A luz batia no rosto.", + "speaker_sim": 0.7758 + }, + { + "id": "001356", + "utmos22_mean": 3.4808, + "utmos22_p10": 3.4808, + "scoreq_mean": 4.2204, + "scoreq_p10": 4.2204, + "dns_p808": 3.6589, + "dns_sig": 3.2443, + "dns_bak": 4.2022, + "dns_ovr": 3.0796, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Dá para guardar alguma coisa?", + "speaker_sim": 0.7712 + }, + { + "id": "004982", + "utmos22_mean": 3.4752, + "utmos22_p10": 3.4752, + "scoreq_mean": 4.0546, + "scoreq_p10": 4.0546, + "dns_p808": 3.6763, + "dns_sig": 3.4281, + "dns_bak": 4.2131, + "dns_ovr": 3.2444, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Coentro estraga a comida toda.", + "speaker_sim": 0.804 + }, + { + "id": "008746", + "utmos22_mean": 3.9336, + "utmos22_p10": 3.9336, + "scoreq_mean": 4.0713, + "scoreq_p10": 4.0713, + "dns_p808": 3.6589, + "dns_sig": 3.3319, + "dns_bak": 4.012, + "dns_ovr": 3.0732, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que doideira esse tempo relativo.", + "speaker_sim": 0.8714 + }, + { + "id": "000788", + "utmos22_mean": 3.637, + "utmos22_p10": 3.637, + "scoreq_mean": 3.9342, + "scoreq_p10": 3.9342, + "dns_p808": 3.8364, + "dns_sig": 3.4483, + "dns_bak": 4.2089, + "dns_ovr": 3.2594, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Use azeite para fritar tudo.", + "speaker_sim": 0.7867 + }, + { + "id": "005176", + "utmos22_mean": 3.6039, + "utmos22_p10": 3.6039, + "scoreq_mean": 4.066, + "scoreq_p10": 4.066, + "dns_p808": 3.7462, + "dns_sig": 3.6824, + "dns_bak": 4.2593, + "dns_ovr": 3.4959, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A floresta parecia não ter fim.", + "speaker_sim": 0.8213 + }, + { + "id": "009887", + "utmos22_mean": 2.8829, + "utmos22_p10": 2.8829, + "scoreq_mean": 3.9814, + "scoreq_p10": 3.9814, + "dns_p808": 4.082, + "dns_sig": 3.5291, + "dns_bak": 4.1755, + "dns_ovr": 3.3176, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A indústria nasceu na Inglaterra Antiga.", + "speaker_sim": 0.8913 + }, + { + "id": "003791", + "utmos22_mean": 3.1553, + "utmos22_p10": 3.1553, + "scoreq_mean": 3.9498, + "scoreq_p10": 3.9498, + "dns_p808": 4.1359, + "dns_sig": 3.0902, + "dns_bak": 4.0759, + "dns_ovr": 2.8818, + "wer": 0.2, + "cer": 0.069, + "asr_text": "Precisamos de mais toalhas lintas.", + "speaker_sim": 0.8772 + }, + { + "id": "005794", + "utmos22_mean": 3.6848, + "utmos22_p10": 3.6848, + "scoreq_mean": 3.9835, + "scoreq_p10": 3.9835, + "dns_p808": 3.8807, + "dns_sig": 3.5643, + "dns_bak": 4.1906, + "dns_ovr": 3.3628, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A Idade Média teve muitos castelos.", + "speaker_sim": 0.9013 + }, + { + "id": "004271", + "utmos22_mean": 3.6308, + "utmos22_p10": 3.6308, + "scoreq_mean": 4.0847, + "scoreq_p10": 4.0847, + "dns_p808": 4.0232, + "dns_sig": 3.2691, + "dns_bak": 4.1235, + "dns_ovr": 3.0732, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ela é uma pessoa decidida.", + "speaker_sim": 0.8614 + }, + { + "id": "002030", + "utmos22_mean": 4.0489, + "utmos22_p10": 4.0489, + "scoreq_mean": 4.4715, + "scoreq_p10": 4.4715, + "dns_p808": 3.8759, + "dns_sig": 3.5944, + "dns_bak": 4.2, + "dns_ovr": 3.3732, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quem aqui acha que eu vou conseguir passar desse nível logo?", + "speaker_sim": 0.8916 + }, + { + "id": "000476", + "utmos22_mean": 3.9963, + "utmos22_p10": 3.9963, + "scoreq_mean": 3.9967, + "scoreq_p10": 3.9967, + "dns_p808": 3.8972, + "dns_sig": 3.439, + "dns_bak": 3.3205, + "dns_ovr": 2.8478, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Tem um cinema antigo que ainda exibe filmes clássicos.", + "speaker_sim": 0.904 + }, + { + "id": "010092", + "utmos22_mean": 3.7293, + "utmos22_p10": 3.7293, + "scoreq_mean": 4.2046, + "scoreq_p10": 4.2046, + "dns_p808": 3.9905, + "dns_sig": 3.6308, + "dns_bak": 4.2306, + "dns_ovr": 3.4178, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu vou deixar um recado com a sua irmã sobre o horário.", + "speaker_sim": 0.8842 + }, + { + "id": "004474", + "utmos22_mean": 3.6152, + "utmos22_p10": 3.6152, + "scoreq_mean": 4.0138, + "scoreq_p10": 4.0138, + "dns_p808": 3.8429, + "dns_sig": 3.4672, + "dns_bak": 4.165, + "dns_ovr": 3.2396, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você sabia que o núcleo da terra é quente como sol?", + "speaker_sim": 0.9118 + }, + { + "id": "010456", + "utmos22_mean": 3.7793, + "utmos22_p10": 3.7793, + "scoreq_mean": 4.2584, + "scoreq_p10": 4.2584, + "dns_p808": 4.0115, + "dns_sig": 3.3856, + "dns_bak": 4.0853, + "dns_ovr": 3.1369, + "wer": 0.0909, + "cer": 0.0577, + "asr_text": "Eu passei a noite inteira tentando resolver esse burro no código.", + "speaker_sim": 0.9321 + }, + { + "id": "002930", + "utmos22_mean": 3.8248, + "utmos22_p10": 3.8248, + "scoreq_mean": 4.2239, + "scoreq_p10": 4.2239, + "dns_p808": 3.9359, + "dns_sig": 3.629, + "dns_bak": 3.9091, + "dns_ovr": 3.2112, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu amo a sensação de fechar os olhos e começar a sonhar.", + "speaker_sim": 0.9071 + }, + { + "id": "007758", + "utmos22_mean": 3.6818, + "utmos22_p10": 3.6818, + "scoreq_mean": 4.2581, + "scoreq_p10": 4.2581, + "dns_p808": 4.0223, + "dns_sig": 3.6233, + "dns_bak": 4.234, + "dns_ovr": 3.4378, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O gato dormia tranquilamente em cima do sofá da sala.", + "speaker_sim": 0.9019 + }, + { + "id": "008302", + "utmos22_mean": 3.3045, + "utmos22_p10": 3.3045, + "scoreq_mean": 4.0544, + "scoreq_p10": 4.0544, + "dns_p808": 3.9146, + "dns_sig": 3.1525, + "dns_bak": 3.7098, + "dns_ovr": 2.7231, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Olha só, a Lua iluminou todo o jardim com esse brilho.", + "speaker_sim": 0.881 + }, + { + "id": "003146", + "utmos22_mean": 3.4043, + "utmos22_p10": 3.4043, + "scoreq_mean": 3.7726, + "scoreq_p10": 3.7726, + "dns_p808": 4.0379, + "dns_sig": 3.5277, + "dns_bak": 4.1946, + "dns_ovr": 3.3413, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu vou trocar a música da live para animar mais o ambiente.", + "speaker_sim": 0.9185 + }, + { + "id": "006905", + "utmos22_mean": 3.9788, + "utmos22_p10": 3.9788, + "scoreq_mean": 4.0621, + "scoreq_p10": 4.0621, + "dns_p808": 4.0731, + "dns_sig": 3.5504, + "dns_bak": 4.1709, + "dns_ovr": 3.3476, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você já sabe onde vai passar a ceia de Natal deste ano.", + "speaker_sim": 0.8932 + }, + { + "id": "009498", + "utmos22_mean": 3.3431, + "utmos22_p10": 3.3431, + "scoreq_mean": 3.8123, + "scoreq_p10": 3.8123, + "dns_p808": 3.9642, + "dns_sig": 3.6676, + "dns_bak": 4.2506, + "dns_ovr": 3.4739, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Aquela televisão antiga precisava de um tapa para funcionar bem.", + "speaker_sim": 0.9326 + }, + { + "id": "000664", + "utmos22_mean": 3.5705, + "utmos22_p10": 3.5705, + "scoreq_mean": 4.1843, + "scoreq_p10": 4.1843, + "dns_p808": 3.7217, + "dns_sig": 3.2164, + "dns_bak": 4.1064, + "dns_ovr": 3.0167, + "wer": 0.0909, + "cer": 0.0222, + "asr_text": "Você já montou a lista de tudo o que precisa fazer amanhã?", + "speaker_sim": 0.9204 + }, + { + "id": "003728", + "utmos22_mean": 3.19, + "utmos22_p10": 3.19, + "scoreq_mean": 4.0022, + "scoreq_p10": 4.0022, + "dns_p808": 3.8243, + "dns_sig": 3.4892, + "dns_bak": 4.2016, + "dns_ovr": 3.289, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Onde eu baixo o driver de vídeo para o meu computador novo.", + "speaker_sim": 0.892 + }, + { + "id": "007273", + "utmos22_mean": 3.8481, + "utmos22_p10": 3.8481, + "scoreq_mean": 3.9448, + "scoreq_p10": 3.9448, + "dns_p808": 3.8042, + "dns_sig": 3.4433, + "dns_bak": 4.1732, + "dns_ovr": 3.2462, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Não suporto quando a comida chega fria no restaurante caro.", + "speaker_sim": 0.9052 + }, + { + "id": "010313", + "utmos22_mean": 3.8851, + "utmos22_p10": 3.8851, + "scoreq_mean": 4.0926, + "scoreq_p10": 4.0926, + "dns_p808": 3.8582, + "dns_sig": 3.6203, + "dns_bak": 4.1639, + "dns_ovr": 3.3825, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O café da manhã do hotel tinha frutas frescas e pão quente.", + "speaker_sim": 0.9075 + }, + { + "id": "003210", + "utmos22_mean": 3.6974, + "utmos22_p10": 3.6974, + "scoreq_mean": 4.0239, + "scoreq_p10": 4.0239, + "dns_p808": 3.7695, + "dns_sig": 3.2526, + "dns_bak": 4.038, + "dns_ovr": 3.0202, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você já planejou como vai investir o seu dinheiro no futuro?", + "speaker_sim": 0.8726 + }, + { + "id": "006836", + "utmos22_mean": 3.7733, + "utmos22_p10": 3.7733, + "scoreq_mean": 4.0181, + "scoreq_p10": 4.0181, + "dns_p808": 3.7613, + "dns_sig": 3.5057, + "dns_bak": 4.1278, + "dns_ovr": 3.2792, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você prefere assistir cinema no shopping ou em casa mesmo?", + "speaker_sim": 0.9183 + }, + { + "id": "010791", + "utmos22_mean": 3.7463, + "utmos22_p10": 3.7463, + "scoreq_mean": 4.2355, + "scoreq_p10": 4.2355, + "dns_p808": 4.1697, + "dns_sig": 3.5766, + "dns_bak": 4.1507, + "dns_ovr": 3.3361, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A internet mudou completamente a forma como a gente se comunica.", + "speaker_sim": 0.817 + }, + { + "id": "007790", + "utmos22_mean": 3.8116, + "utmos22_p10": 3.8116, + "scoreq_mean": 4.0281, + "scoreq_p10": 4.0281, + "dns_p808": 3.9593, + "dns_sig": 3.6675, + "dns_bak": 4.1373, + "dns_ovr": 3.4093, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Por gentileza, prepare um sanduíche simples para o meu café da manhã.", + "speaker_sim": 0.9255 + }, + { + "id": "003372", + "utmos22_mean": 4.0422, + "utmos22_p10": 4.0422, + "scoreq_mean": 4.0744, + "scoreq_p10": 4.0744, + "dns_p808": 4.0379, + "dns_sig": 3.5811, + "dns_bak": 4.2042, + "dns_ovr": 3.38, + "wer": 0.0, + "cer": 0.0, + "asr_text": "As barracas de comida da festa junina são as melhores partes.", + "speaker_sim": 0.9352 + }, + { + "id": "010543", + "utmos22_mean": 3.8041, + "utmos22_p10": 3.8041, + "scoreq_mean": 4.0787, + "scoreq_p10": 4.0787, + "dns_p808": 3.903, + "dns_sig": 3.5852, + "dns_bak": 4.1515, + "dns_ovr": 3.3428, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nada substitui o sabor de um café fresquinho logo pela manhã.", + "speaker_sim": 0.9254 + }, + { + "id": "001601", + "utmos22_mean": 3.704, + "utmos22_p10": 3.704, + "scoreq_mean": 4.1962, + "scoreq_p10": 4.1962, + "dns_p808": 3.9961, + "dns_sig": 3.5726, + "dns_bak": 4.1896, + "dns_ovr": 3.3511, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Onde será que aquele nosso amigo de infância anda morando agora?", + "speaker_sim": 0.9176 + }, + { + "id": "004761", + "utmos22_mean": 3.8054, + "utmos22_p10": 3.8054, + "scoreq_mean": 4.0875, + "scoreq_p10": 4.0875, + "dns_p808": 3.6533, + "dns_sig": 3.4932, + "dns_bak": 4.1886, + "dns_ovr": 3.2857, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A tinta branca escorreu pela parede enquanto eu pintava o teto.", + "speaker_sim": 0.8787 + }, + { + "id": "009510", + "utmos22_mean": 3.8042, + "utmos22_p10": 3.8042, + "scoreq_mean": 3.7848, + "scoreq_p10": 3.7848, + "dns_p808": 3.7447, + "dns_sig": 3.4516, + "dns_bak": 4.1817, + "dns_ovr": 3.247, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você pode trazer os balões coloridos para a festa de aniversário.", + "speaker_sim": 0.9019 + }, + { + "id": "005027", + "utmos22_mean": 3.8451, + "utmos22_p10": 3.8451, + "scoreq_mean": 4.0098, + "scoreq_p10": 4.0098, + "dns_p808": 4.0303, + "dns_sig": 3.4723, + "dns_bak": 4.2084, + "dns_ovr": 3.2799, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Vovó, por favor, me ensine a fazer aquele doce de leite.", + "speaker_sim": 0.8934 + }, + { + "id": "005858", + "utmos22_mean": 3.8187, + "utmos22_p10": 3.8187, + "scoreq_mean": 3.9788, + "scoreq_p10": 3.9788, + "dns_p808": 3.9275, + "dns_sig": 3.6007, + "dns_bak": 4.2233, + "dns_ovr": 3.4029, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O artesanato com recicláveis é uma ótima forma de ajudar natureza.", + "speaker_sim": 0.9192 + }, + { + "id": "003719", + "utmos22_mean": 3.2174, + "utmos22_p10": 3.2174, + "scoreq_mean": 3.4829, + "scoreq_p10": 3.4829, + "dns_p808": 3.8182, + "dns_sig": 3.221, + "dns_bak": 4.0955, + "dns_ovr": 3.0256, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O caminho para a montanha era cheio de curvas e árvores verdes.", + "speaker_sim": 0.8858 + }, + { + "id": "003590", + "utmos22_mean": 3.9457, + "utmos22_p10": 3.9457, + "scoreq_mean": 4.1199, + "scoreq_p10": 4.1199, + "dns_p808": 4.0332, + "dns_sig": 3.4622, + "dns_bak": 4.1261, + "dns_ovr": 3.225, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você lembra de quando a gente passava a noite inteira acordado conversando?", + "speaker_sim": 0.9242 + }, + { + "id": "004697", + "utmos22_mean": 3.6095, + "utmos22_p10": 3.6095, + "scoreq_mean": 3.867, + "scoreq_p10": 3.867, + "dns_p808": 3.8352, + "dns_sig": 3.6157, + "dns_bak": 4.2316, + "dns_ovr": 3.4145, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A gente colecionava figurinhas repetidas e trocava no recreio da escola.", + "speaker_sim": 0.936 + }, + { + "id": "007703", + "utmos22_mean": 4.0387, + "utmos22_p10": 4.0387, + "scoreq_mean": 4.0145, + "scoreq_p10": 4.0145, + "dns_p808": 4.0373, + "dns_sig": 3.5051, + "dns_bak": 4.2077, + "dns_ovr": 3.308, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O sorriso dele iluminava qualquer ambiente. Não importa onde estivéssemos nós.", + "speaker_sim": 0.9204 + }, + { + "id": "001055", + "utmos22_mean": 3.578, + "utmos22_p10": 3.578, + "scoreq_mean": 3.7341, + "scoreq_p10": 3.7341, + "dns_p808": 4.1789, + "dns_sig": 3.4767, + "dns_bak": 4.179, + "dns_ovr": 3.2654, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Meus filhos estão crescendo rápido demais, eu nem consigo acreditar nisso.", + "speaker_sim": 0.9139 + }, + { + "id": "005025", + "utmos22_mean": 3.3931, + "utmos22_p10": 3.3931, + "scoreq_mean": 3.8207, + "scoreq_p10": 3.8207, + "dns_p808": 4.1086, + "dns_sig": 3.5313, + "dns_bak": 4.1669, + "dns_ovr": 3.3137, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O restaurante italiano tem uma decoração rústica com muitas luzes amarelas.", + "speaker_sim": 0.9346 + }, + { + "id": "000311", + "utmos22_mean": 3.4593, + "utmos22_p10": 3.4593, + "scoreq_mean": 3.6087, + "scoreq_p10": 3.6087, + "dns_p808": 4.1246, + "dns_sig": 3.5893, + "dns_bak": 4.2024, + "dns_ovr": 3.367, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O riso dos meus filhos preenche todos os cômodos da casa e traz uma alegria que não acaba.", + "speaker_sim": 0.8989 + }, + { + "id": "006727", + "utmos22_mean": 3.6578, + "utmos22_p10": 3.6578, + "scoreq_mean": 4.1232, + "scoreq_p10": 4.1232, + "dns_p808": 4.0056, + "dns_sig": 3.4401, + "dns_bak": 4.1249, + "dns_ovr": 3.1992, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Eu sempre lembro do cheiro da comida da minha avó e sinto uma paz enorme no meu coração agora.", + "speaker_sim": 0.9294 + }, + { + "id": "010438", + "utmos22_mean": 3.8525, + "utmos22_p10": 3.8525, + "scoreq_mean": 3.6709, + "scoreq_p10": 3.6709, + "dns_p808": 4.0438, + "dns_sig": 3.4182, + "dns_bak": 4.1073, + "dns_ovr": 3.1884, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Gente, me perdoa. Eu me perdi no caminho e não consegui achar o endereço certo do restaurante.", + "speaker_sim": 0.9501 + }, + { + "id": "001260", + "utmos22_mean": 3.7065, + "utmos22_p10": 3.7065, + "scoreq_mean": 3.951, + "scoreq_p10": 3.951, + "dns_p808": 4.0505, + "dns_sig": 3.5489, + "dns_bak": 4.1514, + "dns_ovr": 3.3179, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Aquela cena de luta foi coreografada com tanta precisão que parecia uma dança sincronizada e violenta.", + "speaker_sim": 0.9187 + }, + { + "id": "008515", + "utmos22_mean": 3.9159, + "utmos22_p10": 3.9159, + "scoreq_mean": 3.9628, + "scoreq_p10": 3.9628, + "dns_p808": 3.9728, + "dns_sig": 3.533, + "dns_bak": 4.1901, + "dns_ovr": 3.3305, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Gente, quem fez esse quentão maravilhoso, eu estou sentindo o calorzinho subir e ficando muito feliz agora.", + "speaker_sim": 0.9111 + }, + { + "id": "002356", + "utmos22_mean": 3.928, + "utmos22_p10": 3.928, + "scoreq_mean": 4.1172, + "scoreq_p10": 4.1172, + "dns_p808": 3.9255, + "dns_sig": 3.5015, + "dns_bak": 4.1964, + "dns_ovr": 3.3086, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quem aí concorda que esse personagem é o mais apelão de todos, ou eu estou ficando louca sozinha?", + "speaker_sim": 0.9195 + }, + { + "id": "005566", + "utmos22_mean": 3.5319, + "utmos22_p10": 3.5319, + "scoreq_mean": 4.0636, + "scoreq_p10": 4.0636, + "dns_p808": 3.9495, + "dns_sig": 3.4917, + "dns_bak": 4.1846, + "dns_ovr": 3.2785, + "wer": 0.1111, + "cer": 0.0, + "asr_text": "O meio de campo distribuiu a bola com precisão, criando a chance perfeita para o centro-avante marcar gol.", + "speaker_sim": 0.9222 + }, + { + "id": "007600", + "utmos22_mean": 3.381, + "utmos22_p10": 3.381, + "scoreq_mean": 3.6946, + "scoreq_p10": 3.6946, + "dns_p808": 4.1503, + "dns_sig": 3.6045, + "dns_bak": 4.1903, + "dns_ovr": 3.3873, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nós passamos a tarde inteira discutindo qual era a melhor temporada daquela série de ficção científica antiga.", + "speaker_sim": 0.9508 + }, + { + "id": "003245", + "utmos22_mean": 3.485, + "utmos22_p10": 3.485, + "scoreq_mean": 3.7994, + "scoreq_p10": 3.7994, + "dns_p808": 4.113, + "dns_sig": 3.4754, + "dns_bak": 4.1579, + "dns_ovr": 3.2678, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Caramba, você realmente conseguiu transformar esse pedaço de madeira velha em um porta-joias maravilhoso e super elegante.", + "speaker_sim": 0.938 + } + ] + }, + "soup50_8p/stress_ptbr": { + "summary": { + "utmos22_mean": 3.5693, + "scoreq_mean": 3.8449, + "dns_ovr": 3.3316, + "wer": 0.0426, + "cer": 0.0111, + "speaker_sim": 0.9079, + "n": 36 + }, + "items": [ + { + "id": "cot_00", + "utmos22_mean": 3.3551, + "utmos22_p10": 3.3551, + "scoreq_mean": 3.7692, + "scoreq_p10": 3.7692, + "dns_p808": 3.7735, + "dns_sig": 3.4877, + "dns_bak": 4.1859, + "dns_ovr": 3.2957, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Amanhã de manhã, eu vou pôr o pão na mesa para os irmãos.", + "speaker_sim": 0.8732 + }, + { + "id": "cot_01", + "utmos22_mean": 3.9111, + "utmos22_p10": 3.9111, + "scoreq_mean": 4.0837, + "scoreq_p10": 4.0837, + "dns_p808": 3.7935, + "dns_sig": 3.514, + "dns_bak": 4.1757, + "dns_ovr": 3.3165, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Depois que a tempestade passou, o ar da serra ficou fresco e limpo.", + "speaker_sim": 0.9046 + }, + { + "id": "cot_02", + "utmos22_mean": 3.159, + "utmos22_p10": 3.159, + "scoreq_mean": 3.6058, + "scoreq_p10": 3.6058, + "dns_p808": 3.7035, + "dns_sig": 3.5277, + "dns_bak": 4.0976, + "dns_ovr": 3.2494, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O café brasileiro é reconhecido no mundo inteiro pelo aroma marcante.", + "speaker_sim": 0.9249 + }, + { + "id": "cot_03", + "utmos22_mean": 3.7321, + "utmos22_p10": 3.7321, + "scoreq_mean": 3.9533, + "scoreq_p10": 3.9533, + "dns_p808": 4.0477, + "dns_sig": 3.5033, + "dns_bak": 4.1862, + "dns_ovr": 3.2955, + "wer": 0.0833, + "cer": 0.0164, + "asr_text": "Ela caminhou 10 km pelo parque e voltou para a casa bem disposta.", + "speaker_sim": 0.9064 + }, + { + "id": "cot_04", + "utmos22_mean": 3.5975, + "utmos22_p10": 3.5975, + "scoreq_mean": 3.7144, + "scoreq_p10": 3.7144, + "dns_p808": 3.8302, + "dns_sig": 3.3171, + "dns_bak": 4.1704, + "dns_ovr": 3.1378, + "wer": 0.1429, + "cer": 0.0597, + "asr_text": "Estudaram um pouco todos os dias atrás resultados melhores do que correr na véspera.", + "speaker_sim": 0.9158 + }, + { + "id": "cot_05", + "utmos22_mean": 2.887, + "utmos22_p10": 2.887, + "scoreq_mean": 3.6629, + "scoreq_p10": 3.6629, + "dns_p808": 4.0807, + "dns_sig": 3.6439, + "dns_bak": 4.2567, + "dns_ovr": 3.4543, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Acordei tarde hoje e acabei perdendo a hora do café da manhã na cozinha.", + "speaker_sim": 0.9042 + }, + { + "id": "prg_00", + "utmos22_mean": 3.5953, + "utmos22_p10": 3.5953, + "scoreq_mean": 3.7835, + "scoreq_p10": 3.7835, + "dns_p808": 3.7417, + "dns_sig": 3.58, + "dns_bak": 4.1728, + "dns_ovr": 3.3681, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você tem certeza de que ele vem hoje a tarde?", + "speaker_sim": 0.8214 + }, + { + "id": "prg_01", + "utmos22_mean": 3.7823, + "utmos22_p10": 3.7823, + "scoreq_mean": 4.0843, + "scoreq_p10": 4.0843, + "dns_p808": 3.9647, + "dns_sig": 3.3969, + "dns_bak": 4.1553, + "dns_ovr": 3.1908, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quantas pessoas confirmaram presença na reunião de sexta-feira?", + "speaker_sim": 0.9028 + }, + { + "id": "prg_02", + "utmos22_mean": 3.5829, + "utmos22_p10": 3.5829, + "scoreq_mean": 4.1387, + "scoreq_p10": 4.1387, + "dns_p808": 3.8534, + "dns_sig": 3.6093, + "dns_bak": 4.2214, + "dns_ovr": 3.4206, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Onde você guardou as chaves do carro que estavam em cima da estante?", + "speaker_sim": 0.8934 + }, + { + "id": "prg_03", + "utmos22_mean": 3.5279, + "utmos22_p10": 3.5279, + "scoreq_mean": 3.7101, + "scoreq_p10": 3.7101, + "dns_p808": 3.984, + "dns_sig": 3.6494, + "dns_bak": 4.265, + "dns_ovr": 3.4734, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Será que conseguimos terminar essa tarefa antes do final do expediente?", + "speaker_sim": 0.9323 + }, + { + "id": "prg_04", + "utmos22_mean": 3.6006, + "utmos22_p10": 3.6006, + "scoreq_mean": 4.1534, + "scoreq_p10": 4.1534, + "dns_p808": 3.9532, + "dns_sig": 3.6606, + "dns_bak": 4.2313, + "dns_ovr": 3.4826, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Você já almoçou ou ainda está com muita fome?", + "speaker_sim": 0.8941 + }, + { + "id": "prg_05", + "utmos22_mean": 3.8129, + "utmos22_p10": 3.8129, + "scoreq_mean": 4.2459, + "scoreq_p10": 4.2459, + "dns_p808": 3.8543, + "dns_sig": 3.5981, + "dns_bak": 4.2124, + "dns_ovr": 3.4084, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Como você consegue acordar tão cedo todos os dias sem despertador?", + "speaker_sim": 0.8966 + }, + { + "id": "emo_00", + "utmos22_mean": 3.4277, + "utmos22_p10": 3.4277, + "scoreq_mean": 3.7429, + "scoreq_p10": 3.7429, + "dns_p808": 3.9813, + "dns_sig": 3.5651, + "dns_bak": 4.1868, + "dns_ovr": 3.3569, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que notícia maravilhosa receber a aprovação logo na primeira tentativa!", + "speaker_sim": 0.9276 + }, + { + "id": "emo_01", + "utmos22_mean": 3.5087, + "utmos22_p10": 3.5087, + "scoreq_mean": 3.9057, + "scoreq_p10": 3.9057, + "dns_p808": 3.8711, + "dns_sig": 3.5233, + "dns_bak": 4.2442, + "dns_ovr": 3.3524, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nossa, isso ficou muito mais bonito e natural do que eu imaginava.", + "speaker_sim": 0.9119 + }, + { + "id": "emo_02", + "utmos22_mean": 3.698, + "utmos22_p10": 3.698, + "scoreq_mean": 3.8513, + "scoreq_p10": 3.8513, + "dns_p808": 3.8015, + "dns_sig": 3.6231, + "dns_bak": 4.2296, + "dns_ovr": 3.417, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ufa, que alívio gigantesco. Achei mesmo que tinha perdido todo o trabalho.", + "speaker_sim": 0.878 + }, + { + "id": "emo_03", + "utmos22_mean": 3.8461, + "utmos22_p10": 3.8461, + "scoreq_mean": 4.1102, + "scoreq_p10": 4.1102, + "dns_p808": 3.931, + "dns_sig": 3.5626, + "dns_bak": 4.0704, + "dns_ovr": 3.2555, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Que susto terrível, eu quase caí da cadeira com aquele barulho repentino.", + "speaker_sim": 0.8856 + }, + { + "id": "emo_04", + "utmos22_mean": 3.8004, + "utmos22_p10": 3.8004, + "scoreq_mean": 4.2901, + "scoreq_p10": 4.2901, + "dns_p808": 3.9891, + "dns_sig": 3.619, + "dns_bak": 4.2191, + "dns_ovr": 3.4088, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Ai, que saudade de você, fazia meses que a gente não conversava assim.", + "speaker_sim": 0.9045 + }, + { + "id": "emo_05", + "utmos22_mean": 3.232, + "utmos22_p10": 3.232, + "scoreq_mean": 3.4408, + "scoreq_p10": 3.4408, + "dns_p808": 4.0151, + "dns_sig": 3.5474, + "dns_bak": 4.2207, + "dns_ovr": 3.3502, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Muito obrigado pela paciência, pelo cuidado e pela ajuda durante todo este experimento.", + "speaker_sim": 0.9229 + }, + { + "id": "nrm_00", + "utmos22_mean": 3.5796, + "utmos22_p10": 3.5796, + "scoreq_mean": 3.592, + "scoreq_p10": 3.592, + "dns_p808": 4.1913, + "dns_sig": 3.6505, + "dns_bak": 4.246, + "dns_ovr": 3.46, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Dia 22 de março às 14 horas e 30 minutos custou 40 e 5 reais e 90 centavos à vista você prefere parcelar em 3 vezes", + "speaker_sim": 0.9305 + }, + { + "id": "nrm_01", + "utmos22_mean": 3.732, + "utmos22_p10": 3.732, + "scoreq_mean": 3.6564, + "scoreq_p10": 3.6564, + "dns_p808": 3.9455, + "dns_sig": 3.5545, + "dns_bak": 4.0521, + "dns_ovr": 3.2507, + "wer": 0.0, + "cer": 0.0, + "asr_text": "A taxa de juros caiu 0,5% no último trimestre segundo os dados do IBGE.", + "speaker_sim": 0.9072 + }, + { + "id": "nrm_02", + "utmos22_mean": 3.2205, + "utmos22_p10": 3.2205, + "scoreq_mean": 3.586, + "scoreq_p10": 3.586, + "dns_p808": 3.9695, + "dns_sig": 3.3706, + "dns_bak": 3.9523, + "dns_ovr": 3.0534, + "wer": 0.1053, + "cer": 0.1304, + "asr_text": "A temperatura máxima amanhã deve chegar a 30°C e 2°C perto das 15 horas na região central.", + "speaker_sim": 0.9375 + }, + { + "id": "nrm_03", + "utmos22_mean": 3.5247, + "utmos22_p10": 3.5247, + "scoreq_mean": 3.8258, + "scoreq_p10": 3.8258, + "dns_p808": 4.2072, + "dns_sig": 3.4299, + "dns_bak": 4.1508, + "dns_ovr": 3.2002, + "wer": 0.4706, + "cer": 0.0278, + "asr_text": "O sistema processa mais de 1.500 requisições via P e em C, P, U ou G, P, U sem falhar.", + "speaker_sim": 0.9037 + }, + { + "id": "nrm_04", + "utmos22_mean": 3.0226, + "utmos22_p10": 3.0226, + "scoreq_mean": 3.6398, + "scoreq_p10": 3.6398, + "dns_p808": 3.946, + "dns_sig": 3.5909, + "dns_bak": 4.1749, + "dns_ovr": 3.3601, + "wer": 0.375, + "cer": 0.0847, + "asr_text": "O novo modelo Onix em CL, e gera um arquivo avilimpo a partir de texto jeson.", + "speaker_sim": 0.8981 + }, + { + "id": "nrm_05", + "utmos22_mean": 3.8844, + "utmos22_p10": 3.8844, + "scoreq_mean": 4.0746, + "scoreq_p10": 4.0746, + "dns_p808": 4.0474, + "dns_sig": 3.3339, + "dns_bak": 3.8739, + "dns_ovr": 3.013, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Na sede da empresa, eu sempre almoço cedo e começo o projeto novo com sede de aprender.", + "speaker_sim": 0.9215 + }, + { + "id": "est_00", + "utmos22_mean": 3.8306, + "utmos22_p10": 3.8306, + "scoreq_mean": 3.8732, + "scoreq_p10": 3.8732, + "dns_p808": 3.783, + "dns_sig": 3.5837, + "dns_bak": 4.2182, + "dns_ovr": 3.3643, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Instalei o script em Python no Windows e conectei o fone via Bluetooth sem erro.", + "speaker_sim": 0.8741 + }, + { + "id": "est_01", + "utmos22_mean": 3.4481, + "utmos22_p10": 3.4481, + "scoreq_mean": 4.0888, + "scoreq_p10": 4.0888, + "dns_p808": 3.8688, + "dns_sig": 3.599, + "dns_bak": 4.2185, + "dns_ovr": 3.3895, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Quando o Wi-Fi caiu durante o vídeo no YouTube, mandei uma mensagem no WhatsApp.", + "speaker_sim": 0.9177 + }, + { + "id": "est_02", + "utmos22_mean": 3.1556, + "utmos22_p10": 3.1556, + "scoreq_mean": 3.5369, + "scoreq_p10": 3.5369, + "dns_p808": 3.9715, + "dns_sig": 3.4732, + "dns_bak": 4.0891, + "dns_ovr": 3.2309, + "wer": 0.0, + "cer": 0.0, + "asr_text": "O computador travou justo na hora de salvar o projeto pesado no editor de áudio.", + "speaker_sim": 0.8978 + }, + { + "id": "est_03", + "utmos22_mean": 3.755, + "utmos22_p10": 3.755, + "scoreq_mean": 4.1579, + "scoreq_p10": 4.1579, + "dns_p808": 4.1245, + "dns_sig": 3.5202, + "dns_bak": 4.1123, + "dns_ovr": 3.266, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Reiniciei o roteador da sala e a conexão de internet voltou rapidamente ao normal.", + "speaker_sim": 0.9019 + }, + { + "id": "est_04", + "utmos22_mean": 3.5422, + "utmos22_p10": 3.5422, + "scoreq_mean": 3.7012, + "scoreq_p10": 3.7012, + "dns_p808": 3.9036, + "dns_sig": 3.6332, + "dns_bak": 4.2507, + "dns_ovr": 3.438, + "wer": 0.1538, + "cer": 0.0286, + "asr_text": "Esse framework aberto combina síntese rápida em CPU com exportação direta para o AVI.", + "speaker_sim": 0.9259 + }, + { + "id": "est_05", + "utmos22_mean": 3.6961, + "utmos22_p10": 3.6961, + "scoreq_mean": 3.9724, + "scoreq_p10": 3.9724, + "dns_p808": 3.7424, + "dns_sig": 3.6143, + "dns_bak": 4.23, + "dns_ovr": 3.43, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Baixei a atualização mais recente do aplicativo, mas o servidor demorou para responder.", + "speaker_sim": 0.9394 + }, + { + "id": "fol_00", + "utmos22_mean": 3.7658, + "utmos22_p10": 3.7658, + "scoreq_mean": 3.9898, + "scoreq_p10": 3.9898, + "dns_p808": 3.9976, + "dns_sig": 3.6583, + "dns_bak": 4.2421, + "dns_ovr": 3.4606, + "wer": 0.0435, + "cer": 0.0089, + "asr_text": "Depois que a tempestade passou pela serra silenciosa, o ar da manhã ficou fresco e limpo, trazendo o sossego para toda a cidade adormecida.", + "speaker_sim": 0.9403 + }, + { + "id": "fol_01", + "utmos22_mean": 3.7501, + "utmos22_p10": 3.7501, + "scoreq_mean": 3.7683, + "scoreq_p10": 3.7683, + "dns_p808": 4.1561, + "dns_sig": 3.5053, + "dns_bak": 4.1506, + "dns_ovr": 3.2626, + "wer": 0.0556, + "cer": 0.0167, + "asr_text": "Os seis cientistas analisaram os sinais acústicos sucessivos com bastante precisão, buscando eliminar qualquer axiado ou zumbido sintético.", + "speaker_sim": 0.9042 + }, + { + "id": "fol_02", + "utmos22_mean": 3.2453, + "utmos22_p10": 3.2453, + "scoreq_mean": 3.4812, + "scoreq_p10": 3.4812, + "dns_p808": 4.046, + "dns_sig": 3.6175, + "dns_bak": 4.1506, + "dns_ovr": 3.3672, + "wer": 0.0476, + "cer": 0.0087, + "asr_text": "Sempre que as crianças atravessam a praça ensolarada no fim da tarde, os pássaros sobrevoum as árvores próximas fazendo bastante barulho.", + "speaker_sim": 0.9312 + }, + { + "id": "fol_03", + "utmos22_mean": 3.7159, + "utmos22_p10": 3.7159, + "scoreq_mean": 3.684, + "scoreq_p10": 3.684, + "dns_p808": 4.003, + "dns_sig": 3.5489, + "dns_bak": 4.183, + "dns_ovr": 3.3428, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Nossos sistemas de síntese precisam soar suaves nas sibilantes, expressivos nas perguntas curtas e firmes nas afirmações extensas.", + "speaker_sim": 0.9018 + }, + { + "id": "fol_04", + "utmos22_mean": 3.7017, + "utmos22_p10": 3.7017, + "scoreq_mean": 3.7088, + "scoreq_p10": 3.7088, + "dns_p808": 4.2008, + "dns_sig": 3.6299, + "dns_bak": 4.2355, + "dns_ovr": 3.4481, + "wer": 0.0, + "cer": 0.0, + "asr_text": "Se você escutar com atenção cada sílaba pronunciada em sequência rápida, perceberá imediatamente se a voz respira com naturalidade.", + "speaker_sim": 0.9242 + }, + { + "id": "fol_05", + "utmos22_mean": 3.8679, + "utmos22_p10": 3.8679, + "scoreq_mean": 3.8336, + "scoreq_p10": 3.8336, + "dns_p808": 4.0339, + "dns_sig": 3.5706, + "dns_bak": 4.1835, + "dns_ovr": 3.3651, + "wer": 0.0556, + "cer": 0.0185, + "asr_text": "Durante toda a sessão experimental de sexta-feira, revisamos seis relatórios extensos sobre qualidade sonora, prosódia e edição.", + "speaker_sim": 0.9289 + } + ] + } +} \ No newline at end of file diff --git a/eval/timings.json b/eval/timings.json new file mode 100644 index 0000000000000000000000000000000000000000..d909de3d811070cc1cac90c4e7543d8467ed4259 --- /dev/null +++ b/eval/timings.json @@ -0,0 +1,545 @@ +{ + "stages": [ + { + "stage": "prepare_validation", + "module": "lua_nova_v1.data.prepare", + "args": [ + "--inputs", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\source\\validation.parquet", + "--split", + "validation", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\features" + ], + "started_utc": "2026-11-25T04:49:49.625697+00:00", + "ended_utc": "2026-11-25T04:49:53.700727+00:00", + "duration_sec": 4.08, + "duration_min": 0.07, + "peak_torch_allocated_mib": 0.0, + "peak_torch_reserved_mib": 0.0, + "peak_nvidia_smi_mib": 2266, + "mean_gpu_util_pct": 14.0, + "exit_code": 0, + "error": null + }, + { + "stage": "prepare_test", + "module": "lua_nova_v1.data.prepare", + "args": [ + "--inputs", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\source\\test.parquet", + "--split", + "test", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\features" + ], + "started_utc": "2026-11-25T04:49:55.874098+00:00", + "ended_utc": "2026-11-25T04:49:59.083123+00:00", + "duration_sec": 3.21, + "duration_min": 0.05, + "peak_torch_allocated_mib": 0.0, + "peak_torch_reserved_mib": 0.0, + "peak_nvidia_smi_mib": 2247, + "mean_gpu_util_pct": 14.0, + "exit_code": 0, + "error": null + }, + { + "stage": "prepare_train", + "module": "lua_nova_v1.data.prepare", + "args": [ + "--inputs", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\source\\train.parquet", + "--split", + "train", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\features" + ], + "started_utc": "2026-11-25T04:50:01.458362+00:00", + "ended_utc": "2026-11-25T04:52:07.357312+00:00", + "duration_sec": 125.91, + "duration_min": 2.1, + "peak_torch_allocated_mib": 0.0, + "peak_torch_reserved_mib": 0.0, + "peak_nvidia_smi_mib": 2254, + "mean_gpu_util_pct": 28.4, + "exit_code": 0, + "error": null + }, + { + "stage": "annotate", + "module": "lua_nova_v1.data.annotate", + "args": [ + "--features", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\features", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations", + "--dataset-revision", + "luanova-v1", + "--device", + "cuda", + "--refine", + "2", + "--stage", + "refined-2", + "--local-files-only" + ], + "started_utc": "2026-11-25T04:52:24.378620+00:00", + "ended_utc": "2026-11-25T05:01:19.819705+00:00", + "duration_sec": 535.47, + "duration_min": 8.92, + "peak_torch_allocated_mib": 1344.1, + "peak_torch_reserved_mib": 1528.0, + "peak_nvidia_smi_mib": 6011, + "mean_gpu_util_pct": 53.1, + "exit_code": 0, + "error": null + }, + { + "stage": "annotate_relaxed", + "module": "lua_nova_v1.data.annotate", + "args": [ + "--features", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\features", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations", + "--dataset-revision", + "luanova-v1", + "--device", + "cuda", + "--refine", + "2", + "--stage", + "refined-2", + "--max-weak-phone-fraction", + "0.35", + "--min-token-probability", + "0.45", + "--resume", + "--local-files-only" + ], + "started_utc": "2026-11-25T05:01:54.483976+00:00", + "ended_utc": "2026-11-25T05:02:04.676902+00:00", + "duration_sec": 10.19, + "duration_min": 0.17, + "peak_torch_allocated_mib": 1212.3, + "peak_torch_reserved_mib": 1230.0, + "peak_nvidia_smi_mib": 3465, + "mean_gpu_util_pct": 14.8, + "exit_code": 0, + "error": null + }, + { + "stage": "stage1", + "module": "lua_nova_v1.training.stage1", + "args": [ + "--train", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\train.jsonl", + "--validation", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\validation.jsonl", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\stage1", + "--steps", + "40000", + "--save-every", + "5000", + "--keep-every", + "10000", + "--sample-every", + "5000", + "--max-seconds", + "14400", + "--device", + "cuda" + ], + "started_utc": "2026-11-25T05:02:31.021304+00:00", + "ended_utc": "2026-11-25T05:26:54.369261+00:00", + "duration_sec": 1463.41, + "duration_min": 24.39, + "peak_torch_allocated_mib": 7840.6, + "peak_torch_reserved_mib": 9598.0, + "peak_nvidia_smi_mib": 11646, + "mean_gpu_util_pct": 87.7, + "exit_code": 1, + "error": "AcceleratorError: CUDA error: out of memory\nSearch for `cudaErrorMemoryAllocation' in https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TYPES.html for more information.\n" + }, + { + "stage": "stage1_p2_resume", + "module": "lua_nova_v1.training.stage1", + "args": [ + "--train", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\train.jsonl", + "--validation", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\validation.jsonl", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\stage1_p2", + "--resume", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\stage1_p2\\last.pt", + "--max-seconds", + "7200", + "--device", + "cuda" + ], + "started_utc": "2026-11-25T07:11:50.863536+00:00", + "ended_utc": "2026-11-25T07:12:06.905926+00:00", + "duration_sec": 16.04, + "duration_min": 0.27, + "peak_torch_allocated_mib": 90.4, + "peak_torch_reserved_mib": 98.0, + "peak_nvidia_smi_mib": 1904, + "mean_gpu_util_pct": 38.8, + "exit_code": 1, + "error": "ValueError: resume recipe or dataset mismatch (use --init-from to branch a new run with a changed recipe)" + }, + { + "stage": "stage1_p2_resume", + "module": "lua_nova_v1.training.stage1", + "args": [ + "--train", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\train.jsonl", + "--validation", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\validation.jsonl", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\stage1_p2", + "--resume", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\stage1_p2\\last.pt", + "--steps", + "28000", + "--gan-start", + "100000", + "--batch-frames", + "8000", + "--max-batch", + "28", + "--save-every", + "5000", + "--keep-every", + "10000", + "--sample-every", + "5000", + "--max-seconds", + "7200", + "--device", + "cuda" + ], + "started_utc": "2026-11-25T07:12:28.763883+00:00", + "ended_utc": "2026-11-25T07:33:15.517561+00:00", + "duration_sec": 1246.77, + "duration_min": 20.78, + "peak_torch_allocated_mib": 1918.5, + "peak_torch_reserved_mib": 2926.0, + "peak_nvidia_smi_mib": 7193, + "mean_gpu_util_pct": 79.8, + "exit_code": 0, + "error": null + }, + { + "stage": "prosody_flow", + "module": "lua_nova_v1.training.prosody_flow", + "args": [ + "--train", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\train.jsonl", + "--validation", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\validation.jsonl", + "--init-stage1", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\stage1_p2\\inference.pt", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\prosody_flow", + "--steps", + "12000", + "--batch-frames", + "9000", + "--max-batch", + "32", + "--learning-rate", + "2e-4", + "--warmup", + "600", + "--eval-every", + "2000", + "--save-every", + "3000", + "--sample-every", + "3000", + "--max-seconds", + "7200", + "--device", + "cuda" + ], + "started_utc": "2026-11-25T07:33:18.323944+00:00", + "ended_utc": "2026-11-25T07:52:28.338529+00:00", + "duration_sec": 1150.03, + "duration_min": 19.17, + "peak_torch_allocated_mib": 1007.1, + "peak_torch_reserved_mib": 1136.0, + "peak_nvidia_smi_mib": 3193, + "mean_gpu_util_pct": 51.9, + "exit_code": 0, + "error": null + }, + { + "stage": "cfm_v5", + "module": "lua_nova_v1.training.cfm", + "args": [ + "--train", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\train.jsonl", + "--validation", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\validation.jsonl", + "--init-cfm", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\prosody_flow\\inference_prosody_flow.pt", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\cfm_v5", + "--steps", + "25000", + "--batch-frames", + "6000", + "--max-batch", + "24", + "--lr", + "3e-4", + "--min-lr", + "1.5e-5", + "--warmup", + "500", + "--save-every", + "2500", + "--val-every", + "1000", + "--device", + "cuda" + ], + "started_utc": "2026-11-25T07:52:50.686767+00:00", + "ended_utc": "2026-11-25T08:35:40.020895+00:00", + "duration_sec": 2569.39, + "duration_min": 42.82, + "peak_torch_allocated_mib": 1580.5, + "peak_torch_reserved_mib": 1780.0, + "peak_nvidia_smi_mib": 6295, + "mean_gpu_util_pct": 68.2, + "exit_code": 0, + "error": null + }, + { + "stage": "cfm_e2e_p2", + "module": "lua_nova_v1.training.cfm_e2e", + "args": [ + "--train", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\train.jsonl", + "--validation", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\validation.jsonl", + "--init-v5", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\cfm_e2e\\inference_v5_e2e_step-001000.pt", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\cfm_e2e_p2", + "--steps", + "1000", + "--save-steps", + "500", + "1000", + "--batch-size", + "4", + "--grad-accum", + "3", + "--crop-frames", + "40", + "--lr", + "2.52e-5", + "--min-lr", + "4e-6", + "--warmup", + "20", + "--device", + "cuda" + ], + "started_utc": "2026-11-25T21:27:21.347087+00:00", + "ended_utc": "2026-11-25T21:50:32.139198+00:00", + "duration_sec": 1390.79, + "duration_min": 23.18, + "peak_torch_allocated_mib": 4498.1, + "peak_torch_reserved_mib": 4884.0, + "peak_nvidia_smi_mib": 6715, + "mean_gpu_util_pct": 54.2, + "exit_code": 0, + "error": null + }, + { + "stage": "bigvgan_optB", + "module": "lua_nova_v1.training.vocoder_ft", + "args": [ + "--train", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\train.jsonl", + "--validation", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\validation.jsonl", + "--cfm-ckpt", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\cfm_e2e_p2\\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", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\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" + ], + "started_utc": "2026-11-26T00:05:43.300025+00:00", + "ended_utc": "2026-11-26T00:26:22.987230+00:00", + "duration_sec": 1239.69, + "duration_min": 20.66, + "peak_torch_allocated_mib": 6452.9, + "peak_torch_reserved_mib": 6744.0, + "peak_nvidia_smi_mib": 8534, + "mean_gpu_util_pct": 91.3, + "exit_code": 0, + "error": null + }, + { + "stage": "distill_fast2", + "module": "lua_nova_v1.training.distill", + "args": [ + "--train", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\train.jsonl", + "--validation", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\data\\annotations\\validation.jsonl", + "--teacher", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\cfm_e2e_p2\\inference_v5_soup50.pt", + "--output", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\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", + "--device", + "cuda" + ], + "started_utc": "2026-11-26T00:26:28.028426+00:00", + "ended_utc": "2026-11-26T00:39:03.211479+00:00", + "duration_sec": 755.18, + "duration_min": 12.59, + "peak_torch_allocated_mib": 2208.2, + "peak_torch_reserved_mib": 2484.0, + "peak_nvidia_smi_mib": 4141, + "mean_gpu_util_pct": 85.8, + "exit_code": 0, + "error": null + }, + { + "stage": "onnx_export", + "module": "lua_nova_v1.export.onnx_export", + "args": [ + "--cfm", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\cfm_v5_fast2\\inference_v5_fast2_step-003000.pt", + "--vocoder", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\runs\\bigvgan_base_optB\\bigvgan_ft_step-002000.pt", + "--out-dir", + "C:\\dev\\AjudaEstudos\\experiments\\lua-nova-v1\\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" + ], + "started_utc": "2026-11-26T00:39:05.477108+00:00", + "ended_utc": "2026-11-26T00:39:16.798483+00:00", + "duration_sec": 11.32, + "duration_min": 0.19, + "peak_torch_allocated_mib": 0.0, + "peak_torch_reserved_mib": 0.0, + "peak_nvidia_smi_mib": 1141, + "mean_gpu_util_pct": 0.0, + "exit_code": 0, + "error": null + } + ], + "dataset_build": { + "splits": { + "train": { + "count": 8025, + "duration_sec": 32330.62, + "duration_hours": 8.9807, + "mean_utmos": 3.752, + "mean_cer": 0.00151 + }, + "validation": { + "count": 64, + "duration_sec": 258.62, + "duration_hours": 0.0718, + "mean_utmos": 3.757, + "mean_cer": 0.00103 + }, + "test": { + "count": 64, + "duration_sec": 258.56, + "duration_hours": 0.0718, + "mean_utmos": 3.736, + "mean_cer": 0.00138 + } + }, + "rejected": { + "low_utmos": 2676, + "cer": 87, + "lang": 0, + "duration": 0, + "dup": 0, + "phonemize": 0, + "audio": 0 + }, + "unknown_phones_total": 0, + "duration_sec": 204.95 + } +} \ No newline at end of file diff --git a/onnx/bigvgan_base_ft.onnx b/onnx/bigvgan_base_ft.onnx new file mode 100644 index 0000000000000000000000000000000000000000..24ededf53f1c6741767827e8d047517ca7ba9d99 --- /dev/null +++ b/onnx/bigvgan_base_ft.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b333bfcab25558df0a2dbacecabc1c8f8580cae68983cda5aba9fe3d9dcbdee8 +size 57358067 diff --git a/onnx/cfm_v5_fast2.meta.json b/onnx/cfm_v5_fast2.meta.json new file mode 100644 index 0000000000000000000000000000000000000000..ec544bd83935b5a162a846e7ebc19e4d0e44e019 --- /dev/null +++ b/onnx/cfm_v5_fast2.meta.json @@ -0,0 +1,246 @@ +{ + "sample_rate": 24000, + "hop": 256, + "n_mels": 100, + "max_tokens": 512, + "speakers": [ + "F1" + ], + "n_steps": 2, + "solver": "euler", + "sway_coef": 0.0, + "temperature": 0.35, + "cfg_scale": 1.0, + "seed": 0, + "frontend": { + "frontend_version": 3, + "voice": "pt-br", + "separator": "_", + "symbols": [ + "", + "", + "", + "", + "", + ",", + ".", + "?", + "!", + ";", + ":", + "\"", + "'", + "(", + ")", + "-", + "—", + "…", + "p", + "b", + "t", + "d", + "k", + "ɡ", + "f", + "v", + "θ", + "ð", + "s", + "z", + "ʃ", + "ʒ", + "h", + "x", + "ɣ", + "m", + "n", + "ɲ", + "ŋ", + "l", + "ʎ", + "ɾ", + "r", + "ʁ", + "j", + "w", + "tʃ", + "dʒ", + "ts", + "a", + "ɐ", + "æ", + "e", + "ɛ", + "ə", + "i", + "ɪ", + "y", + "o", + "ɔ", + "u", + "ʊ", + "aː", + "eː", + "iː", + "oː", + "uː", + "ɐ̃", + "ã", + "ẽ", + "ĩ", + "õ", + "ũ", + "ɐ̃ʊ̃", + "aɪ", + "aʊ", + "eɪ", + "eʊ", + "ɛɪ", + "ɛʊ", + "iʊ", + "oɪ", + "oʊ", + "ɔɪ", + "uɪ" + ], + "fallback": { + "aɪə": [ + "aɪ", + "ə" + ], + "aʊɚ": [ + "aʊ", + "ə", + "ɾ" + ], + "dz": [ + "d", + "z" + ], + "g": [ + "ɡ" + ], + "iə": [ + "i", + "ə" + ], + "j̃": [ + "j" + ], + "l̩": [ + "l" + ], + "m̩": [ + "m" + ], + "n̩": [ + "n" + ], + "w̃": [ + "w" + ], + "yː": [ + "y" + ], + "ã": [ + "ɐ̃" + ], + "ç": [ + "ʃ" + ], + "õ": [ + "õ" + ], + "ø": [ + "e" + ], + "øː": [ + "eː" + ], + "ĩ": [ + "ĩ" + ], + "œ": [ + "ɛ" + ], + "ũ": [ + "ũ" + ], + "ɑ": [ + "a" + ], + "ɑː": [ + "aː" + ], + "ɑ̃": [ + "ɐ̃" + ], + "ɒ": [ + "ɔ" + ], + "ɔː": [ + "ɔ" + ], + "ɔ̃": [ + "õ" + ], + "əl": [ + "ə", + "l" + ], + "əʊ": [ + "oʊ" + ], + "ɚ": [ + "ə", + "ɾ" + ], + "ɛː": [ + "ɛ" + ], + "ɛ̃": [ + "ẽ" + ], + "ɜ": [ + "ɛ" + ], + "ɜː": [ + "ɛ" + ], + "ɪː": [ + "iː" + ], + "ɫ": [ + "l" + ], + "ɬ": [ + "l" + ], + "ɹ": [ + "ɾ" + ], + "ɻ": [ + "ɾ" + ], + "ʊː": [ + "uː" + ], + "ʌ": [ + "ɐ" + ], + "ʔ": [ + "h" + ], + "β": [ + "v" + ], + "ᵻ": [ + "i" + ], + "ẽ": [ + "ẽ" + ] + }, + "fingerprint": "d39277dad6f0a5ab5723c74d3ea86752cbee9e03aace2e379757b507811751b3" + } +} diff --git a/onnx/cfm_v5_fast2.onnx b/onnx/cfm_v5_fast2.onnx new file mode 100644 index 0000000000000000000000000000000000000000..6c9ab8e5eafc51af18a11bb12b2bc264bcbab2f5 --- /dev/null +++ b/onnx/cfm_v5_fast2.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98927efb97d52d592b44975d13ba8fbfed03b8636d1f8eefd3364dd7b82eec66 +size 90485191 diff --git a/samples/stress_cot_00.wav b/samples/stress_cot_00.wav new file mode 100644 index 0000000000000000000000000000000000000000..6d8ab0e6a0dd13c6c92c33e0d1c7dfc55e96ef90 --- /dev/null +++ b/samples/stress_cot_00.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:336c9cee478396788d0f52f134710a678affaf1b61cbe7c89fe9e180abe618cc +size 183852 diff --git a/samples/stress_emo_00.wav b/samples/stress_emo_00.wav new file mode 100644 index 0000000000000000000000000000000000000000..a3f5bc0d7aa279f9f57a2effa59bcf5c23b79640 --- /dev/null +++ b/samples/stress_emo_00.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed46f55cf4be9c118b1c376b0a5fcdb7e6ac4bbcc05ce10e098193ad771d0f54 +size 228396 diff --git a/samples/stress_est_00.wav b/samples/stress_est_00.wav new file mode 100644 index 0000000000000000000000000000000000000000..4ff659007712f89ce8dd22ca6034adbd4b332416 --- /dev/null +++ b/samples/stress_est_00.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd4af4f2b96c9e38eba0654b6a9545ec8535310a2732a71cd3e5d64992ea9f01 +size 250924 diff --git a/samples/test_01_gen.wav b/samples/test_01_gen.wav new file mode 100644 index 0000000000000000000000000000000000000000..d6c002d0932eff258db0c263920265b73ea742fe --- /dev/null +++ b/samples/test_01_gen.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:221864a4c93e7ecbe59de88e467f25e63dc87c2a34065ddc0f7f0ebe76d1f1ef +size 178732 diff --git a/samples/test_01_ref.wav b/samples/test_01_ref.wav new file mode 100644 index 0000000000000000000000000000000000000000..1963b71169f6ad38a08d23f4e69f81914311b36c --- /dev/null +++ b/samples/test_01_ref.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b941d9d5d4b69bb883e101d6a082abc1474717fa63990187135a1b9d2324a95 +size 161324 diff --git a/samples/test_02_gen.wav b/samples/test_02_gen.wav new file mode 100644 index 0000000000000000000000000000000000000000..0e734921c1cd4f9f67a8f00adcebd1205d2de805 --- /dev/null +++ b/samples/test_02_gen.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13344448ca5403e4629a3a1ad120e166a59f46699c8f0655aa7ed2556b781814 +size 183852 diff --git a/samples/test_02_ref.wav b/samples/test_02_ref.wav new file mode 100644 index 0000000000000000000000000000000000000000..54e0ae06a8c9ad027ff3b994d7678483b908d1f4 --- /dev/null +++ b/samples/test_02_ref.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a511a67f6a08cf89a9f982e9800bd235202c432edf63df4be4ff2ef5527ee704 +size 169004 diff --git a/samples/test_03_gen.wav b/samples/test_03_gen.wav new file mode 100644 index 0000000000000000000000000000000000000000..93186e391605e584e91c03d379cbb33f04e3b4df --- /dev/null +++ b/samples/test_03_gen.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02db591a1bf67a254efb523fca2ff068178b2f2e9ca0fb11d4ef5ca16f517541 +size 167468 diff --git a/samples/test_03_ref.wav b/samples/test_03_ref.wav new file mode 100644 index 0000000000000000000000000000000000000000..a3baa74a13193a38c928b358d0bcbf0fcefe40e0 --- /dev/null +++ b/samples/test_03_ref.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f0efb0edaa6857f3bbea7e6236fee6d12fc1ec0582024a1582f358bed9d39cc +size 169004 diff --git a/scripts/build_dataset.py b/scripts/build_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..14cc7f931c6a71273fcbed3149ae150d7a49dec7 --- /dev/null +++ b/scripts/build_dataset.py @@ -0,0 +1,228 @@ +import io +import json +import os +import sys +import time +from concurrent.futures import ProcessPoolExecutor, as_completed + +import numpy as np +import pyarrow as pa +import pyarrow.parquet as pq +import soundfile as sf +from scipy.signal import resample_poly + +RELEASED_SRC = r"C:\dev\AjudaEstudos\released\lua-nova-v1\src" +if RELEASED_SRC not in sys.path: + sys.path.insert(0, RELEASED_SRC) + +from lua_nova_v1.text.phonemizer import phonemize # noqa: E402 + +DATASET_DIR = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\hf_dataset\data" +OUT_DIR = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\data\source" +TIMINGS_PATH = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\timings.json" + +TARGET_SR = 24000 +HOP = 256 +MIN_SAMPLES = 32 * HOP + + +def _process_row(item: tuple) -> tuple: + uid, text, norm_text, flac_bytes, dur, utmos, cer, lp = item + try: + ph = phonemize(text) + unk_count = len(ph.unknown) + except Exception: + return ("phonemize", uid) + + wav, sr = sf.read(io.BytesIO(flac_bytes), dtype="float32") + if wav.ndim > 1: + wav = np.mean(wav, axis=-1).astype(np.float32) + if sr == 48000: + wav24 = resample_poly(wav, 1, 2).astype(np.float32) + elif sr == TARGET_SR: + wav24 = wav.astype(np.float32) + else: + return ("audio", uid) + + if not np.all(np.isfinite(wav24)) or len(wav24) < MIN_SAMPLES: + return ("audio", uid) + peak = float(np.max(np.abs(wav24))) + if peak < 1e-4: + return ("audio", uid) + if peak > 0.99: + wav24 = (wav24 * (0.99 / peak)).astype(np.float32) + rms = float(np.sqrt(np.mean(wav24 ** 2))) + if rms < 1e-4: + return ("audio", uid) + + buf = io.BytesIO() + sf.write(buf, wav24, TARGET_SR, format="WAV", subtype="PCM_16") + wav_bytes = buf.getvalue() + return ("ok", unk_count, (uid, text, norm_text, wav_bytes, float(len(wav24) / TARGET_SR), utmos, cer, lp)) + + +def main() -> None: + t0 = time.perf_counter() + os.makedirs(OUT_DIR, exist_ok=True) + test_wav_dir = os.path.join(OUT_DIR, "test_wavs") + os.makedirs(test_wav_dir, exist_ok=True) + + shards = sorted(f for f in os.listdir(DATASET_DIR) if f.endswith(".parquet")) + candidates = [] + seen_texts = set() + seen_ids = set() + rejected = {"low_utmos": 0, "cer": 0, "lang": 0, "duration": 0, "dup": 0, "phonemize": 0, "audio": 0} + unknown_phones_total = 0 + + for shard in shards: + table = pq.read_table( + os.path.join(DATASET_DIR, shard), + columns=["id", "text", "normalized_text", "audio", "duration", "utmos", "cer", "lang_prob_pt", "low_utmos"], + ) + d = table.to_pydict() + for i in range(len(d["id"])): + uid = str(d["id"][i]).strip() + text = (d["text"][i] or "").strip() + norm_text = (d["normalized_text"][i] or "").strip() + dur = float(d["duration"][i]) + utmos = float(d["utmos"][i]) + cer = float(d["cer"][i]) + lp = float(d["lang_prob_pt"][i]) + lu = bool(d["low_utmos"][i]) + + if lu: + rejected["low_utmos"] += 1 + continue + if cer > 0.08: + rejected["cer"] += 1 + continue + if lp < 0.8: + rejected["lang"] += 1 + continue + if not (0.6 <= dur <= 20.0): + rejected["duration"] += 1 + continue + key = text.casefold() + if not uid or not text or key in seen_texts or uid in seen_ids: + rejected["dup"] += 1 + continue + seen_texts.add(key) + seen_ids.add(uid) + candidates.append((uid, text, norm_text, d["audio"][i]["bytes"], dur, utmos, cer, lp)) + + print(f"Filter complete: {len(candidates)} candidates, rejected={rejected}", flush=True) + + t_res = time.perf_counter() + processed = [] + workers = max(1, min(12, os.cpu_count() or 4)) + done_cnt = 0 + with ProcessPoolExecutor(max_workers=workers) as pool: + futures = [pool.submit(_process_row, item) for item in candidates] + for fut in as_completed(futures): + done_cnt += 1 + res = fut.result() + if res[0] == "ok": + unknown_phones_total += res[1] + processed.append(res[2]) + else: + rejected[res[0]] += 1 + if done_cnt % 2000 == 0 or done_cnt == len(candidates): + print( + f"Processed {done_cnt}/{len(candidates)} in {time.perf_counter() - t_res:.1f}s " + f"(ok={len(processed)}, unk_phones={unknown_phones_total})", + flush=True, + ) + + processed.sort(key=lambda r: r[0]) + + # Deterministic duration-stratified split: 64 validation, 64 test, remainder train + by_dur = sorted(processed, key=lambda r: (r[4], r[0])) + val_idx = set(np.linspace(2, len(by_dur) - 3, 64, dtype=int).tolist()) + rem_after_val = [row for idx, row in enumerate(by_dur) if idx not in val_idx] + test_idx = set(np.linspace(2, len(rem_after_val) - 3, 64, dtype=int).tolist()) + + val_rows = [by_dur[idx] for idx in sorted(val_idx)] + test_rows = [rem_after_val[idx] for idx in sorted(test_idx)] + train_rows = [row for idx, row in enumerate(rem_after_val) if idx not in test_idx] + + t_sets = { + "train": {r[1].casefold() for r in train_rows}, + "validation": {r[1].casefold() for r in val_rows}, + "test": {r[1].casefold() for r in test_rows}, + } + assert len(t_sets["train"] & t_sets["validation"]) == 0 + assert len(t_sets["train"] & t_sets["test"]) == 0 + assert len(t_sets["validation"] & t_sets["test"]) == 0 + + audio_type = pa.struct([("bytes", pa.binary()), ("path", pa.string())]) + schema = pa.schema([ + ("id", pa.string()), + ("text", pa.string()), + ("normalized_text", pa.string()), + ("voice_id", pa.string()), + ("duration_24k", pa.float32()), + ("utmos", pa.float32()), + ("cer", pa.float32()), + ("audio", audio_type), + ]) + + summary = {"splits": {}, "rejected": rejected, "unknown_phones_total": unknown_phones_total} + for split_name, rows in [("train", train_rows), ("validation", val_rows), ("test", test_rows)]: + out_path = os.path.join(OUT_DIR, f"{split_name}.parquet") + tbl = pa.table( + { + "id": [r[0] for r in rows], + "text": [r[1] for r in rows], + "normalized_text": [r[2] for r in rows], + "voice_id": ["F1"] * len(rows), + "duration_24k": [np.float32(r[4]) for r in rows], + "utmos": [np.float32(r[5]) for r in rows], + "cer": [np.float32(r[6]) for r in rows], + "audio": [{"bytes": r[3], "path": f"{r[0]}.wav"} for r in rows], + }, + schema=schema, + ) + pq.write_table(tbl, out_path, compression="zstd") + tot_s = sum(r[4] for r in rows) + summary["splits"][split_name] = { + "count": len(rows), + "duration_sec": round(tot_s, 2), + "duration_hours": round(tot_s / 3600.0, 4), + "mean_utmos": round(float(np.mean([r[5] for r in rows])), 3), + "mean_cer": round(float(np.mean([r[6] for r in rows])), 5), + } + print( + f"Wrote {split_name}.parquet: {len(rows)} rows, {tot_s/3600:.3f}h, utmos={summary['splits'][split_name]['mean_utmos']}", + flush=True, + ) + + test_meta = [] + for r in test_rows: + wav_path = os.path.join(test_wav_dir, f"{r[0]}.wav") + with open(wav_path, "wb") as fh: + fh.write(r[3]) + test_meta.append( + {"id": r[0], "text": r[1], "duration_24k": round(r[4], 3), "utmos": round(r[5], 3), "cer": round(r[6], 4)} + ) + with open(os.path.join(OUT_DIR, "test_metadata.json"), "w", encoding="utf-8") as fh: + json.dump(test_meta, fh, indent=2, ensure_ascii=False) + + elapsed = round(time.perf_counter() - t0, 2) + summary["duration_sec"] = elapsed + with open(os.path.join(OUT_DIR, "build_summary.json"), "w", encoding="utf-8") as fh: + json.dump(summary, fh, indent=2, ensure_ascii=False) + + if os.path.exists(TIMINGS_PATH): + with open(TIMINGS_PATH, "r", encoding="utf-8") as fh: + tdata = json.load(fh) + else: + tdata = {"stages": []} + tdata["dataset_build"] = summary + with open(TIMINGS_PATH, "w", encoding="utf-8") as fh: + json.dump(tdata, fh, indent=2, ensure_ascii=False) + + print(f"build_dataset finished cleanly in {elapsed}s", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/env.ps1 b/scripts/env.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..f1cdac7329b39c1fc8c46128198ea98b344e36cd --- /dev/null +++ b/scripts/env.ps1 @@ -0,0 +1,26 @@ +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent $PSScriptRoot +$repoRoot = Split-Path -Parent (Split-Path -Parent $root) + +$env:UV_CACHE_DIR = Join-Path $repoRoot ".cache\uv" +Remove-Item Env:\HF_HOME -ErrorAction SilentlyContinue +$env:HF_HUB_CACHE = Join-Path $root "hf_cache" +$env:HUGGINGFACE_HUB_CACHE = $env:HF_HUB_CACHE +$env:HF_XET_CACHE = Join-Path $root "hf_cache\xet" +$env:HF_ASSETS_CACHE = Join-Path $root "hf_cache\assets" +$env:HF_MODULES_CACHE = Join-Path $root "hf_cache\modules" +$env:HF_DATASETS_CACHE = Join-Path $root "hf_cache\datasets" +$env:TORCH_HOME = Join-Path $root "torch_cache" +$env:TORCHINDUCTOR_CACHE_DIR = Join-Path $root "torch_cache" +$env:TRITON_CACHE_DIR = Join-Path $root "triton_cache" +$env:TMP = Join-Path $root "tmp" +$env:TEMP = Join-Path $root "tmp" +$env:PYTHONUTF8 = "1" +$env:PYTHONIOENCODING = "utf-8" +$env:PYTHONUNBUFFERED = "1" + +foreach ($d in @($env:HF_HUB_CACHE, $env:HF_XET_CACHE, $env:TORCH_HOME, $env:TMP)) { + if (-not (Test-Path $d)) { + New-Item -ItemType Directory -Force -Path $d | Out-Null + } +} diff --git a/scripts/eval_score.py b/scripts/eval_score.py new file mode 100644 index 0000000000000000000000000000000000000000..903a168b78f1ed14cba3c0a9bbc6b63aad572c43 --- /dev/null +++ b/scripts/eval_score.py @@ -0,0 +1,74 @@ +"""Score Lua Nova V1 eval WAVs with tts-eval judges (UTMOS22, SCOREQ, DNSMOS, Whisper WER/CER, ECAPA speaker sim). + +Run with experiments/tts-eval/.venv python after sourcing tts-eval/scripts/env.ps1. +Speaker similarity uses a centroid built from the LuaNovaDataset test references (new voice), +not the tts-eval F1 anchor. +""" +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, r"C:\dev\AjudaEstudos\experiments\tts-eval\src") +from tts_eval.classifiers import ClassifierSuite # noqa: E402 +from tts_eval.env_setup import load_audio_dual_rate, split_windows # noqa: E402 + +EXP = Path(__file__).resolve().parents[1] +EVAL = EXP / "eval" +SUITE = Path(r"C:\dev\AjudaEstudos\experiments\tts-eval\suite\ptbr_eval_v1.json") + + +def texts() -> dict[str, dict[str, str]]: + test = {} + for line in (EXP / "data/annotations/test.jsonl").read_text(encoding="utf-8").splitlines(): + if line.strip(): + r = json.loads(line) + test[r["id"]] = r["text"] + suite = json.loads(SUITE.read_text(encoding="utf-8")) + return {"test": test, "stress_ptbr": {r["id"]: r["text"] for r in suite["stress_ptbr"]}} + + +def main() -> None: + clf = ClassifierSuite() + txt = texts() + ref_dir = EVAL / "reference" / "test" + embs = [clf.spk.embed(load_audio_dual_rate(p)[2]) for p in sorted(ref_dir.glob("*.wav"))] + centroid = np.mean(np.stack(embs), axis=0) + + results: dict = {} + systems = ["reference"] + [d.name for d in sorted(EVAL.iterdir()) if d.is_dir() and d.name != "reference"] + for system in systems: + for split, tmap in txt.items(): + d = EVAL / system / split + if not d.exists(): + continue + rows = [] + for wid, text in tmap.items(): + p = d / f"{wid}.wav" + if not p.exists(): + continue + _, _, w16 = load_audio_dual_rate(p) + wins = split_windows(w16, win_sec=10.0, stride_sec=5.0) + r = {"id": wid} + r.update(clf.utmos.predict(wins)) + r.update(clf.scoreq.predict(wins)) + r.update(clf.dns.predict(w16)) + asr = clf.asr.predict(w16, text) + r.update({"wer": asr["wer"], "cer": asr["cer"], "asr_text": asr["asr_text"]}) + r["speaker_sim"] = float(clf.spk.cosine_to_centroid(w16, centroid)) + rows.append(r) + keys = ["utmos22_mean", "scoreq_mean", "dns_ovr", "wer", "cer", "speaker_sim"] + summary = {k: round(float(np.mean([x[k] for x in rows])), 4) for k in keys} + summary["n"] = len(rows) + results[f"{system}/{split}"] = {"summary": summary, "items": rows} + print(system, split, summary, flush=True) + + (EVAL / "scores.json").write_text(json.dumps(results, indent=2, ensure_ascii=False), encoding="utf-8") + print(json.dumps({k: v["summary"] for k, v in results.items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/eval_synth.py b/scripts/eval_synth.py new file mode 100644 index 0000000000000000000000000000000000000000..be3067a3fe4cac75200e7aaaeeed3bf9d56b1545 --- /dev/null +++ b/scripts/eval_synth.py @@ -0,0 +1,136 @@ +"""Synthesize evaluation sets and benchmark latency for Lua Nova V1 (LuaNovaDataset run). + +Run with experiments/tiny-voca-vocos/.venv python after sourcing scripts/env.ps1. +Outputs: + eval//test/.wav (57 held-out LuaNovaDataset test sentences) + eval//stress_ptbr/.wav (36 tts-eval stress sentences) + eval/reference/test/.wav (ground-truth 24 kHz recordings) + eval/latency.json +""" +from __future__ import annotations + +import io +import json +import sys +import time +from pathlib import Path + +import numpy as np +import pyarrow.parquet as pq +import soundfile as sf +import torch + +EXP = Path(__file__).resolve().parents[1] +sys.path.insert(0, r"C:\dev\AjudaEstudos\released\lua-nova-v1\src") +from lua_nova_v1 import OnnxSynthesizer, Synthesizer # noqa: E402 + +RUNS = EXP / "runs" +EVAL = EXP / "eval" +SUITE = Path(r"C:\dev\AjudaEstudos\experiments\tts-eval\suite\ptbr_eval_v1.json") +VOC = RUNS / "bigvgan_base_optB" / "bigvgan_ft_step-002000.pt" +SYSTEMS = { + # name: (cfm checkpoint, kwargs) + "fast2": (RUNS / "cfm_v5_fast2" / "inference_v5_fast2_step-003000.pt", + dict(n_steps=2, solver="euler", sway_coef=0.0, temperature=0.35)), + "soup50_8p": (RUNS / "cfm_e2e_p2" / "inference_v5_soup50.pt", + dict(n_steps=8, solver="midpoint", sway_coef=-0.5, temperature=0.35)), +} +LAT_TEXTS = [ + "Olá! Tudo bem com você? Hoje vamos testar a síntese de voz em português.", + "O relatório foi entregue às 14h30, e a reunião ficou para amanhã de manhã.", + "Você tem certeza de que o modelo já fala perguntas com naturalidade?", + "Precisamos comprar pão, leite, café e frutas antes de voltar para casa.", + "A destilação reduziu a geração para apenas dois passos, mantendo a qualidade.", +] + + +def load_sets() -> dict[str, list[dict]]: + test_ids = [json.loads(l)["id"] for l in (EXP / "data/annotations/test.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()] + tbl = pq.read_table(EXP / "data/source/test.parquet").to_pylist() + by_id = {r["id"]: r for r in tbl} + ref_dir = EVAL / "reference" / "test" + ref_dir.mkdir(parents=True, exist_ok=True) + test = [] + for i in test_ids: + r = by_id[i] + wav, sr = sf.read(io.BytesIO(r["audio"]["bytes"]), dtype="float32") + p = ref_dir / f"{i}.wav" + if not p.exists(): + sf.write(p, wav, sr, subtype="PCM_16") + test.append({"id": i, "text": r["text"]}) + suite = json.loads(SUITE.read_text(encoding="utf-8")) + stress = [{"id": r["id"], "text": r["text"]} for r in suite["stress_ptbr"]] + return {"test": test, "stress_ptbr": stress} + + +def synth_sets(sets: dict[str, list[dict]]) -> None: + for name, (ckpt, kw) in SYSTEMS.items(): + synth = Synthesizer.from_checkpoints(ckpt, VOC, device="cuda") + for split, rows in sets.items(): + out = EVAL / name / split + out.mkdir(parents=True, exist_ok=True) + for r in rows: + wav = synth.speak(r["text"], seed=0, **kw) + synth.save_wav(out / f"{r['id']}.wav", wav) + print(f"synthesized {name}", flush=True) + del synth + torch.cuda.empty_cache() + + +def bench(fn, texts, sr=24000, stream=False): + fn(texts[0]) # warmup + lats, ttfas, audio = [], [], 0.0 + for t in texts: + t0 = time.perf_counter() + if stream: + first = None + n = 0 + for ch in fn(t): + if first is None: + first = time.perf_counter() - t0 + n += len(ch) + ttfas.append(first) + else: + n = len(fn(t)) + lats.append(time.perf_counter() - t0) + audio += n / sr + res = {"avg_latency_ms": round(1000 * float(np.mean(lats)), 1), + "rtf_speed_x": round(audio / float(np.sum(lats)), 2), + "audio_sec_total": round(audio, 2)} + if stream: + res["avg_ttfa_ms"] = round(1000 * float(np.mean(ttfas)), 1) + return res + + +def latency() -> dict: + torch.set_num_threads(6) + out = {"cpu_threads": 6, "texts": LAT_TEXTS} + for name, (ckpt, kw) in SYSTEMS.items(): + for dev in ("cuda", "cpu"): + s = Synthesizer.from_checkpoints(ckpt, VOC, device=dev) + if dev == "cuda": + torch.cuda.synchronize() + out[f"pytorch_{dev}_{name}"] = bench(lambda t: s.speak(t, **kw), LAT_TEXTS) + if name == "fast2" and dev == "cpu": + out["pytorch_cpu_fast2_stream24"] = bench(lambda t: s.speak_stream(t, chunk_frames=24, **kw), LAT_TEXTS, stream=True) + del s + print(f"latency {name} {dev} done", flush=True) + onnx_dir = RUNS / "onnx_v5" + ox = OnnxSynthesizer(onnx_dir / "cfm_v5_fast2.onnx", onnx_dir / "bigvgan_base_ft.onnx", threads=6) + out["onnx_cpu_fast2"] = bench(lambda t: ox.speak(t), LAT_TEXTS) + out["onnx_cpu_fast2_stream24"] = bench(lambda t: ox.speak_stream(t, chunk_frames=24), LAT_TEXTS, stream=True) + sizes = {p.name: round(p.stat().st_size / 2**20, 1) for p in onnx_dir.glob("*.onnx")} + out["onnx_sizes_mib"] = sizes + return out + + +def main() -> None: + sets = load_sets() + synth_sets(sets) + lat = latency() + (EVAL / "latency.json").write_text(json.dumps(lat, indent=2, ensure_ascii=False), encoding="utf-8") + print(json.dumps(lat, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/scripts/finish_pipeline.ps1 b/scripts/finish_pipeline.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..41434b148e0264d70987f6c5124a5242cf445e86 --- /dev/null +++ b/scripts/finish_pipeline.ps1 @@ -0,0 +1,65 @@ +# Finishes the Lua Nova V1 pipeline on oProfM/LuaNovaDataset: +# Option A E2E (continuation 1000->2000), soup50, Option B BigVGAN FT, distill 2-step, ONNX export. +. "$PSScriptRoot\env.ps1" +$ErrorActionPreference = "Continue" +$exp = Split-Path -Parent $PSScriptRoot +$py = "C:\dev\AjudaEstudos\experiments\tiny-voca-vocos\.venv\Scripts\python.exe" +$runner = Join-Path $PSScriptRoot "run_stage.py" +$src = "C:\dev\AjudaEstudos\released\lua-nova-v1\src" +$ann = Join-Path $exp "data\annotations" +$train = Join-Path $ann "train.jsonl" +$val = Join-Path $ann "validation.jsonl" +$runs = Join-Path $exp "runs" + +function Invoke-Stage([string]$stage, [string]$module, [string[]]$a) { + Write-Output "===== $stage ($(Get-Date -Format s))" + & $py $runner --stage $stage --module $module -- @a + if ($LASTEXITCODE -ne 0) { Write-Output "FAILED: $stage"; exit 1 } +} + +$e2e2 = Join-Path $runs "cfm_e2e_p2" +if (-not (Test-Path (Join-Path $e2e2 "inference_v5_e2e_step-001000.pt"))) { + Invoke-Stage "cfm_e2e_p2" "lua_nova_v1.training.cfm_e2e" @( + "--train", $train, "--validation", $val, + "--init-v5", (Join-Path $runs "cfm_e2e\inference_v5_e2e_step-001000.pt"), + "--output", $e2e2, "--steps", "1000", "--save-steps", "500", "1000", + "--batch-size", "4", "--grad-accum", "3", "--crop-frames", "40", + "--lr", "2.52e-5", "--min-lr", "4e-6", "--warmup", "20", "--device", "cuda") +} + +$soup = Join-Path $runs "cfm_e2e_p2\inference_v5_soup50.pt" +if (-not (Test-Path $soup)) { + Write-Output "===== soup50" + & $py -c "import sys; sys.path.insert(0, r'$src'); from lua_nova_v1.utils import soup_checkpoints; soup_checkpoints(r'$runs\cfm_v5\inference_v5_ema.pt', r'$e2e2\inference_v5_e2e_step-000500.pt', r'$soup', alpha=0.5)" + if ($LASTEXITCODE -ne 0) { Write-Output "FAILED: soup"; exit 1 } +} + +$voc = Join-Path $runs "bigvgan_base_optB" +if (-not (Test-Path (Join-Path $voc "bigvgan_ft_step-002000.pt"))) { + Invoke-Stage "bigvgan_optB" "lua_nova_v1.training.vocoder_ft" @( + "--train", $train, "--validation", $val, "--cfm-ckpt", $soup, + "--cfm-steps", "8", "--cfm-temp", "0.35", "--sway-coef", "-0.5", + "--model-id", "nvidia/bigvgan_base_24khz_100band", "--pretrained-disc", "--disc-warmup", "0", + "--output", $voc, "--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") +} + +$fast = Join-Path $runs "cfm_v5_fast2" +if (-not (Test-Path (Join-Path $fast "inference_v5_fast2_step-003000.pt"))) { + Invoke-Stage "distill_fast2" "lua_nova_v1.training.distill" @( + "--train", $train, "--validation", $val, "--teacher", $soup, "--output", $fast, + "--steps", "3000", "--teacher-steps", "8", "--teacher-sway", "-0.5", "--teacher-temp", "0.35", + "--student-steps", "2", "--lr", "1e-4", "--save-every", "3000", "--device", "cuda") +} + +Invoke-Stage "onnx_export" "lua_nova_v1.export.onnx_export" @( + "--cfm", (Join-Path $fast "inference_v5_fast2_step-003000.pt"), + "--vocoder", (Join-Path $voc "bigvgan_ft_step-002000.pt"), + "--out-dir", (Join-Path $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") + +Write-Output "===== PIPELINE DONE ($(Get-Date -Format s))" diff --git a/scripts/inspect_dataset.py b/scripts/inspect_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..36348c105348f6964c3b344f5547f0a3de78c099 --- /dev/null +++ b/scripts/inspect_dataset.py @@ -0,0 +1,144 @@ +import io +import os +import time + +import truststore + +truststore.inject_into_ssl() + +import numpy as np +import pyarrow.parquet as pq +import soundfile as sf +from huggingface_hub import snapshot_download + + +def main(): + ds_dir = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\hf_dataset" + t0 = time.perf_counter() + snapshot_download( + repo_id="oProfM/LuaNovaDataset", + repo_type="dataset", + local_dir=ds_dir, + allow_patterns=["README.md", "data/*.parquet"], + ) + dl_sec = time.perf_counter() - t0 + print(f"Download finished in {dl_sec:.1f}s") + + data_files = sorted( + f for f in os.listdir(os.path.join(ds_dir, "data")) if f.endswith(".parquet") + ) + print("Data shards:", len(data_files), data_files[0], "...", data_files[-1]) + + total = 0 + low_utmos_cnt = 0 + cer_le_008 = 0 + cer_le_005 = 0 + lang_ge_08 = 0 + clean_all = 0 + clean_strict = 0 + dur_all = 0.0 + dur_clean = 0.0 + dur_strict = 0.0 + diff_text_norm = [] + unique_texts = set() + unique_clean_texts = set() + digits_in_text = 0 + digits_in_norm = 0 + utmos_clean = [] + + for fn in data_files: + pf = pq.read_table( + os.path.join(ds_dir, "data", fn), + columns=[ + "id", + "text", + "normalized_text", + "duration", + "utmos", + "cer", + "lang_prob_pt", + "low_utmos", + ], + ) + d = pf.to_pydict() + n = len(d["id"]) + total += n + for i in range(n): + t = (d["text"][i] or "").strip() + nt = (d["normalized_text"][i] or "").strip() + dur = float(d["duration"][i]) + dur_all += dur + unique_texts.add(t) + if any(c.isdigit() for c in t): + digits_in_text += 1 + if any(c.isdigit() for c in nt): + digits_in_norm += 1 + if t != nt and len(diff_text_norm) < 10: + diff_text_norm.append((d["id"][i], t, nt)) + lu = bool(d["low_utmos"][i]) + cer = float(d["cer"][i]) + lp = float(d["lang_prob_pt"][i]) + utm = float(d["utmos"][i]) + if lu: + low_utmos_cnt += 1 + if cer <= 0.08: + cer_le_008 += 1 + if cer <= 0.05: + cer_le_005 += 1 + if lp >= 0.8: + lang_ge_08 += 1 + if not lu and 0.6 <= dur <= 20.0: + clean_all += 1 + dur_clean += dur + unique_clean_texts.add(t) + utmos_clean.append(utm) + if cer <= 0.08 and lp >= 0.8: + clean_strict += 1 + dur_strict += dur + + print(f"Total rows: {total}, total dur: {dur_all/3600:.2f}h, unique texts: {len(unique_texts)}") + print(f"Digits in text: {digits_in_text}, in normalized_text: {digits_in_norm}") + print(f"low_utmos True: {low_utmos_cnt}, cer<=0.08: {cer_le_008}, cer<=0.05: {cer_le_005}, lang_prob_pt>=0.8: {lang_ge_08}") + print(f"Clean (not low_utmos): {clean_all} rows, {dur_clean/3600:.2f}h, unique: {len(unique_clean_texts)}, mean utmos: {np.mean(utmos_clean):.3f}") + print(f"Strict (not low_utmos & cer<=0.08 & lang>=0.8): {clean_strict} rows, {dur_strict/3600:.2f}h") + print("Sample text != normalized_text count (capped 10):", len(diff_text_norm)) + for item in diff_text_norm[:5]: + print(" DIFF:", item) + + # Compare shard 0 data vs raw audio stats on 100 items + t_data = pq.read_table( + os.path.join(ds_dir, "data", "train-00000.parquet"), + columns=["id", "audio", "breath_removed_ms", "duration"], + ).to_pydict() + t_raw = pq.read_table( + os.path.join(ds_dir, "raw", "train-00000.parquet"), + columns=["id", "audio", "duration"], + ).to_pydict() + raw_by_id = {t_raw["id"][i]: t_raw["audio"][i] for i in range(len(t_raw["id"]))} + + srs = set() + peaks_d, peaks_r, rms_d, rms_r, silence_frac_d, silence_frac_r = [], [], [], [], [], [] + zero_rms_d = 0 + for i in range(100): + uid = t_data["id"][i] + yd, sr_d = sf.read(io.BytesIO(t_data["audio"][i]["bytes"]), dtype="float32") + yr, sr_r = sf.read(io.BytesIO(raw_by_id[uid]["bytes"]), dtype="float32") + srs.add((sr_d, sr_r, yd.ndim, yr.ndim)) + peaks_d.append(float(np.max(np.abs(yd)))) + peaks_r.append(float(np.max(np.abs(yr)))) + rd = float(np.sqrt(np.mean(yd ** 2))) + rr = float(np.sqrt(np.mean(yr ** 2))) + if rd < 1e-5: + zero_rms_d += 1 + rms_d.append(rd) + rms_r.append(rr) + silence_frac_d.append(float(np.mean(np.abs(yd) < 1e-4))) + silence_frac_r.append(float(np.mean(np.abs(yr) < 1e-4))) + + print("Sample rate/ndim pairs:", srs, "zero_rms_d:", zero_rms_d) + print(f"data mean peak={np.mean(peaks_d):.3f} max={np.max(peaks_d):.3f} mean_rms={np.mean(rms_d):.4f} silence_frac={np.mean(silence_frac_d):.3f}") + print(f"raw mean peak={np.mean(peaks_r):.3f} max={np.max(peaks_r):.3f} mean_rms={np.mean(rms_r):.4f} silence_frac={np.mean(silence_frac_r):.3f}") + + +if __name__ == "__main__": + main() diff --git a/scripts/run_stage.py b/scripts/run_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..81a00f3f857f5b7b3258fe0a1b5b22c764c64e2a --- /dev/null +++ b/scripts/run_stage.py @@ -0,0 +1,141 @@ +import argparse +import json +import os +import runpy +import subprocess +import sys +import threading +import time +from datetime import datetime, timezone + +import truststore + +truststore.inject_into_ssl() + +RELEASED_SRC = r"C:\dev\AjudaEstudos\released\lua-nova-v1\src" +TIMINGS_PATH = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\timings.json" + + +def _poll_nvidia_smi(stop_event: threading.Event, stats: dict) -> None: + while not stop_event.is_set(): + try: + out = subprocess.check_output( + ["nvidia-smi", "--query-gpu=memory.used,utilization.gpu", "--format=csv,noheader,nounits"], + text=True, + timeout=3, + ).strip() + if out: + first_line = out.splitlines()[0] + mem_s, util_s = [x.strip() for x in first_line.split(",")[:2]] + mem_mib = int(mem_s) + util = int(util_s) + stats["max_nvidia_smi_mib"] = max(stats["max_nvidia_smi_mib"], mem_mib) + stats["util_samples"].append(util) + except Exception: + pass + stop_event.wait(2.0) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Run a lua_nova_v1 stage and log timing + VRAM metrics.") + parser.add_argument("--stage", required=True, help="Stage identifier for timings.json") + parser.add_argument("--module", required=True, help="Python module path, e.g. lua_nova_v1.training.stage1") + parser.add_argument("module_args", nargs=argparse.REMAINDER, help="Arguments passed after -- to module") + args = parser.parse_args() + + mod_args = list(args.module_args) + if mod_args and mod_args[0] == "--": + mod_args = mod_args[1:] + + if RELEASED_SRC not in sys.path: + sys.path.insert(0, RELEASED_SRC) + + import torch + + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + + vram_stats = {"max_nvidia_smi_mib": 0, "util_samples": []} + stop_event = threading.Event() + poll_thread = threading.Thread(target=_poll_nvidia_smi, args=(stop_event, vram_stats), daemon=True) + poll_thread.start() + + started_iso = datetime.now(timezone.utc).isoformat() + t0 = time.perf_counter() + exit_code = 0 + error_msg = None + + old_argv = sys.argv + sys.argv = [args.module] + mod_args + try: + runpy.run_module(args.module, run_name="__main__") + except SystemExit as exc: + code = exc.code + exit_code = 0 if code in (None, 0) else int(code) if isinstance(code, int) else 1 + if exit_code != 0: + error_msg = f"SystemExit({code})" + except Exception as exc: + exit_code = 1 + error_msg = f"{type(exc).__name__}: {exc}" + raise + finally: + sys.argv = old_argv + elapsed_sec = time.perf_counter() - t0 + stop_event.set() + poll_thread.join(timeout=3.0) + ended_iso = datetime.now(timezone.utc).isoformat() + + peak_alloc_mib = ( + round(torch.cuda.max_memory_allocated() / (1024 * 1024), 1) + if torch.cuda.is_available() + else 0.0 + ) + peak_res_mib = ( + round(torch.cuda.max_memory_reserved() / (1024 * 1024), 1) + if torch.cuda.is_available() + else 0.0 + ) + mean_gpu_util = ( + round(sum(vram_stats["util_samples"]) / len(vram_stats["util_samples"]), 1) + if vram_stats["util_samples"] + else 0.0 + ) + + record = { + "stage": args.stage, + "module": args.module, + "args": mod_args, + "started_utc": started_iso, + "ended_utc": ended_iso, + "duration_sec": round(elapsed_sec, 2), + "duration_min": round(elapsed_sec / 60.0, 2), + "peak_torch_allocated_mib": peak_alloc_mib, + "peak_torch_reserved_mib": peak_res_mib, + "peak_nvidia_smi_mib": vram_stats["max_nvidia_smi_mib"], + "mean_gpu_util_pct": mean_gpu_util, + "exit_code": exit_code, + "error": error_msg, + } + + if os.path.exists(TIMINGS_PATH): + with open(TIMINGS_PATH, "r", encoding="utf-8") as fh: + data = json.load(fh) + else: + data = {"stages": []} + data["stages"].append(record) + with open(TIMINGS_PATH, "w", encoding="utf-8") as fh: + json.dump(data, fh, indent=2, ensure_ascii=False) + + print( + f"\n[run_stage] stage={args.stage} exit={exit_code} " + f"duration={elapsed_sec:.1f}s ({elapsed_sec/60:.2f}m) " + f"peak_torch_alloc={peak_alloc_mib}MiB peak_smi={vram_stats['max_nvidia_smi_mib']}MiB", + flush=True, + ) + + if exit_code != 0: + sys.exit(exit_code) + + +if __name__ == "__main__": + main()