Lua Nova V1 trained on oProfM/LuaNovaDataset: weights, ONNX, eval, code
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +9 -0
- README.md +196 -0
- checkpoints/bigvgan_base_optB_2k.pt +3 -0
- checkpoints/cfm_v5_fast2.pt +3 -0
- checkpoints/cfm_v5_soup50.pt +3 -0
- code/.gitignore +37 -0
- code/LICENSE +202 -0
- code/README.md +208 -0
- code/THIRD_PARTY_NOTICES.md +14 -0
- code/docs/ARCHITECTURE.md +38 -0
- code/docs/FINE_TUNING.md +139 -0
- code/docs/OPTIMIZATION.md +113 -0
- code/docs/TRAINING_FROM_SCRATCH.md +137 -0
- code/pyproject.toml +60 -0
- code/src/lua_nova_v1/__init__.py +26 -0
- code/src/lua_nova_v1/config.py +199 -0
- code/src/lua_nova_v1/data/__init__.py +15 -0
- code/src/lua_nova_v1/data/aligner.py +301 -0
- code/src/lua_nova_v1/data/annotate.py +324 -0
- code/src/lua_nova_v1/data/dataset.py +179 -0
- code/src/lua_nova_v1/data/journal.py +73 -0
- code/src/lua_nova_v1/data/prepare.py +212 -0
- code/src/lua_nova_v1/data/refine.py +152 -0
- code/src/lua_nova_v1/export/__init__.py +30 -0
- code/src/lua_nova_v1/export/onnx_export.py +526 -0
- code/src/lua_nova_v1/inference/__init__.py +7 -0
- code/src/lua_nova_v1/inference/cli.py +131 -0
- code/src/lua_nova_v1/inference/onnx_engine.py +170 -0
- code/src/lua_nova_v1/inference/streaming.py +96 -0
- code/src/lua_nova_v1/inference/synthesizer.py +209 -0
- code/src/lua_nova_v1/models/__init__.py +39 -0
- code/src/lua_nova_v1/models/bigvgan.py +135 -0
- code/src/lua_nova_v1/models/cfm.py +900 -0
- code/src/lua_nova_v1/models/frontend.py +474 -0
- code/src/lua_nova_v1/models/losses.py +130 -0
- code/src/lua_nova_v1/text/__init__.py +69 -0
- code/src/lua_nova_v1/text/normalizer.py +343 -0
- code/src/lua_nova_v1/text/phonemizer.py +347 -0
- code/src/lua_nova_v1/training/__init__.py +31 -0
- code/src/lua_nova_v1/training/cfm.py +269 -0
- code/src/lua_nova_v1/training/cfm_e2e.py +474 -0
- code/src/lua_nova_v1/training/common.py +315 -0
- code/src/lua_nova_v1/training/distill.py +376 -0
- code/src/lua_nova_v1/training/prosody_flow.py +548 -0
- code/src/lua_nova_v1/training/stage1.py +583 -0
- code/src/lua_nova_v1/training/vocoder_ft.py +464 -0
- code/src/lua_nova_v1/utils/__init__.py +31 -0
- code/src/lua_nova_v1/utils/audio.py +141 -0
- code/src/lua_nova_v1/utils/checkpoint.py +67 -0
- code/tests/test_model.py +109 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
samples/stress_cot_00.wav filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
samples/stress_emo_00.wav filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
samples/stress_est_00.wav filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
samples/test_01_gen.wav filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
samples/test_01_ref.wav filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
samples/test_02_gen.wav filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
samples/test_02_ref.wav filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
samples/test_03_gen.wav filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
samples/test_03_ref.wav filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,3 +1,199 @@
|
|
| 1 |
---
|
|
|
|
|
|
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
language:
|
| 3 |
+
- pt
|
| 4 |
license: apache-2.0
|
| 5 |
+
library_name: pytorch
|
| 6 |
+
pipeline_tag: text-to-speech
|
| 7 |
+
tags:
|
| 8 |
+
- text-to-speech
|
| 9 |
+
- tts
|
| 10 |
+
- brazilian-portuguese
|
| 11 |
+
- pt-br
|
| 12 |
+
- flow-matching
|
| 13 |
+
- bigvgan
|
| 14 |
+
- onnx
|
| 15 |
+
- single-speaker
|
| 16 |
+
datasets:
|
| 17 |
+
- oProfM/LuaNovaDataset
|
| 18 |
---
|
| 19 |
+
|
| 20 |
+
# Lua Nova V1 — voz LuaNovaDataset (PT-BR, 24 kHz)
|
| 21 |
+
|
| 22 |
+
Modelo de **texto para fala em português do Brasil** (uma voz feminina, 24 kHz), treinado do zero sobre o
|
| 23 |
+
dataset [`oProfM/LuaNovaDataset`](https://huggingface.co/datasets/oProfM/LuaNovaDataset) com a arquitetura
|
| 24 |
+
Lua Nova V1:
|
| 25 |
+
|
| 26 |
+
- front end fonético eSpeak-NG (85 símbolos) + normalizador de texto PT-BR (números, datas, moeda);
|
| 27 |
+
- encoder fonético + **DurationFlow / ProsodyFlow** generativos;
|
| 28 |
+
- decodificador acústico **OT-CFM v5** (Conditional Flow Matching) em espaço log-mel Slaney 100 bandas, com Sway Sampling;
|
| 29 |
+
- vocoder **BigVGAN-base** (`nvidia/bigvgan_base_24khz_100band`, MIT) com fine-tuning leve nesta voz;
|
| 30 |
+
- versão **destilada de 2 passos Euler** (recomendada) e export **ONNX** para CPU sem PyTorch.
|
| 31 |
+
|
| 32 |
+
> *Synthetic single-speaker Brazilian Portuguese female TTS trained from scratch on `oProfM/LuaNovaDataset`.
|
| 33 |
+
> The dataset voice is synthetic; no real person was recorded or cloned.*
|
| 34 |
+
|
| 35 |
+
## Arquivos
|
| 36 |
+
|
| 37 |
+
| Arquivo | O que é | Tamanho |
|
| 38 |
+
|---|---|---:|
|
| 39 |
+
| `checkpoints/cfm_v5_fast2.pt` | **Recomendado.** CFM destilado, 2 passos Euler | 83 MB |
|
| 40 |
+
| `checkpoints/cfm_v5_soup50.pt` | Professor: soup 50/50 de CFM v5 + Opção A (E2E), 8 passos Midpoint + Sway | 83 MB |
|
| 41 |
+
| `checkpoints/bigvgan_base_optB_2k.pt` | BigVGAN-base com fine-tuning (Opção B, 2.000 passos) | 54 MB |
|
| 42 |
+
| `onnx/cfm_v5_fast2.onnx` + `.meta.json` | Grafo ONNX (opset 17) do acústico, 2 passos | 86 MB |
|
| 43 |
+
| `onnx/bigvgan_base_ft.onnx` | Grafo ONNX do vocoder | 55 MB |
|
| 44 |
+
| `samples/` | Exemplos de áudio (referência × gerado) | |
|
| 45 |
+
| `eval/` | `scores.json`, `latency.json`, `timings.json` (todas as etapas, com args) | |
|
| 46 |
+
| `code/` | Snapshot do código `lua_nova_v1` usado no treino (Apache-2.0; BigVGAN em `third_party/`, MIT) | |
|
| 47 |
+
| `scripts/` | Scripts deste treino (montagem do dataset, runner com cronômetro/VRAM, pipeline final, avaliação) | |
|
| 48 |
+
|
| 49 |
+
## Uso rápido
|
| 50 |
+
|
| 51 |
+
Requer Python 3.11/3.12, [`uv`](https://docs.astral.sh/uv/) e `espeak-ng` no `PATH`.
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
git clone https://huggingface.co/oProfM/LuaNovaV1
|
| 55 |
+
cd LuaNovaV1/code
|
| 56 |
+
uv sync # + "uv sync --extra onnx" para ONNX Runtime
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
```python
|
| 60 |
+
from lua_nova_v1 import Synthesizer
|
| 61 |
+
|
| 62 |
+
synth = Synthesizer.from_checkpoints(
|
| 63 |
+
cfm_path="../checkpoints/cfm_v5_fast2.pt",
|
| 64 |
+
vocoder_path_or_id="../checkpoints/bigvgan_base_optB_2k.pt",
|
| 65 |
+
device="cpu", # ou "cuda"
|
| 66 |
+
)
|
| 67 |
+
wav = synth.speak("Olá! Dia 22/03 às 14h30 custou R$ 45,90; quer testar?",
|
| 68 |
+
n_steps=2, solver="euler", sway_coef=0.0, temperature=0.35)
|
| 69 |
+
synth.save_wav("saida.wav", wav)
|
| 70 |
+
|
| 71 |
+
# streaming em chunks (~0,5 s até o primeiro áudio em CPU)
|
| 72 |
+
for chunk in synth.speak_stream("Este áudio sai em partes.", n_steps=2, solver="euler",
|
| 73 |
+
sway_coef=0.0, chunk_frames=24):
|
| 74 |
+
...
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
ONNX (CPU, sem PyTorch):
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
from lua_nova_v1 import OnnxSynthesizer
|
| 81 |
+
ox = OnnxSynthesizer("../onnx/cfm_v5_fast2.onnx", "../onnx/bigvgan_base_ft.onnx", threads=6)
|
| 82 |
+
ox.save_wav("onnx.wav", ox.speak("Oi! Tudo bem com você?"))
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
Para o professor de 8 passos use `cfm_v5_soup50.pt` com `n_steps=8, solver="midpoint", sway_coef=-0.5`.
|
| 86 |
+
|
| 87 |
+
## Dados
|
| 88 |
+
|
| 89 |
+
Fonte: `oProfM/LuaNovaDataset` (MIT, 10.916 áudios / 12,61 h, 48 kHz FLAC, uma voz feminina sintética).
|
| 90 |
+
|
| 91 |
+
Filtragem e preparo (`scripts/build_dataset.py`):
|
| 92 |
+
|
| 93 |
+
1. Removidos `low_utmos` (2.676) e `cer > 0,08` (87). Nenhuma rejeição por idioma, duração, duplicata ou fonemização.
|
| 94 |
+
2. Todos os textos validados no fonemizador eSpeak-NG (0 fonemas desconhecidos).
|
| 95 |
+
3. Reamostragem 48 kHz → 24 kHz mono WAV.
|
| 96 |
+
4. Splits: **train 8.025** (8,98 h), **validation 64**, **test 64** (UTMOS médio ≈ 3,75; CER médio ≈ 0,15 %).
|
| 97 |
+
5. Extração de features + alinhamento forçado CTC (wav2vec2) com 2 passes de refinamento de fronteiras.
|
| 98 |
+
Gate de anotação ajustado (`--max-weak-phone-fraction 0.35 --min-token-probability 0.45`) para preservar
|
| 99 |
+
frases curtas e perguntas → **7.548 enunciados de treino (8,58 h)**, 61 validação, **57 teste**
|
| 100 |
+
(96,95 % das transições fricativa→vogal dentro de 2 frames).
|
| 101 |
+
|
| 102 |
+
## Treinamento
|
| 103 |
+
|
| 104 |
+
Hardware (tudo local, uma única máquina):
|
| 105 |
+
|
| 106 |
+
- **GPU:** NVIDIA GeForce RTX 4070 12 GB (driver 621.24)
|
| 107 |
+
- **CPU:** AMD Ryzen 5 9600X (6 núcleos / 12 threads)
|
| 108 |
+
- **RAM:** 31 GB
|
| 109 |
+
- **SO:** Windows 11 Pro · Python 3.12.15 · PyTorch 2.14.1 + CUDA 13.0
|
| 110 |
+
|
| 111 |
+
| # | Etapa | Passos | Tempo (GPU) | Pico VRAM (nvidia-smi) | Observações |
|
| 112 |
+
|---|---|---:|---:|---:|---|
|
| 113 |
+
| 0a | Montagem do dataset (filtro, fonemização, 48→24 kHz) | — | 3,4 min | — | 12 workers CPU |
|
| 114 |
+
| 0b | Features acústicas (`prepare`) | — | 2,2 min | 2,3 GB | 100 % aceitos |
|
| 115 |
+
| 0c | Alinhamento CTC + refino ×2 (`annotate`) + re-gate | — | 9,1 min | 6,0 GB | |
|
| 116 |
+
| 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 |
|
| 117 |
+
| 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 |
|
| 118 |
+
| 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 |
|
| 119 |
+
| 3 | OT-CFM v5 (Slaney-100) | 25.000 | 42,8 min | 6,3 GB | `val_cfm = 0,1457` |
|
| 120 |
+
| 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 |
|
| 121 |
+
| 5 | Opção B: fine-tuning do BigVGAN-base (60 % mels previstos / 40 % GT) | 2.000 | 20,7 min⁴ | 8,5 GB | |
|
| 122 |
+
| 6 | Destilação 8p Midpoint → 2p Euler (só o `flow`) | 3.000 | 12,6 min | 4,1 GB | |
|
| 123 |
+
| 7 | Export ONNX + verificação de paridade | — | 0,2 min | — | CFM máx. |Δ| 2,7e-5 · BigVGAN máx. |Δ| 1,3e-7 |
|
| 124 |
+
|
| 125 |
+
**Tempo total efetivo do pipeline ≈ 3 h 40 min** de GPU (≈ 15 min de preparo de dados + ≈ 3 h 25 min de treino),
|
| 126 |
+
numa única RTX 4070. Somando execuções perdidas (OOM, reinício do servidor, uma queda de luz que interrompeu o
|
| 127 |
+
fine-tuning do vocoder, refeito do zero), o tempo de máquina foi um pouco maior. Os números exatos por execução,
|
| 128 |
+
com argumentos de linha de comando, estão em `eval/timings.json`.
|
| 129 |
+
|
| 130 |
+
¹ 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).
|
| 131 |
+
³ ≈ 29,8 min da 1ª parte (sem registro no `timings.json`, pelos timestamps dos arquivos) + 23,2 min da 2ª.
|
| 132 |
+
⁴ Execução final completa; uma execução anterior foi interrompida (queda de luz) e descartada.
|
| 133 |
+
|
| 134 |
+
Hiperparâmetros principais (receita `code/docs/TRAINING_FROM_SCRATCH.md`):
|
| 135 |
+
- E2E: `batch 4 × accum 3`, `crop 40`, 4 passos ODE com `sway -0.5`, `lr 4e-5 → 4e-6`. A 2ª parte foi
|
| 136 |
+
retomada do passo 1.000 com `lr 2,52e-5` (valor do cosseno original nesse ponto) e warmup de 20 passos.
|
| 137 |
+
- 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`.
|
| 138 |
+
- Destilação: professor `soup50` (8 passos Midpoint, sway -0,5, temp 0,35) → aluno 2 passos Euler, `lr 1e-4`, 3.000 passos.
|
| 139 |
+
|
| 140 |
+
## Avaliação
|
| 141 |
+
|
| 142 |
+
Juízes do `tts-eval` (UTMOS22-strong, SCOREQ, DNSMOS P.835, Whisper-small para WER/CER, ECAPA para similaridade
|
| 143 |
+
de locutor). A similaridade de locutor é o cosseno contra o centróide das **gravações de referência do split de teste**.
|
| 144 |
+
|
| 145 |
+
- **test:** 57 frases do split de teste do LuaNovaDataset, nunca vistas no treino, com referência real.
|
| 146 |
+
- **stress_ptbr:** 36 frases difíceis do `tts-eval` (perguntas, exclamações, frases longas, números, homógrafos,
|
| 147 |
+
estrangeirismos), só texto.
|
| 148 |
+
|
| 149 |
+
| Sistema | Conjunto | UTMOS22 ↑ | SCOREQ ↑ | DNSMOS OVR ↑ | WER ↓ | CER ↓ | Sim. locutor ↑ |
|
| 150 |
+
|---|---|---:|---:|---:|---:|---:|---:|
|
| 151 |
+
| Referência do dataset (24 kHz) | test (57) | 3,70 | 3,94 | 3,13 | 0,86 % | 0,19 % | 0,871 |
|
| 152 |
+
| **`fast2` (2p Euler) + BigVGAN FT** | test (57) | 3,69 | **4,03** | 3,26 | 1,57 % | 0,48 % | 0,885 |
|
| 153 |
+
| `soup50` (8p Midpoint) + BigVGAN FT | test (57) | **3,70** | 4,01 | 3,25 | 1,57 % | 0,48 % | 0,885 |
|
| 154 |
+
| **`fast2` (2p Euler) + BigVGAN FT** | stress (36) | **3,59** | **3,86** | **3,35** | 4,26 % | 1,11 % | 0,908 |
|
| 155 |
+
| `soup50` (8p Midpoint) + BigVGAN FT | stress (36) | 3,57 | 3,84 | 3,33 | 4,26 % | 1,11 % | 0,908 |
|
| 156 |
+
|
| 157 |
+
No conjunto de teste o modelo fica praticamente empatado com as gravações do dataset em UTMOS e acima em SCOREQ e
|
| 158 |
+
DNSMOS. A WER é pequena e concentrada em frases muito curtas: uma frase de 5 palavras sozinha pesa 0,4.
|
| 159 |
+
A destilação para 2 passos não perdeu qualidade mensurável em relação ao professor de 8 passos.
|
| 160 |
+
|
| 161 |
+
### Latência
|
| 162 |
+
|
| 163 |
+
5 frases PT-BR (≈ 28 s de áudio no total), aquecimento excluído, CPU com 6 threads.
|
| 164 |
+
|
| 165 |
+
| Modo | Latência média / frase | Velocidade (× tempo real) | 1º áudio (streaming) |
|
| 166 |
+
|---|---:|---:|---:|
|
| 167 |
+
| PyTorch GPU — `fast2` (2p) | 593 ms | 9,3× | — |
|
| 168 |
+
| PyTorch GPU — `soup50` (8p) | 640 ms | 8,6× | — |
|
| 169 |
+
| PyTorch CPU — `fast2` (2p) | 2.546 ms | 2,2× | — |
|
| 170 |
+
| PyTorch CPU — `soup50` (8p) | 3.033 ms | 1,9× | — |
|
| 171 |
+
| **PyTorch CPU — `fast2` streaming (`chunk=24`)** | 2.668 ms | 2,1× | **540 ms** |
|
| 172 |
+
| ONNX CPU — `fast2` | 3.535 ms | 1,6× | — |
|
| 173 |
+
| ONNX CPU — `fast2` streaming (`chunk=24`) | 5.029 ms | 1,1× | 627 ms |
|
| 174 |
+
|
| 175 |
+
## Exemplos
|
| 176 |
+
|
| 177 |
+
| | Texto | Referência | Lua Nova V1 (`fast2`) |
|
| 178 |
+
|---|---|---|---|
|
| 179 |
+
| 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) |
|
| 180 |
+
| 02 | Tem um cinema antigo que ainda exibe filmes clássicos. | [ref](./samples/test_02_ref.wav) | [gerado](./samples/test_02_gen.wav) |
|
| 181 |
+
| 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) |
|
| 182 |
+
| cot_00 | Amanhã de manhã eu vou pôr o pão na mesa para os irmãos. | — | [gerado](./samples/stress_cot_00.wav) |
|
| 183 |
+
| emo_00 | Que notícia maravilhosa receber a aprovação logo na primeira tentativa! | — | [gerado](./samples/stress_emo_00.wav) |
|
| 184 |
+
| est_00 | Instalei o script em Python no Windows e conectei o fone via Bluetooth sem erro. | — | [gerado](./samples/stress_est_00.wav) |
|
| 185 |
+
|
| 186 |
+
## Limitações
|
| 187 |
+
|
| 188 |
+
- Uma única voz (`F1`), só português do Brasil. Sem controle de emoção além da pontuação.
|
| 189 |
+
- A voz de origem é sintética, então o teto de qualidade é o do dataset (UTMOS ≈ 3,7).
|
| 190 |
+
- Frases muito curtas (1–3 palavras) têm WER relativa mais alta.
|
| 191 |
+
- `code/README.md` e `code/docs/` são a documentação do código e trazem benchmarks de outra voz/dataset. Os números
|
| 192 |
+
**deste** modelo são os desta página.
|
| 193 |
+
- Não use para se passar por pessoas reais nem para gerar conteúdo enganoso.
|
| 194 |
+
|
| 195 |
+
## Licenças
|
| 196 |
+
|
| 197 |
+
- Pesos e código deste repositório: **Apache-2.0**.
|
| 198 |
+
- `code/third_party/bigvgan` e o vocoder base `nvidia/bigvgan_base_24khz_100band`: **MIT** (NVIDIA).
|
| 199 |
+
- Dataset de treino `oProfM/LuaNovaDataset`: **MIT**.
|
checkpoints/bigvgan_base_optB_2k.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:db0fe65486dd98892b282bb5c07c02f18e43bdb946dd1a58134dcd7206ff53ea
|
| 3 |
+
size 56285259
|
checkpoints/cfm_v5_fast2.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:89431d10d153160fa54b41f3a6a2db7dbe917ea9ce959a5e4ad2a772b6406885
|
| 3 |
+
size 87242383
|
checkpoints/cfm_v5_soup50.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ce6297351ce0e8b5535e77f8be61b7f946aa07895c76cf4c1166442416df734b
|
| 3 |
+
size 87243013
|
code/.gitignore
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Model weights, binaries, tensors, and caches (publish checkpoints to Hugging Face, not Git)
|
| 2 |
+
*.pt
|
| 3 |
+
*.pth
|
| 4 |
+
*.onnx
|
| 5 |
+
*.onnx.data
|
| 6 |
+
*.safetensors
|
| 7 |
+
*.ckpt
|
| 8 |
+
*.bin
|
| 9 |
+
*.npy
|
| 10 |
+
*.npz
|
| 11 |
+
|
| 12 |
+
# Python & environments
|
| 13 |
+
.venv/
|
| 14 |
+
__pycache__/
|
| 15 |
+
*.py[cod]
|
| 16 |
+
*$py.class
|
| 17 |
+
build/
|
| 18 |
+
dist/
|
| 19 |
+
*.egg-info/
|
| 20 |
+
.pytest_cache/
|
| 21 |
+
.mypy_cache/
|
| 22 |
+
.ruff_cache/
|
| 23 |
+
|
| 24 |
+
# Local datasets, training runs, and caches (root-anchored so src packages are never ignored)
|
| 25 |
+
/data/
|
| 26 |
+
/runs/
|
| 27 |
+
/outputs/
|
| 28 |
+
/models/
|
| 29 |
+
/checkpoints/
|
| 30 |
+
/hf_home/
|
| 31 |
+
/torch_home/
|
| 32 |
+
/tmp/
|
| 33 |
+
/.cache/
|
| 34 |
+
|
| 35 |
+
# OS & editor artifacts
|
| 36 |
+
.DS_Store
|
| 37 |
+
Thumbs.db
|
code/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
code/README.md
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Lua Nova V1
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
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).
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## Highlights & Benchmarks (`tts-eval` v1.0.0)
|
| 10 |
+
|
| 11 |
+
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):
|
| 12 |
+
|
| 13 |
+
| System | Held-out (30) Pass | Held-out Comp ↑ | Nat ↑ | Anti-Rob ↑ | SCOREQ ↑ | UTMOS22 ↑ | Stress (36) Comp ↑ | Stress Anti-Rob ↑ | Stress WER ↓ | Stress CER Phon ↓ |
|
| 14 |
+
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
|
| 15 |
+
| Real Studio Recording (`24 kHz`) | 30/30 | 88.1 | 95.1 | 77.8 | 3.77 | 3.61 | — | — | — | — |
|
| 16 |
+
| `BigVGAN v1 Large` Copy-GT *(stock oracle)* | 30/30 | 82.7 | 88.4 | 63.8 | 3.59 | 3.42 | — | — | — | — |
|
| 17 |
+
| `BigVGAN-base` Copy-GT *(stock oracle)* | 30/30 | 78.8 | 84.1 | 53.9 | 3.51 | 3.28 | — | — | — | — |
|
| 18 |
+
| `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% |
|
| 19 |
+
| `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% |
|
| 20 |
+
| `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% |
|
| 21 |
+
| **`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%** |
|
| 22 |
+
| `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% |
|
| 23 |
+
|
| 24 |
+
### CPU, GPU & Streaming Latency (`v1.0.0` vs. `v1.1.0`)
|
| 25 |
+
|
| 26 |
+
Measured across 5 representative PT-BR sentences (`24.5 s` audio total, warmup excluded; 6 physical / 12 logical CPU cores + RTX 4070 GPU):
|
| 27 |
+
|
| 28 |
+
| Mode | Avg Latency / Sentence | Speed (RT ↑) | Streaming TTFA (avg) | Model Size |
|
| 29 |
+
|---|---:|---:|---:|---:|
|
| 30 |
+
| PyTorch CPU — `v1.0.0` Baseline (`8p` Sway Midpoint) | 3,213 ms | `1.53×` | 3,213 ms | 188.8 MB (`135.1 + 53.7`) |
|
| 31 |
+
| **PyTorch CPU — `v1.1.0` Distilled (`2p` Euler)** | **2,337 ms** | **`2.10×`** | 2,337 ms | **136.9 MB** (`83.2 + 53.7`) |
|
| 32 |
+
| **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`) |
|
| 33 |
+
| ONNX CPU (`6` threads) — `8p` Sway Midpoint | 4,223 ms | `1.16×` | 4,223 ms | 145.0 MB (`90.3 + 54.7`) |
|
| 34 |
+
| 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`) |
|
| 35 |
+
| **ONNX CPU (`6` threads) — Streaming (`2p` Euler, `chunk=24`)** | 5,166 ms | `0.95×` | **`554.9 ms`** | **141.0 MB** (`86.3 + 54.7`) |
|
| 36 |
+
| PyTorch GPU — `8p` -> **`2p` Euler** | 535 ms -> **437 ms** | `9.10×` -> **`11.13×`** | — | `192 MB` loaded / `319 MB` peak VRAM |
|
| 37 |
+
|
| 38 |
+
See [CPU & Latency Optimization Guide](./docs/OPTIMIZATION.md) for distillation training, split ONNX export, and chunked streaming details.
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
## Audio Comparison Samples
|
| 43 |
+
|
| 44 |
+
Reference 24 kHz studio recordings compared side-by-side against unconstrained `CFM v5 Option A+B + BigVGAN-base FT` synthesis from raw text:
|
| 45 |
+
|
| 46 |
+
| Sample | Text | Reference (`24 kHz`) | Synthesized (`Lua Nova V1`) |
|
| 47 |
+
|---|---|---|---|
|
| 48 |
+
| `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) |
|
| 49 |
+
| `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) |
|
| 50 |
+
| `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) |
|
| 51 |
+
|
| 52 |
+
---
|
| 53 |
+
|
| 54 |
+
## Installation
|
| 55 |
+
|
| 56 |
+
### Prerequisites
|
| 57 |
+
|
| 58 |
+
1. **Python 3.11 or 3.12** and [`uv`](https://docs.astral.sh/uv/).
|
| 59 |
+
2. **`espeak-ng`** available on `PATH` (used at runtime and alignment for PT-BR G2P, invoked only as an external subprocess):
|
| 60 |
+
- **Linux (Debian/Ubuntu):** `sudo apt-get install espeak-ng`
|
| 61 |
+
- **macOS:** `brew install espeak-ng`
|
| 62 |
+
- **Windows:** install [eSpeak NG](https://github.com/espeak-ng/espeak-ng/releases) and ensure `espeak-ng.exe` is in `PATH`.
|
| 63 |
+
|
| 64 |
+
### Install with `uv`
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
# Inference only
|
| 68 |
+
uv sync
|
| 69 |
+
|
| 70 |
+
# Inference + full training & forced alignment stack
|
| 71 |
+
uv sync --extra train
|
| 72 |
+
|
| 73 |
+
# Optional: ONNX tools
|
| 74 |
+
uv sync --extra onnx
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
> **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.
|
| 78 |
+
|
| 79 |
+
---
|
| 80 |
+
|
| 81 |
+
## Model Weights (Hugging Face)
|
| 82 |
+
|
| 83 |
+
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):
|
| 84 |
+
|
| 85 |
+
- **CFM checkpoints:**
|
| 86 |
+
- `cfm_v5_fast2.pt` *(recommended, `v1.1.0`)* — 2-step Euler distilled from `cfm_v5_soup50.pt` (`2.10× RT` CPU / `465 ms` TTFA)
|
| 87 |
+
- `cfm_v5_soup50.pt` *(baseline, `v1.0.0`)* — 8-step Sway Midpoint teacher (50/50 weight soup of `CFM v5` + `Option A` E2E)
|
| 88 |
+
- **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`)
|
| 89 |
+
|
| 90 |
+
You can also strip legacy `Vocos` buffers from a training checkpoint before uploading to Hugging Face:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
from lua_nova_v1.utils import strip_legacy_vocoder
|
| 94 |
+
strip_legacy_vocoder("runs/cfm_v5_e2e/inference_v5_soup50.pt", "release_weights/cfm_v5_soup50_fp16.pt", fp16=True)
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
---
|
| 98 |
+
|
| 99 |
+
## Quickstart
|
| 100 |
+
|
| 101 |
+
### CLI Inference
|
| 102 |
+
|
| 103 |
+
```bash
|
| 104 |
+
uv run lua-nova-speak \
|
| 105 |
+
--text "Olá! Dia 22/03 às 14h30 custou R$ 45,90; você prefere testar o modelo agora?" \
|
| 106 |
+
--out output.wav \
|
| 107 |
+
--cfm checkpoints/cfm_v5_soup50.pt \
|
| 108 |
+
--vocoder checkpoints/bigvgan_base_optB_2k.pt \
|
| 109 |
+
--device cpu
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
### Python API (PyTorch Streaming & 2-Step Fast Mode)
|
| 113 |
+
|
| 114 |
+
```python
|
| 115 |
+
import numpy as np
|
| 116 |
+
from lua_nova_v1 import Synthesizer
|
| 117 |
+
|
| 118 |
+
synth = Synthesizer.from_checkpoints(
|
| 119 |
+
cfm_path="checkpoints/cfm_v5_fast2.pt",
|
| 120 |
+
vocoder_path_or_id="checkpoints/bigvgan_base_optB_2k.pt",
|
| 121 |
+
device="cpu",
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
# Full utterance (2 Euler steps)
|
| 125 |
+
wav = synth.speak(
|
| 126 |
+
"Você tem certeza de que o modelo já fala perguntas com naturalidade?",
|
| 127 |
+
n_steps=2,
|
| 128 |
+
solver="euler",
|
| 129 |
+
sway_coef=0.0,
|
| 130 |
+
temperature=0.35,
|
| 131 |
+
)
|
| 132 |
+
synth.save_wav("output.wav", wav)
|
| 133 |
+
|
| 134 |
+
# Low-latency chunked streaming (TTFA ~465 ms on CPU)
|
| 135 |
+
chunks = list(
|
| 136 |
+
synth.speak_stream(
|
| 137 |
+
"Olá! Este áudio está sendo gerado em partes com transição suave.",
|
| 138 |
+
n_steps=2,
|
| 139 |
+
solver="euler",
|
| 140 |
+
sway_coef=0.0,
|
| 141 |
+
chunk_frames=24,
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
synth.save_wav("output_stream.wav", np.concatenate(chunks))
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
### ONNX Runtime CPU (PyTorch-free Deployment)
|
| 148 |
+
|
| 149 |
+
```bash
|
| 150 |
+
# Export split opset-17 ONNX graphs
|
| 151 |
+
uv run lua-nova-export-onnx \
|
| 152 |
+
--cfm checkpoints/cfm_v5_fast2.pt \
|
| 153 |
+
--vocoder checkpoints/bigvgan_base_optB_2k.pt \
|
| 154 |
+
--out-dir checkpoints/onnx \
|
| 155 |
+
--steps 2 --solver euler --sway-coef 0.0 --verify
|
| 156 |
+
|
| 157 |
+
# Synthesize directly with ONNX Runtime CPU + streaming
|
| 158 |
+
uv run lua-nova-speak \
|
| 159 |
+
--onnx-cfm checkpoints/onnx/cfm_v5.onnx \
|
| 160 |
+
--onnx-vocoder checkpoints/onnx/bigvgan_base_ft.onnx \
|
| 161 |
+
--text "Síntese em CPU via ONNX Runtime com streaming por chunks." \
|
| 162 |
+
--out output_onnx.wav --stream --chunk-frames 24
|
| 163 |
+
```
|
| 164 |
+
|
| 165 |
+
```python
|
| 166 |
+
from lua_nova_v1 import OnnxSynthesizer
|
| 167 |
+
|
| 168 |
+
ox = OnnxSynthesizer("checkpoints/onnx/cfm_v5.onnx", "checkpoints/onnx/bigvgan_base_ft.onnx")
|
| 169 |
+
wav = ox.speak("Oi! Tudo bem com você?")
|
| 170 |
+
ox.save_wav("onnx.wav", wav)
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
---
|
| 174 |
+
|
| 175 |
+
## Documentation & Guides
|
| 176 |
+
|
| 177 |
+
- [Architecture & Key Design Choices](./docs/ARCHITECTURE.md)
|
| 178 |
+
- [CPU & Latency Optimization Guide (Distillation, ONNX & Streaming)](./docs/OPTIMIZATION.md)
|
| 179 |
+
- [Fine-Tuning on a New Voice](./docs/FINE_TUNING.md)
|
| 180 |
+
- [Training From Scratch Guide](./docs/TRAINING_FROM_SCRATCH.md)
|
| 181 |
+
- [Third-Party Notices & Licenses](./THIRD_PARTY_NOTICES.md)
|
| 182 |
+
|
| 183 |
+
---
|
| 184 |
+
|
| 185 |
+
## Repository Layout
|
| 186 |
+
|
| 187 |
+
```text
|
| 188 |
+
lua-nova-v1/
|
| 189 |
+
├── assets/samples/ # Paired 24 kHz studio reference & generated audio examples
|
| 190 |
+
├── docs/ # Architecture, optimization, training, and fine-tuning guides
|
| 191 |
+
├── src/lua_nova_v1/
|
| 192 |
+
│ ├── config.py # ModelConfig & CFMConfig dataclasses
|
| 193 |
+
│ ├── text/ # PT-BR normalizer (numbers, currency, dates) & eSpeak G2P
|
| 194 |
+
│ ├── models/ # Front end, ProsodyFlow, OT-CFM v5 + Sway Sampling, BigVGAN wrapper
|
| 195 |
+
│ ├── data/ # Acoustic prep, wav2vec2 CTC forced aligner, Dataset & BucketSampler
|
| 196 |
+
│ ├── training/ # Stage 1, ProsodyFlow, CFM v5, Option A (E2E), Option B (Vocoder FT), Distill
|
| 197 |
+
│ ├── export/ # Split opset-17 ONNX exporters for CFM v5 and BigVGAN
|
| 198 |
+
│ ├── inference/ # PyTorch Synthesizer, OnnxSynthesizer, overlap-crossfade streaming, CLI
|
| 199 |
+
│ └── utils/ # RMS/fade/PCM16 post-processing, weight souping, checkpoint stripping
|
| 200 |
+
├── tests/ # Unit & end-to-end synthetic verification tests
|
| 201 |
+
└── third_party/bigvgan/ # MIT-licensed NVIDIA BigVGAN generator, losses & discriminators
|
| 202 |
+
```
|
| 203 |
+
|
| 204 |
+
---
|
| 205 |
+
|
| 206 |
+
## License
|
| 207 |
+
|
| 208 |
+
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).
|
code/THIRD_PARTY_NOTICES.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Third-Party Notices
|
| 2 |
+
|
| 3 |
+
This repository includes and builds upon the following permissively licensed open-source projects:
|
| 4 |
+
|
| 5 |
+
1. **tiny-voca** (Apache License 2.0)
|
| 6 |
+
- Upstream front end, alignment pipeline, prosody/acoustic backbone, and Source-Filter architecture.
|
| 7 |
+
- License: see [LICENSE](./LICENSE).
|
| 8 |
+
|
| 9 |
+
2. **NVIDIA BigVGAN** (MIT License)
|
| 10 |
+
- Files included under `third_party/bigvgan/` (`bigvgan.py`, `activations.py`, `env.py`, `utils.py`, `meldataset.py`, `discriminators.py`, `loss.py`, `alias_free_activation/`).
|
| 11 |
+
- License: see [third_party/bigvgan/LICENSE](./third_party/bigvgan/LICENSE).
|
| 12 |
+
|
| 13 |
+
3. **eSpeak NG** (GPL-3.0+, invoked strictly as an external subprocess binary at runtime)
|
| 14 |
+
- Phonetic G2P (`espeak-ng -v pt-br`) is executed as an external system command and is not bundled in this repository.
|
code/docs/ARCHITECTURE.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Architecture Overview
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
```text
|
| 6 |
+
Raw Text
|
| 7 |
+
└─▶ PT-BR Normalizer (numbers, currency, dates, ordinals, time, abbreviations)
|
| 8 |
+
└─▶ eSpeak-NG G2P (`pt-br`, 85-symbol inventory + primary/secondary lexical stress)
|
| 9 |
+
└─▶ 4-layer RoPE Text Encoder
|
| 10 |
+
├─▶ LinguisticContextAdapter (26 word/stress/clause geometry features)
|
| 11 |
+
├─▶ Duration Predictor + 4-step Generative DurationFlow
|
| 12 |
+
└─▶ Frame Expansion + 4-step Multiscale ProsodyFlow (F0, voicing, energy)
|
| 13 |
+
└─▶ 5-layer RoPE Acoustic Prior
|
| 14 |
+
└─▶ 8-layer FlowDecoder (OT-CFM, d=320, Sway Sampling s=-0.5)
|
| 15 |
+
└─▶ Slaney 100-Band Physical Log-Mel [24 kHz, hop=256]
|
| 16 |
+
└─▶ BigVGAN-base (MIT, gently adapted via Option B)
|
| 17 |
+
└─▶ 24 kHz PCM Waveform
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
## Core Components
|
| 21 |
+
|
| 22 |
+
### 1. Deterministic Text Normalizer & Unified G2P (`src/lua_nova_v1/text/`)
|
| 23 |
+
- **`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.
|
| 24 |
+
- **`phonemizer.py`:** Tokenizes `espeak-ng --ipa` output into a fixed 85-symbol vocabulary (`PHONES + PUNCTUATION + SPECIALS`) paired with a parallel stress tensor (`0 = unstressed`, `1 = primary`, `2 = secondary`). Explicit `<sp>` and punctuation tokens carry predicted silence pauses.
|
| 25 |
+
|
| 26 |
+
### 2. Generative Prosody & Context (`src/lua_nova_v1/models/cfm.py`)
|
| 27 |
+
- **`LinguisticContextAdapter`:** Computes 26 ONNX-safe utterance, word, stress-distance, and clause geometry features so questions (`?`), exclamations (`!`), and comma boundaries modulate intonation globally.
|
| 28 |
+
- **`DurationFlow`:** 4-step OT-CFM flow predictor over phoneme `log1p(frames)`, paired with a separate binary pause-presence head.
|
| 29 |
+
- **`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.
|
| 30 |
+
|
| 31 |
+
### 3. Slaney-100 OT-CFM Decoder (`FlowDecoder`)
|
| 32 |
+
- 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`).
|
| 33 |
+
- 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).
|
| 34 |
+
|
| 35 |
+
### 4. Artifact Elimination Strategy (Option A + Option B)
|
| 36 |
+
Why two gentle stages beat brute-force training:
|
| 37 |
+
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.
|
| 38 |
+
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.
|
code/docs/FINE_TUNING.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Fine-Tuning Guide (New PT-BR Speaker or Domain)
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Requirements
|
| 8 |
+
|
| 9 |
+
- **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`).
|
| 10 |
+
- **Audio Data:**
|
| 11 |
+
- **Minimum:** `30–60 minutes` of clean `24 kHz` mono speech (single speaker, quiet studio or denoised).
|
| 12 |
+
- **Recommended:** `2–4 hours` for maximum voice likeness and prosody stability.
|
| 13 |
+
- **Estimated Time (RTX 4070 class GPU):**
|
| 14 |
+
- Data preparation + CTC alignment: `~3–6 min` for 1h of audio
|
| 15 |
+
- Acoustic CFM adaptation (`10k–15k` steps): `~15–22 min`
|
| 16 |
+
- *(Optional)* Gentle BigVGAN-base Option B polish (`1k–2k` steps): `~8–15 min`
|
| 17 |
+
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
## 1. Prepare Your Dataset Manifest
|
| 21 |
+
|
| 22 |
+
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:
|
| 23 |
+
|
| 24 |
+
```json
|
| 25 |
+
{"id": "utt_0001", "text": "Olá, esta é uma frase de teste em português.", "voice_id": "F1", "audio": "wavs/utt_0001.wav"}
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
> 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$.
|
| 29 |
+
|
| 30 |
+
> **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.
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## 2. Extract Acoustic Features & Forced Alignments
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
# Step A: Acoustic feature extraction (wave, 80-mel, F0 pitch via Parselmouth, RMS energy)
|
| 38 |
+
uv run lua-nova-prepare --inputs data/raw/train.jsonl --split train --output data/features
|
| 39 |
+
uv run lua-nova-prepare --inputs data/raw/validation.jsonl --split validation --output data/features
|
| 40 |
+
|
| 41 |
+
# Step B: Forced alignment via pretrained wav2vec2 CTC espeak recognizer
|
| 42 |
+
uv run lua-nova-annotate \
|
| 43 |
+
--features data/features \
|
| 44 |
+
--output data/annotations \
|
| 45 |
+
--dataset-revision my-voice-v1 \
|
| 46 |
+
--device cuda \
|
| 47 |
+
--refine 2 --stage refined-2
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
> Both steps are resumable via `--resume`. Alignments check phoneme rate, vowel voicing, and silence pauses automatically, writing rejected outliers to `rejected.jsonl`.
|
| 51 |
+
|
| 52 |
+
---
|
| 53 |
+
|
| 54 |
+
## 3. Fine-Tune `LuaNovaCFM v5` on Your Voice
|
| 55 |
+
|
| 56 |
+
Start directly from the pretrained `cfm_v5_soup50.pt` checkpoint downloaded from Hugging Face:
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
uv run lua-nova-train-cfm \
|
| 60 |
+
--train data/annotations/train.jsonl \
|
| 61 |
+
--validation data/annotations/validation.jsonl \
|
| 62 |
+
--init-cfm checkpoints/cfm_v5_soup50.pt \
|
| 63 |
+
--no-freeze-frontend \
|
| 64 |
+
--output runs/my_voice_cfm \
|
| 65 |
+
--steps 12000 \
|
| 66 |
+
--lr 1.5e-4 --min-lr 1e-5 --warmup 300 \
|
| 67 |
+
--save-every 3000 --val-every 500 \
|
| 68 |
+
--device cuda
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
- Use `--no-freeze-frontend` when adapting timbre **plus** speaking cadence/pitch range to a brand-new speaker.
|
| 72 |
+
- Use `--freeze-frontend` if your voice has very few minutes (`< 45 min`) or matches existing speaking cadence closely and only needs acoustic timbre tuning.
|
| 73 |
+
|
| 74 |
+
*(Optional)* If your voice expresses notably different intonation patterns (questions, pauses, stress shifts), run a short ProsodyFlow stage first before `lua-nova-train-cfm`:
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
uv run lua-nova-train-prosody \
|
| 78 |
+
--train data/annotations/train.jsonl \
|
| 79 |
+
--validation data/annotations/validation.jsonl \
|
| 80 |
+
--init-cfm checkpoints/cfm_v5_soup50.pt \
|
| 81 |
+
--output runs/my_voice_prosody \
|
| 82 |
+
--steps 4000 --eval-every 1000 --save-every 2000 --device cuda
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
---
|
| 86 |
+
|
| 87 |
+
## 4. *(Optional)* Option A + Option B Final Polish
|
| 88 |
+
|
| 89 |
+
Once `runs/my_voice_cfm/inference_v5_ema.pt` converges, you can optionally remove subtle acoustic-vocoder mismatch:
|
| 90 |
+
|
| 91 |
+
1. **Option A (E2E through frozen BigVGAN + frozen NVIDIA MIT discriminators):**
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
uv run lua-nova-train-e2e \
|
| 95 |
+
--train data/annotations/train.jsonl \
|
| 96 |
+
--validation data/annotations/validation.jsonl \
|
| 97 |
+
--init-v5 runs/my_voice_cfm/inference_v5_ema.pt \
|
| 98 |
+
--output runs/my_voice_optA \
|
| 99 |
+
--steps 1500 --save-steps 1000 1500 --device cuda
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
And create a 50/50 weight soup in Python:
|
| 103 |
+
|
| 104 |
+
```python
|
| 105 |
+
from lua_nova_v1.utils import soup_checkpoints
|
| 106 |
+
soup_checkpoints(
|
| 107 |
+
"runs/my_voice_cfm/inference_v5_ema.pt",
|
| 108 |
+
"runs/my_voice_optA/inference_v5_e2e_step-001500.pt",
|
| 109 |
+
"runs/my_voice_optA/inference_v5_soup50.pt",
|
| 110 |
+
alpha=0.5,
|
| 111 |
+
)
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
2. **Option B (Gentle `BigVGAN-base` FT with NVIDIA 5M-step pretrained discriminators):**
|
| 115 |
+
|
| 116 |
+
```bash
|
| 117 |
+
uv run lua-nova-train-vocoder \
|
| 118 |
+
--train data/annotations/train.jsonl \
|
| 119 |
+
--validation data/annotations/validation.jsonl \
|
| 120 |
+
--cfm-ckpt runs/my_voice_optA/inference_v5_soup50.pt \
|
| 121 |
+
--model-id nvidia/bigvgan_base_24khz_100band \
|
| 122 |
+
--pretrained-disc --disc-warmup 0 \
|
| 123 |
+
--output runs/my_voice_vocoder_optB \
|
| 124 |
+
--steps 2000 --save-steps 1000 1500 2000 \
|
| 125 |
+
--batch-size 6 --grad-accum 2 --lr-g 1e-5 --lr-d 1e-5 --device cuda
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
---
|
| 129 |
+
|
| 130 |
+
## 5. Run Inference on Your New Voice
|
| 131 |
+
|
| 132 |
+
```bash
|
| 133 |
+
uv run lua-nova-speak \
|
| 134 |
+
--text "Minha nova voz em português está pronta para falar!" \
|
| 135 |
+
--out test_voice.wav \
|
| 136 |
+
--cfm runs/my_voice_optA/inference_v5_soup50.pt \
|
| 137 |
+
--vocoder runs/my_voice_vocoder_optB/bigvgan_ft_step-002000.pt \
|
| 138 |
+
--device cpu
|
| 139 |
+
```
|
code/docs/OPTIMIZATION.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CPU & Latency Optimization Guide (`v1.1.0`)
|
| 2 |
+
|
| 3 |
+
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):
|
| 4 |
+
|
| 5 |
+
1. **Trajectory Distillation (`8-step Sway Midpoint -> 2-step Euler`)** via `lua-nova-train-distill`
|
| 6 |
+
2. **Split ONNX Runtime CPU Export (opset 17)** via `lua-nova-export-onnx` and `OnnxSynthesizer`
|
| 7 |
+
3. **Overlap-Crossfaded Chunked Streaming** (`Synthesizer.speak_stream` / `OnnxSynthesizer.speak_stream`)
|
| 8 |
+
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
## 1. Benchmark Results (Before vs. After)
|
| 12 |
+
|
| 13 |
+
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).
|
| 14 |
+
|
| 15 |
+
### Latency & Throughput
|
| 16 |
+
|
| 17 |
+
| Runtime & Configuration | Audio / Wall (avg per utt) | Speed (RT ↑) | Streaming TTFA (avg) | Model Footprint |
|
| 18 |
+
|---|---:|---:|---:|---:|
|
| 19 |
+
| PyTorch CPU — Baseline (`8p` Sway Midpoint) | 3,213 ms | `1.53×` | 3,213 ms | 188.8 MB (`135.1 + 53.7`) |
|
| 20 |
+
| **PyTorch CPU — Distilled (`2p` Euler)** | **2,337 ms** | **`2.10×`** | 2,337 ms | **136.9 MB** (`83.2 + 53.7`) |
|
| 21 |
+
| **PyTorch CPU — Streaming (`2p` Euler, `chunk=24`)** | 2,610 ms | `1.88×` | **`465.3 ms`** | **136.9 MB** (`83.2 + 53.7`) |
|
| 22 |
+
| ONNX CPU (`6` threads) — Baseline (`8p` Sway Midpoint) | 4,223 ms | `1.16×` | 4,223 ms | 145.0 MB (`90.3 + 54.7`) |
|
| 23 |
+
| ONNX CPU (`6` threads) — Distilled (`2p` Euler) | 3,469 ms | `1.41×` | 3,469 ms | **141.0 MB** (`86.3 + 54.7`) |
|
| 24 |
+
| **ONNX CPU (`6` threads) — Streaming (`2p` Euler, `chunk=24`)** | 5,166 ms | `0.95×` | **`554.9 ms`** | **141.0 MB** (`86.3 + 54.7`) |
|
| 25 |
+
| PyTorch GPU — Baseline (`8p` Sway Midpoint) | 535 ms | `9.10×` | 535 ms | — |
|
| 26 |
+
| **PyTorch GPU — Distilled (`2p` Euler)** | **437 ms** | **`11.13×`** | 437 ms | — |
|
| 27 |
+
|
| 28 |
+
> **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.
|
| 29 |
+
|
| 30 |
+
### Frozen `tts-eval` v1.0.0 Quality Preservation
|
| 31 |
+
|
| 32 |
+
| Model Variant | Held-out (30) | Nat | Anti-Rob | SCOREQ ↑ | Stress PT-BR (36) | WER ↓ | Phonetic CER ↓ |
|
| 33 |
+
|---|---:|---:|---:|---:|---:|---:|---:|
|
| 34 |
+
| Human Studio Reference (`24 kHz`) | **88.1** | 95.1 | 77.8 | 3.77 | — | — | — |
|
| 35 |
+
| `v1.0.0` Baseline (`8p` Sway Midpoint) | **83.9** | 91.6 | 59.1 | 3.74 | **85.0** | 1.85% | 0.28% |
|
| 36 |
+
| **`v1.1.0` Distilled (`2p` Euler, 3k steps)** | **85.2** | 91.0 | **64.4** | 3.74 | **84.8** | **1.67%** | **0.23%** |
|
| 37 |
+
|
| 38 |
+
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).
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
## 2. How to Run Each Optimization
|
| 43 |
+
|
| 44 |
+
### A. Distill an `8-step Sway Midpoint` Model to `2-step Euler`
|
| 45 |
+
|
| 46 |
+
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`):
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
lua-nova-train-distill \
|
| 50 |
+
--train data/annotations/train.jsonl \
|
| 51 |
+
--validation data/annotations/validation.jsonl \
|
| 52 |
+
--teacher runs/cfm_v5_e2e/inference_v5_soup50.pt \
|
| 53 |
+
--output runs/cfm_v5_fast2 \
|
| 54 |
+
--steps 3000 \
|
| 55 |
+
--teacher-steps 8 \
|
| 56 |
+
--teacher-sway -0.5 \
|
| 57 |
+
--teacher-temp 0.35 \
|
| 58 |
+
--student-steps 2 \
|
| 59 |
+
--lr 1e-4 \
|
| 60 |
+
--save-every 3000
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
Synthesize with the distilled checkpoint in PyTorch:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
lua-nova-speak \
|
| 67 |
+
--cfm runs/cfm_v5_fast2/inference_v5_fast2_step-003000.pt \
|
| 68 |
+
--vocoder runs/bigvgan_base_optB/bigvgan_ft_step-002000.pt \
|
| 69 |
+
--steps 2 --solver euler --sway-coef 0.0 --temperature 0.35 \
|
| 70 |
+
--text "Olá! A destilação reduziu a geração para dois passos Euler." \
|
| 71 |
+
--out fast2.wav --stream --chunk-frames 24
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
### B. Export Split ONNX Graphs (opset 17)
|
| 75 |
+
|
| 76 |
+
Lua Nova V1 exports two composable ONNX graphs so clients can reuse the same vocoder across acoustic checkpoints or decode mel chunks for streaming:
|
| 77 |
+
|
| 78 |
+
- **`cfm_v5_fast2.onnx`**: `("tokens", "stress", "voice", "speed", "pitch_shift", "pitch_range") -> ("phys_mel", "frame_lengths")` plus `<stem>.meta.json`
|
| 79 |
+
- **`bigvgan_base_ft.onnx`**: `("mel",) -> ("audio",)` with dynamic `frames` axis (`[1, T, 100] -> [1, T*256]`) and folded alias-free resampling weights
|
| 80 |
+
|
| 81 |
+
```bash
|
| 82 |
+
lua-nova-export-onnx \
|
| 83 |
+
--cfm runs/cfm_v5_fast2/inference_v5_fast2_step-003000.pt \
|
| 84 |
+
--vocoder runs/bigvgan_base_optB/bigvgan_ft_step-002000.pt \
|
| 85 |
+
--out-dir runs/onnx_v5 \
|
| 86 |
+
--cfm-name cfm_v5_fast2.onnx \
|
| 87 |
+
--vocoder-name bigvgan_base_ft.onnx \
|
| 88 |
+
--steps 2 --solver euler --sway-coef 0.0 --temperature 0.35 --verify
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
### C. Streaming Python & CLI Inference
|
| 92 |
+
|
| 93 |
+
```python
|
| 94 |
+
import numpy as np
|
| 95 |
+
from lua_nova_v1 import OnnxSynthesizer
|
| 96 |
+
|
| 97 |
+
synth = OnnxSynthesizer("runs/onnx_v5/cfm_v5_fast2.onnx", "runs/onnx_v5/bigvgan_base_ft.onnx")
|
| 98 |
+
chunks = list(synth.speak_stream("Primeira frase curta. Segunda frase longa com pausas.", chunk_frames=24))
|
| 99 |
+
wav = np.concatenate(chunks)
|
| 100 |
+
synth.save_wav("streamed.wav", wav)
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
Or via CLI:
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
lua-nova-speak \
|
| 107 |
+
--onnx-cfm runs/onnx_v5/cfm_v5_fast2.onnx \
|
| 108 |
+
--onnx-vocoder runs/onnx_v5/bigvgan_base_ft.onnx \
|
| 109 |
+
--text "Síntese em CPU sem PyTorch e com streaming por chunks." \
|
| 110 |
+
--out onnx_stream.wav --stream --chunk-frames 24
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
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.
|
code/docs/TRAINING_FROM_SCRATCH.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Training From Scratch Guide
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Recommended Hardware & Dataset Size
|
| 8 |
+
|
| 9 |
+
- **Dataset:** `6–10+ hours` (`~5,000–8,000` clean 24 kHz mono utterances, e.g., multi-thousand sentence single-speaker studio corpus).
|
| 10 |
+
- **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.
|
| 11 |
+
- **Total Wall Time (RTX 4070 reference):** `~2 hours` across all stages.
|
| 12 |
+
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
## Stage 0 — Acoustic Features & CTC Forced Alignment
|
| 16 |
+
|
| 17 |
+
Ensure `train.jsonl` and `validation.jsonl` share **zero texts or IDs**. Audio files must be `24,000 Hz` mono WAV.
|
| 18 |
+
|
| 19 |
+
```bash
|
| 20 |
+
uv run lua-nova-prepare --inputs data/raw/train.jsonl --split train --output data/features
|
| 21 |
+
uv run lua-nova-prepare --inputs data/raw/validation.jsonl --split validation --output data/features
|
| 22 |
+
|
| 23 |
+
uv run lua-nova-annotate \
|
| 24 |
+
--features data/features \
|
| 25 |
+
--output data/annotations \
|
| 26 |
+
--dataset-revision ptbr-scratch-v1 \
|
| 27 |
+
--device cuda \
|
| 28 |
+
--refine 2 --stage refined-2
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
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`.
|
| 32 |
+
|
| 33 |
+
---
|
| 34 |
+
|
| 35 |
+
## Stage 1 — Phonetic Front End & Baseline (`lua-nova-train-stage1`)
|
| 36 |
+
|
| 37 |
+
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):
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
uv run lua-nova-train-stage1 \
|
| 41 |
+
--train data/annotations/train.jsonl \
|
| 42 |
+
--validation data/annotations/validation.jsonl \
|
| 43 |
+
--output runs/stage1 \
|
| 44 |
+
--steps 40000 \
|
| 45 |
+
--batch-frames 9000 --max-batch 32 \
|
| 46 |
+
--learning-rate 3e-4 --warmup 1000 \
|
| 47 |
+
--save-every 5000 --keep-every 10000 --device cuda
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
---
|
| 51 |
+
|
| 52 |
+
## Stage 2 — Linguistic Context & ProsodyFlow (`lua-nova-train-prosody`)
|
| 53 |
+
|
| 54 |
+
Freezes encoder/acoustic modules and trains the 26-channel `LinguisticContextAdapter`, 4-step `DurationFlow`, and 4-step multiscale `ProsodyFlow`:
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
uv run lua-nova-train-prosody \
|
| 58 |
+
--train data/annotations/train.jsonl \
|
| 59 |
+
--validation data/annotations/validation.jsonl \
|
| 60 |
+
--init-stage1 runs/stage1/inference.pt \
|
| 61 |
+
--output runs/prosody_flow \
|
| 62 |
+
--steps 12000 \
|
| 63 |
+
--learning-rate 2e-4 --warmup 600 \
|
| 64 |
+
--eval-every 2000 --save-every 3000 --sample-every 0 --device cuda
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
---
|
| 68 |
+
|
| 69 |
+
## Stage 3 — OT-CFM v5 in Slaney-100 Mel Space (`lua-nova-train-cfm`)
|
| 70 |
+
|
| 71 |
+
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:
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
uv run lua-nova-train-cfm \
|
| 75 |
+
--train data/annotations/train.jsonl \
|
| 76 |
+
--validation data/annotations/validation.jsonl \
|
| 77 |
+
--init-cfm runs/prosody_flow/inference_item3.pt \
|
| 78 |
+
--output runs/cfm_v5 \
|
| 79 |
+
--steps 25000 \
|
| 80 |
+
--batch-frames 6000 --max-batch 24 \
|
| 81 |
+
--lr 3e-4 --min-lr 1.5e-5 --warmup 500 \
|
| 82 |
+
--save-every 5000 --val-every 1000 --device cuda
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
---
|
| 86 |
+
|
| 87 |
+
## Stage 4 — Option A: E2E Polish Through Frozen BigVGAN + NVIDIA MIT Discriminators
|
| 88 |
+
|
| 89 |
+
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:
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
uv run lua-nova-train-e2e \
|
| 93 |
+
--train data/annotations/train.jsonl \
|
| 94 |
+
--validation data/annotations/validation.jsonl \
|
| 95 |
+
--init-v5 runs/cfm_v5/inference_v5_ema.pt \
|
| 96 |
+
--output runs/cfm_v5_e2e \
|
| 97 |
+
--steps 2000 --save-steps 1000 1500 2000 \
|
| 98 |
+
--batch-size 4 --grad-accum 3 --crop-frames 40 \
|
| 99 |
+
--lr 4e-5 --min-lr 4e-6 --device cuda
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
Create the 50/50 weight soup (`1500` steps gave the best trade-off between perceptual cleanliness and spectral sharpness):
|
| 103 |
+
|
| 104 |
+
```python
|
| 105 |
+
from lua_nova_v1.utils import soup_checkpoints
|
| 106 |
+
|
| 107 |
+
soup_checkpoints(
|
| 108 |
+
"runs/cfm_v5/inference_v5_ema.pt",
|
| 109 |
+
"runs/cfm_v5_e2e/inference_v5_e2e_step-001500.pt",
|
| 110 |
+
"runs/cfm_v5_e2e/inference_v5_soup50.pt",
|
| 111 |
+
alpha=0.5,
|
| 112 |
+
)
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
---
|
| 116 |
+
|
| 117 |
+
## Stage 5 — Option B: Gentle Vocoder Adaptation (`lua-nova-train-vocoder`)
|
| 118 |
+
|
| 119 |
+
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:
|
| 120 |
+
|
| 121 |
+
```bash
|
| 122 |
+
uv run lua-nova-train-vocoder \
|
| 123 |
+
--train data/annotations/train.jsonl \
|
| 124 |
+
--validation data/annotations/validation.jsonl \
|
| 125 |
+
--cfm-ckpt runs/cfm_v5_e2e/inference_v5_soup50.pt \
|
| 126 |
+
--cfm-steps 8 --cfm-temp 0.35 --sway-coef -0.5 \
|
| 127 |
+
--model-id nvidia/bigvgan_base_24khz_100band \
|
| 128 |
+
--pretrained-disc --disc-warmup 0 \
|
| 129 |
+
--output runs/bigvgan_base_optB \
|
| 130 |
+
--steps 2000 --save-steps 500 1000 1500 2000 \
|
| 131 |
+
--batch-size 6 --grad-accum 2 --crop-frames 32 --cfm-prob 0.60 \
|
| 132 |
+
--lr-g 1e-5 --min-lr-g 1e-6 --warmup-g 100 \
|
| 133 |
+
--lr-d 1e-5 --lr-d-post 1e-5 --min-lr-d 1e-6 \
|
| 134 |
+
--val-every 250 --log-every 10 --device cuda
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
> 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`.
|
code/pyproject.toml
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=68"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "lua-nova-v1"
|
| 7 |
+
version = "1.1.0"
|
| 8 |
+
description = "Compact 24 kHz Brazilian Portuguese TTS combining OT-CFM, ProsodyFlow, Sway Sampling, and BigVGAN-base"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
license = { text = "Apache-2.0" }
|
| 11 |
+
requires-python = ">=3.11,<3.13"
|
| 12 |
+
dependencies = [
|
| 13 |
+
"torch>=2.7",
|
| 14 |
+
"torchaudio>=2.7",
|
| 15 |
+
"numpy>=1.24,<3",
|
| 16 |
+
"soundfile>=0.12,<1",
|
| 17 |
+
"librosa>=0.10.2,<1",
|
| 18 |
+
"huggingface-hub>=0.34,<2",
|
| 19 |
+
"scipy>=1.10,<2",
|
| 20 |
+
"truststore>=0.10",
|
| 21 |
+
"matplotlib>=3.8",
|
| 22 |
+
"tqdm>=4.66",
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
[project.optional-dependencies]
|
| 26 |
+
train = [
|
| 27 |
+
"vocos>=0.1.0",
|
| 28 |
+
"pyarrow>=15",
|
| 29 |
+
"transformers>=4.40,<5",
|
| 30 |
+
"praat-parselmouth>=0.4.7",
|
| 31 |
+
"faster-whisper>=1.2.1",
|
| 32 |
+
"av<19",
|
| 33 |
+
"jiwer>=3,<5",
|
| 34 |
+
]
|
| 35 |
+
onnx = [
|
| 36 |
+
"onnx>=1.16",
|
| 37 |
+
"onnxruntime>=1.18",
|
| 38 |
+
"onnxscript>=0.1",
|
| 39 |
+
]
|
| 40 |
+
dev = [
|
| 41 |
+
"pytest>=8",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
[project.scripts]
|
| 45 |
+
lua-nova-speak = "lua_nova_v1.inference.cli:main"
|
| 46 |
+
lua-nova-prepare = "lua_nova_v1.data.prepare:main"
|
| 47 |
+
lua-nova-annotate = "lua_nova_v1.data.annotate:main"
|
| 48 |
+
lua-nova-train-stage1 = "lua_nova_v1.training.stage1:main"
|
| 49 |
+
lua-nova-train-prosody = "lua_nova_v1.training.prosody_flow:main"
|
| 50 |
+
lua-nova-train-cfm = "lua_nova_v1.training.cfm:main"
|
| 51 |
+
lua-nova-train-e2e = "lua_nova_v1.training.cfm_e2e:main"
|
| 52 |
+
lua-nova-train-vocoder = "lua_nova_v1.training.vocoder_ft:main"
|
| 53 |
+
lua-nova-train-distill = "lua_nova_v1.training.distill:main"
|
| 54 |
+
lua-nova-export-onnx = "lua_nova_v1.export.onnx_export:main"
|
| 55 |
+
|
| 56 |
+
[tool.setuptools.packages.find]
|
| 57 |
+
where = ["src"]
|
| 58 |
+
|
| 59 |
+
[tool.uv]
|
| 60 |
+
package = true
|
code/src/lua_nova_v1/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lua Nova V1: Compact 24 kHz Brazilian Portuguese Text-to-Speech."""
|
| 2 |
+
|
| 3 |
+
from .config import ANNOTATION_VERSION, CHECKPOINT_FORMAT, CFMConfig, Config, ModelConfig
|
| 4 |
+
from .inference import OnnxSynthesizer, Synthesizer
|
| 5 |
+
from .models import BigVGANMelExtractor, BigVGANVocoderWrapper, LuaNovaBase, LuaNovaCFM
|
| 6 |
+
from .text import normalize_ptbr_text, phonemize, phonemize_ptbr
|
| 7 |
+
|
| 8 |
+
__version__ = "1.1.0"
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"ANNOTATION_VERSION",
|
| 12 |
+
"BigVGANMelExtractor",
|
| 13 |
+
"BigVGANVocoderWrapper",
|
| 14 |
+
"CFMConfig",
|
| 15 |
+
"CHECKPOINT_FORMAT",
|
| 16 |
+
"Config",
|
| 17 |
+
"ModelConfig",
|
| 18 |
+
"OnnxSynthesizer",
|
| 19 |
+
"Synthesizer",
|
| 20 |
+
"LuaNovaBase",
|
| 21 |
+
"LuaNovaCFM",
|
| 22 |
+
"__version__",
|
| 23 |
+
"normalize_ptbr_text",
|
| 24 |
+
"phonemize",
|
| 25 |
+
"phonemize_ptbr",
|
| 26 |
+
]
|
code/src/lua_nova_v1/config.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model and Flow-Matching configuration dataclasses for Lua Nova V1."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from dataclasses import asdict, dataclass
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
CHECKPOINT_FORMAT = 4
|
| 9 |
+
ANNOTATION_VERSION = 3
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _digest(value: object) -> str:
|
| 13 |
+
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass(frozen=True)
|
| 17 |
+
class Config:
|
| 18 |
+
"""Acoustic front-end configuration (24 kHz PT-BR, 85-symbol eSpeak-NG inventory)."""
|
| 19 |
+
|
| 20 |
+
sample_rate: int = 24000
|
| 21 |
+
hop: int = 256
|
| 22 |
+
n_fft: int = 1024
|
| 23 |
+
n_mels: int = 80
|
| 24 |
+
f0_min: float = 50.0
|
| 25 |
+
f0_max: float = 600.0
|
| 26 |
+
speakers: tuple[str, ...] = ("F1",)
|
| 27 |
+
vocab_size: int = 85
|
| 28 |
+
channels: int = 192
|
| 29 |
+
heads: int = 4
|
| 30 |
+
feedforward: int = 640
|
| 31 |
+
kernel: int = 7
|
| 32 |
+
encoder_layers: int = 4
|
| 33 |
+
prosody_layers: int = 2
|
| 34 |
+
acoustic_layers: int = 5
|
| 35 |
+
dropout: float = 0.1
|
| 36 |
+
predictor_channels: int = 128
|
| 37 |
+
synth_fft: int = 512
|
| 38 |
+
synth_hop: int = 128
|
| 39 |
+
noise_fft: int = 256
|
| 40 |
+
noise_hop: int = 64
|
| 41 |
+
cep_causal: int = 80
|
| 42 |
+
cep_anti: int = 16
|
| 43 |
+
noise_cep: int = 32
|
| 44 |
+
harmonic_limit: float = 0.47
|
| 45 |
+
vocoder_type: str = "source_filter"
|
| 46 |
+
vocos_model: str = "charactr/vocos-mel-24khz"
|
| 47 |
+
vocos_n_mels: int = 100
|
| 48 |
+
max_tokens: int = 512
|
| 49 |
+
max_frames: int = 3000
|
| 50 |
+
mel_mean: float = -5.0
|
| 51 |
+
mel_scale: float = 5.0
|
| 52 |
+
energy_mean: float = -4.0
|
| 53 |
+
energy_scale: float = 2.0
|
| 54 |
+
pitch_reference_hz: float = 200.0
|
| 55 |
+
|
| 56 |
+
def __post_init__(self) -> None:
|
| 57 |
+
from .text.phonemizer import SYMBOLS
|
| 58 |
+
|
| 59 |
+
if self.vocab_size != len(SYMBOLS):
|
| 60 |
+
raise ValueError(f"vocab_size must equal the phoneme inventory size {len(SYMBOLS)}")
|
| 61 |
+
if self.channels % self.heads or (self.channels // self.heads) % 2:
|
| 62 |
+
raise ValueError("channels must be divisible by heads with an even head width")
|
| 63 |
+
if not self.speakers or len(set(self.speakers)) != len(self.speakers):
|
| 64 |
+
raise ValueError("speaker names must be unique and nonempty")
|
| 65 |
+
for fft, hop in ((self.synth_fft, self.synth_hop), (self.noise_fft, self.noise_hop)):
|
| 66 |
+
if fft != 4 * hop or self.hop % hop:
|
| 67 |
+
raise ValueError("synthesis windows need 4x overlap and a hop dividing the acoustic hop")
|
| 68 |
+
if self.cep_causal + self.cep_anti >= self.synth_fft // 2 or self.noise_cep >= self.noise_fft // 2:
|
| 69 |
+
raise ValueError("cepstrum orders must be well below half the synthesis FFT size")
|
| 70 |
+
if min(self.encoder_layers, self.prosody_layers, self.acoustic_layers, self.kernel) < 1 or not self.kernel % 2:
|
| 71 |
+
raise ValueError("layer counts must be positive and the kernel odd")
|
| 72 |
+
if min(self.mel_scale, self.energy_scale) <= 0 or not 0 < self.harmonic_limit < 0.5:
|
| 73 |
+
raise ValueError("invalid normalization scale or harmonic limit")
|
| 74 |
+
if self.vocoder_type not in ("source_filter", "vocos") or self.vocos_n_mels < 1:
|
| 75 |
+
raise ValueError("invalid vocoder_type or vocos_n_mels")
|
| 76 |
+
|
| 77 |
+
def to_dict(self) -> dict:
|
| 78 |
+
return asdict(self)
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def from_dict(cls, value: dict) -> "Config":
|
| 82 |
+
return cls(**{**value, "speakers": tuple(value["speakers"])})
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def fingerprint(self) -> str:
|
| 86 |
+
return _digest(self.to_dict())
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def acoustic_config(self) -> dict:
|
| 90 |
+
"""Settings that determine stored wave/mel/prosody tensors."""
|
| 91 |
+
fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max")
|
| 92 |
+
return {
|
| 93 |
+
**{key: getattr(self, key) for key in fields},
|
| 94 |
+
"feature_version": 2,
|
| 95 |
+
"pitch_reference_hz": 200,
|
| 96 |
+
"log_floor": 1e-5,
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def acoustic_fingerprint(self) -> str:
|
| 101 |
+
return _digest(self.acoustic_config)
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def legacy_feature_fingerprint(self) -> str:
|
| 105 |
+
fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max", "speakers")
|
| 106 |
+
return _digest(
|
| 107 |
+
{
|
| 108 |
+
**{key: getattr(self, key) for key in fields},
|
| 109 |
+
"vocab_size": 259,
|
| 110 |
+
"feature_version": 2,
|
| 111 |
+
"frontend_version": 2,
|
| 112 |
+
"pitch_reference_hz": 200,
|
| 113 |
+
"log_floor": 1e-5,
|
| 114 |
+
}
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
ModelConfig = Config
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@dataclass
|
| 122 |
+
class CFMConfig:
|
| 123 |
+
"""Conditional Flow Matching + ProsodyFlow configuration."""
|
| 124 |
+
|
| 125 |
+
base: Config
|
| 126 |
+
flow_channels: int = 256
|
| 127 |
+
flow_layers: int = 6
|
| 128 |
+
flow_heads: int = 4
|
| 129 |
+
flow_feedforward: int = 768
|
| 130 |
+
flow_kernel: int = 5
|
| 131 |
+
flow_dropout: float = 0.05
|
| 132 |
+
prior_sigma: float = 0.40
|
| 133 |
+
cfg_dropout: float = 0.10
|
| 134 |
+
use_acoustic_prior: bool = True
|
| 135 |
+
use_f0_harmonics: bool = True
|
| 136 |
+
prosody_hidden_dropout: float = 0.15
|
| 137 |
+
acoustic_from_frames: bool = False
|
| 138 |
+
use_energy_gate: bool = False
|
| 139 |
+
use_ling_context: bool = False
|
| 140 |
+
use_duration_flow: bool = False
|
| 141 |
+
use_prosody_flow: bool = False
|
| 142 |
+
prosody_context_layers: int = 2
|
| 143 |
+
dur_flow_channels: int = 128
|
| 144 |
+
dur_flow_layers: int = 3
|
| 145 |
+
dur_flow_heads: int = 4
|
| 146 |
+
dur_flow_feedforward: int = 384
|
| 147 |
+
dur_flow_kernel: int = 3
|
| 148 |
+
dur_flow_sigma: float = 0.25
|
| 149 |
+
dur_flow_steps: int = 4
|
| 150 |
+
dur_flow_temp: float = 0.50
|
| 151 |
+
prosody_flow_channels: int = 128
|
| 152 |
+
prosody_flow_layers: int = 4
|
| 153 |
+
prosody_flow_heads: int = 4
|
| 154 |
+
prosody_flow_feedforward: int = 384
|
| 155 |
+
prosody_flow_kernel: int = 7
|
| 156 |
+
prosody_flow_sigma: float = 0.22
|
| 157 |
+
prosody_flow_steps: int = 4
|
| 158 |
+
prosody_flow_temp: float = 0.75
|
| 159 |
+
default_pitch_range: float = 1.0
|
| 160 |
+
mel_space: str = "vocos"
|
| 161 |
+
|
| 162 |
+
def to_dict(self) -> dict:
|
| 163 |
+
d = asdict(self)
|
| 164 |
+
d["base"] = self.base.to_dict()
|
| 165 |
+
return d
|
| 166 |
+
|
| 167 |
+
@classmethod
|
| 168 |
+
def from_dict(cls, data: dict) -> "CFMConfig":
|
| 169 |
+
d = dict(data)
|
| 170 |
+
d["base"] = Config.from_dict(d["base"])
|
| 171 |
+
d.setdefault("use_acoustic_prior", False)
|
| 172 |
+
d.setdefault("use_f0_harmonics", False)
|
| 173 |
+
d.setdefault("prior_sigma", 0.65)
|
| 174 |
+
d.setdefault("prosody_hidden_dropout", 0.0)
|
| 175 |
+
d.setdefault("acoustic_from_frames", False)
|
| 176 |
+
d.setdefault("use_energy_gate", False)
|
| 177 |
+
d.setdefault("use_ling_context", False)
|
| 178 |
+
d.setdefault("use_duration_flow", False)
|
| 179 |
+
d.setdefault("use_prosody_flow", False)
|
| 180 |
+
d.setdefault("prosody_context_layers", 2)
|
| 181 |
+
d.setdefault("dur_flow_channels", 128)
|
| 182 |
+
d.setdefault("dur_flow_layers", 3)
|
| 183 |
+
d.setdefault("dur_flow_heads", 4)
|
| 184 |
+
d.setdefault("dur_flow_feedforward", 384)
|
| 185 |
+
d.setdefault("dur_flow_kernel", 3)
|
| 186 |
+
d.setdefault("dur_flow_sigma", 0.25)
|
| 187 |
+
d.setdefault("dur_flow_steps", 4)
|
| 188 |
+
d.setdefault("dur_flow_temp", 0.50)
|
| 189 |
+
d.setdefault("prosody_flow_channels", 128)
|
| 190 |
+
d.setdefault("prosody_flow_layers", 4)
|
| 191 |
+
d.setdefault("prosody_flow_heads", 4)
|
| 192 |
+
d.setdefault("prosody_flow_feedforward", 384)
|
| 193 |
+
d.setdefault("prosody_flow_kernel", 7)
|
| 194 |
+
d.setdefault("prosody_flow_sigma", 0.22)
|
| 195 |
+
d.setdefault("prosody_flow_steps", 4)
|
| 196 |
+
d.setdefault("prosody_flow_temp", 0.75)
|
| 197 |
+
d.setdefault("default_pitch_range", 1.0)
|
| 198 |
+
d.setdefault("mel_space", "vocos")
|
| 199 |
+
return cls(**d)
|
code/src/lua_nova_v1/data/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dataset loading, alignment, and preparation tools."""
|
| 2 |
+
|
| 3 |
+
from .aligner import ALIGNER_MODEL, AlignmentSettings, PhoneRecognizer, align_utterance
|
| 4 |
+
from .dataset import AnnotatedDataset, BucketSampler, collate, continuous_pitch
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
"ALIGNER_MODEL",
|
| 8 |
+
"AlignmentSettings",
|
| 9 |
+
"AnnotatedDataset",
|
| 10 |
+
"BucketSampler",
|
| 11 |
+
"PhoneRecognizer",
|
| 12 |
+
"align_utterance",
|
| 13 |
+
"collate",
|
| 14 |
+
"continuous_pitch",
|
| 15 |
+
]
|
code/src/lua_nova_v1/data/aligner.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline phoneme-level forced alignment. Annotation time only.
|
| 2 |
+
|
| 3 |
+
A pretrained multilingual phoneme recogniser (wav2vec 2.0 fine-tuned with CTC on
|
| 4 |
+
eSpeak phoneme labels, ``facebook/wav2vec2-lv-60-espeak-cv-ft``) labels the
|
| 5 |
+
existing recordings. It is used ONLY to annotate training data: none of its
|
| 6 |
+
weights, features or outputs enter the TTS model, which never sees it.
|
| 7 |
+
|
| 8 |
+
Why this replaces the learned Gaussian aligner: that objective normalised scores
|
| 9 |
+
over the token positions of one utterance, so a frequent token whose key matched
|
| 10 |
+
the average spectrum (first BOS, later the word spaces) won the softmax on most
|
| 11 |
+
frames and every other token was left with single frames. Here each frame is
|
| 12 |
+
scored against phoneme classes shared by the whole language, and the transcript
|
| 13 |
+
only constrains their order.
|
| 14 |
+
|
| 15 |
+
Per utterance:
|
| 16 |
+
1. CTC Viterbi alignment of the eSpeak phoneme sequence (20 ms frames).
|
| 17 |
+
2. This recogniser emits a label once, at the START of the phone (measured on
|
| 18 |
+
our recordings against pitch-tracker voicing flips: a phone begins about
|
| 19 |
+
19 ms before the start of its first emission frame, for both voices; see
|
| 20 |
+
``scripts/calibrate_aligner_timing.py``). A phone therefore lasts from its
|
| 21 |
+
own onset to the next phone's onset.
|
| 22 |
+
3. Silence is found from signal energy at acoustic resolution and given to the
|
| 23 |
+
explicit pause-capable token at that position (BOS, EOS, punctuation, word
|
| 24 |
+
boundary). Tokens without a pause get zero frames.
|
| 25 |
+
4. Durations are counted on the acoustic frame grid, so they sum to the frame
|
| 26 |
+
count exactly and every phoneme has at least one frame.
|
| 27 |
+
|
| 28 |
+
``refine.py`` can then sharpen the boundaries with a classifier trained from
|
| 29 |
+
scratch on these labels.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
from dataclasses import dataclass
|
| 33 |
+
import math
|
| 34 |
+
import numpy as np
|
| 35 |
+
|
| 36 |
+
from ..text.phonemizer import PHONE_SET, PUNCTUATION, SP, UNK, VOICELESS, VOWEL_SET
|
| 37 |
+
|
| 38 |
+
ALIGNER_MODEL = "facebook/wav2vec2-lv-60-espeak-cv-ft"
|
| 39 |
+
ALIGNER_RATE = 16000
|
| 40 |
+
ALIGNER_STRIDE = 320 # samples at 16 kHz: 20 ms
|
| 41 |
+
ALIGNER_CENTER = 200 # a frame's centre: 12.5 ms after its start
|
| 42 |
+
ALIGNMENT_VERSION = 2
|
| 43 |
+
PAUSING = (",", ".", "?", "!", ";", ":", "—", "…")
|
| 44 |
+
# Every inventory phone is a label of the recogniser (checked when it loads);
|
| 45 |
+
# only the unknown-phone token needs a stand-in.
|
| 46 |
+
ALIGNER_LABEL_FALLBACK = {UNK: "<unk>"}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass(frozen=True)
|
| 50 |
+
class AlignmentSettings:
|
| 51 |
+
onset_offset_seconds: float = -0.019 # phone onset relative to the start of its first emission frame
|
| 52 |
+
min_pause_frames: int = 7 # ~75 ms of silence: less stays with the neighbouring phones (stop closures)
|
| 53 |
+
silence_below_peak_db: float = 45.0
|
| 54 |
+
silence_above_floor_db: float = 8.0
|
| 55 |
+
silence_ceiling_below_peak_db: float = 30.0
|
| 56 |
+
energy_window: int = 512
|
| 57 |
+
|
| 58 |
+
def to_dict(self):
|
| 59 |
+
return {"alignment_version": ALIGNMENT_VERSION, "aligner": ALIGNER_MODEL, **self.__dict__}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def ctc_viterbi(log_probs, labels, blank=0):
|
| 63 |
+
"""Best CTC path. Returns per-frame extended-state indices (token k is state 2k+1).
|
| 64 |
+
|
| 65 |
+
Plain numpy reference, also used when torchaudio's implementation is absent.
|
| 66 |
+
"""
|
| 67 |
+
frames, count = log_probs.shape[0], len(labels)
|
| 68 |
+
if count < 1:
|
| 69 |
+
raise ValueError("no labels to align")
|
| 70 |
+
states = 2 * count + 1
|
| 71 |
+
extended = np.full(states, blank, dtype=np.int64)
|
| 72 |
+
extended[1::2] = labels
|
| 73 |
+
skip = np.zeros(states, dtype=bool)
|
| 74 |
+
skip[3::2] = extended[3::2] != extended[1:-2:2]
|
| 75 |
+
score = np.full(states, -np.inf)
|
| 76 |
+
score[0] = log_probs[0, blank]
|
| 77 |
+
score[1] = log_probs[0, extended[1]]
|
| 78 |
+
back = np.zeros((frames, states), dtype=np.int8)
|
| 79 |
+
for t in range(1, frames):
|
| 80 |
+
one = np.concatenate(([-np.inf], score[:-1]))
|
| 81 |
+
two = np.concatenate(([-np.inf, -np.inf], score[:-2]))
|
| 82 |
+
two[~skip] = -np.inf
|
| 83 |
+
options = np.stack((score, one, two))
|
| 84 |
+
choice = options.argmax(0)
|
| 85 |
+
score = options[choice, np.arange(states)] + log_probs[t, extended]
|
| 86 |
+
back[t] = choice
|
| 87 |
+
state = states - 1 if score[states - 1] >= score[states - 2] else states - 2
|
| 88 |
+
if not np.isfinite(score[state]):
|
| 89 |
+
raise ValueError("audio is too short for this phoneme sequence")
|
| 90 |
+
path = np.empty(frames, dtype=np.int64)
|
| 91 |
+
for t in range(frames - 1, -1, -1):
|
| 92 |
+
path[t] = state
|
| 93 |
+
state -= back[t, state]
|
| 94 |
+
return path
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def spans_from_states(states, count):
|
| 98 |
+
spans = []
|
| 99 |
+
for index in range(count):
|
| 100 |
+
where = np.flatnonzero(states == 2 * index + 1)
|
| 101 |
+
if not where.size:
|
| 102 |
+
raise ValueError("forced alignment did not visit every phoneme")
|
| 103 |
+
spans.append((int(where[0]), int(where[-1])))
|
| 104 |
+
return spans
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def token_spans(log_probs, labels, blank=0):
|
| 108 |
+
"""Inclusive ``(first, last)`` emission frames of every label on the best CTC path."""
|
| 109 |
+
count = len(labels)
|
| 110 |
+
repeats = sum(1 for a, b in zip(labels[:-1], labels[1:]) if a == b)
|
| 111 |
+
if log_probs.shape[0] < count + repeats:
|
| 112 |
+
raise ValueError("audio is too short for this phoneme sequence")
|
| 113 |
+
try:
|
| 114 |
+
import torch
|
| 115 |
+
from torchaudio.functional import forced_align
|
| 116 |
+
except ImportError:
|
| 117 |
+
return spans_from_states(ctc_viterbi(log_probs, np.asarray(labels), blank), count)
|
| 118 |
+
path, _ = forced_align(torch.from_numpy(np.ascontiguousarray(log_probs, dtype=np.float32))[None],
|
| 119 |
+
torch.tensor([list(labels)], dtype=torch.long), blank=blank)
|
| 120 |
+
spans, previous = [], blank
|
| 121 |
+
for frame, label in enumerate(path[0].tolist()):
|
| 122 |
+
if label != blank and (previous == blank or label != previous):
|
| 123 |
+
spans.append([frame, frame])
|
| 124 |
+
elif label != blank:
|
| 125 |
+
spans[-1][1] = frame
|
| 126 |
+
previous = label
|
| 127 |
+
if len(spans) != count:
|
| 128 |
+
raise ValueError("forced alignment did not visit every phoneme")
|
| 129 |
+
return [(a, b) for a, b in spans]
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def frame_energy_db(wave, hop, window=512):
|
| 133 |
+
"""RMS level per acoustic frame, window centred on the frame centre i*hop."""
|
| 134 |
+
frames = len(wave) // hop
|
| 135 |
+
padded = np.pad(np.asarray(wave, dtype=np.float64), (window // 2, window // 2))
|
| 136 |
+
squares = np.concatenate(([0.0], np.cumsum(padded ** 2)))
|
| 137 |
+
starts = np.arange(frames) * hop
|
| 138 |
+
mean = (squares[starts + window] - squares[starts]) / window
|
| 139 |
+
return 10 * np.log10(np.maximum(mean, 1e-12))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def silence_mask(level_db, settings):
|
| 143 |
+
loud, floor = np.percentile(level_db, 95), np.percentile(level_db, 2)
|
| 144 |
+
threshold = min(loud - settings.silence_ceiling_below_peak_db,
|
| 145 |
+
max(loud - settings.silence_below_peak_db, floor + settings.silence_above_floor_db))
|
| 146 |
+
return level_db < threshold, float(threshold)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def pause_carrier(symbols, group):
|
| 150 |
+
"""Index of the token that receives a pause inside a run of non-phone tokens."""
|
| 151 |
+
for wanted in (PAUSING, PUNCTUATION, (SP,)):
|
| 152 |
+
for index in group:
|
| 153 |
+
if symbols[index] in wanted:
|
| 154 |
+
return index
|
| 155 |
+
return group[0]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def assemble(symbols, spans, frames, silent, hop, sample_rate, settings):
|
| 159 |
+
"""Durations in acoustic frames for every token (sums to ``frames``).
|
| 160 |
+
|
| 161 |
+
Acoustic frame i is centred on sample ``i * hop`` (the convention of the
|
| 162 |
+
stored mel/pitch features and of the synthesis frames).
|
| 163 |
+
"""
|
| 164 |
+
phones = [i for i, s in enumerate(symbols) if s in PHONE_SET or s == UNK]
|
| 165 |
+
count = len(phones)
|
| 166 |
+
if count != len(spans) or count < 1:
|
| 167 |
+
raise ValueError("phoneme count differs from alignment")
|
| 168 |
+
stride = ALIGNER_STRIDE / ALIGNER_RATE
|
| 169 |
+
emission = np.array([first for first, _ in spans], dtype=np.float64) * stride
|
| 170 |
+
seconds = np.arange(frames) * hop / sample_rate
|
| 171 |
+
# One protected frame per phone at its emission centre; phones cannot lose it.
|
| 172 |
+
keep = np.clip(np.round((emission + ALIGNER_CENTER / ALIGNER_RATE) * sample_rate / hop).astype(np.int64), 0, frames - 1)
|
| 173 |
+
for k in range(1, count):
|
| 174 |
+
keep[k] = max(keep[k], keep[k - 1] + 1)
|
| 175 |
+
if keep[-1] > frames - 1:
|
| 176 |
+
raise ValueError("audio is too short for this phoneme sequence")
|
| 177 |
+
starts = np.minimum(np.searchsorted(seconds, emission + settings.onset_offset_seconds, side="left"), keep)
|
| 178 |
+
starts[0] = 0
|
| 179 |
+
for k in range(1, count):
|
| 180 |
+
starts[k] = max(starts[k], keep[k - 1] + 1)
|
| 181 |
+
token = np.empty(frames, dtype=np.int64)
|
| 182 |
+
bounds = np.append(starts, frames)
|
| 183 |
+
for k in range(count):
|
| 184 |
+
token[bounds[k]:bounds[k + 1]] = phones[k]
|
| 185 |
+
# A pause runs from the first to the last silent frame between two protected
|
| 186 |
+
# frames. Whatever lies between them (a breath, a stop release) is not part
|
| 187 |
+
# of either phone's steady sound and stays with the pause.
|
| 188 |
+
quiet = np.flatnonzero(silent[:keep[0]])
|
| 189 |
+
if quiet.size: # leading silence -> BOS
|
| 190 |
+
token[:quiet[-1] + 1] = 0
|
| 191 |
+
quiet = np.flatnonzero(silent[keep[-1] + 1:]) + keep[-1] + 1
|
| 192 |
+
if quiet.size: # trailing silence -> EOS
|
| 193 |
+
token[quiet[0]:] = len(symbols) - 1
|
| 194 |
+
for k in range(count - 1): # interior pauses -> pause-capable token
|
| 195 |
+
left, right = phones[k], phones[k + 1]
|
| 196 |
+
if right == left + 1:
|
| 197 |
+
continue
|
| 198 |
+
quiet = np.flatnonzero(silent[keep[k] + 1:keep[k + 1]]) + keep[k] + 1
|
| 199 |
+
if quiet.size < settings.min_pause_frames:
|
| 200 |
+
continue
|
| 201 |
+
token[keep[k] + 1:quiet[0]] = left
|
| 202 |
+
token[quiet[0]:quiet[-1] + 1] = pause_carrier(symbols, range(left + 1, right))
|
| 203 |
+
token[quiet[-1] + 1:keep[k + 1]] = right
|
| 204 |
+
if np.any(np.diff(token) < 0):
|
| 205 |
+
raise ValueError("alignment is not monotonic")
|
| 206 |
+
durations = np.bincount(token, minlength=len(symbols)).astype(np.int64)
|
| 207 |
+
if durations.sum() != frames or np.any(durations[phones] < 1):
|
| 208 |
+
raise ValueError("durations do not cover the acoustic frames")
|
| 209 |
+
return durations
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def quality(symbols, durations, spans, log_probs, labels, voiced, level_db, hop, sample_rate):
|
| 213 |
+
"""Label-free checks of one alignment against the recording itself."""
|
| 214 |
+
durations = np.asarray(durations)
|
| 215 |
+
ends = np.cumsum(durations)
|
| 216 |
+
starts = ends - durations
|
| 217 |
+
token_probability = np.array([float(np.exp(log_probs[a:b + 1, label]).mean()) for (a, b), label in zip(spans, labels)])
|
| 218 |
+
phone_frames = np.array([d for s, d in zip(symbols, durations) if s in PHONE_SET or s == UNK])
|
| 219 |
+
|
| 220 |
+
def voiced_share(wanted):
|
| 221 |
+
total = hits = 0
|
| 222 |
+
for symbol, start, end in zip(symbols, starts, ends):
|
| 223 |
+
if wanted(symbol) and end - start >= 3: # interior frames only
|
| 224 |
+
total += end - start - 2
|
| 225 |
+
hits += float(voiced[start + 1:end - 1].sum())
|
| 226 |
+
return round(hits / total, 4) if total else None
|
| 227 |
+
|
| 228 |
+
pause = np.zeros(len(voiced), dtype=bool)
|
| 229 |
+
for symbol, start, end in zip(symbols, starts, ends):
|
| 230 |
+
if symbol not in PHONE_SET and symbol != UNK:
|
| 231 |
+
pause[start:end] = True
|
| 232 |
+
speech_seconds = float((~pause).sum() * hop / sample_rate)
|
| 233 |
+
return {
|
| 234 |
+
"token_probability_mean": round(float(token_probability.mean()), 4),
|
| 235 |
+
"weak_phone_fraction": round(float((token_probability < 0.1).mean()), 4),
|
| 236 |
+
"max_phone_frames": int(phone_frames.max()),
|
| 237 |
+
"one_frame_phone_fraction": round(float((phone_frames == 1).mean()), 4),
|
| 238 |
+
"phones_per_second": round(len(phone_frames) / max(speech_seconds, 1e-6), 2),
|
| 239 |
+
"pause_frames": int(pause.sum()),
|
| 240 |
+
"leading_frames": int(durations[0]),
|
| 241 |
+
"trailing_frames": int(durations[-1]),
|
| 242 |
+
"vowel_voiced": voiced_share(lambda s: s in VOWEL_SET),
|
| 243 |
+
"voiceless_voiced": voiced_share(lambda s: s in VOICELESS),
|
| 244 |
+
"pause_voiced": round(float(voiced[pause].mean()), 4) if pause.any() else None,
|
| 245 |
+
"pause_level_db": round(float(level_db[pause].mean()), 1) if pause.any() else None,
|
| 246 |
+
"speech_level_db": round(float(np.percentile(level_db[~pause], 95)), 1) if (~pause).any() else None,
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class PhoneRecognizer:
|
| 251 |
+
"""Pretrained multilingual CTC phoneme recognizer for offline forced alignment."""
|
| 252 |
+
|
| 253 |
+
def __init__(self, device="cuda", name=ALIGNER_MODEL, local_files_only=False):
|
| 254 |
+
import json
|
| 255 |
+
from pathlib import Path
|
| 256 |
+
import torch
|
| 257 |
+
from huggingface_hub import hf_hub_download
|
| 258 |
+
from transformers import Wav2Vec2ForCTC
|
| 259 |
+
self.torch, self.device = torch, torch.device(device)
|
| 260 |
+
self.model = Wav2Vec2ForCTC.from_pretrained(name, local_files_only=local_files_only).to(self.device).eval()
|
| 261 |
+
if self.device.type == "cuda":
|
| 262 |
+
self.model = self.model.half()
|
| 263 |
+
vocabulary = Path(hf_hub_download(name, "vocab.json", local_files_only=local_files_only))
|
| 264 |
+
self.vocabulary = json.loads(vocabulary.read_text(encoding="utf-8"))
|
| 265 |
+
self.blank = int(self.model.config.pad_token_id)
|
| 266 |
+
self.name = name
|
| 267 |
+
self.revision = vocabulary.parent.name # snapshot directory = commit hash
|
| 268 |
+
missing = [p for p in sorted(PHONE_SET) if p not in self.vocabulary and p not in ALIGNER_LABEL_FALLBACK]
|
| 269 |
+
if missing:
|
| 270 |
+
raise ValueError(f"recogniser has no label for inventory phones {missing}")
|
| 271 |
+
|
| 272 |
+
def label(self, symbol):
|
| 273 |
+
symbol = symbol if symbol in self.vocabulary else ALIGNER_LABEL_FALLBACK[symbol]
|
| 274 |
+
return int(self.vocabulary[symbol])
|
| 275 |
+
|
| 276 |
+
def log_probs(self, wave, sample_rate):
|
| 277 |
+
from scipy.signal import resample_poly
|
| 278 |
+
torch = self.torch
|
| 279 |
+
factor = math.gcd(sample_rate, ALIGNER_RATE)
|
| 280 |
+
audio = resample_poly(np.asarray(wave, dtype=np.float64), ALIGNER_RATE // factor, sample_rate // factor)
|
| 281 |
+
audio = (audio - audio.mean()) / np.sqrt(audio.var() + 1e-7)
|
| 282 |
+
with torch.inference_mode():
|
| 283 |
+
values = torch.from_numpy(audio.astype(np.float32))[None].to(self.device, self.model.dtype)
|
| 284 |
+
return self.model(values).logits[0].float().log_softmax(-1).cpu().numpy()
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def align_utterance(recognizer, phonemized, wave, voiced, config, settings):
|
| 288 |
+
"""Return ``(durations, qc)`` for one recording or raise ``ValueError``."""
|
| 289 |
+
symbols = phonemized.symbols
|
| 290 |
+
frames = len(wave) // config.hop
|
| 291 |
+
if len(wave) != frames * config.hop or len(voiced) != frames:
|
| 292 |
+
raise ValueError("waveform length must be frames * hop")
|
| 293 |
+
labels = [recognizer.label(s) for s in symbols if s in PHONE_SET or s == UNK]
|
| 294 |
+
log_probs = recognizer.log_probs(wave, config.sample_rate)
|
| 295 |
+
spans = token_spans(log_probs, labels, recognizer.blank)
|
| 296 |
+
level = frame_energy_db(wave, config.hop, settings.energy_window)
|
| 297 |
+
silent, threshold = silence_mask(level, settings)
|
| 298 |
+
durations = assemble(symbols, spans, frames, silent, config.hop, config.sample_rate, settings)
|
| 299 |
+
qc = quality(symbols, durations, spans, log_probs, labels, np.asarray(voiced) > 0.5, level, config.hop, config.sample_rate)
|
| 300 |
+
qc["silence_threshold_db"] = round(threshold, 1)
|
| 301 |
+
return durations.tolist(), qc
|
code/src/lua_nova_v1/data/annotate.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned annotation layer: phoneme tokens and validated CTC durations."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
import concurrent.futures
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import time
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from .aligner import ALIGNER_MODEL, AlignmentSettings, PhoneRecognizer, align_utterance
|
| 14 |
+
from ..config import ANNOTATION_VERSION, Config
|
| 15 |
+
from .journal import append, atomic_json, file_hash, recover
|
| 16 |
+
from ..text.phonemizer import (PHONE_SET, SYMBOL_TO_ID, UNK, VOICELESS, VOWEL_SET, Phonemized, frontend_fingerprint,
|
| 17 |
+
frontend_identity, frontend_runtime, phonemize)
|
| 18 |
+
|
| 19 |
+
SPLITS = ("train", "validation", "test")
|
| 20 |
+
FRICATIVES = frozenset(("f", "θ", "s", "ʃ", "x"))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def load_acoustic_rows(features, split, config):
|
| 24 |
+
metadata = features / (split + ".preparation.json")
|
| 25 |
+
if not metadata.exists() or not json.loads(metadata.read_text()).get("complete"):
|
| 26 |
+
raise ValueError(f"acoustic preparation for {split} is missing or incomplete")
|
| 27 |
+
rows = [json.loads(line) for line in (features / (split + ".jsonl")).read_text(encoding="utf-8").split("\n") if line.strip()]
|
| 28 |
+
for row in rows:
|
| 29 |
+
# Current acoustic-only files, or files from the byte-token preparation:
|
| 30 |
+
# same audio/DSP settings, stale tokens that are ignored here.
|
| 31 |
+
if row.get("acoustic") != config.acoustic_fingerprint and row.get("features") != config.legacy_feature_fingerprint:
|
| 32 |
+
raise ValueError("feature files were not produced with compatible audio/DSP settings; rerun acoustic preparation")
|
| 33 |
+
if row["speaker"] not in config.speakers:
|
| 34 |
+
raise ValueError(f"unknown speaker {row['speaker']!r}")
|
| 35 |
+
return rows
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def text_key(text):
|
| 39 |
+
return hashlib.sha256(text.strip().encode()).hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def phonemize_texts(rows, cache, workers=16, log=print):
|
| 43 |
+
known = {}
|
| 44 |
+
for record in recover(cache):
|
| 45 |
+
known[record["text_hash"]] = Phonemized(tuple(record["symbols"]), tuple(SYMBOL_TO_ID[s] for s in record["symbols"]),
|
| 46 |
+
tuple(record["stress"]), tuple(record["unknown"]))
|
| 47 |
+
todo = {}
|
| 48 |
+
for row in rows:
|
| 49 |
+
if row["text_hash"] != text_key(row["text"]):
|
| 50 |
+
raise ValueError(f"text hash mismatch for {row['id']}")
|
| 51 |
+
if row["text_hash"] not in known:
|
| 52 |
+
todo[row["text_hash"]] = row["text"]
|
| 53 |
+
if todo:
|
| 54 |
+
log(f"phonemizing {len(todo)} distinct texts")
|
| 55 |
+
with cache.open("a", encoding="utf-8") as stream, concurrent.futures.ThreadPoolExecutor(workers) as pool:
|
| 56 |
+
for key, result in zip(todo, pool.map(phonemize, todo.values())):
|
| 57 |
+
known[key] = result
|
| 58 |
+
append(stream, {"text_hash": key, "symbols": list(result.symbols), "stress": list(result.stress),
|
| 59 |
+
"unknown": list(result.unknown)}, sync=False)
|
| 60 |
+
return known
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def boundary_offsets(symbols, durations, voiced, reach=6):
|
| 64 |
+
"""Label-free timing probe. At vowel -> voiceless-consonant and voiceless
|
| 65 |
+
fricative -> vowel boundaries the pitch tracker's voicing must flip; return
|
| 66 |
+
the signed distance (frames) from the aligned boundary to the nearest flip."""
|
| 67 |
+
found = {"vowel_to_voiceless": [], "fricative_to_vowel": []}
|
| 68 |
+
ends = np.cumsum(durations)
|
| 69 |
+
active = [i for i, d in enumerate(durations) if d > 0]
|
| 70 |
+
for a, b in zip(active[:-1], active[1:]):
|
| 71 |
+
if symbols[a] in VOWEL_SET and symbols[b] in VOICELESS:
|
| 72 |
+
kind, before = "vowel_to_voiceless", True
|
| 73 |
+
elif symbols[a] in FRICATIVES and symbols[b] in VOWEL_SET:
|
| 74 |
+
kind, before = "fricative_to_vowel", False
|
| 75 |
+
else:
|
| 76 |
+
continue
|
| 77 |
+
boundary = int(ends[a])
|
| 78 |
+
best = None
|
| 79 |
+
for shift in range(-reach, reach + 1):
|
| 80 |
+
f = boundary + shift
|
| 81 |
+
if 0 < f < len(voiced) and bool(voiced[f - 1]) == before and bool(voiced[f]) != before:
|
| 82 |
+
if best is None or abs(shift) < abs(best):
|
| 83 |
+
best = shift
|
| 84 |
+
found[kind].append(best)
|
| 85 |
+
return found
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def summarize_offsets(collected):
|
| 89 |
+
summary = {}
|
| 90 |
+
for kind, values in collected.items():
|
| 91 |
+
hits = np.array([v for v in values if v is not None], dtype=np.float64)
|
| 92 |
+
summary[kind] = {"boundaries": len(values), "flip_found": round(len(hits) / max(len(values), 1), 4)}
|
| 93 |
+
if len(hits):
|
| 94 |
+
summary[kind].update(mean_offset_frames=round(float(hits.mean()), 3), mean_abs_frames=round(float(np.abs(hits).mean()), 3),
|
| 95 |
+
within_1_frame=round(float((np.abs(hits) <= 1).mean()), 4),
|
| 96 |
+
within_2_frames=round(float((np.abs(hits) <= 2).mean()), 4))
|
| 97 |
+
return summary
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def gate(row, limits):
|
| 101 |
+
qc, reasons = row["qc"], []
|
| 102 |
+
if row["unknown"]:
|
| 103 |
+
reasons.append("unknown_phoneme")
|
| 104 |
+
if qc["weak_phone_fraction"] > limits["max_weak_phone_fraction"]:
|
| 105 |
+
reasons.append("weak_alignment")
|
| 106 |
+
if qc["token_probability_mean"] < limits["min_token_probability"]:
|
| 107 |
+
reasons.append("low_confidence")
|
| 108 |
+
if qc["max_phone_frames"] > limits["max_phone_frames"]:
|
| 109 |
+
reasons.append("overlong_phone")
|
| 110 |
+
if qc["vowel_voiced"] is not None and qc["vowel_voiced"] < limits["min_vowel_voiced"]:
|
| 111 |
+
reasons.append("vowels_not_voiced")
|
| 112 |
+
if not limits["min_phones_per_second"] <= qc["phones_per_second"] <= limits["max_phones_per_second"]:
|
| 113 |
+
reasons.append("implausible_rate")
|
| 114 |
+
return reasons
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def quantiles(values):
|
| 118 |
+
values = np.asarray([v for v in values if v is not None], dtype=np.float64)
|
| 119 |
+
if not len(values):
|
| 120 |
+
return None
|
| 121 |
+
return {str(q): round(float(np.percentile(values, q)), 4) for q in (0, 1, 5, 25, 50, 75, 95, 99, 100)}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def main():
|
| 125 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 126 |
+
parser.add_argument("--features", type=Path, required=True, help="Directory with <split>.jsonl acoustic manifests")
|
| 127 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 128 |
+
parser.add_argument("--dataset-revision", required=True)
|
| 129 |
+
parser.add_argument("--config", type=Path)
|
| 130 |
+
parser.add_argument("--device", default="cuda")
|
| 131 |
+
parser.add_argument("--splits", nargs="+", default=list(SPLITS), choices=SPLITS)
|
| 132 |
+
parser.add_argument("--limit", type=int, help="Annotate only the first N rows per split (smoke test; never complete)")
|
| 133 |
+
parser.add_argument("--resume", action="store_true")
|
| 134 |
+
parser.add_argument("--refine", type=int, default=0, help="Boundary refinement passes with the from-scratch frame classifier")
|
| 135 |
+
parser.add_argument("--refine-band", type=int, default=4)
|
| 136 |
+
parser.add_argument("--stage", default="ctc", help="Durations used for the final manifests: ctc or refined-<n>")
|
| 137 |
+
parser.add_argument("--min-pause-frames", type=int, default=AlignmentSettings.min_pause_frames)
|
| 138 |
+
parser.add_argument("--max-weak-phone-fraction", type=float, default=0.25)
|
| 139 |
+
parser.add_argument("--min-token-probability", type=float, default=0.5)
|
| 140 |
+
parser.add_argument("--max-phone-frames", type=int, default=70)
|
| 141 |
+
parser.add_argument("--min-vowel-voiced", type=float, default=0.5)
|
| 142 |
+
parser.add_argument("--min-phones-per-second", type=float, default=4.0)
|
| 143 |
+
parser.add_argument("--max-phones-per-second", type=float, default=30.0)
|
| 144 |
+
parser.add_argument("--local-files-only", action="store_true", help="Load aligner weights from local Hugging Face cache only")
|
| 145 |
+
args = parser.parse_args()
|
| 146 |
+
config = Config.from_dict(json.loads(args.config.read_text())) if args.config else Config()
|
| 147 |
+
settings = AlignmentSettings(min_pause_frames=args.min_pause_frames)
|
| 148 |
+
limits = {key: getattr(args, key) for key in ("max_weak_phone_fraction", "min_token_probability", "max_phone_frames",
|
| 149 |
+
"min_vowel_voiced", "min_phones_per_second", "max_phones_per_second")}
|
| 150 |
+
started = time.time()
|
| 151 |
+
|
| 152 |
+
def log(message):
|
| 153 |
+
print(json.dumps({"elapsed": round(time.time() - started, 1), "message": message}), flush=True)
|
| 154 |
+
|
| 155 |
+
rows = {split: load_acoustic_rows(args.features, split, config) for split in args.splits}
|
| 156 |
+
if args.limit:
|
| 157 |
+
rows = {split: value[:args.limit] for split, value in rows.items()}
|
| 158 |
+
recognizer = PhoneRecognizer(args.device, local_files_only=args.local_files_only)
|
| 159 |
+
identity = {
|
| 160 |
+
"annotation_version": ANNOTATION_VERSION, "acoustic": config.acoustic_fingerprint, "frontend": frontend_fingerprint(),
|
| 161 |
+
**frontend_runtime(), "aligner": {"model": ALIGNER_MODEL, "revision": recognizer.revision},
|
| 162 |
+
"alignment": settings.to_dict(), "dataset_revision": args.dataset_revision, "limit": args.limit,
|
| 163 |
+
"sources": {split: file_hash(args.features / (split + ".jsonl")) for split in args.splits},
|
| 164 |
+
}
|
| 165 |
+
fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
|
| 166 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 167 |
+
metadata_path = args.output / "annotations.json"
|
| 168 |
+
if metadata_path.exists():
|
| 169 |
+
if not args.resume:
|
| 170 |
+
raise FileExistsError("annotation directory exists; use --resume or a new directory")
|
| 171 |
+
if json.loads(metadata_path.read_text())["identity"] != identity:
|
| 172 |
+
raise ValueError("front end, aligner, settings or sources changed: these annotations are stale; use a new directory")
|
| 173 |
+
atomic_json(metadata_path, {"identity": identity, "fingerprint": fingerprint, "complete": False})
|
| 174 |
+
(args.output / "raw").mkdir(exist_ok=True)
|
| 175 |
+
|
| 176 |
+
every = [row for split in args.splits for row in rows[split]]
|
| 177 |
+
phonemes = phonemize_texts(every, args.output / "phonemes.jsonl", log=log)
|
| 178 |
+
hashes = {split: {row["text_hash"] for row in rows[split]} for split in args.splits}
|
| 179 |
+
for i, a in enumerate(args.splits):
|
| 180 |
+
for b in args.splits[i + 1:]:
|
| 181 |
+
if hashes[a] & hashes[b]:
|
| 182 |
+
raise ValueError(f"sentence leakage between {a} and {b}")
|
| 183 |
+
|
| 184 |
+
# 1. CTC alignment, journalled per utterance.
|
| 185 |
+
raw = {}
|
| 186 |
+
voicing = {}
|
| 187 |
+
for split in args.splits:
|
| 188 |
+
journal = args.output / "raw" / (split + ".jsonl")
|
| 189 |
+
done = {record["id"]: record for record in recover(journal)}
|
| 190 |
+
pending = [row for row in rows[split] if row["id"] not in done]
|
| 191 |
+
log(f"aligning {split}: {len(pending)} pending, {len(done)} done")
|
| 192 |
+
with journal.open("a", encoding="utf-8") as stream:
|
| 193 |
+
for count, row in enumerate(pending, 1):
|
| 194 |
+
item = torch.load(args.features / row["path"], map_location="cpu", weights_only=True)
|
| 195 |
+
voicing[row["id"]] = item["prosody"][:, 1].numpy() > 0.5
|
| 196 |
+
try:
|
| 197 |
+
if item["mel"].shape[0] != row["frames"]:
|
| 198 |
+
raise ValueError("frame count differs from the manifest")
|
| 199 |
+
durations, qc = align_utterance(recognizer, phonemes[row["text_hash"]], item["wave"].numpy(),
|
| 200 |
+
item["prosody"][:, 1].numpy(), config, settings)
|
| 201 |
+
record = {"id": row["id"], "ok": True, "durations": durations, "qc": qc}
|
| 202 |
+
except (ValueError, RuntimeError) as error:
|
| 203 |
+
record = {"id": row["id"], "ok": False, "reason": f"{type(error).__name__}: {error}"}
|
| 204 |
+
append(stream, record, sync=count % 200 == 0 or count == len(pending))
|
| 205 |
+
done[row["id"]] = record
|
| 206 |
+
if count % 500 == 0:
|
| 207 |
+
log(f"aligned {split} {count}/{len(pending)}")
|
| 208 |
+
raw[split] = done
|
| 209 |
+
del recognizer
|
| 210 |
+
if args.device.startswith("cuda"):
|
| 211 |
+
torch.cuda.empty_cache()
|
| 212 |
+
|
| 213 |
+
# 2. Optional boundary refinement over all splits together.
|
| 214 |
+
stages = {"ctc": {split: {key: value["durations"] for key, value in raw[split].items() if value["ok"]} for split in args.splits}}
|
| 215 |
+
if args.refine:
|
| 216 |
+
from .refine import refine
|
| 217 |
+
directories = [args.output / f"refined-{n + 1}" for n in range(args.refine)]
|
| 218 |
+
if all((d / (split + ".jsonl")).exists() for d in directories for split in args.splits):
|
| 219 |
+
for n, directory in enumerate(directories):
|
| 220 |
+
stages[f"refined-{n + 1}"] = {split: {r["id"]: r["durations"] for r in recover(directory / (split + ".jsonl"))} for split in args.splits}
|
| 221 |
+
else:
|
| 222 |
+
items, owners = [], []
|
| 223 |
+
for split in args.splits:
|
| 224 |
+
for row in rows[split]:
|
| 225 |
+
if raw[split][row["id"]]["ok"]:
|
| 226 |
+
item = torch.load(args.features / row["path"], map_location="cpu", weights_only=True)
|
| 227 |
+
items.append({"symbols": phonemes[row["text_hash"]].symbols, "durations": raw[split][row["id"]]["durations"],
|
| 228 |
+
"mel": item["mel"], "speaker": config.speakers.index(row["speaker"]), "group": row["text_hash"]})
|
| 229 |
+
owners.append((split, row["id"]))
|
| 230 |
+
log(f"refining {len(items)} alignments")
|
| 231 |
+
for n, durations in enumerate(refine(items, config, args.device, args.refine, args.refine_band, log=log)):
|
| 232 |
+
directory = directories[n]
|
| 233 |
+
directory.mkdir(exist_ok=True)
|
| 234 |
+
stage = {split: {} for split in args.splits}
|
| 235 |
+
for (split, identifier), value in zip(owners, durations):
|
| 236 |
+
stage[split][identifier] = value
|
| 237 |
+
for split in args.splits:
|
| 238 |
+
temporary = directory / (split + ".jsonl.tmp")
|
| 239 |
+
temporary.write_text("".join(json.dumps({"id": k, "durations": v}) + "\n" for k, v in stage[split].items()))
|
| 240 |
+
temporary.replace(directory / (split + ".jsonl"))
|
| 241 |
+
stages[f"refined-{n + 1}"] = stage
|
| 242 |
+
del items
|
| 243 |
+
if args.stage not in stages:
|
| 244 |
+
raise ValueError(f"unknown stage {args.stage!r}; available: {sorted(stages)}")
|
| 245 |
+
|
| 246 |
+
# 3. Label-free timing probe for every stage, then gate and write manifests.
|
| 247 |
+
probe = {}
|
| 248 |
+
for name, stage in stages.items():
|
| 249 |
+
collected = {voice: defaultdict(list) for voice in config.speakers}
|
| 250 |
+
for split in args.splits:
|
| 251 |
+
for row in rows[split]:
|
| 252 |
+
if row["id"] not in stage[split]:
|
| 253 |
+
continue
|
| 254 |
+
if row["id"] not in voicing:
|
| 255 |
+
voicing[row["id"]] = torch.load(args.features / row["path"], map_location="cpu", weights_only=True)["prosody"][:, 1].numpy() > 0.5
|
| 256 |
+
found = boundary_offsets(phonemes[row["text_hash"]].symbols, stage[split][row["id"]], voicing[row["id"]])
|
| 257 |
+
for kind, values in found.items():
|
| 258 |
+
collected[row["speaker"]][kind].extend(values)
|
| 259 |
+
probe[name] = {voice: summarize_offsets(collected[voice]) for voice in config.speakers}
|
| 260 |
+
log({"timing_probe": name, **probe[name]})
|
| 261 |
+
|
| 262 |
+
summary = {"limits": limits, "stage": args.stage, "timing_probe": probe, "splits": {}}
|
| 263 |
+
chosen = stages[args.stage]
|
| 264 |
+
phone_frames = {voice: defaultdict(list) for voice in config.speakers}
|
| 265 |
+
pause_tokens = Counter()
|
| 266 |
+
pause_nonzero = Counter()
|
| 267 |
+
for split in args.splits:
|
| 268 |
+
accepted, rejected = [], []
|
| 269 |
+
for row in rows[split]:
|
| 270 |
+
record = raw[split][row["id"]]
|
| 271 |
+
result = phonemes[row["text_hash"]]
|
| 272 |
+
if not record["ok"]:
|
| 273 |
+
rejected.append({"id": row["id"], "speaker": row["speaker"], "text": row["text"], "reasons": [record["reason"]]})
|
| 274 |
+
continue
|
| 275 |
+
durations = chosen[split][row["id"]]
|
| 276 |
+
entry = {"id": row["id"], "split": split, "speaker": row["speaker"], "text": row["text"], "text_hash": row["text_hash"],
|
| 277 |
+
"path": row["path"], "frames": row["frames"], "symbols": " ".join(result.symbols), "tokens": list(result.ids),
|
| 278 |
+
"stress": list(result.stress), "durations": durations, "unknown": list(result.unknown), "qc": record["qc"],
|
| 279 |
+
"provenance": {**row.get("provenance", {}), "dataset_revision": args.dataset_revision},
|
| 280 |
+
"acoustic": config.acoustic_fingerprint, "frontend": frontend_fingerprint(), "annotation": fingerprint}
|
| 281 |
+
if sum(durations) != row["frames"] or len(durations) != len(result.ids):
|
| 282 |
+
raise RuntimeError(f"durations of {row['id']} do not match its frames/tokens")
|
| 283 |
+
reasons = gate(entry, limits)
|
| 284 |
+
if reasons:
|
| 285 |
+
rejected.append({"id": row["id"], "speaker": row["speaker"], "text": row["text"], "reasons": reasons, "qc": record["qc"]})
|
| 286 |
+
continue
|
| 287 |
+
accepted.append(entry)
|
| 288 |
+
for symbol, frames in zip(result.symbols, durations):
|
| 289 |
+
if symbol in PHONE_SET or symbol == UNK:
|
| 290 |
+
phone_frames[row["speaker"]][symbol].append(frames)
|
| 291 |
+
else:
|
| 292 |
+
pause_tokens[symbol] += 1
|
| 293 |
+
pause_nonzero[symbol] += frames > 0
|
| 294 |
+
for name, payload in ((split + ".jsonl", accepted), (split + ".rejected.jsonl", rejected)):
|
| 295 |
+
temporary = args.output / (name + ".tmp")
|
| 296 |
+
temporary.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in payload), encoding="utf-8")
|
| 297 |
+
temporary.replace(args.output / name)
|
| 298 |
+
by_voice = {voice: sum(r["speaker"] == voice for r in accepted) for voice in config.speakers}
|
| 299 |
+
summary["splits"][split] = {
|
| 300 |
+
"accepted": len(accepted), "rejected": len(rejected), "accepted_by_voice": by_voice,
|
| 301 |
+
"accepted_hours": round(sum(r["frames"] for r in accepted) * config.hop / config.sample_rate / 3600, 3),
|
| 302 |
+
"rejection_reasons": dict(Counter(reason.split(":")[0] for r in rejected for reason in r["reasons"])),
|
| 303 |
+
"qc_quantiles": {key: quantiles([raw[split][r["id"]]["qc"].get(key) for r in rows[split] if raw[split][r["id"]]["ok"]])
|
| 304 |
+
for key in ("token_probability_mean", "weak_phone_fraction", "max_phone_frames", "one_frame_phone_fraction",
|
| 305 |
+
"phones_per_second", "vowel_voiced", "voiceless_voiced", "pause_voiced", "leading_frames",
|
| 306 |
+
"trailing_frames", "pause_level_db")},
|
| 307 |
+
}
|
| 308 |
+
summary["phone_duration_frames"] = {
|
| 309 |
+
voice: {symbol: {"count": len(values), "mean": round(float(np.mean(values)), 2), "median": float(np.median(values)),
|
| 310 |
+
"one_frame": round(float(np.mean(np.asarray(values) == 1)), 3)}
|
| 311 |
+
for symbol, values in sorted(table.items(), key=lambda kv: -len(kv[1]))}
|
| 312 |
+
for voice, table in phone_frames.items()}
|
| 313 |
+
summary["pause_tokens"] = {symbol: {"count": pause_tokens[symbol], "with_frames": round(pause_nonzero[symbol] / pause_tokens[symbol], 4)}
|
| 314 |
+
for symbol in pause_tokens}
|
| 315 |
+
complete = not args.limit and set(args.splits) == set(SPLITS)
|
| 316 |
+
atomic_json(args.output / "summary.json", summary)
|
| 317 |
+
atomic_json(metadata_path, {"identity": identity, "fingerprint": fingerprint, "complete": complete, "stage": args.stage,
|
| 318 |
+
"acoustic_root": str(args.features.resolve()), "limits": limits,
|
| 319 |
+
"counts": {split: summary["splits"][split]["accepted"] for split in args.splits}})
|
| 320 |
+
log({"complete": complete, "splits": {s: {k: v for k, v in summary["splits"][s].items() if k != "qc_quantiles"} for s in args.splits}})
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
if __name__ == "__main__":
|
| 324 |
+
main()
|
code/src/lua_nova_v1/data/dataset.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training data: acoustic feature files joined with the annotation layer."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import torch
|
| 7 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 8 |
+
|
| 9 |
+
from ..text.phonemizer import PHONE_IDS, SYMBOL_TO_ID, VOWELS, frontend_fingerprint
|
| 10 |
+
|
| 11 |
+
VOWEL_IDS = frozenset(SYMBOL_TO_ID[v] for v in VOWELS)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def continuous_pitch(pitch, voiced, default=0.0, window=5, tolerance=0.45):
|
| 15 |
+
"""Clean a pitch track and make it continuous.
|
| 16 |
+
|
| 17 |
+
``pitch`` is log(F0/reference) on voiced frames. Values further than
|
| 18 |
+
``tolerance`` (about 0.65 octave) from the local median are tracker errors
|
| 19 |
+
(octave jumps); they stay voiced but their value is not trusted. Untrusted
|
| 20 |
+
and unvoiced frames are filled by linear interpolation so the oscillator and
|
| 21 |
+
the pitch predictor see one smooth curve. Returns ``(curve, trusted)``.
|
| 22 |
+
"""
|
| 23 |
+
voiced = voiced > 0.5
|
| 24 |
+
trusted = voiced.clone()
|
| 25 |
+
if int(voiced.sum()) >= 3:
|
| 26 |
+
values = pitch[voiced]
|
| 27 |
+
padded = torch.nn.functional.pad(values[None, None], (window // 2, window // 2), mode="replicate")[0, 0]
|
| 28 |
+
median = padded.unfold(0, window, 1).median(dim=1).values
|
| 29 |
+
trusted[voiced.nonzero().squeeze(1)[(values - median).abs() > tolerance]] = False
|
| 30 |
+
index = trusted.nonzero().squeeze(1)
|
| 31 |
+
if index.numel() == 0:
|
| 32 |
+
return torch.full_like(pitch, default), trusted.float()
|
| 33 |
+
position = torch.arange(pitch.numel())
|
| 34 |
+
right = torch.searchsorted(index, position).clamp(max=index.numel() - 1)
|
| 35 |
+
left = (torch.searchsorted(index, position, right=True) - 1).clamp(min=0)
|
| 36 |
+
a, b = index[left], index[right]
|
| 37 |
+
span = (b - a).clamp(min=1).float()
|
| 38 |
+
weight = ((position - a).float() / span).clamp(0, 1)
|
| 39 |
+
curve = pitch[a] * (1 - weight) + pitch[b] * weight
|
| 40 |
+
return curve, trusted.float()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class AnnotatedDataset:
|
| 44 |
+
def __init__(self, manifest, config, acoustic_root=None, cache=True, voiced_vowels=False, require_vocos_mel=False):
|
| 45 |
+
self.manifest = Path(manifest)
|
| 46 |
+
metadata_path = self.manifest.parent / "annotations.json"
|
| 47 |
+
if not metadata_path.exists():
|
| 48 |
+
raise ValueError("not an annotation manifest (legacy byte-token manifests are stale): run lua-nova-annotate")
|
| 49 |
+
metadata = json.loads(metadata_path.read_text())
|
| 50 |
+
if not metadata.get("complete"):
|
| 51 |
+
raise ValueError("annotation run is incomplete; finish it with --resume before training")
|
| 52 |
+
self.annotation = metadata["fingerprint"]
|
| 53 |
+
self.root = Path(acoustic_root or metadata["acoustic_root"])
|
| 54 |
+
self.fingerprint = hashlib.sha256(self.manifest.read_bytes()).hexdigest()
|
| 55 |
+
# Physical LF-delimited records: Unicode separators inside text are data.
|
| 56 |
+
self.rows = [json.loads(line) for line in self.manifest.read_text(encoding="utf-8").split("\n") if line.strip()]
|
| 57 |
+
self.config = config
|
| 58 |
+
self.require_vocos_mel = bool(require_vocos_mel)
|
| 59 |
+
if not self.rows:
|
| 60 |
+
raise ValueError("empty dataset")
|
| 61 |
+
frontend = frontend_fingerprint()
|
| 62 |
+
for row in self.rows:
|
| 63 |
+
if "durations" not in row or row.get("frontend") != frontend:
|
| 64 |
+
raise ValueError("tokens were produced by a different front end; re-run annotation")
|
| 65 |
+
if row.get("acoustic") != config.acoustic_fingerprint:
|
| 66 |
+
raise ValueError("acoustic feature settings differ from this configuration")
|
| 67 |
+
if row.get("annotation") != self.annotation:
|
| 68 |
+
raise ValueError("manifest rows come from a different annotation run")
|
| 69 |
+
if len(row["tokens"]) != len(row["durations"]) or len(row["tokens"]) != len(row["stress"]):
|
| 70 |
+
raise ValueError(f"token/duration length mismatch: {row['id']}")
|
| 71 |
+
if sum(row["durations"]) != row["frames"] or min(row["durations"]) < 0:
|
| 72 |
+
raise ValueError(f"durations do not cover the frames exactly: {row['id']}")
|
| 73 |
+
if any(d < 1 for t, d in zip(row["tokens"], row["durations"]) if t in PHONE_IDS):
|
| 74 |
+
raise ValueError(f"phoneme without frames: {row['id']}")
|
| 75 |
+
if not 0 < len(row["tokens"]) <= config.max_tokens or not 0 < row["frames"] <= config.max_frames:
|
| 76 |
+
raise ValueError(f"utterance exceeds model limits: {row['id']}")
|
| 77 |
+
if max(row["tokens"]) >= config.vocab_size or min(row["tokens"]) < 1 or row["speaker"] not in config.speakers:
|
| 78 |
+
raise ValueError(f"invalid token or speaker: {row['id']}")
|
| 79 |
+
ids = [r["id"] for r in self.rows]
|
| 80 |
+
if len(ids) != len(set(ids)):
|
| 81 |
+
raise ValueError("duplicate IDs in manifest")
|
| 82 |
+
self.lengths = [r["frames"] for r in self.rows]
|
| 83 |
+
self._cache = {} if cache else None
|
| 84 |
+
self.voiced_vowels = voiced_vowels
|
| 85 |
+
|
| 86 |
+
def __len__(self):
|
| 87 |
+
return len(self.rows)
|
| 88 |
+
|
| 89 |
+
def preload(self, indices=None, workers=8):
|
| 90 |
+
"""Read feature files into memory up front (about 10 ms each otherwise
|
| 91 |
+
lands on the first training steps). Needs ``cache=True``."""
|
| 92 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 93 |
+
with ThreadPoolExecutor(workers) as pool:
|
| 94 |
+
list(pool.map(self.__getitem__, range(len(self)) if indices is None else indices))
|
| 95 |
+
|
| 96 |
+
def __getitem__(self, index):
|
| 97 |
+
if self._cache is not None and index in self._cache:
|
| 98 |
+
return self._cache[index]
|
| 99 |
+
row, c = self.rows[index], self.config
|
| 100 |
+
path = (self.root / row["path"]).resolve()
|
| 101 |
+
if not path.is_relative_to(self.root.resolve()):
|
| 102 |
+
raise ValueError("feature file escapes the acoustic root")
|
| 103 |
+
stored = torch.load(path, map_location="cpu", weights_only=True)
|
| 104 |
+
t = row["frames"]
|
| 105 |
+
if stored["mel"].shape != (t, c.n_mels) or stored["prosody"].shape != (t, 3) or stored["wave"].shape != (t * c.hop,):
|
| 106 |
+
raise ValueError(f"feature dimensions differ from the manifest: {path.name}")
|
| 107 |
+
if any(not torch.isfinite(stored[k]).all() for k in ("mel", "prosody", "wave")):
|
| 108 |
+
raise ValueError("non-finite features")
|
| 109 |
+
if self.require_vocos_mel and c.vocoder_type == "vocos":
|
| 110 |
+
if "vocos_mel" not in stored:
|
| 111 |
+
raise ValueError(f"missing vocos_mel in {path.name}")
|
| 112 |
+
if stored["vocos_mel"].shape != (t, c.vocos_n_mels) or not torch.isfinite(stored["vocos_mel"]).all():
|
| 113 |
+
raise ValueError(f"vocos_mel dimensions/values invalid in {path.name}")
|
| 114 |
+
pitch, trusted = continuous_pitch(stored["prosody"][:, 0], stored["prosody"][:, 1])
|
| 115 |
+
voiced = stored["prosody"][:, 1]
|
| 116 |
+
if self.voiced_vowels:
|
| 117 |
+
# The pitch tracker misses low, creaky vowels (12% of M2's vowel frames),
|
| 118 |
+
# and a model trained on those labels drops whole vowels. A vowel is voiced
|
| 119 |
+
# by definition: mark its frames voiced. Their pitch stays interpolated and
|
| 120 |
+
# untrusted, so the pitch loss still ignores what the tracker did not measure.
|
| 121 |
+
vowel = torch.repeat_interleave(torch.tensor([t in VOWEL_IDS for t in row["tokens"]]), torch.tensor(row["durations"]))
|
| 122 |
+
voiced = torch.maximum(voiced, vowel.to(voiced.dtype))
|
| 123 |
+
item = {
|
| 124 |
+
"tokens": torch.tensor(row["tokens"], dtype=torch.long), "stress": torch.tensor(row["stress"], dtype=torch.long),
|
| 125 |
+
"durations": torch.tensor(row["durations"], dtype=torch.long), "speaker": c.speakers.index(row["speaker"]),
|
| 126 |
+
"wave": stored["wave"], "mel": stored["mel"],
|
| 127 |
+
# Continuous log pitch, voiced flag, normalized log energy.
|
| 128 |
+
"prosody": torch.stack((pitch, voiced, (stored["prosody"][:, 2] - c.energy_mean) / c.energy_scale), dim=-1),
|
| 129 |
+
"pitch_trusted": trusted,
|
| 130 |
+
}
|
| 131 |
+
if "vocos_mel" in stored:
|
| 132 |
+
item["vocos_mel"] = stored["vocos_mel"]
|
| 133 |
+
if self._cache is not None:
|
| 134 |
+
self._cache[index] = item
|
| 135 |
+
return item
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def collate(items, device="cpu"):
|
| 139 |
+
keys = ["tokens", "stress", "durations", "mel", "prosody", "pitch_trusted", "wave"]
|
| 140 |
+
if "vocos_mel" in items[0]:
|
| 141 |
+
keys.append("vocos_mel")
|
| 142 |
+
batch = {key: pad_sequence([x[key] for x in items], batch_first=True).to(device) for key in keys}
|
| 143 |
+
batch["token_lengths"] = torch.tensor([x["tokens"].numel() for x in items], device=device)
|
| 144 |
+
batch["frame_lengths"] = torch.tensor([x["mel"].shape[0] for x in items], device=device)
|
| 145 |
+
batch["speakers"] = torch.tensor([x["speaker"] for x in items], device=device)
|
| 146 |
+
return batch
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class BucketSampler:
|
| 150 |
+
"""Random batches of similar length under a padded-frame budget.
|
| 151 |
+
|
| 152 |
+
Sampling is with replacement from pools; the generator state and the
|
| 153 |
+
not-yet-used batches are checkpointed, so a resumed run sees the same data.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
def __init__(self, lengths, frame_budget, max_batch, seed, pool=256):
|
| 157 |
+
self.lengths, self.frame_budget, self.max_batch, self.pool = lengths, frame_budget, max_batch, pool
|
| 158 |
+
self.generator = torch.Generator().manual_seed(seed)
|
| 159 |
+
self.pending = []
|
| 160 |
+
|
| 161 |
+
def next(self):
|
| 162 |
+
if not self.pending:
|
| 163 |
+
indices = sorted(torch.randint(len(self.lengths), (self.pool,), generator=self.generator).tolist(), key=lambda i: self.lengths[i])
|
| 164 |
+
batches, current = [], []
|
| 165 |
+
for index in indices:
|
| 166 |
+
if current and (len(current) == self.max_batch or (len(current) + 1) * self.lengths[index] > self.frame_budget):
|
| 167 |
+
batches.append(current)
|
| 168 |
+
current = []
|
| 169 |
+
current.append(index)
|
| 170 |
+
batches.append(current)
|
| 171 |
+
self.pending = [batches[i] for i in torch.randperm(len(batches), generator=self.generator).tolist()]
|
| 172 |
+
return self.pending.pop()
|
| 173 |
+
|
| 174 |
+
def state(self):
|
| 175 |
+
return {"generator": self.generator.get_state(), "pending": [list(b) for b in self.pending]}
|
| 176 |
+
|
| 177 |
+
def load_state(self, state):
|
| 178 |
+
self.generator.set_state(state["generator"].cpu())
|
| 179 |
+
self.pending = [list(b) for b in state["pending"]]
|
code/src/lua_nova_v1/data/journal.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Durable JSONL preparation journals. A partial final write is recoverable."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def file_hash(path):
|
| 11 |
+
digest = hashlib.sha256()
|
| 12 |
+
with Path(path).open("rb") as stream:
|
| 13 |
+
for chunk in iter(lambda: stream.read(1024*1024), b""):
|
| 14 |
+
digest.update(chunk)
|
| 15 |
+
return digest.hexdigest()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def json_safe(value):
|
| 19 |
+
if value is None or isinstance(value, (str, bool, int)):
|
| 20 |
+
return value
|
| 21 |
+
if isinstance(value, float):
|
| 22 |
+
return value if math.isfinite(value) else str(value)
|
| 23 |
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
| 24 |
+
return {"binary_bytes":len(value), "sha256":hashlib.sha256(value).hexdigest()}
|
| 25 |
+
if isinstance(value, dict):
|
| 26 |
+
return {str(k):json_safe(v) for k, v in value.items()}
|
| 27 |
+
if isinstance(value, (list, tuple)):
|
| 28 |
+
return [json_safe(v) for v in value]
|
| 29 |
+
raise TypeError(f"unsupported provenance type: {type(value).__name__}")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def recover(path):
|
| 33 |
+
"""Read physical LF-delimited records and truncate only an incomplete tail.
|
| 34 |
+
|
| 35 |
+
A malformed complete line is corruption, not an interrupted append: fail.
|
| 36 |
+
The caller must hold the split's exclusive preparation lock.
|
| 37 |
+
"""
|
| 38 |
+
path = Path(path)
|
| 39 |
+
if not path.exists():
|
| 40 |
+
return []
|
| 41 |
+
records = []
|
| 42 |
+
with path.open("r+b") as stream:
|
| 43 |
+
while True:
|
| 44 |
+
position = stream.tell()
|
| 45 |
+
line = stream.readline()
|
| 46 |
+
if not line:
|
| 47 |
+
break
|
| 48 |
+
if not line.endswith(b"\n"):
|
| 49 |
+
stream.seek(position)
|
| 50 |
+
stream.truncate()
|
| 51 |
+
stream.flush()
|
| 52 |
+
os.fsync(stream.fileno())
|
| 53 |
+
break
|
| 54 |
+
records.append(json.loads(line))
|
| 55 |
+
return records
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def append(stream, value, sync=True):
|
| 59 |
+
"""Append one record. ``sync=False`` batches the fsync (the caller must end
|
| 60 |
+
with a synced record); a torn tail is still recoverable either way."""
|
| 61 |
+
payload = json.dumps(value, ensure_ascii=False, allow_nan=False)+"\n"
|
| 62 |
+
stream.write(payload)
|
| 63 |
+
stream.flush()
|
| 64 |
+
if sync:
|
| 65 |
+
os.fsync(stream.fileno())
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def atomic_json(path, value):
|
| 69 |
+
path = Path(path)
|
| 70 |
+
temporary = path.with_suffix(path.suffix+".tmp")
|
| 71 |
+
with temporary.open("w", encoding="utf-8") as stream:
|
| 72 |
+
append(stream, value)
|
| 73 |
+
os.replace(temporary, path)
|
code/src/lua_nova_v1/data/prepare.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Acoustic feature preparation from local JSONL or Parquet datasets."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
try:
|
| 5 |
+
import fcntl
|
| 6 |
+
except ImportError:
|
| 7 |
+
fcntl = None
|
| 8 |
+
import hashlib
|
| 9 |
+
import io
|
| 10 |
+
import json
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import numpy as np
|
| 15 |
+
import soundfile as sf
|
| 16 |
+
import torch
|
| 17 |
+
from ..config import Config
|
| 18 |
+
from .journal import append, atomic_json, file_hash, json_safe, recover
|
| 19 |
+
|
| 20 |
+
MIN_FRAMES = 32
|
| 21 |
+
_MEL_CACHE: dict[tuple[int, int, int], np.ndarray] = {}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _mel_filters(sample_rate: int, n_fft: int, n_mels: int) -> np.ndarray:
|
| 25 |
+
key = (sample_rate, n_fft, n_mels)
|
| 26 |
+
if key not in _MEL_CACHE:
|
| 27 |
+
import librosa
|
| 28 |
+
_MEL_CACHE[key] = librosa.filters.mel(sr=sample_rate, n_fft=n_fft, n_mels=n_mels)
|
| 29 |
+
return _MEL_CACHE[key]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _extract_pitch(wave: np.ndarray, frames: int, c: Config) -> tuple[np.ndarray, np.ndarray]:
|
| 33 |
+
try:
|
| 34 |
+
import parselmouth
|
| 35 |
+
except ImportError:
|
| 36 |
+
parselmouth = None
|
| 37 |
+
if parselmouth is not None and len(wave) >= int(c.sample_rate * 3.0 / c.f0_min) + 16:
|
| 38 |
+
sound = parselmouth.Sound(wave.astype(np.float64), sampling_frequency=float(c.sample_rate))
|
| 39 |
+
pitch_obj = sound.to_pitch_ac(
|
| 40 |
+
time_step=c.hop / c.sample_rate,
|
| 41 |
+
pitch_floor=float(c.f0_min),
|
| 42 |
+
pitch_ceiling=float(c.f0_max),
|
| 43 |
+
)
|
| 44 |
+
freq = pitch_obj.selected_array["frequency"]
|
| 45 |
+
f0 = np.zeros(frames, dtype=np.float32)
|
| 46 |
+
if freq.size:
|
| 47 |
+
t = np.arange(frames) * (c.hop / c.sample_rate)
|
| 48 |
+
idx = np.rint((t - pitch_obj.x1) / pitch_obj.dx).astype(np.int64)
|
| 49 |
+
ok = (idx >= 0) & (idx < freq.size)
|
| 50 |
+
f0[ok] = freq[idx[ok]]
|
| 51 |
+
return f0, f0 > 0
|
| 52 |
+
import librosa
|
| 53 |
+
f0, voiced, _ = librosa.pyin(
|
| 54 |
+
wave, fmin=c.f0_min, fmax=c.f0_max, sr=c.sample_rate,
|
| 55 |
+
frame_length=c.n_fft, hop_length=c.hop, center=True, pad_mode="constant",
|
| 56 |
+
)
|
| 57 |
+
return f0[:frames], voiced[:frames]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def records(source):
|
| 61 |
+
if source.suffix == ".jsonl":
|
| 62 |
+
with source.open(encoding="utf-8") as stream:
|
| 63 |
+
for line in stream:
|
| 64 |
+
if line.strip():
|
| 65 |
+
try:
|
| 66 |
+
yield json.loads(line)
|
| 67 |
+
except json.JSONDecodeError as error:
|
| 68 |
+
yield {"_input_error":str(error)}
|
| 69 |
+
elif source.suffix == ".parquet":
|
| 70 |
+
import pyarrow.parquet as pq
|
| 71 |
+
for batch in pq.ParquetFile(source).iter_batches(batch_size=16):
|
| 72 |
+
yield from batch.to_pylist()
|
| 73 |
+
else:
|
| 74 |
+
raise ValueError("input must be .jsonl or .parquet")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def extract(wave, config):
|
| 78 |
+
import librosa
|
| 79 |
+
c = config
|
| 80 |
+
if wave.ndim != 1 or not np.isfinite(wave).all() or not wave.size:
|
| 81 |
+
raise ValueError("expected finite mono audio")
|
| 82 |
+
frames = math.ceil(len(wave)/c.hop)
|
| 83 |
+
if frames < 1:
|
| 84 |
+
raise ValueError("empty audio")
|
| 85 |
+
if np.max(np.abs(wave)) > 1.01 or np.sqrt(np.mean(wave**2)) < 1e-5:
|
| 86 |
+
raise ValueError("audio is clipped/out of range or effectively silent")
|
| 87 |
+
wave = np.pad(wave, (0, frames*c.hop-len(wave))).astype(np.float32)
|
| 88 |
+
spectrum = librosa.stft(wave, n_fft=c.n_fft, hop_length=c.hop, center=True, pad_mode="constant")[:, :frames]
|
| 89 |
+
filters = _mel_filters(c.sample_rate, c.n_fft, c.n_mels)
|
| 90 |
+
mel = np.log(np.maximum(filters @ np.abs(spectrum)**2, 1e-5)).T
|
| 91 |
+
f0, voiced = _extract_pitch(wave, frames, c)
|
| 92 |
+
pitch = np.where(voiced, np.log(np.maximum(np.nan_to_num(f0, nan=200.0), 1)/200.0), 0)
|
| 93 |
+
rms = librosa.feature.rms(y=wave, frame_length=c.n_fft, hop_length=c.hop, center=True, pad_mode="constant")[0, :frames]
|
| 94 |
+
prosody = np.stack((pitch, voiced.astype(np.float32), np.log(np.maximum(rms, 1e-5))), axis=-1)
|
| 95 |
+
return {"wave": torch.from_numpy(wave), "mel": torch.from_numpy(mel.astype(np.float32)),
|
| 96 |
+
"prosody": torch.from_numpy(prosody.astype(np.float32))}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def main():
|
| 100 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 101 |
+
parser.add_argument("--inputs", nargs="+", type=Path, required=True)
|
| 102 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 103 |
+
parser.add_argument("--text-column", default="text")
|
| 104 |
+
parser.add_argument("--speaker-column", default="voice_id")
|
| 105 |
+
parser.add_argument("--config", type=Path)
|
| 106 |
+
parser.add_argument("--split", choices=("train", "validation", "test"), required=True)
|
| 107 |
+
parser.add_argument("--resume", action="store_true", help="Skip durably accepted/rejected records from these same inputs")
|
| 108 |
+
args = parser.parse_args()
|
| 109 |
+
c = Config.from_dict(json.loads(args.config.read_text())) if args.config else Config()
|
| 110 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 111 |
+
# Lock is held through completion or an exception. Different splits may run separately.
|
| 112 |
+
with (args.output/(args.split+".lock")).open("a") as lock:
|
| 113 |
+
if fcntl is not None:
|
| 114 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 115 |
+
prepare_split(args, c)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def prepare_split(args, c):
|
| 119 |
+
manifest = args.output / (args.split+".jsonl")
|
| 120 |
+
rejects = args.output / (args.split+".rejected.jsonl")
|
| 121 |
+
metadata_path = args.output/(args.split+".preparation.json")
|
| 122 |
+
identity = {"acoustic":c.acoustic_fingerprint,
|
| 123 |
+
"sources":[{"path":str(p.resolve()), "sha256":file_hash(p)} for p in args.inputs],
|
| 124 |
+
"text_column":args.text_column, "speaker_column":args.speaker_column, "speakers":list(c.speakers),
|
| 125 |
+
# Admission limits affect which rows finish as rejects, not tensor contents.
|
| 126 |
+
"admission":{"max_frames":c.max_frames, "min_frames":MIN_FRAMES}}
|
| 127 |
+
if metadata_path.exists():
|
| 128 |
+
if not args.resume:
|
| 129 |
+
raise FileExistsError("preparation exists; use --resume or a new directory")
|
| 130 |
+
if json.loads(metadata_path.read_text())["identity"] != identity:
|
| 131 |
+
raise ValueError("resume inputs, feature schema or admission limits changed")
|
| 132 |
+
elif manifest.exists() or rejects.exists():
|
| 133 |
+
raise ValueError("manifest has no compatible preparation metadata; use a new directory")
|
| 134 |
+
feature_schema = args.output/"features.json"
|
| 135 |
+
if feature_schema.exists() and json.loads(feature_schema.read_text())["fingerprint"] != c.acoustic_fingerprint:
|
| 136 |
+
raise ValueError("feature schema differs from other splits in this directory")
|
| 137 |
+
atomic_json(feature_schema, {"fingerprint":c.acoustic_fingerprint, "fields":c.acoustic_config})
|
| 138 |
+
atomic_json(metadata_path, {"identity":identity, "complete":False})
|
| 139 |
+
feature_dir = args.output / args.split
|
| 140 |
+
feature_dir.mkdir(exist_ok=True)
|
| 141 |
+
entries, rejected = recover(manifest), recover(rejects)
|
| 142 |
+
done = {r["record_key"] for r in entries+rejected}
|
| 143 |
+
seen = {r["id"] for r in entries}
|
| 144 |
+
for entry in entries:
|
| 145 |
+
if not (args.output/entry["path"]).is_file():
|
| 146 |
+
raise ValueError(f"committed feature file is missing: {entry['path']}")
|
| 147 |
+
accepted_count, rejected_count = len(entries), len(rejected)
|
| 148 |
+
with manifest.open("a", encoding="utf-8") as accepted_stream, rejects.open("a", encoding="utf-8") as rejected_stream:
|
| 149 |
+
for source_index, source in enumerate(args.inputs):
|
| 150 |
+
for index, row in enumerate(records(source)):
|
| 151 |
+
record_key = f"{source_index}:{index}"
|
| 152 |
+
if record_key in done:
|
| 153 |
+
continue
|
| 154 |
+
identifier = None
|
| 155 |
+
try:
|
| 156 |
+
if not isinstance(row, dict):
|
| 157 |
+
raise ValueError("row must be an object")
|
| 158 |
+
if "_input_error" in row:
|
| 159 |
+
raise ValueError(row["_input_error"])
|
| 160 |
+
identifier = row.get("id")
|
| 161 |
+
if not isinstance(identifier, str) or not identifier:
|
| 162 |
+
raise ValueError("row must have a stable nonempty string id")
|
| 163 |
+
if identifier in seen:
|
| 164 |
+
raise ValueError("duplicate id")
|
| 165 |
+
if row.get("split", args.split) != args.split:
|
| 166 |
+
raise ValueError("row split differs from --split")
|
| 167 |
+
text, speaker = row[args.text_column], row[args.speaker_column]
|
| 168 |
+
if not isinstance(text, str) or not text.strip():
|
| 169 |
+
raise ValueError("text must be a nonempty string")
|
| 170 |
+
if speaker not in c.speakers:
|
| 171 |
+
raise ValueError(f"unknown speaker {speaker!r}; expected {c.speakers}")
|
| 172 |
+
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})
|
| 173 |
+
audio = row["audio"]
|
| 174 |
+
if isinstance(audio, dict):
|
| 175 |
+
audio = io.BytesIO(audio["bytes"]) if audio.get("bytes") is not None else source.parent / audio["path"]
|
| 176 |
+
else:
|
| 177 |
+
audio = source.parent / audio
|
| 178 |
+
wave, sr = sf.read(audio, dtype="float32")
|
| 179 |
+
if sr != c.sample_rate:
|
| 180 |
+
raise ValueError(f"expected {c.sample_rate} Hz; got {sr}. Resample explicitly before preparation")
|
| 181 |
+
frames = math.ceil(len(wave)/c.hop)
|
| 182 |
+
if not MIN_FRAMES <= frames <= c.max_frames:
|
| 183 |
+
raise ValueError("audio duration outside admission limits")
|
| 184 |
+
name = hashlib.sha256(identifier.encode()).hexdigest()+".pt"
|
| 185 |
+
entry = {"record_key":record_key, "id":identifier, "path":f"{args.split}/{name}", "acoustic":c.acoustic_fingerprint,
|
| 186 |
+
"text_hash":hashlib.sha256(text.strip().encode()).hexdigest(), "text":text,
|
| 187 |
+
"speaker":speaker, "source_file":str(source), "frames":frames, "provenance":provenance}
|
| 188 |
+
json.dumps(entry, ensure_ascii=False, allow_nan=False) # Validate before expensive DSP.
|
| 189 |
+
sample = extract(wave, c)
|
| 190 |
+
sample.update(speaker=c.speakers.index(speaker))
|
| 191 |
+
temporary = feature_dir/(name+".tmp")
|
| 192 |
+
with temporary.open("wb") as stream:
|
| 193 |
+
torch.save(sample, stream)
|
| 194 |
+
stream.flush()
|
| 195 |
+
os.fsync(stream.fileno())
|
| 196 |
+
os.replace(temporary, feature_dir/name)
|
| 197 |
+
except Exception as error:
|
| 198 |
+
append(rejected_stream, {"record_key":record_key, "id":str(identifier), "source":str(source), "reason":f"{type(error).__name__}: {error}"})
|
| 199 |
+
rejected_count += 1
|
| 200 |
+
else:
|
| 201 |
+
# Journal write failures must abort, not masquerade as bad source rows.
|
| 202 |
+
append(accepted_stream, entry)
|
| 203 |
+
seen.add(identifier)
|
| 204 |
+
accepted_count += 1
|
| 205 |
+
atomic_json(metadata_path, {"identity":identity, "complete":True, "accepted":accepted_count, "rejected":rejected_count})
|
| 206 |
+
print(json.dumps({"accepted":accepted_count, "rejected":rejected_count, "manifest":str(manifest)}))
|
| 207 |
+
if not accepted_count:
|
| 208 |
+
raise SystemExit("no usable records; inspect rejected.jsonl")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
if __name__ == "__main__":
|
| 212 |
+
main()
|
code/src/lua_nova_v1/data/refine.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Boundary refinement with a small frame classifier trained from scratch.
|
| 2 |
+
|
| 3 |
+
The pretrained recogniser works on 20 ms frames and its CTC emissions are
|
| 4 |
+
sparse, so phone boundaries from it are coarse. This module trains a tiny
|
| 5 |
+
convolutional phone classifier on OUR recordings (random initialisation, labels
|
| 6 |
+
from the CTC alignment), then moves each boundary by at most ``band`` acoustic
|
| 7 |
+
frames to where that classifier sees the change. It never adds or removes a
|
| 8 |
+
pause and never reorders tokens. Like the recogniser it is annotation-only.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
from torch.nn import functional as F
|
| 15 |
+
|
| 16 |
+
from ..text.phonemizer import PHONES, PHONE_SET
|
| 17 |
+
|
| 18 |
+
SILENCE_CLASS = len(PHONES)
|
| 19 |
+
OTHER_CLASS = len(PHONES) + 1
|
| 20 |
+
CLASSES = len(PHONES) + 2
|
| 21 |
+
_PHONE_CLASS = {phone: index for index, phone in enumerate(PHONES)}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def symbol_class(symbol):
|
| 25 |
+
if symbol in PHONE_SET:
|
| 26 |
+
return _PHONE_CLASS[symbol]
|
| 27 |
+
return OTHER_CLASS if symbol == "<unk>" else SILENCE_CLASS
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class FrameClassifier(nn.Module):
|
| 31 |
+
"""Receptive field of 11 acoustic frames: it labels what a frame sounds
|
| 32 |
+
like, with too little context to learn a systematic timing offset."""
|
| 33 |
+
|
| 34 |
+
def __init__(self, n_mels, speakers, channels=256):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.speaker = nn.Embedding(speakers, channels)
|
| 37 |
+
self.input = nn.Conv1d(n_mels, channels, 5, padding=2)
|
| 38 |
+
self.blocks = nn.ModuleList(nn.Conv1d(channels, channels, 3, padding=1) for _ in range(3))
|
| 39 |
+
self.output = nn.Conv1d(channels, CLASSES, 1)
|
| 40 |
+
|
| 41 |
+
def forward(self, mel, speaker):
|
| 42 |
+
x = self.input(mel.transpose(1, 2)) + self.speaker(speaker).transpose(1, 2)
|
| 43 |
+
for block in self.blocks:
|
| 44 |
+
x = x + block(F.gelu(x))
|
| 45 |
+
return self.output(F.gelu(x)).transpose(1, 2)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def frame_labels(symbols, durations):
|
| 49 |
+
return np.repeat([symbol_class(s) for s in symbols], durations)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def banded_viterbi(scores, starts, ends, band):
|
| 53 |
+
"""Re-time a fixed state sequence. ``scores`` is [frames, states]; state s
|
| 54 |
+
originally covered ``starts[s]:ends[s]`` and may move by ``band`` frames."""
|
| 55 |
+
frames, states = scores.shape
|
| 56 |
+
low = np.maximum(np.asarray(starts) - band, 0)
|
| 57 |
+
high = np.minimum(np.asarray(ends) + band, frames)
|
| 58 |
+
low[0], high[-1] = 0, frames
|
| 59 |
+
time = np.arange(frames)[:, None]
|
| 60 |
+
scores = np.where((time >= low[None]) & (time < high[None]), scores, -np.inf)
|
| 61 |
+
previous = np.full(states, -np.inf)
|
| 62 |
+
previous[0] = scores[0, 0]
|
| 63 |
+
advanced = np.zeros((frames, states), dtype=bool)
|
| 64 |
+
for t in range(1, frames):
|
| 65 |
+
shifted = np.concatenate(([-np.inf], previous[:-1]))
|
| 66 |
+
advanced[t] = shifted > previous
|
| 67 |
+
previous = np.where(advanced[t], shifted, previous) + scores[t]
|
| 68 |
+
if not np.isfinite(previous[-1]):
|
| 69 |
+
raise ValueError("no path inside the band")
|
| 70 |
+
durations = np.zeros(states, dtype=np.int64)
|
| 71 |
+
state = states - 1
|
| 72 |
+
for t in range(frames - 1, -1, -1):
|
| 73 |
+
durations[state] += 1
|
| 74 |
+
if advanced[t, state]:
|
| 75 |
+
state -= 1
|
| 76 |
+
if state != 0 or np.any(durations < 1):
|
| 77 |
+
raise ValueError("invalid refined path")
|
| 78 |
+
return durations
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def refine(items, config, device="cuda", iterations=2, band=4, steps=3000, batch=256, window=128,
|
| 82 |
+
prior_scale=0.5, seed=20261113, log=print):
|
| 83 |
+
"""Refine durations for ``items``: dicts with ``symbols``, ``durations``,
|
| 84 |
+
``mel`` (float tensor [frames, n_mels]), ``speaker`` (int) and ``group``
|
| 85 |
+
(hex text hash; both voices of a sentence share a fold).
|
| 86 |
+
|
| 87 |
+
Returns one list of per-utterance duration lists per iteration.
|
| 88 |
+
"""
|
| 89 |
+
generator = torch.Generator().manual_seed(seed)
|
| 90 |
+
torch.manual_seed(seed)
|
| 91 |
+
# Two-fold cross-fitting by sentence: a recording is re-timed only by a
|
| 92 |
+
# classifier that never saw it (or the other voice's reading of its text),
|
| 93 |
+
# so the classifier cannot simply reproduce the labels it was given.
|
| 94 |
+
fold = np.array([int(str(item["group"])[:8], 16) % 2 for item in items])
|
| 95 |
+
order = np.argsort(fold, kind="stable")
|
| 96 |
+
items = [items[i] for i in order]
|
| 97 |
+
fold = fold[order]
|
| 98 |
+
lengths = [int(item["mel"].shape[0]) for item in items]
|
| 99 |
+
offsets = np.concatenate(([0], np.cumsum(lengths)))
|
| 100 |
+
split = int(offsets[int((fold == 0).sum())])
|
| 101 |
+
if min(split, offsets[-1] - split) <= 2 * window:
|
| 102 |
+
raise ValueError("too few recordings for cross-fitted refinement")
|
| 103 |
+
mel = ((torch.cat([item["mel"] for item in items]) - config.mel_mean) / config.mel_scale).to(device)
|
| 104 |
+
speaker = torch.cat([torch.full((n,), int(item["speaker"]), dtype=torch.long) for item, n in zip(items, lengths)]).to(device)
|
| 105 |
+
reference = [np.asarray(item["durations"], dtype=np.int64) for item in items]
|
| 106 |
+
current = [d.copy() for d in reference]
|
| 107 |
+
results = []
|
| 108 |
+
for iteration in range(iterations):
|
| 109 |
+
labels = torch.from_numpy(np.concatenate([frame_labels(item["symbols"], d) for item, d in zip(items, current)])).to(device)
|
| 110 |
+
refined, moved, agree = [None] * len(items), [], []
|
| 111 |
+
for held_out in (0, 1):
|
| 112 |
+
low_train, high_train = (split, int(offsets[-1])) if held_out == 0 else (0, split)
|
| 113 |
+
model = FrameClassifier(config.n_mels, len(config.speakers)).to(device)
|
| 114 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-2)
|
| 115 |
+
schedule = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=2e-3, total_steps=steps)
|
| 116 |
+
model.train()
|
| 117 |
+
for step in range(steps):
|
| 118 |
+
start = torch.randint(low_train, high_train - window, (batch,), generator=generator).to(device)
|
| 119 |
+
index = start[:, None] + torch.arange(window, device=device)[None]
|
| 120 |
+
loss = F.cross_entropy(model(mel[index], speaker[index]).flatten(0, 1), labels[index].flatten(), label_smoothing=0.05)
|
| 121 |
+
optimizer.zero_grad(set_to_none=True)
|
| 122 |
+
loss.backward()
|
| 123 |
+
optimizer.step()
|
| 124 |
+
schedule.step()
|
| 125 |
+
if step % 1000 == 0 or step == steps - 1:
|
| 126 |
+
log(f"refine iteration={iteration + 1} held_out_fold={held_out} step={step + 1} loss={loss.item():.4f}")
|
| 127 |
+
model.eval()
|
| 128 |
+
prior = torch.bincount(labels[low_train:high_train], minlength=CLASSES).float().clamp_min(1)
|
| 129 |
+
prior = (prior / prior.sum()).log()
|
| 130 |
+
with torch.inference_mode():
|
| 131 |
+
for number in np.flatnonzero(fold == held_out):
|
| 132 |
+
item, low, high = items[number], int(offsets[number]), int(offsets[number + 1])
|
| 133 |
+
original, now = reference[number], current[number]
|
| 134 |
+
logits = model(mel[low:high][None], speaker[low:high][None])[0]
|
| 135 |
+
agree.append(float((logits.argmax(-1) == labels[low:high]).float().mean()))
|
| 136 |
+
scores = (logits.log_softmax(-1) - prior_scale * prior).cpu().numpy().astype(np.float64)
|
| 137 |
+
active = np.flatnonzero(original > 0)
|
| 138 |
+
ends = np.cumsum(original)[active]
|
| 139 |
+
classes = [symbol_class(item["symbols"][i]) for i in active]
|
| 140 |
+
durations = np.zeros_like(original)
|
| 141 |
+
durations[active] = banded_viterbi(scores[:, classes], ends - original[active], ends, band)
|
| 142 |
+
refined[number] = durations
|
| 143 |
+
moved.append(np.abs(np.cumsum(durations)[active][:-1] - np.cumsum(now)[active][:-1]))
|
| 144 |
+
shift = np.concatenate(moved) if moved else np.zeros(1)
|
| 145 |
+
log(f"refine iteration={iteration + 1} held_out_frame_accuracy={np.mean(agree):.4f} "
|
| 146 |
+
f"boundary_shift_mean={shift.mean():.3f} unchanged={np.mean(shift == 0):.3f} max={shift.max()}")
|
| 147 |
+
current = refined
|
| 148 |
+
restored = [None] * len(items)
|
| 149 |
+
for position, source in enumerate(order):
|
| 150 |
+
restored[source] = refined[position].tolist()
|
| 151 |
+
results.append(restored)
|
| 152 |
+
return results
|
code/src/lua_nova_v1/export/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ONNX export utilities for Lua Nova V1 (acoustic CFM v5 and BigVGAN vocoder)."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from .onnx_export import (
|
| 5 |
+
BIGVGAN_INPUTS,
|
| 6 |
+
BIGVGAN_OUTPUTS,
|
| 7 |
+
CFM_INPUTS,
|
| 8 |
+
CFM_OUTPUTS,
|
| 9 |
+
ExportableBigVGAN,
|
| 10 |
+
ExportableCFMAcoustic,
|
| 11 |
+
example_cfm_inputs,
|
| 12 |
+
export_bigvgan_onnx,
|
| 13 |
+
export_cfm_onnx,
|
| 14 |
+
verify_bigvgan_onnx,
|
| 15 |
+
verify_cfm_onnx,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"BIGVGAN_INPUTS",
|
| 20 |
+
"BIGVGAN_OUTPUTS",
|
| 21 |
+
"CFM_INPUTS",
|
| 22 |
+
"CFM_OUTPUTS",
|
| 23 |
+
"ExportableBigVGAN",
|
| 24 |
+
"ExportableCFMAcoustic",
|
| 25 |
+
"example_cfm_inputs",
|
| 26 |
+
"export_bigvgan_onnx",
|
| 27 |
+
"export_cfm_onnx",
|
| 28 |
+
"verify_bigvgan_onnx",
|
| 29 |
+
"verify_cfm_onnx",
|
| 30 |
+
]
|
code/src/lua_nova_v1/export/onnx_export.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Split ONNX Runtime CPU export (opset 17) for LuaNovaCFM v5 and BigVGAN."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import copy
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
from torch import nn
|
| 13 |
+
from torch.nn import functional as F
|
| 14 |
+
|
| 15 |
+
from ..models.bigvgan import BigVGANVocoderWrapper
|
| 16 |
+
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_prosody_noise
|
| 17 |
+
from ..text.phonemizer import frontend_fingerprint, frontend_identity, phonemize
|
| 18 |
+
from ..training.common import load_cfm_model
|
| 19 |
+
|
| 20 |
+
CFM_INPUTS = ("tokens", "stress", "voice", "speed", "pitch_shift", "pitch_range")
|
| 21 |
+
CFM_OUTPUTS = ("phys_mel", "frame_lengths")
|
| 22 |
+
BIGVGAN_INPUTS = ("mel",)
|
| 23 |
+
BIGVGAN_OUTPUTS = ("audio",)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def example_cfm_inputs(text: str = "Olá, tudo bem?", device: str = "cpu") -> tuple[torch.Tensor, ...]:
|
| 27 |
+
"""Build valid dummy inputs matching the exported ``CFM_INPUTS`` signature."""
|
| 28 |
+
phones = phonemize(text)
|
| 29 |
+
return (
|
| 30 |
+
torch.tensor([phones.ids], dtype=torch.long, device=device),
|
| 31 |
+
torch.tensor([phones.stress], dtype=torch.long, device=device),
|
| 32 |
+
torch.tensor([0], dtype=torch.long, device=device),
|
| 33 |
+
torch.tensor([1.0], dtype=torch.float32, device=device),
|
| 34 |
+
torch.tensor([0.0], dtype=torch.float32, device=device),
|
| 35 |
+
torch.tensor([1.05], dtype=torch.float32, device=device),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ExportableCFMAcoustic(nn.Module):
|
| 40 |
+
"""ONNX-traceable unrolled acoustic front-end + OT-CFM ODE predicting physical 100-band log-mel."""
|
| 41 |
+
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
model: LuaNovaCFM,
|
| 45 |
+
n_steps: int = 2,
|
| 46 |
+
cfg_scale: float = 1.0,
|
| 47 |
+
temperature: float = 0.35,
|
| 48 |
+
solver: str = "euler",
|
| 49 |
+
sway_coef: float = 0.0,
|
| 50 |
+
seed: int = 0,
|
| 51 |
+
dur_steps: int | None = None,
|
| 52 |
+
dur_temp: float | None = None,
|
| 53 |
+
prosody_steps: int | None = None,
|
| 54 |
+
prosody_temp: float | None = None,
|
| 55 |
+
) -> None:
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.model = model.eval()
|
| 58 |
+
self.n_steps = int(n_steps)
|
| 59 |
+
self.cfg_scale = float(cfg_scale)
|
| 60 |
+
self.temperature = float(temperature)
|
| 61 |
+
self.solver = str(solver)
|
| 62 |
+
self.sway_coef = float(sway_coef)
|
| 63 |
+
cc = model.cfm_config
|
| 64 |
+
c = model.config
|
| 65 |
+
self.dur_steps = int(cc.dur_flow_steps if dur_steps is None else dur_steps)
|
| 66 |
+
self.dur_temp = float(cc.dur_flow_temp if dur_temp is None else dur_temp)
|
| 67 |
+
self.prosody_steps = int(cc.prosody_flow_steps if prosody_steps is None else prosody_steps)
|
| 68 |
+
self.prosody_temp = float(cc.prosody_flow_temp if prosody_temp is None else prosody_temp)
|
| 69 |
+
|
| 70 |
+
gen = torch.Generator().manual_seed(int(seed))
|
| 71 |
+
self.register_buffer(
|
| 72 |
+
"base_noise",
|
| 73 |
+
torch.randn((1, c.max_frames, c.vocos_n_mels), generator=gen, dtype=torch.float32),
|
| 74 |
+
persistent=False,
|
| 75 |
+
)
|
| 76 |
+
if model.dur_flow is not None:
|
| 77 |
+
dur_gen = torch.Generator().manual_seed(int(seed) + 101)
|
| 78 |
+
self.register_buffer(
|
| 79 |
+
"base_dur_noise",
|
| 80 |
+
torch.randn((1, c.max_tokens, 1), generator=dur_gen, dtype=torch.float32),
|
| 81 |
+
persistent=False,
|
| 82 |
+
)
|
| 83 |
+
if model.prosody_flow is not None:
|
| 84 |
+
pros_gen = torch.Generator().manual_seed(int(seed) + 202)
|
| 85 |
+
self.register_buffer(
|
| 86 |
+
"base_prosody_noise",
|
| 87 |
+
torch.randn((1, c.max_frames, 2), generator=pros_gen, dtype=torch.float32),
|
| 88 |
+
persistent=False,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def _velocity(
|
| 92 |
+
self,
|
| 93 |
+
x: torch.Tensor,
|
| 94 |
+
t_val: float,
|
| 95 |
+
cond: torch.Tensor,
|
| 96 |
+
prior_mel: torch.Tensor,
|
| 97 |
+
frame_mask: torch.Tensor,
|
| 98 |
+
f0_feats: torch.Tensor | None,
|
| 99 |
+
) -> torch.Tensor:
|
| 100 |
+
t_vec = torch.full((1,), float(t_val), device=x.device, dtype=torch.float32)
|
| 101 |
+
v_c = self.model.flow(x, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
|
| 102 |
+
if self.cfg_scale == 1.0:
|
| 103 |
+
return v_c
|
| 104 |
+
v_u = self.model.flow(
|
| 105 |
+
x,
|
| 106 |
+
t_vec,
|
| 107 |
+
torch.zeros_like(cond),
|
| 108 |
+
torch.zeros_like(prior_mel),
|
| 109 |
+
frame_mask,
|
| 110 |
+
f0_feats=torch.zeros_like(f0_feats) if f0_feats is not None else None,
|
| 111 |
+
)
|
| 112 |
+
return v_u + self.cfg_scale * (v_c - v_u)
|
| 113 |
+
|
| 114 |
+
def forward(
|
| 115 |
+
self,
|
| 116 |
+
tokens: torch.Tensor,
|
| 117 |
+
stress: torch.Tensor,
|
| 118 |
+
voice: torch.Tensor,
|
| 119 |
+
speed: torch.Tensor,
|
| 120 |
+
pitch_shift: torch.Tensor,
|
| 121 |
+
pitch_range: torch.Tensor,
|
| 122 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 123 |
+
m, c = self.model, self.model.config
|
| 124 |
+
mask = torch.ones_like(tokens, dtype=torch.bool)
|
| 125 |
+
hidden = m.encoder(m.tokens(tokens) + m.stress(stress) + m.voices(voice)[:, None], mask)
|
| 126 |
+
prosody_token_ctx, clause_ctx_tok = m.encode_prosody_context(hidden, tokens, stress, mask)
|
| 127 |
+
|
| 128 |
+
raw = m.duration(prosody_token_ctx, mask).float()
|
| 129 |
+
prior_z = raw[..., 0].clamp(0.0, math.log1p(400.0))
|
| 130 |
+
if m.dur_flow is not None:
|
| 131 |
+
sigma_d = m.cfm_config.dur_flow_sigma * self.dur_temp
|
| 132 |
+
z = prior_z[..., None] + sigma_d * self.base_dur_noise[:, : tokens.shape[1], :]
|
| 133 |
+
dt_d = 1.0 / max(self.dur_steps, 1)
|
| 134 |
+
for i in range(self.dur_steps):
|
| 135 |
+
t_d = torch.full((1,), i * dt_d, device=tokens.device, dtype=torch.float32)
|
| 136 |
+
v_d = m.dur_flow(z, t_d, prior_z[..., None], prosody_token_ctx, mask)
|
| 137 |
+
z = z + dt_d * v_d
|
| 138 |
+
z1 = z.squeeze(-1)
|
| 139 |
+
else:
|
| 140 |
+
z1 = prior_z
|
| 141 |
+
frames = torch.round((torch.exp(z1.clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
|
| 142 |
+
durations = torch.where(m.phone_tokens[tokens] | (raw[..., 1] > 0), frames, torch.zeros_like(frames))
|
| 143 |
+
|
| 144 |
+
ends = durations.cumsum(1)
|
| 145 |
+
total = ends[0, -1]
|
| 146 |
+
frame = torch.arange(total, device=tokens.device)[None]
|
| 147 |
+
# Cumulative comparison avoids torch.searchsorted which is absent from ONNX opset 17.
|
| 148 |
+
index = (ends[:, :, None] <= frame[:, None, :]).sum(1).clamp(max=tokens.shape[1] - 1)
|
| 149 |
+
owned = durations.gather(1, index).clamp_min(1)
|
| 150 |
+
offset = frame - (ends.gather(1, index) - durations.gather(1, index))
|
| 151 |
+
relative = (offset.float() + 0.5) / owned.float()
|
| 152 |
+
features = torch.stack((relative, 1.0 - relative, torch.log1p(owned.float()) / 4.0), dim=-1)
|
| 153 |
+
pos_voice = m.frame_position(features) + m.frame_voices(voice)[:, None]
|
| 154 |
+
expanded = hidden.gather(1, index[..., None].expand(-1, -1, c.channels)) + pos_voice
|
| 155 |
+
frame_mask = torch.ones((1, total), device=tokens.device, dtype=torch.bool)
|
| 156 |
+
if m.context_adapter is not None or m.frame_ctx_proj is not None:
|
| 157 |
+
prosody_frames = prosody_token_ctx.gather(1, index[..., None].expand(-1, -1, c.channels)) + pos_voice
|
| 158 |
+
if m.frame_ctx_proj is not None:
|
| 159 |
+
f_pos = (frame.float() + 0.5) / total.float()
|
| 160 |
+
f_rem = 1.0 - f_pos
|
| 161 |
+
c_f = clause_ctx_tok.gather(1, index[..., None].expand(-1, -1, 4))
|
| 162 |
+
ctx_6 = torch.cat((f_pos[..., None], f_rem[..., None], c_f.float()), dim=-1)
|
| 163 |
+
prosody_frames = prosody_frames + m.frame_ctx_proj(ctx_6)
|
| 164 |
+
else:
|
| 165 |
+
prosody_frames = expanded
|
| 166 |
+
|
| 167 |
+
prosody_hidden, prosody = m.predict_prosody(prosody_frames, frame_mask)
|
| 168 |
+
if m.prosody_flow is not None:
|
| 169 |
+
eps_sm = smooth_prosody_noise(self.base_prosody_noise[:, :total, :], frame_mask, m.prosody_noise_kernel)
|
| 170 |
+
prior_fe = torch.stack((prosody[..., 0].float(), prosody[..., 2].float()), dim=-1)
|
| 171 |
+
voicing_prob = torch.sigmoid(prosody[..., 1:2].float())
|
| 172 |
+
sigma_p = m.cfm_config.prosody_flow_sigma * self.prosody_temp
|
| 173 |
+
y = prior_fe + sigma_p * eps_sm
|
| 174 |
+
dt_p = 1.0 / max(self.prosody_steps, 1)
|
| 175 |
+
for i in range(self.prosody_steps):
|
| 176 |
+
t_p = torch.full((1,), i * dt_p, device=tokens.device, dtype=torch.float32)
|
| 177 |
+
v_p = m.prosody_flow(y, t_p, prior_fe, voicing_prob, prosody_hidden, frame_mask)
|
| 178 |
+
y = y + dt_p * v_p
|
| 179 |
+
prosody = torch.cat((y[..., :1], prosody[..., 1:2].float(), y[..., 1:2]), dim=-1)
|
| 180 |
+
|
| 181 |
+
is_vowel = m.vowel_tokens[tokens.gather(1, index)]
|
| 182 |
+
prosody = torch.cat(
|
| 183 |
+
(
|
| 184 |
+
prosody[..., :1],
|
| 185 |
+
torch.where(is_vowel, prosody[..., 1].clamp_min(1.0), prosody[..., 1])[..., None],
|
| 186 |
+
prosody[..., 2:],
|
| 187 |
+
),
|
| 188 |
+
dim=-1,
|
| 189 |
+
)
|
| 190 |
+
voiced = (prosody[..., 1] > 0).float()
|
| 191 |
+
mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1.0)
|
| 192 |
+
pitch = mean + (prosody[..., 0] - mean) * pitch_range + pitch_shift
|
| 193 |
+
prosody = torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1)
|
| 194 |
+
hard_p = m.hard_prosody(prosody)
|
| 195 |
+
base_h = expanded if m.cfm_config.acoustic_from_frames else prosody_hidden
|
| 196 |
+
cond, prior_mel = m.condition_and_prior(base_h, hard_p, frame_mask)
|
| 197 |
+
f0_feats = f0_features(hard_p, frame_mask) if m.cfm_config.use_f0_harmonics else None
|
| 198 |
+
|
| 199 |
+
sigma = m.cfm_config.prior_sigma * self.temperature
|
| 200 |
+
noise_gate = energy_noise_gate(hard_p, frame_mask) if m.cfm_config.use_energy_gate else 1.0
|
| 201 |
+
x = prior_mel + sigma * noise_gate * self.base_noise[:, :total, :]
|
| 202 |
+
|
| 203 |
+
t_grid = m.sway_time_grid(self.n_steps, self.sway_coef)
|
| 204 |
+
for i in range(self.n_steps):
|
| 205 |
+
t0, t1 = t_grid[i], t_grid[i + 1]
|
| 206 |
+
dt_i = t1 - t0
|
| 207 |
+
v0 = self._velocity(x, t0, cond, prior_mel, frame_mask, f0_feats)
|
| 208 |
+
if self.solver == "midpoint":
|
| 209 |
+
v_mid = self._velocity(x + 0.5 * dt_i * v0, t0 + 0.5 * dt_i, cond, prior_mel, frame_mask, f0_feats)
|
| 210 |
+
x = x + dt_i * v_mid
|
| 211 |
+
else:
|
| 212 |
+
x = x + dt_i * v0
|
| 213 |
+
|
| 214 |
+
phys_mel = (x * m.vocoder.mel_scale + m.vocoder.mel_mean).clamp(min=-11.512925)
|
| 215 |
+
frame_lengths = ends[:, -1].long()
|
| 216 |
+
return phys_mel, frame_lengths
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class _OnnxUpSample1d(nn.Module):
|
| 220 |
+
"""Static-channel ONNX-safe replacement for ``alias_free_activation.UpSample1d``."""
|
| 221 |
+
|
| 222 |
+
def __init__(self, orig: nn.Module, channels: int) -> None:
|
| 223 |
+
super().__init__()
|
| 224 |
+
self.stride = int(orig.stride)
|
| 225 |
+
self.pad = int(orig.pad)
|
| 226 |
+
self.pad_left = int(orig.pad_left)
|
| 227 |
+
self.pad_right = int(orig.pad_right)
|
| 228 |
+
self.channels = int(channels)
|
| 229 |
+
scaled = orig.filter.detach() * float(orig.ratio)
|
| 230 |
+
self.register_buffer("weight", scaled.expand(self.channels, 1, -1).contiguous())
|
| 231 |
+
|
| 232 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 233 |
+
if self.pad > 0:
|
| 234 |
+
left = x[:, :, :1].expand(-1, -1, self.pad)
|
| 235 |
+
right = x[:, :, -1:].expand(-1, -1, self.pad)
|
| 236 |
+
x = torch.cat((left, x, right), dim=-1)
|
| 237 |
+
x = F.conv_transpose1d(x, self.weight, stride=self.stride, groups=self.channels)
|
| 238 |
+
return x[:, :, self.pad_left : -self.pad_right]
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class _OnnxLowPassFilter1d(nn.Module):
|
| 242 |
+
"""Static-channel ONNX-safe replacement for ``alias_free_activation.LowPassFilter1d``."""
|
| 243 |
+
|
| 244 |
+
def __init__(self, orig: nn.Module, channels: int) -> None:
|
| 245 |
+
super().__init__()
|
| 246 |
+
self.stride = int(orig.stride)
|
| 247 |
+
self.padding = bool(orig.padding)
|
| 248 |
+
self.pad_left = int(orig.pad_left)
|
| 249 |
+
self.pad_right = int(orig.pad_right)
|
| 250 |
+
self.channels = int(channels)
|
| 251 |
+
self.register_buffer("weight", orig.filter.detach().expand(self.channels, 1, -1).contiguous())
|
| 252 |
+
|
| 253 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 254 |
+
if self.padding:
|
| 255 |
+
left = x[:, :, :1].expand(-1, -1, self.pad_left)
|
| 256 |
+
right = x[:, :, -1:].expand(-1, -1, self.pad_right)
|
| 257 |
+
x = torch.cat((left, x, right), dim=-1)
|
| 258 |
+
return F.conv1d(x, self.weight, stride=self.stride, groups=self.channels)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _make_bigvgan_onnx_safe(net: nn.Module) -> nn.Module:
|
| 262 |
+
net_copy = copy.deepcopy(net).eval()
|
| 263 |
+
for mod in net_copy.modules():
|
| 264 |
+
if hasattr(mod, "act") and hasattr(mod, "upsample") and hasattr(mod, "downsample"):
|
| 265 |
+
channels = int(getattr(mod.act, "in_features"))
|
| 266 |
+
mod.upsample = _OnnxUpSample1d(mod.upsample, channels)
|
| 267 |
+
mod.downsample.lowpass = _OnnxLowPassFilter1d(mod.downsample.lowpass, channels)
|
| 268 |
+
return net_copy
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class ExportableBigVGAN(nn.Module):
|
| 272 |
+
"""ONNX-traceable BigVGAN wrapper mapping physical log-mel ``[B, T, 100]`` -> audio ``[B, T*256]``."""
|
| 273 |
+
|
| 274 |
+
def __init__(self, vocoder: BigVGANVocoderWrapper) -> None:
|
| 275 |
+
super().__init__()
|
| 276 |
+
self.net = _make_bigvgan_onnx_safe(vocoder.net)
|
| 277 |
+
|
| 278 |
+
def forward(self, mel: torch.Tensor) -> torch.Tensor:
|
| 279 |
+
return self.net(mel.transpose(1, 2).contiguous()).squeeze(1)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _export_torch_onnx(
|
| 283 |
+
module: nn.Module,
|
| 284 |
+
args: tuple[torch.Tensor, ...],
|
| 285 |
+
out_path: Path,
|
| 286 |
+
input_names: list[str],
|
| 287 |
+
output_names: list[str],
|
| 288 |
+
dynamic_axes: dict[str, dict[int, str]],
|
| 289 |
+
opset: int,
|
| 290 |
+
) -> Path:
|
| 291 |
+
import onnx
|
| 292 |
+
|
| 293 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 294 |
+
kwargs = dict(
|
| 295 |
+
input_names=input_names,
|
| 296 |
+
output_names=output_names,
|
| 297 |
+
dynamic_axes=dynamic_axes,
|
| 298 |
+
opset_version=opset,
|
| 299 |
+
do_constant_folding=True,
|
| 300 |
+
)
|
| 301 |
+
try:
|
| 302 |
+
torch.onnx.export(module, args, str(out_path), dynamo=False, **kwargs)
|
| 303 |
+
except TypeError:
|
| 304 |
+
torch.onnx.export(module, args, str(out_path), **kwargs)
|
| 305 |
+
onnx_model = onnx.load(str(out_path))
|
| 306 |
+
onnx.checker.check_model(onnx_model)
|
| 307 |
+
return out_path
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def export_cfm_onnx(
|
| 311 |
+
cfm_path_or_model: Path | str | LuaNovaCFM,
|
| 312 |
+
out_path: Path | str,
|
| 313 |
+
n_steps: int = 2,
|
| 314 |
+
cfg_scale: float = 1.0,
|
| 315 |
+
temperature: float = 0.35,
|
| 316 |
+
solver: str = "euler",
|
| 317 |
+
sway_coef: float = 0.0,
|
| 318 |
+
seed: int = 0,
|
| 319 |
+
opset: int = 17,
|
| 320 |
+
) -> Path:
|
| 321 |
+
"""Export LuaNovaCFM acoustic predictor to ONNX + companion ``.meta.json``."""
|
| 322 |
+
model = (
|
| 323 |
+
cfm_path_or_model
|
| 324 |
+
if isinstance(cfm_path_or_model, LuaNovaCFM)
|
| 325 |
+
else load_cfm_model(cfm_path_or_model, device="cpu", load_vocos=False)
|
| 326 |
+
).cpu().eval()
|
| 327 |
+
wrapper = ExportableCFMAcoustic(
|
| 328 |
+
model,
|
| 329 |
+
n_steps=n_steps,
|
| 330 |
+
cfg_scale=cfg_scale,
|
| 331 |
+
temperature=temperature,
|
| 332 |
+
solver=solver,
|
| 333 |
+
sway_coef=sway_coef,
|
| 334 |
+
seed=seed,
|
| 335 |
+
).eval()
|
| 336 |
+
dummy = example_cfm_inputs()
|
| 337 |
+
target = Path(out_path)
|
| 338 |
+
with torch.no_grad():
|
| 339 |
+
_export_torch_onnx(
|
| 340 |
+
wrapper,
|
| 341 |
+
dummy,
|
| 342 |
+
target,
|
| 343 |
+
input_names=list(CFM_INPUTS),
|
| 344 |
+
output_names=list(CFM_OUTPUTS),
|
| 345 |
+
dynamic_axes={"tokens": {1: "tokens"}, "stress": {1: "tokens"}, "phys_mel": {1: "frames"}},
|
| 346 |
+
opset=opset,
|
| 347 |
+
)
|
| 348 |
+
meta = {
|
| 349 |
+
"sample_rate": int(model.config.sample_rate),
|
| 350 |
+
"hop": int(model.config.hop),
|
| 351 |
+
"n_mels": int(model.config.vocos_n_mels),
|
| 352 |
+
"max_tokens": int(model.config.max_tokens),
|
| 353 |
+
"speakers": list(model.config.speakers),
|
| 354 |
+
"n_steps": int(n_steps),
|
| 355 |
+
"solver": str(solver),
|
| 356 |
+
"sway_coef": float(sway_coef),
|
| 357 |
+
"temperature": float(temperature),
|
| 358 |
+
"cfg_scale": float(cfg_scale),
|
| 359 |
+
"seed": int(seed),
|
| 360 |
+
"frontend": {**frontend_identity(), "fingerprint": frontend_fingerprint()},
|
| 361 |
+
}
|
| 362 |
+
meta_path = target.with_suffix(".meta.json")
|
| 363 |
+
meta_path.write_text(json.dumps(meta, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 364 |
+
return target
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def export_bigvgan_onnx(
|
| 368 |
+
vocoder_path_or_id: Path | str | BigVGANVocoderWrapper,
|
| 369 |
+
out_path: Path | str,
|
| 370 |
+
opset: int = 17,
|
| 371 |
+
dummy_frames: int = 40,
|
| 372 |
+
) -> Path:
|
| 373 |
+
"""Export MIT BigVGAN 24 kHz 100-band vocoder to dynamic-length ONNX."""
|
| 374 |
+
if isinstance(vocoder_path_or_id, BigVGANVocoderWrapper):
|
| 375 |
+
vocoder = vocoder_path_or_id.cpu().eval()
|
| 376 |
+
else:
|
| 377 |
+
voc_target = Path(vocoder_path_or_id)
|
| 378 |
+
if voc_target.is_file():
|
| 379 |
+
vocoder = BigVGANVocoderWrapper(ckpt_path=voc_target, device="cpu")
|
| 380 |
+
else:
|
| 381 |
+
vocoder = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device="cpu")
|
| 382 |
+
wrapper = ExportableBigVGAN(vocoder).eval()
|
| 383 |
+
dummy_mel = torch.full((1, int(dummy_frames), 100), -5.0, dtype=torch.float32)
|
| 384 |
+
target = Path(out_path)
|
| 385 |
+
with torch.no_grad():
|
| 386 |
+
return _export_torch_onnx(
|
| 387 |
+
wrapper,
|
| 388 |
+
(dummy_mel,),
|
| 389 |
+
target,
|
| 390 |
+
input_names=list(BIGVGAN_INPUTS),
|
| 391 |
+
output_names=list(BIGVGAN_OUTPUTS),
|
| 392 |
+
dynamic_axes={"mel": {1: "frames"}, "audio": {1: "samples"}},
|
| 393 |
+
opset=opset,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def verify_cfm_onnx(
|
| 398 |
+
cfm_path_or_model: Path | str | LuaNovaCFM,
|
| 399 |
+
onnx_path: Path | str,
|
| 400 |
+
n_steps: int = 2,
|
| 401 |
+
cfg_scale: float = 1.0,
|
| 402 |
+
temperature: float = 0.35,
|
| 403 |
+
solver: str = "euler",
|
| 404 |
+
sway_coef: float = 0.0,
|
| 405 |
+
seed: int = 0,
|
| 406 |
+
text: str = "Olá, tudo bem com você hoje?",
|
| 407 |
+
) -> dict[str, float]:
|
| 408 |
+
"""Compare exported ONNX acoustic predictions against PyTorch ``ExportableCFMAcoustic``."""
|
| 409 |
+
import onnxruntime as ort
|
| 410 |
+
|
| 411 |
+
model = (
|
| 412 |
+
cfm_path_or_model
|
| 413 |
+
if isinstance(cfm_path_or_model, LuaNovaCFM)
|
| 414 |
+
else load_cfm_model(cfm_path_or_model, device="cpu", load_vocos=False)
|
| 415 |
+
).cpu().eval()
|
| 416 |
+
wrapper = ExportableCFMAcoustic(
|
| 417 |
+
model,
|
| 418 |
+
n_steps=n_steps,
|
| 419 |
+
cfg_scale=cfg_scale,
|
| 420 |
+
temperature=temperature,
|
| 421 |
+
solver=solver,
|
| 422 |
+
sway_coef=sway_coef,
|
| 423 |
+
seed=seed,
|
| 424 |
+
).eval()
|
| 425 |
+
inputs = example_cfm_inputs(text=text, device="cpu")
|
| 426 |
+
with torch.no_grad():
|
| 427 |
+
mel_pt, flen_pt = wrapper(*inputs)
|
| 428 |
+
sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
|
| 429 |
+
feed = {name: arr.numpy() for name, arr in zip(CFM_INPUTS, inputs)}
|
| 430 |
+
mel_ort, flen_ort = sess.run(list(CFM_OUTPUTS), feed)
|
| 431 |
+
diff = np.abs(mel_pt.numpy() - mel_ort)
|
| 432 |
+
return {
|
| 433 |
+
"max_abs_diff": float(diff.max()),
|
| 434 |
+
"mean_abs_diff": float(diff.mean()),
|
| 435 |
+
"frames_match": float(int(flen_pt.item()) == int(flen_ort.item())),
|
| 436 |
+
"frames": float(int(flen_ort.item())),
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def verify_bigvgan_onnx(
|
| 441 |
+
vocoder_path_or_id: Path | str | BigVGANVocoderWrapper,
|
| 442 |
+
onnx_path: Path | str,
|
| 443 |
+
test_frames: int = 67,
|
| 444 |
+
) -> dict[str, float]:
|
| 445 |
+
"""Compare exported BigVGAN ONNX output against PyTorch at an arbitrary frame length."""
|
| 446 |
+
import onnxruntime as ort
|
| 447 |
+
|
| 448 |
+
if isinstance(vocoder_path_or_id, BigVGANVocoderWrapper):
|
| 449 |
+
vocoder = vocoder_path_or_id.cpu().eval()
|
| 450 |
+
else:
|
| 451 |
+
voc_target = Path(vocoder_path_or_id)
|
| 452 |
+
if voc_target.is_file():
|
| 453 |
+
vocoder = BigVGANVocoderWrapper(ckpt_path=voc_target, device="cpu")
|
| 454 |
+
else:
|
| 455 |
+
vocoder = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device="cpu")
|
| 456 |
+
mel = torch.randn((1, int(test_frames), 100), dtype=torch.float32) * 0.5 - 5.0
|
| 457 |
+
flen = torch.tensor([test_frames], dtype=torch.long)
|
| 458 |
+
with torch.no_grad():
|
| 459 |
+
wav_pt = vocoder.decode_raw_mel(mel, flen).numpy()
|
| 460 |
+
sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
|
| 461 |
+
(wav_ort,) = sess.run(list(BIGVGAN_OUTPUTS), {"mel": mel.numpy()})
|
| 462 |
+
diff = np.abs(wav_pt - wav_ort)
|
| 463 |
+
return {
|
| 464 |
+
"max_abs_diff": float(diff.max()),
|
| 465 |
+
"mean_abs_diff": float(diff.mean()),
|
| 466 |
+
"samples": float(wav_ort.shape[-1]),
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def main() -> None:
|
| 471 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 472 |
+
parser.add_argument("--cfm", type=Path, default=None, help="Path to CFM v5 checkpoint (.pt)")
|
| 473 |
+
parser.add_argument("--vocoder", default=None, help="Path to BigVGAN .pt checkpoint or HF model ID")
|
| 474 |
+
parser.add_argument("--out-dir", type=Path, required=True)
|
| 475 |
+
parser.add_argument("--cfm-name", default="cfm_v5.onnx")
|
| 476 |
+
parser.add_argument("--vocoder-name", default="bigvgan_base_ft.onnx")
|
| 477 |
+
parser.add_argument("--steps", type=int, default=2)
|
| 478 |
+
parser.add_argument("--solver", default="euler", choices=["euler", "midpoint"])
|
| 479 |
+
parser.add_argument("--sway-coef", type=float, default=0.0)
|
| 480 |
+
parser.add_argument("--temperature", type=float, default=0.35)
|
| 481 |
+
parser.add_argument("--cfg-scale", type=float, default=1.0)
|
| 482 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 483 |
+
parser.add_argument("--opset", type=int, default=17)
|
| 484 |
+
parser.add_argument("--verify", action="store_true")
|
| 485 |
+
args = parser.parse_args()
|
| 486 |
+
|
| 487 |
+
if args.cfm is None and args.vocoder is None:
|
| 488 |
+
parser.error("provide at least --cfm or --vocoder")
|
| 489 |
+
|
| 490 |
+
args.out_dir.mkdir(parents=True, exist_ok=True)
|
| 491 |
+
if args.cfm is not None:
|
| 492 |
+
cfm_out = export_cfm_onnx(
|
| 493 |
+
args.cfm,
|
| 494 |
+
args.out_dir / args.cfm_name,
|
| 495 |
+
n_steps=args.steps,
|
| 496 |
+
cfg_scale=args.cfg_scale,
|
| 497 |
+
temperature=args.temperature,
|
| 498 |
+
solver=args.solver,
|
| 499 |
+
sway_coef=args.sway_coef,
|
| 500 |
+
seed=args.seed,
|
| 501 |
+
opset=args.opset,
|
| 502 |
+
)
|
| 503 |
+
print(f"Exported CFM ONNX -> {cfm_out}", flush=True)
|
| 504 |
+
if args.verify:
|
| 505 |
+
stats = verify_cfm_onnx(
|
| 506 |
+
args.cfm,
|
| 507 |
+
cfm_out,
|
| 508 |
+
n_steps=args.steps,
|
| 509 |
+
cfg_scale=args.cfg_scale,
|
| 510 |
+
temperature=args.temperature,
|
| 511 |
+
solver=args.solver,
|
| 512 |
+
sway_coef=args.sway_coef,
|
| 513 |
+
seed=args.seed,
|
| 514 |
+
)
|
| 515 |
+
print("CFM parity:", json.dumps(stats), flush=True)
|
| 516 |
+
|
| 517 |
+
if args.vocoder is not None:
|
| 518 |
+
voc_out = export_bigvgan_onnx(args.vocoder, args.out_dir / args.vocoder_name, opset=args.opset)
|
| 519 |
+
print(f"Exported BigVGAN ONNX -> {voc_out}", flush=True)
|
| 520 |
+
if args.verify:
|
| 521 |
+
stats = verify_bigvgan_onnx(args.vocoder, voc_out)
|
| 522 |
+
print("BigVGAN parity:", json.dumps(stats), flush=True)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
if __name__ == "__main__":
|
| 526 |
+
main()
|
code/src/lua_nova_v1/inference/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference synthesizers, streaming helpers, and CLI entrypoints."""
|
| 2 |
+
|
| 3 |
+
from .onnx_engine import OnnxSynthesizer
|
| 4 |
+
from .streaming import iter_speakable_pieces, stream_vocoder_chunks
|
| 5 |
+
from .synthesizer import Synthesizer
|
| 6 |
+
|
| 7 |
+
__all__ = ["OnnxSynthesizer", "Synthesizer", "iter_speakable_pieces", "stream_vocoder_chunks"]
|
code/src/lua_nova_v1/inference/cli.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Command-line interface for Lua Nova V1 PyTorch & ONNX Runtime CPU synthesis."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from .onnx_engine import OnnxSynthesizer
|
| 11 |
+
from .synthesizer import Synthesizer
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main() -> None:
|
| 15 |
+
parser = argparse.ArgumentParser(description="Synthesize 24 kHz PT-BR speech with LuaNovaBase CFM v5 + BigVGAN")
|
| 16 |
+
parser.add_argument("--text", required=True, help="Input Portuguese text")
|
| 17 |
+
parser.add_argument("--out", type=Path, required=True, help="Output .wav path")
|
| 18 |
+
|
| 19 |
+
# PyTorch backend
|
| 20 |
+
parser.add_argument("--cfm", type=Path, default=None, help="Path to CFM v5 checkpoint (.pt)")
|
| 21 |
+
parser.add_argument(
|
| 22 |
+
"--vocoder",
|
| 23 |
+
default="nvidia/bigvgan_base_24khz_100band",
|
| 24 |
+
help="Path to fine-tuned BigVGAN .pt checkpoint or Hugging Face model ID",
|
| 25 |
+
)
|
| 26 |
+
parser.add_argument("--device", default="cpu")
|
| 27 |
+
parser.add_argument("--steps", type=int, default=8)
|
| 28 |
+
parser.add_argument("--solver", default="midpoint", choices=["euler", "midpoint"])
|
| 29 |
+
parser.add_argument("--temperature", type=float, default=0.35)
|
| 30 |
+
parser.add_argument("--cfg-scale", type=float, default=1.0)
|
| 31 |
+
parser.add_argument("--sway-coef", type=float, default=-0.5)
|
| 32 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 33 |
+
|
| 34 |
+
# ONNX Runtime CPU backend
|
| 35 |
+
parser.add_argument("--onnx-cfm", type=Path, default=None, help="Path to exported cfm_v5.onnx")
|
| 36 |
+
parser.add_argument("--onnx-vocoder", type=Path, default=None, help="Path to exported bigvgan.onnx")
|
| 37 |
+
parser.add_argument("--threads", type=int, default=None, help="ONNX Runtime intra-op CPU threads")
|
| 38 |
+
|
| 39 |
+
# Shared & streaming options
|
| 40 |
+
parser.add_argument("--voice", default="F1")
|
| 41 |
+
parser.add_argument("--pitch-range", type=float, default=1.05)
|
| 42 |
+
parser.add_argument("--speed", type=float, default=1.0)
|
| 43 |
+
parser.add_argument("--no-normalize", action="store_true", help="Disable PT-BR text normalization")
|
| 44 |
+
parser.add_argument("--no-postprocess", action="store_true", help="Disable RMS normalization and edge fades")
|
| 45 |
+
parser.add_argument("--stream", action="store_true", help="Synthesize via chunked streaming and report TTFA")
|
| 46 |
+
parser.add_argument("--chunk-frames", type=int, default=36, help="Mel frames per streamed vocoder chunk")
|
| 47 |
+
args = parser.parse_args()
|
| 48 |
+
|
| 49 |
+
use_onnx = args.onnx_cfm is not None or args.onnx_vocoder is not None
|
| 50 |
+
if use_onnx:
|
| 51 |
+
if args.onnx_cfm is None or args.onnx_vocoder is None:
|
| 52 |
+
parser.error("both --onnx-cfm and --onnx-vocoder are required for ONNX inference")
|
| 53 |
+
synth = OnnxSynthesizer(args.onnx_cfm, args.onnx_vocoder, threads=args.threads)
|
| 54 |
+
t0 = time.perf_counter()
|
| 55 |
+
if args.stream:
|
| 56 |
+
chunks: list[np.ndarray] = []
|
| 57 |
+
ttfa_ms = None
|
| 58 |
+
for chunk in synth.speak_stream(
|
| 59 |
+
args.text,
|
| 60 |
+
voice=args.voice,
|
| 61 |
+
speed=args.speed,
|
| 62 |
+
pitch_range=args.pitch_range,
|
| 63 |
+
normalize=not args.no_normalize,
|
| 64 |
+
chunk_frames=args.chunk_frames,
|
| 65 |
+
):
|
| 66 |
+
if ttfa_ms is None:
|
| 67 |
+
ttfa_ms = (time.perf_counter() - t0) * 1000.0
|
| 68 |
+
chunks.append(chunk)
|
| 69 |
+
wav = np.concatenate(chunks, axis=0) if chunks else np.zeros(0, dtype=np.float32)
|
| 70 |
+
else:
|
| 71 |
+
ttfa_ms = None
|
| 72 |
+
wav = synth.speak(
|
| 73 |
+
args.text,
|
| 74 |
+
voice=args.voice,
|
| 75 |
+
speed=args.speed,
|
| 76 |
+
pitch_range=args.pitch_range,
|
| 77 |
+
normalize=not args.no_normalize,
|
| 78 |
+
postprocess=not args.no_postprocess,
|
| 79 |
+
)
|
| 80 |
+
else:
|
| 81 |
+
if args.cfm is None:
|
| 82 |
+
parser.error("provide --cfm (PyTorch) or --onnx-cfm/--onnx-vocoder (ONNX Runtime)")
|
| 83 |
+
synth = Synthesizer.from_checkpoints(args.cfm, args.vocoder, device=args.device)
|
| 84 |
+
t0 = time.perf_counter()
|
| 85 |
+
if args.stream:
|
| 86 |
+
chunks = []
|
| 87 |
+
ttfa_ms = None
|
| 88 |
+
for chunk in synth.speak_stream(
|
| 89 |
+
args.text,
|
| 90 |
+
voice=args.voice,
|
| 91 |
+
n_steps=args.steps,
|
| 92 |
+
temperature=args.temperature,
|
| 93 |
+
cfg_scale=args.cfg_scale,
|
| 94 |
+
sway_coef=args.sway_coef,
|
| 95 |
+
solver=args.solver,
|
| 96 |
+
pitch_range=args.pitch_range,
|
| 97 |
+
speed=args.speed,
|
| 98 |
+
normalize=not args.no_normalize,
|
| 99 |
+
seed=args.seed,
|
| 100 |
+
chunk_frames=args.chunk_frames,
|
| 101 |
+
):
|
| 102 |
+
if ttfa_ms is None:
|
| 103 |
+
ttfa_ms = (time.perf_counter() - t0) * 1000.0
|
| 104 |
+
chunks.append(chunk)
|
| 105 |
+
wav = np.concatenate(chunks, axis=0) if chunks else np.zeros(0, dtype=np.float32)
|
| 106 |
+
else:
|
| 107 |
+
ttfa_ms = None
|
| 108 |
+
wav = synth.speak(
|
| 109 |
+
args.text,
|
| 110 |
+
voice=args.voice,
|
| 111 |
+
n_steps=args.steps,
|
| 112 |
+
temperature=args.temperature,
|
| 113 |
+
cfg_scale=args.cfg_scale,
|
| 114 |
+
sway_coef=args.sway_coef,
|
| 115 |
+
solver=args.solver,
|
| 116 |
+
pitch_range=args.pitch_range,
|
| 117 |
+
speed=args.speed,
|
| 118 |
+
normalize=not args.no_normalize,
|
| 119 |
+
postprocess=not args.no_postprocess,
|
| 120 |
+
seed=args.seed,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
elapsed = time.perf_counter() - t0
|
| 124 |
+
out_path = synth.save_wav(args.out, wav)
|
| 125 |
+
dur_s = len(wav) / synth.sample_rate
|
| 126 |
+
ttfa_info = f", TTFA={ttfa_ms:.1f}ms" if ttfa_ms is not None else ""
|
| 127 |
+
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})")
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
main()
|
code/src/lua_nova_v1/inference/onnx_engine.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pure-CPU ONNX Runtime synthesizer and chunked streaming engine for Lua Nova V1."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections.abc import Iterator
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import soundfile as sf
|
| 11 |
+
|
| 12 |
+
from ..text.phonemizer import phonemize
|
| 13 |
+
from ..utils.audio import DEFAULT_FADE_MS, DEFAULT_TARGET_RMS_DB, pcm16, postprocess_audio
|
| 14 |
+
from .streaming import iter_speakable_pieces, stream_vocoder_chunks
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class OnnxSynthesizer:
|
| 18 |
+
"""Fast CPU TTS engine running split ``cfm_v5.onnx`` + ``bigvgan.onnx`` via ONNX Runtime."""
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
cfm_onnx_path: Path | str,
|
| 23 |
+
vocoder_onnx_path: Path | str,
|
| 24 |
+
threads: int | None = None,
|
| 25 |
+
speakers: tuple[str, ...] | None = None,
|
| 26 |
+
sample_rate: int | None = None,
|
| 27 |
+
hop: int | None = None,
|
| 28 |
+
max_tokens: int | None = None,
|
| 29 |
+
) -> None:
|
| 30 |
+
import onnxruntime as ort
|
| 31 |
+
|
| 32 |
+
cfm_path = Path(cfm_onnx_path)
|
| 33 |
+
voc_path = Path(vocoder_onnx_path)
|
| 34 |
+
meta_path = cfm_path.with_suffix(".meta.json")
|
| 35 |
+
meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.is_file() else {}
|
| 36 |
+
|
| 37 |
+
self.speakers = tuple(speakers or meta.get("speakers", ("F1",)))
|
| 38 |
+
self.sample_rate = int(sample_rate or meta.get("sample_rate", 24000))
|
| 39 |
+
self.hop = int(hop or meta.get("hop", 256))
|
| 40 |
+
self.max_tokens = int(max_tokens or meta.get("max_tokens", 512))
|
| 41 |
+
self.threads = int(threads) if threads is not None else max(1, (os.cpu_count() or 4) // 2)
|
| 42 |
+
|
| 43 |
+
opts = ort.SessionOptions()
|
| 44 |
+
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 45 |
+
opts.intra_op_num_threads = self.threads
|
| 46 |
+
opts.inter_op_num_threads = 1
|
| 47 |
+
opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
| 48 |
+
|
| 49 |
+
self.cfm_sess = ort.InferenceSession(str(cfm_path), sess_options=opts, providers=["CPUExecutionProvider"])
|
| 50 |
+
self.voc_sess = ort.InferenceSession(str(voc_path), sess_options=opts, providers=["CPUExecutionProvider"])
|
| 51 |
+
self.cfm_meta = meta
|
| 52 |
+
|
| 53 |
+
def predict_mel(
|
| 54 |
+
self,
|
| 55 |
+
piece: str,
|
| 56 |
+
voice: str = "F1",
|
| 57 |
+
speed: float = 1.0,
|
| 58 |
+
pitch_shift: float = 0.0,
|
| 59 |
+
pitch_range: float = 1.05,
|
| 60 |
+
) -> np.ndarray:
|
| 61 |
+
"""Predict unnormalized physical 100-band log-mel ``[T, 100]`` for one phrase piece."""
|
| 62 |
+
if voice not in self.speakers:
|
| 63 |
+
raise ValueError(f"unknown speaker {voice!r}; available: {self.speakers}")
|
| 64 |
+
phones = phonemize(piece)
|
| 65 |
+
feed = {
|
| 66 |
+
"tokens": np.asarray([phones.ids], dtype=np.int64),
|
| 67 |
+
"stress": np.asarray([phones.stress], dtype=np.int64),
|
| 68 |
+
"voice": np.asarray([self.speakers.index(voice)], dtype=np.int64),
|
| 69 |
+
"speed": np.asarray([speed], dtype=np.float32),
|
| 70 |
+
"pitch_shift": np.asarray([pitch_shift], dtype=np.float32),
|
| 71 |
+
"pitch_range": np.asarray([pitch_range], dtype=np.float32),
|
| 72 |
+
}
|
| 73 |
+
phys_mel, flen = self.cfm_sess.run(["phys_mel", "frame_lengths"], feed)
|
| 74 |
+
n_frames = int(flen[0])
|
| 75 |
+
return phys_mel[0, :n_frames, :].astype(np.float32, copy=False)
|
| 76 |
+
|
| 77 |
+
def decode_mel(self, phys_mel: np.ndarray) -> np.ndarray:
|
| 78 |
+
"""Decode physical log-mel ``[T, 100]`` (or ``[1, T, 100]``) to mono 24 kHz float32 audio."""
|
| 79 |
+
mel = np.asarray(phys_mel, dtype=np.float32)
|
| 80 |
+
if mel.ndim == 2:
|
| 81 |
+
mel = mel[None, :, :]
|
| 82 |
+
(wav,) = self.voc_sess.run(["audio"], {"mel": mel})
|
| 83 |
+
return wav[0].astype(np.float32, copy=False)
|
| 84 |
+
|
| 85 |
+
def decode_mel_stream(
|
| 86 |
+
self,
|
| 87 |
+
phys_mel: np.ndarray,
|
| 88 |
+
chunk_frames: int = 36,
|
| 89 |
+
context_frames: int = 8,
|
| 90 |
+
fade_frames: int = 4,
|
| 91 |
+
) -> Iterator[np.ndarray]:
|
| 92 |
+
"""Yield overlap-crossfaded 24 kHz waveform chunks from physical log-mel ``[T, 100]``."""
|
| 93 |
+
return stream_vocoder_chunks(
|
| 94 |
+
self.decode_mel,
|
| 95 |
+
phys_mel,
|
| 96 |
+
hop=self.hop,
|
| 97 |
+
chunk_frames=chunk_frames,
|
| 98 |
+
context_frames=context_frames,
|
| 99 |
+
fade_frames=fade_frames,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def speak(
|
| 103 |
+
self,
|
| 104 |
+
text: str,
|
| 105 |
+
voice: str = "F1",
|
| 106 |
+
speed: float = 1.0,
|
| 107 |
+
pitch_shift: float = 0.0,
|
| 108 |
+
pitch_range: float = 1.05,
|
| 109 |
+
normalize: bool = True,
|
| 110 |
+
postprocess: bool = True,
|
| 111 |
+
pause_ms: float = 120.0,
|
| 112 |
+
) -> np.ndarray:
|
| 113 |
+
"""Synthesize full-utterance mono 24 kHz float32 waveform in ``[-1, 1]``."""
|
| 114 |
+
pieces = iter_speakable_pieces(text, self.max_tokens, normalize=normalize)
|
| 115 |
+
waves = [self.decode_mel(self.predict_mel(p, voice, speed, pitch_shift, pitch_range)) for p in pieces]
|
| 116 |
+
if len(waves) == 1:
|
| 117 |
+
combined = waves[0]
|
| 118 |
+
else:
|
| 119 |
+
gap = np.zeros(int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0)), dtype=np.float32)
|
| 120 |
+
parts: list[np.ndarray] = []
|
| 121 |
+
for idx, w in enumerate(waves):
|
| 122 |
+
if idx > 0 and gap.size:
|
| 123 |
+
parts.append(gap)
|
| 124 |
+
parts.append(w)
|
| 125 |
+
combined = np.concatenate(parts, axis=0)
|
| 126 |
+
|
| 127 |
+
if postprocess:
|
| 128 |
+
combined = postprocess_audio(
|
| 129 |
+
combined,
|
| 130 |
+
sample_rate=self.sample_rate,
|
| 131 |
+
target_rms_db=DEFAULT_TARGET_RMS_DB,
|
| 132 |
+
fade_ms=DEFAULT_FADE_MS,
|
| 133 |
+
)
|
| 134 |
+
pcm, _ = pcm16(combined)
|
| 135 |
+
return pcm.astype(np.float32)
|
| 136 |
+
|
| 137 |
+
def speak_stream(
|
| 138 |
+
self,
|
| 139 |
+
text: str,
|
| 140 |
+
voice: str = "F1",
|
| 141 |
+
speed: float = 1.0,
|
| 142 |
+
pitch_shift: float = 0.0,
|
| 143 |
+
pitch_range: float = 1.05,
|
| 144 |
+
normalize: bool = True,
|
| 145 |
+
pause_ms: float = 120.0,
|
| 146 |
+
chunk_frames: int = 36,
|
| 147 |
+
context_frames: int = 8,
|
| 148 |
+
fade_frames: int = 4,
|
| 149 |
+
) -> Iterator[np.ndarray]:
|
| 150 |
+
"""Stream 24 kHz mono float32 audio chunks phrase-by-phrase and mel-chunk-by-chunk."""
|
| 151 |
+
pieces = iter_speakable_pieces(text, self.max_tokens, normalize=normalize)
|
| 152 |
+
gap_samples = int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0))
|
| 153 |
+
for idx, piece in enumerate(pieces):
|
| 154 |
+
if idx > 0 and gap_samples > 0:
|
| 155 |
+
yield np.zeros(gap_samples, dtype=np.float32)
|
| 156 |
+
mel = self.predict_mel(piece, voice=voice, speed=speed, pitch_shift=pitch_shift, pitch_range=pitch_range)
|
| 157 |
+
yield from self.decode_mel_stream(
|
| 158 |
+
mel,
|
| 159 |
+
chunk_frames=chunk_frames,
|
| 160 |
+
context_frames=context_frames,
|
| 161 |
+
fade_frames=fade_frames,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def save_wav(self, path: Path | str, wav: np.ndarray) -> Path:
|
| 165 |
+
"""Save synthesized audio as 16-bit 24 kHz PCM WAV."""
|
| 166 |
+
out_path = Path(path)
|
| 167 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 168 |
+
pcm, _ = pcm16(wav)
|
| 169 |
+
sf.write(out_path, pcm, self.sample_rate, subtype="PCM_16")
|
| 170 |
+
return out_path
|
code/src/lua_nova_v1/inference/streaming.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared streaming and chunk-stitching helpers for PyTorch and ONNX synthesizers."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections.abc import Callable, Iterator
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from ..text.normalizer import normalize_ptbr_text
|
| 9 |
+
from ..text.phonemizer import phonemize
|
| 10 |
+
from ..utils.audio import finished, sentences, shorter
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _split_piece_by_tokens(piece: str, max_tokens: int) -> list[str]:
|
| 14 |
+
phones = phonemize(piece)
|
| 15 |
+
if len(phones) <= max_tokens:
|
| 16 |
+
return [piece]
|
| 17 |
+
halves = shorter(piece)
|
| 18 |
+
if len(halves) > 1:
|
| 19 |
+
out: list[str] = []
|
| 20 |
+
for sub in halves:
|
| 21 |
+
if sub.strip():
|
| 22 |
+
out.extend(_split_piece_by_tokens(sub, max_tokens))
|
| 23 |
+
return out
|
| 24 |
+
raise ValueError(f"chunk exceeds max_tokens={max_tokens}: {piece[:80]!r}")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def iter_speakable_pieces(text: str, max_tokens: int, normalize: bool = True) -> list[str]:
|
| 28 |
+
"""Normalize text and split it into sentence/clause pieces fitting within ``max_tokens``."""
|
| 29 |
+
if not text or not text.strip():
|
| 30 |
+
raise ValueError("input text must not be empty")
|
| 31 |
+
clean = normalize_ptbr_text(text) if normalize else text.strip()
|
| 32 |
+
sent_list = [finished(s) for s in sentences(clean)] or [finished(clean)]
|
| 33 |
+
pieces: list[str] = []
|
| 34 |
+
for sent in sent_list:
|
| 35 |
+
pieces.extend(_split_piece_by_tokens(sent, max_tokens))
|
| 36 |
+
return pieces
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def stream_vocoder_chunks(
|
| 40 |
+
decode_mel_fn: Callable[[np.ndarray], np.ndarray],
|
| 41 |
+
phys_mel: np.ndarray,
|
| 42 |
+
hop: int = 256,
|
| 43 |
+
chunk_frames: int = 36,
|
| 44 |
+
context_frames: int = 8,
|
| 45 |
+
fade_frames: int = 4,
|
| 46 |
+
) -> Iterator[np.ndarray]:
|
| 47 |
+
"""Yield click-free mono waveform chunks from physical log-mel ``[T, 100]``.
|
| 48 |
+
|
| 49 |
+
Each chunk includes symmetrical convolutional lookback/lookahead ``context_frames`` when
|
| 50 |
+
decoding and applies a raised-cosine Hann crossfade across ``fade_frames`` at boundaries so
|
| 51 |
+
concatenating all yielded chunks matches exact length ``T * hop``.
|
| 52 |
+
"""
|
| 53 |
+
mel = np.asarray(phys_mel, dtype=np.float32)
|
| 54 |
+
if mel.ndim == 3:
|
| 55 |
+
mel = mel[0]
|
| 56 |
+
total_frames = int(mel.shape[0])
|
| 57 |
+
if total_frames <= 0:
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
chunk = max(int(chunk_frames), 4)
|
| 61 |
+
ctx = max(int(context_frames), 0)
|
| 62 |
+
fade = min(max(int(fade_frames), 0), chunk // 2)
|
| 63 |
+
pending_tail: np.ndarray | None = None
|
| 64 |
+
start = 0
|
| 65 |
+
|
| 66 |
+
while start < total_frames:
|
| 67 |
+
end = min(total_frames, start + chunk)
|
| 68 |
+
if total_frames - end <= max(fade, chunk // 3):
|
| 69 |
+
end = total_frames
|
| 70 |
+
|
| 71 |
+
out_start = start - fade if pending_tail is not None and fade > 0 else start
|
| 72 |
+
in_start = max(0, out_start - ctx)
|
| 73 |
+
in_end = min(total_frames, end + ctx)
|
| 74 |
+
|
| 75 |
+
raw = np.asarray(decode_mel_fn(mel[in_start:in_end]), dtype=np.float32).reshape(-1)
|
| 76 |
+
left_trim = (out_start - in_start) * hop
|
| 77 |
+
out_samples = (end - out_start) * hop
|
| 78 |
+
seg = raw[left_trim : left_trim + out_samples].copy()
|
| 79 |
+
|
| 80 |
+
if pending_tail is not None and pending_tail.size > 0:
|
| 81 |
+
n_fade = int(pending_tail.size)
|
| 82 |
+
t = np.linspace(0.0, 1.0, n_fade, dtype=np.float32)
|
| 83 |
+
w = 0.5 * (1.0 - np.cos(np.pi * t))
|
| 84 |
+
seg[:n_fade] = (1.0 - w) * pending_tail + w * seg[:n_fade]
|
| 85 |
+
|
| 86 |
+
if end < total_frames and fade > 0:
|
| 87 |
+
tail_samples = fade * hop
|
| 88 |
+
pending_tail = seg[-tail_samples:].copy()
|
| 89 |
+
emit = seg[:-tail_samples]
|
| 90 |
+
else:
|
| 91 |
+
pending_tail = None
|
| 92 |
+
emit = seg
|
| 93 |
+
|
| 94 |
+
if emit.size > 0:
|
| 95 |
+
yield np.clip(emit, -0.99, 0.99).astype(np.float32, copy=False)
|
| 96 |
+
start = end
|
code/src/lua_nova_v1/inference/synthesizer.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""High-level PyTorch inference synthesizer for Lua Nova V1."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections.abc import Iterator
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import soundfile as sf
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from ..models.bigvgan import BigVGANVocoderWrapper
|
| 12 |
+
from ..models.cfm import LuaNovaCFM
|
| 13 |
+
from ..text.phonemizer import phonemize
|
| 14 |
+
from ..training.common import load_cfm_model
|
| 15 |
+
from ..utils.audio import (
|
| 16 |
+
DEFAULT_FADE_MS,
|
| 17 |
+
DEFAULT_TARGET_RMS_DB,
|
| 18 |
+
pcm16,
|
| 19 |
+
postprocess_audio,
|
| 20 |
+
)
|
| 21 |
+
from .streaming import iter_speakable_pieces, stream_vocoder_chunks
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Synthesizer:
|
| 25 |
+
"""End-to-end Brazilian Portuguese TTS pipeline (CFM v5 + BigVGAN 24 kHz)."""
|
| 26 |
+
|
| 27 |
+
def __init__(self, cfm: LuaNovaCFM, vocoder: BigVGANVocoderWrapper, device: str = "cpu") -> None:
|
| 28 |
+
self.cfm = cfm.to(device).eval()
|
| 29 |
+
self.vocoder = vocoder.to(device).eval()
|
| 30 |
+
self.device = str(device)
|
| 31 |
+
self.sample_rate = int(self.cfm.config.sample_rate)
|
| 32 |
+
self.hop = int(self.cfm.config.hop)
|
| 33 |
+
|
| 34 |
+
@classmethod
|
| 35 |
+
def from_checkpoints(
|
| 36 |
+
cls,
|
| 37 |
+
cfm_path: Path | str,
|
| 38 |
+
vocoder_path_or_id: Path | str = "nvidia/bigvgan_base_24khz_100band",
|
| 39 |
+
device: str = "cpu",
|
| 40 |
+
) -> "Synthesizer":
|
| 41 |
+
"""Load acoustic CFM weights and either a local fine-tuned vocoder `.pt` or Hugging Face repo ID."""
|
| 42 |
+
cfm = load_cfm_model(cfm_path, device=device, load_vocos=False)
|
| 43 |
+
voc_target = Path(vocoder_path_or_id)
|
| 44 |
+
if voc_target.is_file():
|
| 45 |
+
voc = BigVGANVocoderWrapper(ckpt_path=voc_target, device=device)
|
| 46 |
+
else:
|
| 47 |
+
voc = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device=device)
|
| 48 |
+
return cls(cfm=cfm, vocoder=voc, device=device)
|
| 49 |
+
|
| 50 |
+
def _predict_piece_mel(
|
| 51 |
+
self,
|
| 52 |
+
piece: str,
|
| 53 |
+
voice: str,
|
| 54 |
+
n_steps: int,
|
| 55 |
+
temperature: float,
|
| 56 |
+
cfg_scale: float,
|
| 57 |
+
sway_coef: float,
|
| 58 |
+
solver: str,
|
| 59 |
+
pitch_range: float | None,
|
| 60 |
+
speed: float,
|
| 61 |
+
pitch_shift: float,
|
| 62 |
+
seed: int,
|
| 63 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 64 |
+
if voice not in self.cfm.config.speakers:
|
| 65 |
+
raise ValueError(f"unknown speaker {voice!r}; available: {self.cfm.config.speakers}")
|
| 66 |
+
phones = phonemize(piece)
|
| 67 |
+
tok = torch.tensor([phones.ids], device=self.device)
|
| 68 |
+
st = torch.tensor([phones.stress], device=self.device)
|
| 69 |
+
ln = torch.tensor([len(phones)], device=self.device)
|
| 70 |
+
sp = torch.tensor([self.cfm.config.speakers.index(voice)], device=self.device)
|
| 71 |
+
with torch.inference_mode():
|
| 72 |
+
phys_mel, flen, _ = self.cfm.predict_physical_mel(
|
| 73 |
+
tok,
|
| 74 |
+
st,
|
| 75 |
+
ln,
|
| 76 |
+
sp,
|
| 77 |
+
speed=speed,
|
| 78 |
+
pitch_shift=pitch_shift,
|
| 79 |
+
seed=seed,
|
| 80 |
+
pitch_range=pitch_range,
|
| 81 |
+
n_steps=n_steps,
|
| 82 |
+
cfg_scale=cfg_scale,
|
| 83 |
+
temperature=temperature,
|
| 84 |
+
solver=solver,
|
| 85 |
+
sway_coef=sway_coef,
|
| 86 |
+
)
|
| 87 |
+
return phys_mel, flen
|
| 88 |
+
|
| 89 |
+
def _decode_mel_slice(self, mel_chunk: np.ndarray) -> np.ndarray:
|
| 90 |
+
mel_t = torch.from_numpy(mel_chunk[None, :, :]).to(device=self.device, dtype=torch.float32)
|
| 91 |
+
flen = torch.tensor([mel_t.shape[1]], device=self.device, dtype=torch.long)
|
| 92 |
+
with torch.inference_mode():
|
| 93 |
+
wav = self.vocoder.decode_raw_mel(mel_t, flen)[0, : int(flen[0]) * self.hop]
|
| 94 |
+
return wav.cpu().numpy()
|
| 95 |
+
|
| 96 |
+
def speak(
|
| 97 |
+
self,
|
| 98 |
+
text: str,
|
| 99 |
+
voice: str = "F1",
|
| 100 |
+
n_steps: int = 8,
|
| 101 |
+
temperature: float = 0.35,
|
| 102 |
+
cfg_scale: float = 1.0,
|
| 103 |
+
sway_coef: float = -0.5,
|
| 104 |
+
solver: str = "midpoint",
|
| 105 |
+
pitch_range: float | None = 1.05,
|
| 106 |
+
speed: float = 1.0,
|
| 107 |
+
pitch_shift: float = 0.0,
|
| 108 |
+
normalize: bool = True,
|
| 109 |
+
postprocess: bool = True,
|
| 110 |
+
pause_ms: float = 120.0,
|
| 111 |
+
seed: int = 0,
|
| 112 |
+
) -> np.ndarray:
|
| 113 |
+
"""Synthesize arbitrary-length PT-BR text into a mono 24 kHz float32 waveform in [-1, 1]."""
|
| 114 |
+
pieces = iter_speakable_pieces(text, self.cfm.config.max_tokens, normalize=normalize)
|
| 115 |
+
waves: list[torch.Tensor] = []
|
| 116 |
+
for idx, piece in enumerate(pieces):
|
| 117 |
+
phys_mel, flen = self._predict_piece_mel(
|
| 118 |
+
piece,
|
| 119 |
+
voice,
|
| 120 |
+
n_steps,
|
| 121 |
+
temperature,
|
| 122 |
+
cfg_scale,
|
| 123 |
+
sway_coef,
|
| 124 |
+
solver,
|
| 125 |
+
pitch_range,
|
| 126 |
+
speed,
|
| 127 |
+
pitch_shift,
|
| 128 |
+
seed + idx,
|
| 129 |
+
)
|
| 130 |
+
with torch.inference_mode():
|
| 131 |
+
wav = self.vocoder.decode_raw_mel(phys_mel, flen)[0, : int(flen[0]) * self.hop]
|
| 132 |
+
waves.append(wav.cpu())
|
| 133 |
+
|
| 134 |
+
if len(waves) == 1:
|
| 135 |
+
combined = waves[0]
|
| 136 |
+
else:
|
| 137 |
+
gap = torch.zeros(int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0)), dtype=torch.float32)
|
| 138 |
+
parts: list[torch.Tensor] = []
|
| 139 |
+
for idx, w in enumerate(waves):
|
| 140 |
+
if idx > 0 and gap.numel():
|
| 141 |
+
parts.append(gap)
|
| 142 |
+
parts.append(w)
|
| 143 |
+
combined = torch.cat(parts, dim=0)
|
| 144 |
+
|
| 145 |
+
if postprocess:
|
| 146 |
+
combined = postprocess_audio(
|
| 147 |
+
combined,
|
| 148 |
+
sample_rate=self.sample_rate,
|
| 149 |
+
target_rms_db=DEFAULT_TARGET_RMS_DB,
|
| 150 |
+
fade_ms=DEFAULT_FADE_MS,
|
| 151 |
+
)
|
| 152 |
+
pcm, _ = pcm16(combined)
|
| 153 |
+
return pcm.astype(np.float32)
|
| 154 |
+
|
| 155 |
+
def speak_stream(
|
| 156 |
+
self,
|
| 157 |
+
text: str,
|
| 158 |
+
voice: str = "F1",
|
| 159 |
+
n_steps: int = 8,
|
| 160 |
+
temperature: float = 0.35,
|
| 161 |
+
cfg_scale: float = 1.0,
|
| 162 |
+
sway_coef: float = -0.5,
|
| 163 |
+
solver: str = "midpoint",
|
| 164 |
+
pitch_range: float | None = 1.05,
|
| 165 |
+
speed: float = 1.0,
|
| 166 |
+
pitch_shift: float = 0.0,
|
| 167 |
+
normalize: bool = True,
|
| 168 |
+
pause_ms: float = 120.0,
|
| 169 |
+
seed: int = 0,
|
| 170 |
+
chunk_frames: int = 36,
|
| 171 |
+
context_frames: int = 8,
|
| 172 |
+
fade_frames: int = 4,
|
| 173 |
+
) -> Iterator[np.ndarray]:
|
| 174 |
+
"""Yield low-latency 24 kHz waveform chunks via overlap-crossfaded mel streaming."""
|
| 175 |
+
pieces = iter_speakable_pieces(text, self.cfm.config.max_tokens, normalize=normalize)
|
| 176 |
+
gap_samples = int(round(self.sample_rate * max(pause_ms, 0.0) / 1000.0))
|
| 177 |
+
for idx, piece in enumerate(pieces):
|
| 178 |
+
if idx > 0 and gap_samples > 0:
|
| 179 |
+
yield np.zeros(gap_samples, dtype=np.float32)
|
| 180 |
+
phys_mel, flen = self._predict_piece_mel(
|
| 181 |
+
piece,
|
| 182 |
+
voice,
|
| 183 |
+
n_steps,
|
| 184 |
+
temperature,
|
| 185 |
+
cfg_scale,
|
| 186 |
+
sway_coef,
|
| 187 |
+
solver,
|
| 188 |
+
pitch_range,
|
| 189 |
+
speed,
|
| 190 |
+
pitch_shift,
|
| 191 |
+
seed + idx,
|
| 192 |
+
)
|
| 193 |
+
mel_np = phys_mel[0, : int(flen[0]), :].cpu().numpy()
|
| 194 |
+
yield from stream_vocoder_chunks(
|
| 195 |
+
self._decode_mel_slice,
|
| 196 |
+
mel_np,
|
| 197 |
+
hop=self.hop,
|
| 198 |
+
chunk_frames=chunk_frames,
|
| 199 |
+
context_frames=context_frames,
|
| 200 |
+
fade_frames=fade_frames,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
def save_wav(self, path: Path | str, wav: np.ndarray) -> Path:
|
| 204 |
+
"""Save synthesized audio as 16-bit 24 kHz PCM WAV."""
|
| 205 |
+
out_path = Path(path)
|
| 206 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 207 |
+
pcm, _ = pcm16(wav)
|
| 208 |
+
sf.write(out_path, pcm, self.sample_rate, subtype="PCM_16")
|
| 209 |
+
return out_path
|
code/src/lua_nova_v1/models/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Neural acoustic, prosody, flow-matching, and BigVGAN vocoder modules."""
|
| 2 |
+
|
| 3 |
+
from .bigvgan import BigVGANMelExtractor, BigVGANVocoderWrapper
|
| 4 |
+
from .cfm import (
|
| 5 |
+
DurationFlow,
|
| 6 |
+
FlowDecoder,
|
| 7 |
+
LinguisticContextAdapter,
|
| 8 |
+
MelStatsHead,
|
| 9 |
+
ProsodyFlow,
|
| 10 |
+
LuaNovaCFM,
|
| 11 |
+
energy_noise_gate,
|
| 12 |
+
f0_features,
|
| 13 |
+
smooth_f0_channel,
|
| 14 |
+
smooth_prosody_noise,
|
| 15 |
+
)
|
| 16 |
+
from .frontend import LuaNovaBase, UtteranceTooLong
|
| 17 |
+
from .losses import Discriminators, SpectralLoss, discriminator_loss, generator_gan_loss, masked_mean
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"BigVGANMelExtractor",
|
| 21 |
+
"BigVGANVocoderWrapper",
|
| 22 |
+
"Discriminators",
|
| 23 |
+
"DurationFlow",
|
| 24 |
+
"FlowDecoder",
|
| 25 |
+
"LinguisticContextAdapter",
|
| 26 |
+
"MelStatsHead",
|
| 27 |
+
"ProsodyFlow",
|
| 28 |
+
"SpectralLoss",
|
| 29 |
+
"LuaNovaBase",
|
| 30 |
+
"LuaNovaCFM",
|
| 31 |
+
"UtteranceTooLong",
|
| 32 |
+
"discriminator_loss",
|
| 33 |
+
"energy_noise_gate",
|
| 34 |
+
"f0_features",
|
| 35 |
+
"generator_gan_loss",
|
| 36 |
+
"masked_mean",
|
| 37 |
+
"smooth_f0_channel",
|
| 38 |
+
"smooth_prosody_noise",
|
| 39 |
+
]
|
code/src/lua_nova_v1/models/bigvgan.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MIT-licensed BigVGAN-v2 / BigVGAN-base 24 kHz 100-band Slaney mel extractor and vocoder wrapper."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
from librosa.filters import mel as librosa_mel_fn
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
_REPO_ROOT = Path(__file__).resolve().parents[3]
|
| 13 |
+
_BIGVGAN_DIR = _REPO_ROOT / "third_party" / "bigvgan"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _ensure_bigvgan_importable() -> None:
|
| 17 |
+
if str(_BIGVGAN_DIR) not in sys.path:
|
| 18 |
+
sys.path.insert(0, str(_BIGVGAN_DIR))
|
| 19 |
+
try:
|
| 20 |
+
import truststore
|
| 21 |
+
|
| 22 |
+
truststore.inject_into_ssl()
|
| 23 |
+
except ImportError:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class BigVGANMelExtractor(nn.Module):
|
| 28 |
+
"""Exact 24 kHz 100-band Slaney log-mel extractor matching MIT BigVGAN ``meldataset.py``."""
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
sample_rate: int = 24000,
|
| 33 |
+
n_fft: int = 1024,
|
| 34 |
+
hop_size: int = 256,
|
| 35 |
+
win_size: int = 1024,
|
| 36 |
+
n_mels: int = 100,
|
| 37 |
+
fmin: float = 0.0,
|
| 38 |
+
fmax: float | None = None,
|
| 39 |
+
) -> None:
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.sample_rate = int(sample_rate)
|
| 42 |
+
self.n_fft = int(n_fft)
|
| 43 |
+
self.hop_size = int(hop_size)
|
| 44 |
+
self.win_size = int(win_size)
|
| 45 |
+
self.n_mels = int(n_mels)
|
| 46 |
+
self.fmin = float(fmin)
|
| 47 |
+
self.fmax = fmax
|
| 48 |
+
mel_np = librosa_mel_fn(
|
| 49 |
+
sr=self.sample_rate,
|
| 50 |
+
n_fft=self.n_fft,
|
| 51 |
+
n_mels=self.n_mels,
|
| 52 |
+
fmin=self.fmin,
|
| 53 |
+
fmax=self.fmax,
|
| 54 |
+
)
|
| 55 |
+
self.register_buffer("mel_basis", torch.from_numpy(mel_np).float(), persistent=False)
|
| 56 |
+
self.register_buffer("hann_window", torch.hann_window(self.win_size).float(), persistent=False)
|
| 57 |
+
|
| 58 |
+
def forward(self, wave: torch.Tensor) -> torch.Tensor:
|
| 59 |
+
"""Compute BigVGAN Slaney log-mel ``[B, T, 100]`` from 24 kHz waveform ``[B, T*256]`` (or ``[T*256]``)."""
|
| 60 |
+
w = wave.float()
|
| 61 |
+
if w.dim() == 1:
|
| 62 |
+
w = w.unsqueeze(0)
|
| 63 |
+
pad = (self.n_fft - self.hop_size) // 2
|
| 64 |
+
if w.shape[-1] <= pad:
|
| 65 |
+
w = F.pad(w.unsqueeze(1), (pad, pad), mode="constant").squeeze(1)
|
| 66 |
+
else:
|
| 67 |
+
w = F.pad(w.unsqueeze(1), (pad, pad), mode="reflect").squeeze(1)
|
| 68 |
+
spec = torch.stft(
|
| 69 |
+
w,
|
| 70 |
+
self.n_fft,
|
| 71 |
+
hop_length=self.hop_size,
|
| 72 |
+
win_length=self.win_size,
|
| 73 |
+
window=self.hann_window,
|
| 74 |
+
center=False,
|
| 75 |
+
pad_mode="reflect",
|
| 76 |
+
normalized=False,
|
| 77 |
+
onesided=True,
|
| 78 |
+
return_complex=True,
|
| 79 |
+
)
|
| 80 |
+
mag = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9)
|
| 81 |
+
mel = torch.matmul(self.mel_basis, mag)
|
| 82 |
+
log_mel = torch.log(torch.clamp(mel, min=1e-5))
|
| 83 |
+
return log_mel.transpose(1, 2).contiguous()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class BigVGANVocoderWrapper(nn.Module):
|
| 87 |
+
"""Thin inference wrapper over MIT NVIDIA BigVGAN-v2 / BigVGAN-base 24 kHz 100-band."""
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
model_id: str = "nvidia/bigvgan_v2_24khz_100band_256x",
|
| 92 |
+
ckpt_path: Path | None = None,
|
| 93 |
+
device: str = "cuda",
|
| 94 |
+
use_cuda_kernel: bool = False,
|
| 95 |
+
) -> None:
|
| 96 |
+
super().__init__()
|
| 97 |
+
_ensure_bigvgan_importable()
|
| 98 |
+
import bigvgan
|
| 99 |
+
from env import AttrDict
|
| 100 |
+
|
| 101 |
+
if ckpt_path is not None:
|
| 102 |
+
ck = torch.load(ckpt_path, map_location="cpu", weights_only=True)
|
| 103 |
+
self.model_id = str(ck.get("model_id", model_id))
|
| 104 |
+
if "h" in ck:
|
| 105 |
+
model = bigvgan.BigVGAN(AttrDict(ck["h"]), use_cuda_kernel=use_cuda_kernel)
|
| 106 |
+
else:
|
| 107 |
+
model = bigvgan.BigVGAN.from_pretrained(self.model_id, use_cuda_kernel=use_cuda_kernel)
|
| 108 |
+
if ck.get("weight_norm_removed", False):
|
| 109 |
+
model.remove_weight_norm()
|
| 110 |
+
model.load_state_dict(ck["state_dict"], strict=True)
|
| 111 |
+
else:
|
| 112 |
+
model.load_state_dict(ck["state_dict"], strict=True)
|
| 113 |
+
model.remove_weight_norm()
|
| 114 |
+
else:
|
| 115 |
+
self.model_id = str(model_id)
|
| 116 |
+
model = bigvgan.BigVGAN.from_pretrained(self.model_id, use_cuda_kernel=use_cuda_kernel)
|
| 117 |
+
model.remove_weight_norm()
|
| 118 |
+
self.net = model.eval().to(device)
|
| 119 |
+
for p in self.net.parameters():
|
| 120 |
+
p.requires_grad_(False)
|
| 121 |
+
self.hop_size = int(self.net.h.hop_size)
|
| 122 |
+
self.sample_rate = int(self.net.h.sampling_rate)
|
| 123 |
+
|
| 124 |
+
@torch.inference_mode()
|
| 125 |
+
def decode_raw_mel(self, phys_mel: torch.Tensor, lengths: torch.Tensor | None = None) -> torch.Tensor:
|
| 126 |
+
"""Synthesize 24 kHz waveform ``[B, T*hop]`` from physical log-mel ``[B, T, 100]``."""
|
| 127 |
+
mel_bct = phys_mel.float().transpose(1, 2).contiguous()
|
| 128 |
+
wav = self.net(mel_bct).squeeze(1)
|
| 129 |
+
if lengths is not None:
|
| 130 |
+
total = phys_mel.shape[1] * self.hop_size
|
| 131 |
+
if wav.shape[1] > total:
|
| 132 |
+
wav = wav[:, :total]
|
| 133 |
+
sample_mask = (torch.arange(wav.shape[1], device=wav.device)[None] < (lengths.to(wav.device)[:, None] * self.hop_size)).float()
|
| 134 |
+
wav = wav * sample_mask
|
| 135 |
+
return wav
|
code/src/lua_nova_v1/models/cfm.py
ADDED
|
@@ -0,0 +1,900 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LuaNovaCFM: PT-BR phonetic front end, ProsodyFlow, and OT-CFM Slaney-100 mel decoder."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
|
| 10 |
+
from ..config import CFMConfig, Config
|
| 11 |
+
from ..text.phonemizer import PHONE_IDS, PUNCTUATION, SYMBOL_TO_ID, VOICELESS, VOWELS
|
| 12 |
+
from .frontend import (
|
| 13 |
+
Predictor,
|
| 14 |
+
Stack,
|
| 15 |
+
UtteranceTooLong,
|
| 16 |
+
VocosHead,
|
| 17 |
+
length_mask,
|
| 18 |
+
rotary_table,
|
| 19 |
+
rotate,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
_SP_ID = SYMBOL_TO_ID["<sp>"]
|
| 23 |
+
_COMMA_ID = SYMBOL_TO_ID[","]
|
| 24 |
+
_PERIOD_ID = SYMBOL_TO_ID["."]
|
| 25 |
+
_QUESTION_ID = SYMBOL_TO_ID["?"]
|
| 26 |
+
_EXCLAM_ID = SYMBOL_TO_ID["!"]
|
| 27 |
+
_SEMICOLON_ID = SYMBOL_TO_ID[";"]
|
| 28 |
+
_COLON_ID = SYMBOL_TO_ID[":"]
|
| 29 |
+
_DASH_ID = SYMBOL_TO_ID["—"]
|
| 30 |
+
_ELLIPSIS_ID = SYMBOL_TO_ID["…"]
|
| 31 |
+
_CLAUSE_PUNCT_IDS = tuple(SYMBOL_TO_ID[p] for p in (",", ";", ":", "—", "…", ".", "?", "!"))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class MelStatsHead(nn.Module):
|
| 35 |
+
"""Lightweight mel normalization statistics container for external vocoders such as BigVGAN."""
|
| 36 |
+
|
| 37 |
+
def __init__(self, c: Config) -> None:
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.config = c
|
| 40 |
+
self.vocos = None
|
| 41 |
+
self.frozen = True
|
| 42 |
+
self.register_buffer("mel_mean", torch.zeros(c.vocos_n_mels, dtype=torch.float32))
|
| 43 |
+
self.register_buffer("mel_scale", torch.ones(c.vocos_n_mels, dtype=torch.float32))
|
| 44 |
+
|
| 45 |
+
def freeze_vocoder(self, frozen: bool = True) -> None:
|
| 46 |
+
self.frozen = frozen
|
| 47 |
+
|
| 48 |
+
def set_mel_stats(self, mean, scale) -> None:
|
| 49 |
+
mean_t = torch.as_tensor(mean, dtype=torch.float32, device=self.mel_mean.device)
|
| 50 |
+
scale_t = torch.as_tensor(scale, dtype=torch.float32, device=self.mel_scale.device).clamp_min(1e-6)
|
| 51 |
+
if mean_t.shape != (self.config.vocos_n_mels,) or scale_t.shape != (self.config.vocos_n_mels,):
|
| 52 |
+
raise ValueError("vocoder mel stats shape mismatch")
|
| 53 |
+
self.mel_mean.copy_(mean_t)
|
| 54 |
+
self.mel_scale.copy_(scale_t)
|
| 55 |
+
|
| 56 |
+
def decode_mel(self, mel_norm: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
|
| 57 |
+
raise RuntimeError("External BigVGAN vocoder wrapper is required to decode waveforms in BigVGAN mel space")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def make_prosody_noise_kernel(length: int = 25, sigma_wide: float = 5.0, sigma_narrow: float = 1.5) -> torch.Tensor:
|
| 61 |
+
"""Kernel 1D multiescala normalizado para variancia unitaria do ruido prosodico [2, 1, K]."""
|
| 62 |
+
half = length // 2
|
| 63 |
+
idx = torch.arange(length, dtype=torch.float32) - float(half)
|
| 64 |
+
g_wide = torch.exp(-0.5 * (idx / sigma_wide) ** 2)
|
| 65 |
+
g_wide = g_wide / g_wide.sum()
|
| 66 |
+
g_narrow = torch.exp(-0.5 * (idx / sigma_narrow) ** 2)
|
| 67 |
+
g_narrow = g_narrow / g_narrow.sum()
|
| 68 |
+
w = 0.65 * g_wide + 0.35 * g_narrow
|
| 69 |
+
w = w / torch.sqrt((w ** 2).sum()).clamp_min(1e-8)
|
| 70 |
+
return w[None, None, :].expand(2, 1, length).contiguous()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def smooth_prosody_noise(eps: torch.Tensor, frame_mask: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
|
| 74 |
+
"""Convolucao multiescala ONNX-safe em ruido gaussiano [B, T, 2] para eliminar micro-jitter de F0."""
|
| 75 |
+
pad = kernel.shape[-1] // 2
|
| 76 |
+
sm = F.conv1d(eps.float().transpose(1, 2), kernel.to(eps.device, dtype=torch.float32), padding=pad, groups=2)
|
| 77 |
+
return sm.transpose(1, 2) * frame_mask[..., None].float()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def linguistic_context_features(
|
| 81 |
+
tokens: torch.Tensor,
|
| 82 |
+
stress: torch.Tensor,
|
| 83 |
+
token_mask: torch.Tensor,
|
| 84 |
+
phone_tokens: torch.Tensor,
|
| 85 |
+
vowel_tokens: torch.Tensor,
|
| 86 |
+
voiceless_tokens: torch.Tensor,
|
| 87 |
+
clause_punct_tokens: torch.Tensor,
|
| 88 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 89 |
+
"""Extrai 26 canais de contexto palavra/tonica/clausula/frase + matriz same_word (100% ONNX opset 17)."""
|
| 90 |
+
mask_f = token_mask.float()
|
| 91 |
+
is_phone = (phone_tokens[tokens] & token_mask).float()
|
| 92 |
+
is_vowel = (vowel_tokens[tokens] & token_mask).float()
|
| 93 |
+
is_voiceless = (voiceless_tokens[tokens] & token_mask).float()
|
| 94 |
+
is_voiced_cons = is_phone * (1.0 - is_vowel) * (1.0 - is_voiceless)
|
| 95 |
+
is_sp = ((tokens == _SP_ID) & token_mask).float()
|
| 96 |
+
is_cb = (clause_punct_tokens[tokens] & token_mask).float()
|
| 97 |
+
|
| 98 |
+
l_dim = tokens.shape[1]
|
| 99 |
+
idx_f = torch.arange(l_dim, device=tokens.device, dtype=torch.float32)[None, :]
|
| 100 |
+
tri_le = (idx_f[:, :, None] >= idx_f[:, None, :]).float()
|
| 101 |
+
|
| 102 |
+
# 1..6: Utterance-level structure and punctuation indicators
|
| 103 |
+
utt_len = mask_f.sum(dim=1, keepdim=True).clamp_min(1.0)
|
| 104 |
+
utt_pos = ((idx_f + 0.5) / utt_len) * mask_f
|
| 105 |
+
utt_rem = ((utt_len - 1.0 - idx_f).clamp_min(0.0) / utt_len) * mask_f
|
| 106 |
+
utt_log_len = (torch.log1p(utt_len) / 6.0) * mask_f
|
| 107 |
+
utt_has_q = ((tokens == _QUESTION_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f
|
| 108 |
+
utt_has_ex = ((tokens == _EXCLAM_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f
|
| 109 |
+
utt_has_comma = ((tokens == _COMMA_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f
|
| 110 |
+
|
| 111 |
+
# 7..13: Word-level & lexical stress geometry
|
| 112 |
+
is_delim = (1.0 - is_phone) * mask_f
|
| 113 |
+
word_id = is_delim.long().cumsum(dim=1)
|
| 114 |
+
same_word = (word_id[:, :, None] == word_id[:, None, :]).float() * (is_phone[:, :, None] * is_phone[:, None, :])
|
| 115 |
+
word_phones = same_word.sum(dim=-1)
|
| 116 |
+
word_log_phones = (torch.log1p(word_phones) / 4.0) * is_phone
|
| 117 |
+
word_vowels = (same_word * is_vowel[:, None, :]).sum(dim=-1)
|
| 118 |
+
word_log_vowels = (torch.log1p(word_vowels) / 3.0) * is_phone
|
| 119 |
+
is_prim_stress = ((stress == 1) & token_mask).float() * is_phone
|
| 120 |
+
stress_weights = same_word * is_prim_stress[:, None, :]
|
| 121 |
+
stress_sum = stress_weights.sum(dim=-1)
|
| 122 |
+
word_has_stress = stress_sum.clamp(0.0, 1.0) * is_phone
|
| 123 |
+
pos_in_word = (((same_word * tri_le).sum(dim=-1) - 0.5).clamp_min(0.0) / word_phones.clamp_min(1.0)) * is_phone
|
| 124 |
+
stress_idx = (stress_weights * idx_f[None, ...]).sum(dim=-1) / stress_sum.clamp_min(1.0)
|
| 125 |
+
dist_to_stress = ((idx_f - stress_idx) / 6.0).clamp(-2.0, 2.0) * word_has_stress
|
| 126 |
+
|
| 127 |
+
prev_phone = torch.cat((torch.zeros_like(is_phone[:, :1]), is_phone[:, :-1]), dim=1)
|
| 128 |
+
word_start = is_phone * (1.0 - prev_phone)
|
| 129 |
+
total_words = word_start.sum(dim=1, keepdim=True).clamp_min(1.0)
|
| 130 |
+
cum_words = word_start.cumsum(dim=1)
|
| 131 |
+
word_pos_utt = ((cum_words - 0.5).clamp_min(0.0) / total_words) * is_phone
|
| 132 |
+
log_total_words = (torch.log1p(total_words) / 4.0) * mask_f
|
| 133 |
+
|
| 134 |
+
# 14..21: Clause-level structure (segmented at , ; : — … . ? !)
|
| 135 |
+
cb_prev = torch.cat((torch.zeros_like(is_cb[:, :1]), is_cb[:, :-1]), dim=1)
|
| 136 |
+
clause_id = cb_prev.long().cumsum(dim=1)
|
| 137 |
+
same_clause = (clause_id[:, :, None] == clause_id[:, None, :]).float() * (mask_f[:, :, None] * mask_f[:, None, :])
|
| 138 |
+
clause_len = same_clause.sum(dim=-1).clamp_min(1.0)
|
| 139 |
+
clause_log_len = (torch.log1p(clause_len) / 5.0) * mask_f
|
| 140 |
+
pos_in_clause_raw = (same_clause * tri_le).sum(dim=-1)
|
| 141 |
+
pos_in_clause = ((pos_in_clause_raw - 0.5).clamp_min(0.0) / clause_len) * mask_f
|
| 142 |
+
clause_rem = ((clause_len - pos_in_clause_raw).clamp_min(0.0) / clause_len) * mask_f
|
| 143 |
+
|
| 144 |
+
q_tok = ((tokens == _QUESTION_ID) & token_mask).float()
|
| 145 |
+
ex_tok = ((tokens == _EXCLAM_ID) & token_mask).float()
|
| 146 |
+
comma_tok = ((tokens == _COMMA_ID) & token_mask).float()
|
| 147 |
+
period_tok = ((tokens == _PERIOD_ID) & token_mask).float()
|
| 148 |
+
other_cb_tok = (
|
| 149 |
+
((tokens == _SEMICOLON_ID) | (tokens == _COLON_ID) | (tokens == _DASH_ID) | (tokens == _ELLIPSIS_ID))
|
| 150 |
+
& token_mask
|
| 151 |
+
).float()
|
| 152 |
+
clause_ends_q = (same_clause * q_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
|
| 153 |
+
clause_ends_ex = (same_clause * ex_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
|
| 154 |
+
clause_ends_comma = (same_clause * comma_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
|
| 155 |
+
clause_ends_period = (same_clause * period_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
|
| 156 |
+
clause_ends_other = (same_clause * other_cb_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
|
| 157 |
+
|
| 158 |
+
ling_feats = torch.stack(
|
| 159 |
+
(
|
| 160 |
+
utt_pos, utt_rem, utt_log_len, utt_has_q, utt_has_ex, utt_has_comma,
|
| 161 |
+
word_log_phones, word_log_vowels, word_has_stress, pos_in_word, dist_to_stress, word_pos_utt, log_total_words,
|
| 162 |
+
clause_log_len, pos_in_clause, clause_rem,
|
| 163 |
+
clause_ends_q, clause_ends_ex, clause_ends_comma, clause_ends_period, clause_ends_other,
|
| 164 |
+
is_vowel, is_voiced_cons, is_voiceless, is_sp, is_cb,
|
| 165 |
+
),
|
| 166 |
+
dim=-1,
|
| 167 |
+
) * mask_f[..., None]
|
| 168 |
+
clause_ctx_tok = torch.stack((pos_in_clause, clause_rem, clause_ends_q, clause_ends_comma), dim=-1) * mask_f[..., None]
|
| 169 |
+
return ling_feats, same_word, clause_ctx_tok
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def energy_noise_gate(
|
| 173 |
+
condition: torch.Tensor,
|
| 174 |
+
frame_mask: torch.Tensor,
|
| 175 |
+
center: float = -1.6,
|
| 176 |
+
slope: float = 2.5,
|
| 177 |
+
floor: float = 0.05,
|
| 178 |
+
) -> torch.Tensor:
|
| 179 |
+
"""Porta suave por energia e vozeamento para zerar ruido inicial em pausas (ONNX opset 17)."""
|
| 180 |
+
eng = condition[..., 2].float()
|
| 181 |
+
voiced = condition[..., 1].float()
|
| 182 |
+
g = torch.sigmoid(slope * (eng - center))
|
| 183 |
+
g = torch.maximum(g, 0.85 * voiced)
|
| 184 |
+
g = floor + (1.0 - floor) * g
|
| 185 |
+
return g[..., None] * frame_mask[..., None].float()
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def smooth_f0_channel(condition: torch.Tensor, prob: float) -> torch.Tensor:
|
| 189 |
+
"""Aplica filtro caixa 3-frames no canal F0 em uma fracao ``prob`` do batch."""
|
| 190 |
+
if prob <= 0.0 or condition.shape[1] < 2:
|
| 191 |
+
return condition
|
| 192 |
+
mask = (torch.rand(condition.shape[0], device=condition.device) < prob)[:, None]
|
| 193 |
+
if not bool(mask.any()):
|
| 194 |
+
return condition
|
| 195 |
+
f0 = condition[..., 0].float()
|
| 196 |
+
sm = F.avg_pool1d(F.pad(f0.unsqueeze(1), (1, 1), mode="replicate"), 3, stride=1).squeeze(1)
|
| 197 |
+
f0_out = torch.where(mask, sm.to(condition.dtype), condition[..., 0])
|
| 198 |
+
return torch.cat((f0_out[..., None], condition[..., 1:]), dim=-1)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def f0_features(condition: torch.Tensor, frame_mask: torch.Tensor) -> torch.Tensor:
|
| 202 |
+
"""Extrai 12 canais prosodicos/harmonicos explicitos de ``condition`` [B, T, 3] (100% ONNX opset 17)."""
|
| 203 |
+
c = condition.float()
|
| 204 |
+
log_f0 = c[..., 0]
|
| 205 |
+
voiced = c[..., 1]
|
| 206 |
+
energy = c[..., 2]
|
| 207 |
+
delta_f0 = F.pad(log_f0[:, 1:] - log_f0[:, :-1], (1, 0))
|
| 208 |
+
f0_norm = torch.exp(log_f0.clamp(-2.0, 1.5))
|
| 209 |
+
feats = [log_f0, delta_f0, voiced, energy]
|
| 210 |
+
for k in (1.0, 2.0, 3.0, 4.0):
|
| 211 |
+
ang = (2.0 * math.pi * k) * f0_norm
|
| 212 |
+
feats.append(voiced * torch.sin(ang))
|
| 213 |
+
feats.append(voiced * torch.cos(ang))
|
| 214 |
+
return torch.stack(feats, dim=-1) * frame_mask[..., None].float()
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 218 |
+
def __init__(self, dim: int):
|
| 219 |
+
super().__init__()
|
| 220 |
+
self.dim = dim
|
| 221 |
+
self.mlp = nn.Sequential(
|
| 222 |
+
nn.Linear(dim, dim * 2),
|
| 223 |
+
nn.SiLU(),
|
| 224 |
+
nn.Linear(dim * 2, dim),
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
def forward(self, t: torch.Tensor) -> torch.Tensor:
|
| 228 |
+
half = self.dim // 2
|
| 229 |
+
freqs = torch.exp(
|
| 230 |
+
-math.log(10000.0) * torch.arange(half, device=t.device, dtype=torch.float32) / max(half - 1, 1)
|
| 231 |
+
)
|
| 232 |
+
args = t.float()[:, None] * freqs[None, :] * 1000.0
|
| 233 |
+
emb = torch.cat((args.sin(), args.cos()), dim=-1)
|
| 234 |
+
return self.mlp(emb)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class FlowAttention(nn.Module):
|
| 238 |
+
def __init__(self, channels: int, heads: int, dropout: float):
|
| 239 |
+
super().__init__()
|
| 240 |
+
self.heads = heads
|
| 241 |
+
self.dropout = dropout
|
| 242 |
+
self.qkv = nn.Linear(channels, 3 * channels)
|
| 243 |
+
self.out = nn.Linear(channels, channels)
|
| 244 |
+
|
| 245 |
+
def forward(self, x: torch.Tensor, mask: torch.Tensor, table: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
|
| 246 |
+
b, t, c = x.shape
|
| 247 |
+
q, k, v = self.qkv(x).view(b, t, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4)
|
| 248 |
+
y = F.scaled_dot_product_attention(
|
| 249 |
+
rotate(q, table),
|
| 250 |
+
rotate(k, table),
|
| 251 |
+
v,
|
| 252 |
+
attn_mask=mask[:, None, None, :],
|
| 253 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 254 |
+
)
|
| 255 |
+
return self.out(y.transpose(1, 2).reshape(b, t, c))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class FlowBlock(nn.Module):
|
| 259 |
+
"""Bloco Transformer RoPE + Conv depthwise com modulação AdaLN-Zero pelo tempo t."""
|
| 260 |
+
|
| 261 |
+
def __init__(self, channels: int, heads: int, feedforward: int, kernel: int, dropout: float):
|
| 262 |
+
super().__init__()
|
| 263 |
+
self.norm1 = nn.LayerNorm(channels, elementwise_affine=False)
|
| 264 |
+
self.attention = FlowAttention(channels, heads, dropout)
|
| 265 |
+
self.norm2 = nn.LayerNorm(channels, elementwise_affine=False)
|
| 266 |
+
self.depthwise = nn.Conv1d(channels, channels, kernel, padding=kernel // 2, groups=channels)
|
| 267 |
+
self.expand = nn.Linear(channels, feedforward)
|
| 268 |
+
self.project = nn.Linear(feedforward, channels)
|
| 269 |
+
self.dropout = nn.Dropout(dropout)
|
| 270 |
+
# 6 modulations: shift1, scale1, gate1, shift2, scale2, gate2
|
| 271 |
+
self.ada = nn.Sequential(nn.SiLU(), nn.Linear(channels, 6 * channels))
|
| 272 |
+
nn.init.zeros_(self.ada[1].weight)
|
| 273 |
+
nn.init.zeros_(self.ada[1].bias)
|
| 274 |
+
|
| 275 |
+
def forward(self, x: torch.Tensor, t_emb: torch.Tensor, mask: torch.Tensor, table) -> torch.Tensor:
|
| 276 |
+
keep = mask[..., None]
|
| 277 |
+
s1, sc1, g1, s2, sc2, g2 = self.ada(t_emb)[:, None, :].chunk(6, dim=-1)
|
| 278 |
+
h = self.norm1(x) * (1.0 + sc1) + s1
|
| 279 |
+
x = (x + g1 * self.dropout(self.attention(h, mask, table))) * keep
|
| 280 |
+
h2 = (self.norm2(x) * (1.0 + sc2) + s2) * keep
|
| 281 |
+
y = self.depthwise(h2.transpose(1, 2)).transpose(1, 2)
|
| 282 |
+
y = self.project(self.dropout(F.gelu(self.expand(y))))
|
| 283 |
+
return (x + g2 * self.dropout(y)) * keep
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class FlowDecoder(nn.Module):
|
| 287 |
+
"""Preditor de velocidade v_theta(x_t, t | cond, prior_mel, f0_feats) no espaço mel-100 do Vocos."""
|
| 288 |
+
|
| 289 |
+
def __init__(self, cfg: CFMConfig):
|
| 290 |
+
super().__init__()
|
| 291 |
+
c = cfg.base
|
| 292 |
+
d = cfg.flow_channels
|
| 293 |
+
self.n_mels = c.vocos_n_mels
|
| 294 |
+
self.use_f0_harmonics = bool(cfg.use_f0_harmonics)
|
| 295 |
+
in_dim = self.n_mels * 2 + c.channels + (12 if self.use_f0_harmonics else 0)
|
| 296 |
+
self.time_emb = SinusoidalTimeEmbedding(d)
|
| 297 |
+
self.in_proj = nn.Linear(in_dim, d)
|
| 298 |
+
self.blocks = nn.ModuleList(
|
| 299 |
+
FlowBlock(d, cfg.flow_heads, cfg.flow_feedforward, cfg.flow_kernel, cfg.flow_dropout)
|
| 300 |
+
for _ in range(cfg.flow_layers)
|
| 301 |
+
)
|
| 302 |
+
self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
|
| 303 |
+
self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
|
| 304 |
+
self.out_proj = nn.Linear(d, self.n_mels)
|
| 305 |
+
nn.init.zeros_(self.final_ada[1].weight)
|
| 306 |
+
nn.init.zeros_(self.final_ada[1].bias)
|
| 307 |
+
nn.init.zeros_(self.out_proj.weight)
|
| 308 |
+
nn.init.zeros_(self.out_proj.bias)
|
| 309 |
+
self.head_width = d // cfg.flow_heads
|
| 310 |
+
|
| 311 |
+
def forward(
|
| 312 |
+
self,
|
| 313 |
+
x_t: torch.Tensor,
|
| 314 |
+
t: torch.Tensor,
|
| 315 |
+
cond: torch.Tensor,
|
| 316 |
+
prior_mel: torch.Tensor,
|
| 317 |
+
frame_mask: torch.Tensor,
|
| 318 |
+
f0_feats: torch.Tensor | None = None,
|
| 319 |
+
) -> torch.Tensor:
|
| 320 |
+
keep = frame_mask[..., None]
|
| 321 |
+
t_emb = self.time_emb(t)
|
| 322 |
+
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)
|
| 323 |
+
h = self.in_proj(torch.cat(parts, dim=-1)) * keep
|
| 324 |
+
table = rotary_table(x_t.shape[1], self.head_width, x_t.device)
|
| 325 |
+
for block in self.blocks:
|
| 326 |
+
h = block(h, t_emb, frame_mask, table)
|
| 327 |
+
shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
|
| 328 |
+
h = self.final_norm(h) * (1.0 + scale) + shift
|
| 329 |
+
return self.out_proj(h) * keep
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class LinguisticContextAdapter(nn.Module):
|
| 333 |
+
"""Adaptador residual zero-inicializado para contexto de palavra, tonica e clausula."""
|
| 334 |
+
|
| 335 |
+
def __init__(self, c: Config, layers: int = 2, ling_dim: int = 26):
|
| 336 |
+
super().__init__()
|
| 337 |
+
self.ling_proj = nn.Linear(ling_dim, c.channels)
|
| 338 |
+
self.word_proj = nn.Linear(c.channels, c.channels)
|
| 339 |
+
self.stack = Stack(c, layers)
|
| 340 |
+
self.out_proj = nn.Linear(c.channels, c.channels)
|
| 341 |
+
nn.init.zeros_(self.out_proj.weight)
|
| 342 |
+
nn.init.zeros_(self.out_proj.bias)
|
| 343 |
+
|
| 344 |
+
def forward(
|
| 345 |
+
self,
|
| 346 |
+
hidden: torch.Tensor,
|
| 347 |
+
ling_feats: torch.Tensor,
|
| 348 |
+
same_word: torch.Tensor,
|
| 349 |
+
token_mask: torch.Tensor,
|
| 350 |
+
) -> torch.Tensor:
|
| 351 |
+
w = same_word.to(hidden.dtype)
|
| 352 |
+
w = w / w.sum(dim=-1, keepdim=True).clamp_min(1.0)
|
| 353 |
+
word_mean = torch.bmm(w, hidden)
|
| 354 |
+
x = (hidden + self.ling_proj(ling_feats.to(hidden.dtype)) + self.word_proj(word_mean)) * token_mask[..., None]
|
| 355 |
+
return (hidden + self.out_proj(self.stack(x, token_mask))) * token_mask[..., None]
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class DurationFlow(nn.Module):
|
| 359 |
+
"""Preditor generativo OT-CFM para log1p(duracao) de fonemas e pausas."""
|
| 360 |
+
|
| 361 |
+
def __init__(self, cfg: CFMConfig):
|
| 362 |
+
super().__init__()
|
| 363 |
+
d = cfg.dur_flow_channels
|
| 364 |
+
in_dim = 2 + cfg.base.channels
|
| 365 |
+
self.time_emb = SinusoidalTimeEmbedding(d)
|
| 366 |
+
self.in_proj = nn.Linear(in_dim, d)
|
| 367 |
+
self.blocks = nn.ModuleList(
|
| 368 |
+
FlowBlock(d, cfg.dur_flow_heads, cfg.dur_flow_feedforward, cfg.dur_flow_kernel, 0.05)
|
| 369 |
+
for _ in range(cfg.dur_flow_layers)
|
| 370 |
+
)
|
| 371 |
+
self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
|
| 372 |
+
self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
|
| 373 |
+
self.out_proj = nn.Linear(d, 1)
|
| 374 |
+
nn.init.zeros_(self.final_ada[1].weight)
|
| 375 |
+
nn.init.zeros_(self.final_ada[1].bias)
|
| 376 |
+
nn.init.zeros_(self.out_proj.weight)
|
| 377 |
+
nn.init.zeros_(self.out_proj.bias)
|
| 378 |
+
self.head_width = d // cfg.dur_flow_heads
|
| 379 |
+
|
| 380 |
+
def forward(
|
| 381 |
+
self,
|
| 382 |
+
z_t: torch.Tensor,
|
| 383 |
+
t: torch.Tensor,
|
| 384 |
+
prior_log_dur: torch.Tensor,
|
| 385 |
+
token_ctx: torch.Tensor,
|
| 386 |
+
token_mask: torch.Tensor,
|
| 387 |
+
) -> torch.Tensor:
|
| 388 |
+
keep = token_mask[..., None]
|
| 389 |
+
t_emb = self.time_emb(t)
|
| 390 |
+
h = self.in_proj(torch.cat((z_t.float(), prior_log_dur.float(), token_ctx.float()), dim=-1)) * keep
|
| 391 |
+
table = rotary_table(z_t.shape[1], self.head_width, z_t.device)
|
| 392 |
+
for block in self.blocks:
|
| 393 |
+
h = block(h, t_emb, token_mask, table)
|
| 394 |
+
shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
|
| 395 |
+
h = self.final_norm(h) * (1.0 + scale) + shift
|
| 396 |
+
return self.out_proj(h) * keep
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class ProsodyFlow(nn.Module):
|
| 400 |
+
"""Preditor generativo OT-CFM para contorno [log_F0, energia] em nivel de frame."""
|
| 401 |
+
|
| 402 |
+
def __init__(self, cfg: CFMConfig):
|
| 403 |
+
super().__init__()
|
| 404 |
+
d = cfg.prosody_flow_channels
|
| 405 |
+
in_dim = 5 + cfg.base.channels
|
| 406 |
+
self.time_emb = SinusoidalTimeEmbedding(d)
|
| 407 |
+
self.in_proj = nn.Linear(in_dim, d)
|
| 408 |
+
self.blocks = nn.ModuleList(
|
| 409 |
+
FlowBlock(d, cfg.prosody_flow_heads, cfg.prosody_flow_feedforward, cfg.prosody_flow_kernel, 0.05)
|
| 410 |
+
for _ in range(cfg.prosody_flow_layers)
|
| 411 |
+
)
|
| 412 |
+
self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
|
| 413 |
+
self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
|
| 414 |
+
self.out_proj = nn.Linear(d, 2)
|
| 415 |
+
nn.init.zeros_(self.final_ada[1].weight)
|
| 416 |
+
nn.init.zeros_(self.final_ada[1].bias)
|
| 417 |
+
nn.init.zeros_(self.out_proj.weight)
|
| 418 |
+
nn.init.zeros_(self.out_proj.bias)
|
| 419 |
+
self.head_width = d // cfg.prosody_flow_heads
|
| 420 |
+
|
| 421 |
+
def forward(
|
| 422 |
+
self,
|
| 423 |
+
y_t: torch.Tensor,
|
| 424 |
+
t: torch.Tensor,
|
| 425 |
+
prior_fe: torch.Tensor,
|
| 426 |
+
voicing_prob: torch.Tensor,
|
| 427 |
+
prosody_hidden: torch.Tensor,
|
| 428 |
+
frame_mask: torch.Tensor,
|
| 429 |
+
) -> torch.Tensor:
|
| 430 |
+
keep = frame_mask[..., None]
|
| 431 |
+
t_emb = self.time_emb(t)
|
| 432 |
+
h = self.in_proj(
|
| 433 |
+
torch.cat((y_t.float(), prior_fe.float(), voicing_prob.float(), prosody_hidden.float()), dim=-1)
|
| 434 |
+
) * keep
|
| 435 |
+
table = rotary_table(y_t.shape[1], self.head_width, y_t.device)
|
| 436 |
+
for block in self.blocks:
|
| 437 |
+
h = block(h, t_emb, frame_mask, table)
|
| 438 |
+
shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
|
| 439 |
+
h = self.final_norm(h) * (1.0 + scale) + shift
|
| 440 |
+
return self.out_proj(h) * keep
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
class LuaNovaCFM(nn.Module):
|
| 444 |
+
"""Front-end fonético CTC do LuaNovaBase + Prior Mel + FlowDecoder OT-CFM + Vocos 24 kHz."""
|
| 445 |
+
|
| 446 |
+
FRONTEND_MODULES = (
|
| 447 |
+
"tokens", "stress", "voices", "encoder", "duration",
|
| 448 |
+
"frame_voices", "frame_position", "prosody_stack", "prosody_head",
|
| 449 |
+
)
|
| 450 |
+
ITEM3_MODULES = ("context_adapter", "frame_ctx_proj", "dur_flow", "prosody_flow")
|
| 451 |
+
|
| 452 |
+
def __init__(self, cfg: CFMConfig, vocos_model=None, load_vocos: bool | None = None):
|
| 453 |
+
super().__init__()
|
| 454 |
+
self.cfm_config = cfg
|
| 455 |
+
self.config = c = cfg.base
|
| 456 |
+
# Front-end idêntico ao LuaNovaBase (carrega pesos direto do checkpoint Stage 1!)
|
| 457 |
+
self.tokens = nn.Embedding(c.vocab_size, c.channels, padding_idx=0)
|
| 458 |
+
self.stress = nn.Embedding(3, c.channels)
|
| 459 |
+
self.voices = nn.Embedding(len(c.speakers), c.channels)
|
| 460 |
+
self.encoder = Stack(c, c.encoder_layers)
|
| 461 |
+
self.duration = Predictor(c, 2)
|
| 462 |
+
self.frame_voices = nn.Embedding(len(c.speakers), c.channels)
|
| 463 |
+
self.frame_position = nn.Linear(3, c.channels)
|
| 464 |
+
self.prosody_stack = Stack(c, c.prosody_layers)
|
| 465 |
+
self.prosody_head = nn.Linear(c.channels, 3)
|
| 466 |
+
self.prosody_projection = nn.Linear(3, c.channels)
|
| 467 |
+
# Item 3 (opcionais para manter retrocompatibilidade v1/v2/v3)
|
| 468 |
+
self.context_adapter = LinguisticContextAdapter(c, layers=cfg.prosody_context_layers) if cfg.use_ling_context else None
|
| 469 |
+
if cfg.use_ling_context:
|
| 470 |
+
self.frame_ctx_proj = nn.Linear(6, c.channels)
|
| 471 |
+
nn.init.zeros_(self.frame_ctx_proj.weight)
|
| 472 |
+
nn.init.zeros_(self.frame_ctx_proj.bias)
|
| 473 |
+
else:
|
| 474 |
+
self.frame_ctx_proj = None
|
| 475 |
+
self.dur_flow = DurationFlow(cfg) if cfg.use_duration_flow else None
|
| 476 |
+
self.prosody_flow = ProsodyFlow(cfg) if cfg.use_prosody_flow else None
|
| 477 |
+
# Prior mel determinístico (5 camadas RoPE quando use_acoustic_prior=True) + Flow Matching decoder
|
| 478 |
+
self.acoustic_stack = Stack(c, c.acoustic_layers) if cfg.use_acoustic_prior else None
|
| 479 |
+
self.prior_head = nn.Linear(c.channels, c.vocos_n_mels)
|
| 480 |
+
self.flow = FlowDecoder(cfg)
|
| 481 |
+
use_vocos = (cfg.mel_space == "vocos") if load_vocos is None else bool(load_vocos)
|
| 482 |
+
self.vocoder = VocosHead(c, vocos_model=vocos_model) if (use_vocos or vocos_model is not None) else MelStatsHead(c)
|
| 483 |
+
self.vocoder.freeze_vocoder(True)
|
| 484 |
+
|
| 485 |
+
phones = torch.zeros(c.vocab_size, dtype=torch.bool)
|
| 486 |
+
phones[sorted(PHONE_IDS)] = True
|
| 487 |
+
self.register_buffer("phone_tokens", phones, persistent=False)
|
| 488 |
+
vowels = torch.zeros(c.vocab_size, dtype=torch.bool)
|
| 489 |
+
vowels[[SYMBOL_TO_ID[v] for v in VOWELS]] = True
|
| 490 |
+
self.register_buffer("vowel_tokens", vowels, persistent=False)
|
| 491 |
+
voiceless = torch.zeros(c.vocab_size, dtype=torch.bool)
|
| 492 |
+
voiceless[[SYMBOL_TO_ID[v] for v in VOICELESS]] = True
|
| 493 |
+
self.register_buffer("voiceless_tokens", voiceless, persistent=False)
|
| 494 |
+
puncts = torch.zeros(c.vocab_size, dtype=torch.bool)
|
| 495 |
+
puncts[[SYMBOL_TO_ID[p] for p in PUNCTUATION]] = True
|
| 496 |
+
self.register_buffer("punct_tokens", puncts, persistent=False)
|
| 497 |
+
clause_puncts = torch.zeros(c.vocab_size, dtype=torch.bool)
|
| 498 |
+
clause_puncts[list(_CLAUSE_PUNCT_IDS)] = True
|
| 499 |
+
self.register_buffer("clause_punct_tokens", clause_puncts, persistent=False)
|
| 500 |
+
self.register_buffer("prosody_noise_kernel", make_prosody_noise_kernel(), persistent=False)
|
| 501 |
+
self._frontend_frozen = False
|
| 502 |
+
|
| 503 |
+
def freeze_frontend(self, frozen: bool = True) -> None:
|
| 504 |
+
self._frontend_frozen = frozen
|
| 505 |
+
for name in self.FRONTEND_MODULES + self.ITEM3_MODULES:
|
| 506 |
+
mod = getattr(self, name)
|
| 507 |
+
if mod is None:
|
| 508 |
+
continue
|
| 509 |
+
for p in mod.parameters():
|
| 510 |
+
p.requires_grad_(not frozen)
|
| 511 |
+
if frozen:
|
| 512 |
+
mod.eval()
|
| 513 |
+
|
| 514 |
+
def train(self, mode: bool = True):
|
| 515 |
+
super().train(mode)
|
| 516 |
+
if self.vocoder.frozen and getattr(self.vocoder, "vocos", None) is not None:
|
| 517 |
+
self.vocoder.vocos.eval()
|
| 518 |
+
if self._frontend_frozen:
|
| 519 |
+
for name in self.FRONTEND_MODULES + self.ITEM3_MODULES:
|
| 520 |
+
mod = getattr(self, name)
|
| 521 |
+
if mod is not None:
|
| 522 |
+
mod.eval()
|
| 523 |
+
return self
|
| 524 |
+
|
| 525 |
+
def load_frontend(
|
| 526 |
+
self, state_dict: dict, prosody_state_dict: dict | None = None
|
| 527 |
+
) -> list[str]:
|
| 528 |
+
"""Carrega pesos do front-end (+ acoustic_stack/prior_head/Vocos se use_acoustic_prior) e prosodia refinada."""
|
| 529 |
+
loaded = []
|
| 530 |
+
own = self.state_dict()
|
| 531 |
+
prefix = "model." if any(k.startswith("model.encoder.") for k in state_dict) else ""
|
| 532 |
+
keep_prefixes = tuple(f"{m}." for m in self.FRONTEND_MODULES) + (
|
| 533 |
+
"prosody_projection.",
|
| 534 |
+
"vocoder.mel_mean",
|
| 535 |
+
"vocoder.mel_scale",
|
| 536 |
+
)
|
| 537 |
+
if self.acoustic_stack is not None:
|
| 538 |
+
keep_prefixes = keep_prefixes + ("acoustic_stack.",)
|
| 539 |
+
for k, v in state_dict.items():
|
| 540 |
+
if prefix and not k.startswith(prefix):
|
| 541 |
+
continue
|
| 542 |
+
key = k[len(prefix):] if prefix else k
|
| 543 |
+
if self.acoustic_stack is not None and key == "vocoder.proj.weight" and "prior_head.weight" in own:
|
| 544 |
+
if own["prior_head.weight"].shape == v.shape:
|
| 545 |
+
own["prior_head.weight"] = v
|
| 546 |
+
loaded.append("prior_head.weight")
|
| 547 |
+
continue
|
| 548 |
+
if self.acoustic_stack is not None and key == "vocoder.proj.bias" and "prior_head.bias" in own:
|
| 549 |
+
if own["prior_head.bias"].shape == v.shape:
|
| 550 |
+
own["prior_head.bias"] = v
|
| 551 |
+
loaded.append("prior_head.bias")
|
| 552 |
+
continue
|
| 553 |
+
if any(key == p or key.startswith(p) for p in keep_prefixes) and key in own and own[key].shape == v.shape:
|
| 554 |
+
own[key] = v
|
| 555 |
+
loaded.append(key)
|
| 556 |
+
|
| 557 |
+
if prosody_state_dict is not None:
|
| 558 |
+
ppref = "model." if any(k.startswith("model.prosody_stack.") for k in prosody_state_dict) else ""
|
| 559 |
+
for k, v in prosody_state_dict.items():
|
| 560 |
+
if ppref and not k.startswith(ppref):
|
| 561 |
+
continue
|
| 562 |
+
key = k[len(ppref):] if ppref else k
|
| 563 |
+
if key.startswith(("prosody_stack.", "prosody_head.")) and key in own and own[key].shape == v.shape:
|
| 564 |
+
own[key] = v
|
| 565 |
+
if key not in loaded:
|
| 566 |
+
loaded.append(key)
|
| 567 |
+
|
| 568 |
+
self.load_state_dict(own, strict=True)
|
| 569 |
+
return loaded
|
| 570 |
+
|
| 571 |
+
def encode(self, tokens, stress, lengths, speakers):
|
| 572 |
+
mask = length_mask(lengths, tokens.shape[1])
|
| 573 |
+
x = (self.tokens(tokens) + self.stress(stress) + self.voices(speakers)[:, None]) * mask[..., None]
|
| 574 |
+
return self.encoder(x, mask), mask
|
| 575 |
+
|
| 576 |
+
def encode_prosody_context(
|
| 577 |
+
self,
|
| 578 |
+
hidden: torch.Tensor,
|
| 579 |
+
tokens: torch.Tensor,
|
| 580 |
+
stress: torch.Tensor,
|
| 581 |
+
token_mask: torch.Tensor,
|
| 582 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 583 |
+
if self.context_adapter is None:
|
| 584 |
+
return hidden, None
|
| 585 |
+
ling_feats, same_word, clause_ctx_tok = linguistic_context_features(
|
| 586 |
+
tokens,
|
| 587 |
+
stress,
|
| 588 |
+
token_mask,
|
| 589 |
+
self.phone_tokens,
|
| 590 |
+
self.vowel_tokens,
|
| 591 |
+
self.voiceless_tokens,
|
| 592 |
+
self.clause_punct_tokens,
|
| 593 |
+
)
|
| 594 |
+
prosody_token_ctx = self.context_adapter(hidden, ling_feats, same_word, token_mask)
|
| 595 |
+
return prosody_token_ctx, clause_ctx_tok
|
| 596 |
+
|
| 597 |
+
def _expand_indices(self, durations: torch.Tensor):
|
| 598 |
+
lengths = durations.sum(1)
|
| 599 |
+
if bool((lengths < 1).any()):
|
| 600 |
+
raise ValueError("utterance has no frames")
|
| 601 |
+
if bool((lengths > self.config.max_frames).any()):
|
| 602 |
+
raise UtteranceTooLong("utterance exceeds max_frames; split the input")
|
| 603 |
+
size = int(lengths.max())
|
| 604 |
+
ends = durations.cumsum(1)
|
| 605 |
+
frame = torch.arange(size, device=durations.device)[None].expand(durations.shape[0], size).contiguous()
|
| 606 |
+
index = torch.searchsorted(ends, frame, right=True).clamp(max=durations.shape[1] - 1)
|
| 607 |
+
owned = durations.gather(1, index).clamp_min(1)
|
| 608 |
+
offset = frame - (ends.gather(1, index) - durations.gather(1, index))
|
| 609 |
+
relative = (offset.float() + 0.5) / owned.float()
|
| 610 |
+
features = torch.stack((relative, 1.0 - relative, torch.log1p(owned.float()) / 4.0), dim=-1)
|
| 611 |
+
mask = frame < lengths[:, None]
|
| 612 |
+
return frame, index, features, mask, lengths
|
| 613 |
+
|
| 614 |
+
def expand(self, hidden, durations, token_mask, speakers):
|
| 615 |
+
_frame, index, features, mask, lengths = self._expand_indices(durations)
|
| 616 |
+
expanded = hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1]))
|
| 617 |
+
expanded = expanded + self.frame_position(features.to(hidden.dtype)) + self.frame_voices(speakers)[:, None]
|
| 618 |
+
return expanded * mask[..., None], mask, lengths
|
| 619 |
+
|
| 620 |
+
def expand_with_context(
|
| 621 |
+
self,
|
| 622 |
+
hidden: torch.Tensor,
|
| 623 |
+
prosody_token_ctx: torch.Tensor,
|
| 624 |
+
clause_ctx_tok: torch.Tensor | None,
|
| 625 |
+
durations: torch.Tensor,
|
| 626 |
+
token_mask: torch.Tensor,
|
| 627 |
+
speakers: torch.Tensor,
|
| 628 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 629 |
+
frame, index, features, mask, lengths = self._expand_indices(durations)
|
| 630 |
+
pos_voice = self.frame_position(features.to(hidden.dtype)) + self.frame_voices(speakers)[:, None]
|
| 631 |
+
acoustic_frames = (hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1])) + pos_voice) * mask[..., None]
|
| 632 |
+
if self.context_adapter is None and self.frame_ctx_proj is None:
|
| 633 |
+
return acoustic_frames, acoustic_frames, mask, lengths
|
| 634 |
+
prosody_frames = prosody_token_ctx.gather(1, index[..., None].expand(-1, -1, prosody_token_ctx.shape[-1])) + pos_voice
|
| 635 |
+
if self.frame_ctx_proj is not None:
|
| 636 |
+
if clause_ctx_tok is None:
|
| 637 |
+
raise ValueError("clause_ctx_tok required when frame_ctx_proj is enabled")
|
| 638 |
+
f_pos = (frame.float() + 0.5) / lengths.clamp_min(1).float()[:, None]
|
| 639 |
+
f_rem = 1.0 - f_pos
|
| 640 |
+
c_f = clause_ctx_tok.gather(1, index[..., None].expand(-1, -1, 4))
|
| 641 |
+
ctx_6 = torch.cat((f_pos[..., None], f_rem[..., None], c_f.float()), dim=-1) * mask[..., None].float()
|
| 642 |
+
prosody_frames = prosody_frames + self.frame_ctx_proj(ctx_6.to(prosody_frames.dtype))
|
| 643 |
+
return acoustic_frames, prosody_frames * mask[..., None], mask, lengths
|
| 644 |
+
|
| 645 |
+
def predict_prosody(self, frames, frame_mask):
|
| 646 |
+
hidden = self.prosody_stack(frames, frame_mask)
|
| 647 |
+
return hidden, self.prosody_head(hidden) * frame_mask[..., None]
|
| 648 |
+
|
| 649 |
+
@staticmethod
|
| 650 |
+
def hard_prosody(prediction):
|
| 651 |
+
return torch.stack(
|
| 652 |
+
(prediction[..., 0].clamp(-2.0, 1.5), (prediction[..., 1] > 0).to(prediction.dtype), prediction[..., 2].clamp(-4.5, 3.0)),
|
| 653 |
+
dim=-1,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
def predict_durations(self, hidden, mask, tokens, speed=1.0):
|
| 657 |
+
output = self.duration(hidden, mask).float()
|
| 658 |
+
frames = torch.round((torch.exp(output[..., 0].clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
|
| 659 |
+
present = self.phone_tokens[tokens] | (output[..., 1] > 0)
|
| 660 |
+
return torch.where(present, frames, torch.zeros_like(frames)) * mask
|
| 661 |
+
|
| 662 |
+
def sample_durations(
|
| 663 |
+
self,
|
| 664 |
+
prosody_token_ctx: torch.Tensor,
|
| 665 |
+
token_mask: torch.Tensor,
|
| 666 |
+
tokens: torch.Tensor,
|
| 667 |
+
speed: float = 1.0,
|
| 668 |
+
seed: int = 0,
|
| 669 |
+
temperature: float | None = None,
|
| 670 |
+
steps: int | None = None,
|
| 671 |
+
noise: torch.Tensor | None = None,
|
| 672 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 673 |
+
raw = self.duration(prosody_token_ctx, token_mask).float()
|
| 674 |
+
prior_z = raw[..., 0].clamp(0.0, math.log1p(400.0))
|
| 675 |
+
if self.dur_flow is not None:
|
| 676 |
+
n_steps = int(self.cfm_config.dur_flow_steps if steps is None else steps)
|
| 677 |
+
temp = float(self.cfm_config.dur_flow_temp if temperature is None else temperature)
|
| 678 |
+
b, l_len, _ = prosody_token_ctx.shape
|
| 679 |
+
if noise is None:
|
| 680 |
+
gen = torch.Generator(device=prosody_token_ctx.device).manual_seed(int(seed) + 101)
|
| 681 |
+
eps = torch.randn((b, l_len, 1), generator=gen, device=prosody_token_ctx.device, dtype=torch.float32)
|
| 682 |
+
else:
|
| 683 |
+
eps = noise.float()
|
| 684 |
+
sigma = self.cfm_config.dur_flow_sigma * temp
|
| 685 |
+
z = (prior_z[..., None] + sigma * eps) * token_mask[..., None].float()
|
| 686 |
+
dt = 1.0 / max(n_steps, 1)
|
| 687 |
+
for i in range(n_steps):
|
| 688 |
+
t_vec = torch.full((b,), i * dt, device=z.device, dtype=torch.float32)
|
| 689 |
+
v = self.dur_flow(z, t_vec, prior_z[..., None], prosody_token_ctx, token_mask)
|
| 690 |
+
z = (z + dt * v) * token_mask[..., None].float()
|
| 691 |
+
z1 = z.squeeze(-1)
|
| 692 |
+
else:
|
| 693 |
+
z1 = prior_z
|
| 694 |
+
frames = torch.round((torch.exp(z1.clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
|
| 695 |
+
present = self.phone_tokens[tokens] | (raw[..., 1] > 0)
|
| 696 |
+
durations = torch.where(present, frames, torch.zeros_like(frames)) * token_mask
|
| 697 |
+
return durations, raw
|
| 698 |
+
|
| 699 |
+
def sample_prosody(
|
| 700 |
+
self,
|
| 701 |
+
prosody_frames: torch.Tensor,
|
| 702 |
+
frame_mask: torch.Tensor,
|
| 703 |
+
seed: int = 0,
|
| 704 |
+
temperature: float | None = None,
|
| 705 |
+
steps: int | None = None,
|
| 706 |
+
noise: torch.Tensor | None = None,
|
| 707 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 708 |
+
prosody_hidden, prior_raw = self.predict_prosody(prosody_frames, frame_mask)
|
| 709 |
+
if self.prosody_flow is None:
|
| 710 |
+
return prosody_hidden, prior_raw, prior_raw
|
| 711 |
+
n_steps = int(self.cfm_config.prosody_flow_steps if steps is None else steps)
|
| 712 |
+
temp = float(self.cfm_config.prosody_flow_temp if temperature is None else temperature)
|
| 713 |
+
b, t_len, _ = prosody_frames.shape
|
| 714 |
+
if noise is None:
|
| 715 |
+
gen = torch.Generator(device=prosody_frames.device).manual_seed(int(seed) + 202)
|
| 716 |
+
eps = torch.randn((b, t_len, 2), generator=gen, device=prosody_frames.device, dtype=torch.float32)
|
| 717 |
+
else:
|
| 718 |
+
eps = noise.float()
|
| 719 |
+
eps_sm = smooth_prosody_noise(eps, frame_mask, self.prosody_noise_kernel)
|
| 720 |
+
prior_fe = torch.stack((prior_raw[..., 0].float(), prior_raw[..., 2].float()), dim=-1)
|
| 721 |
+
voicing_prob = torch.sigmoid(prior_raw[..., 1:2].float())
|
| 722 |
+
sigma = self.cfm_config.prosody_flow_sigma * temp
|
| 723 |
+
y = (prior_fe + sigma * eps_sm) * frame_mask[..., None].float()
|
| 724 |
+
dt = 1.0 / max(n_steps, 1)
|
| 725 |
+
for i in range(n_steps):
|
| 726 |
+
t_vec = torch.full((b,), i * dt, device=y.device, dtype=torch.float32)
|
| 727 |
+
v = self.prosody_flow(y, t_vec, prior_fe, voicing_prob, prosody_hidden, frame_mask)
|
| 728 |
+
y = (y + dt * v) * frame_mask[..., None].float()
|
| 729 |
+
prosody = torch.cat((y[..., :1], prior_raw[..., 1:2].float(), y[..., 1:2]), dim=-1) * frame_mask[..., None].float()
|
| 730 |
+
return prosody_hidden, prosody, prior_raw
|
| 731 |
+
|
| 732 |
+
def condition_and_prior(self, prosody_hidden, condition, frame_mask):
|
| 733 |
+
ph = prosody_hidden
|
| 734 |
+
if (
|
| 735 |
+
not self.cfm_config.acoustic_from_frames
|
| 736 |
+
and self.acoustic_stack is not None
|
| 737 |
+
and self.training
|
| 738 |
+
and self.cfm_config.prosody_hidden_dropout > 0
|
| 739 |
+
):
|
| 740 |
+
ph = F.dropout1d(ph.transpose(1, 2), p=self.cfm_config.prosody_hidden_dropout, training=True).transpose(1, 2)
|
| 741 |
+
proj = (ph + self.prosody_projection(condition.to(ph.dtype))) * frame_mask[..., None]
|
| 742 |
+
cond = self.acoustic_stack(proj, frame_mask) if self.acoustic_stack is not None else proj
|
| 743 |
+
prior_mel = self.prior_head(cond.float()) * frame_mask[..., None]
|
| 744 |
+
return cond, prior_mel
|
| 745 |
+
|
| 746 |
+
@staticmethod
|
| 747 |
+
def widen_pitch(prosody, frame_mask, pitch_range):
|
| 748 |
+
if pitch_range == 1.0:
|
| 749 |
+
return prosody
|
| 750 |
+
voiced = ((prosody[..., 1] > 0) & frame_mask).to(prosody.dtype)
|
| 751 |
+
mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1)
|
| 752 |
+
pitch = mean + (prosody[..., 0] - mean) * pitch_range
|
| 753 |
+
return torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
|
| 754 |
+
|
| 755 |
+
@staticmethod
|
| 756 |
+
def sway_time_grid(n_steps: int, sway_coef: float = 0.0) -> list[float]:
|
| 757 |
+
"""Return monotone ODE time schedule in [0, 1]; uniform when ``sway_coef == 0.0``."""
|
| 758 |
+
if sway_coef == 0.0:
|
| 759 |
+
return [i / n_steps for i in range(n_steps + 1)]
|
| 760 |
+
s = max(-1.0, min(1.0, float(sway_coef)))
|
| 761 |
+
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))]
|
| 762 |
+
|
| 763 |
+
def sample_mel(
|
| 764 |
+
self,
|
| 765 |
+
cond: torch.Tensor,
|
| 766 |
+
prior_mel: torch.Tensor,
|
| 767 |
+
frame_mask: torch.Tensor,
|
| 768 |
+
n_steps: int = 8,
|
| 769 |
+
cfg_scale: float = 1.2,
|
| 770 |
+
temperature: float = 0.85,
|
| 771 |
+
solver: str = "midpoint",
|
| 772 |
+
seed: int = 0,
|
| 773 |
+
f0_feats: torch.Tensor | None = None,
|
| 774 |
+
noise_gate: torch.Tensor | None = None,
|
| 775 |
+
sway_coef: float = 0.0,
|
| 776 |
+
) -> torch.Tensor:
|
| 777 |
+
"""Integra o campo de velocidade OT-CFM em ``n_steps`` passos (Euler ou Midpoint)."""
|
| 778 |
+
b, t_len, m = prior_mel.shape
|
| 779 |
+
gen = torch.Generator(device=prior_mel.device).manual_seed(int(seed))
|
| 780 |
+
sigma = self.cfm_config.prior_sigma * temperature
|
| 781 |
+
eps = torch.randn((b, t_len, m), generator=gen, device=prior_mel.device, dtype=torch.float32)
|
| 782 |
+
noise = sigma * eps if noise_gate is None else sigma * noise_gate * eps
|
| 783 |
+
x = (prior_mel + noise) * frame_mask[..., None]
|
| 784 |
+
zero_cond = torch.zeros_like(cond)
|
| 785 |
+
zero_prior = torch.zeros_like(prior_mel)
|
| 786 |
+
zero_f0 = torch.zeros_like(f0_feats) if f0_feats is not None else None
|
| 787 |
+
|
| 788 |
+
def velocity(x_cur: torch.Tensor, t_val: float) -> torch.Tensor:
|
| 789 |
+
t_vec = torch.full((b,), t_val, device=x_cur.device, dtype=torch.float32)
|
| 790 |
+
v_c = self.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
|
| 791 |
+
if cfg_scale == 1.0:
|
| 792 |
+
return v_c
|
| 793 |
+
v_u = self.flow(x_cur, t_vec, zero_cond, zero_prior, frame_mask, f0_feats=zero_f0)
|
| 794 |
+
return v_u + cfg_scale * (v_c - v_u)
|
| 795 |
+
|
| 796 |
+
if sway_coef == 0.0:
|
| 797 |
+
dt = 1.0 / n_steps
|
| 798 |
+
steps = [(i * dt, dt) for i in range(n_steps)]
|
| 799 |
+
else:
|
| 800 |
+
t_grid = self.sway_time_grid(n_steps, sway_coef)
|
| 801 |
+
steps = [(t_grid[i], t_grid[i + 1] - t_grid[i]) for i in range(n_steps)]
|
| 802 |
+
for t0, dt_i in steps:
|
| 803 |
+
if solver == "midpoint":
|
| 804 |
+
v0 = velocity(x, t0)
|
| 805 |
+
x_mid = (x + 0.5 * dt_i * v0) * frame_mask[..., None]
|
| 806 |
+
v_mid = velocity(x_mid, t0 + 0.5 * dt_i)
|
| 807 |
+
x = (x + dt_i * v_mid) * frame_mask[..., None]
|
| 808 |
+
else:
|
| 809 |
+
v0 = velocity(x, t0)
|
| 810 |
+
x = (x + dt_i * v0) * frame_mask[..., None]
|
| 811 |
+
return x
|
| 812 |
+
|
| 813 |
+
@torch.inference_mode()
|
| 814 |
+
def predict_physical_mel(
|
| 815 |
+
self,
|
| 816 |
+
tokens,
|
| 817 |
+
stress,
|
| 818 |
+
lengths,
|
| 819 |
+
speakers,
|
| 820 |
+
speed: float = 1.0,
|
| 821 |
+
pitch_shift: float = 0.0,
|
| 822 |
+
seed: int = 0,
|
| 823 |
+
pitch_range: float | None = None,
|
| 824 |
+
n_steps: int = 8,
|
| 825 |
+
cfg_scale: float = 1.0,
|
| 826 |
+
temperature: float = 0.35,
|
| 827 |
+
solver: str = "midpoint",
|
| 828 |
+
sway_coef: float = 0.0,
|
| 829 |
+
voiced_vowels: bool = True,
|
| 830 |
+
dur_steps: int | None = None,
|
| 831 |
+
dur_temp: float | None = None,
|
| 832 |
+
prosody_steps: int | None = None,
|
| 833 |
+
prosody_temp: float | None = None,
|
| 834 |
+
) -> tuple[torch.Tensor, torch.Tensor, dict]:
|
| 835 |
+
"""Predict unnormalized physical log-mel ``[B, T, 100]``, ``frame_lengths``, and details."""
|
| 836 |
+
pr = self.cfm_config.default_pitch_range if pitch_range is None else float(pitch_range)
|
| 837 |
+
hidden, mask = self.encode(tokens, stress, lengths, speakers)
|
| 838 |
+
prosody_token_ctx, clause_ctx_tok = self.encode_prosody_context(hidden, tokens, stress, mask)
|
| 839 |
+
durations, _ = self.sample_durations(
|
| 840 |
+
prosody_token_ctx, mask, tokens, speed=speed, seed=seed, temperature=dur_temp, steps=dur_steps
|
| 841 |
+
)
|
| 842 |
+
acoustic_frames, prosody_frames, frame_mask, frame_lengths = self.expand_with_context(
|
| 843 |
+
hidden, prosody_token_ctx, clause_ctx_tok, durations, mask, speakers
|
| 844 |
+
)
|
| 845 |
+
prosody_hidden, prosody, _ = self.sample_prosody(
|
| 846 |
+
prosody_frames, frame_mask, seed=seed, temperature=prosody_temp, steps=prosody_steps
|
| 847 |
+
)
|
| 848 |
+
if voiced_vowels:
|
| 849 |
+
ends = durations.cumsum(1)
|
| 850 |
+
frame = torch.arange(prosody_frames.shape[1], device=tokens.device)[None].expand(len(lengths), -1).contiguous()
|
| 851 |
+
index = torch.searchsorted(ends, frame, right=True).clamp(max=tokens.shape[1] - 1)
|
| 852 |
+
is_vowel = self.vowel_tokens[tokens.gather(1, index)] & frame_mask
|
| 853 |
+
prosody = torch.cat((prosody[..., :1], torch.where(is_vowel, prosody[..., 1].clamp_min(1.0), prosody[..., 1])[..., None], prosody[..., 2:]), dim=-1)
|
| 854 |
+
prosody = self.widen_pitch(prosody, frame_mask, pr)
|
| 855 |
+
if pitch_shift != 0.0:
|
| 856 |
+
prosody = torch.cat((prosody[..., :1] + pitch_shift, prosody[..., 1:]), dim=-1) * frame_mask[..., None]
|
| 857 |
+
hard_p = self.hard_prosody(prosody)
|
| 858 |
+
base_h = acoustic_frames if self.cfm_config.acoustic_from_frames else prosody_hidden
|
| 859 |
+
cond, prior_mel = self.condition_and_prior(base_h, hard_p, frame_mask)
|
| 860 |
+
f0_feats = f0_features(hard_p, frame_mask) if self.cfm_config.use_f0_harmonics else None
|
| 861 |
+
noise_gate = energy_noise_gate(hard_p, frame_mask) if self.cfm_config.use_energy_gate else None
|
| 862 |
+
mel_norm = self.sample_mel(
|
| 863 |
+
cond, prior_mel, frame_mask, n_steps=n_steps, cfg_scale=cfg_scale,
|
| 864 |
+
temperature=temperature, solver=solver, seed=seed, f0_feats=f0_feats,
|
| 865 |
+
noise_gate=noise_gate, sway_coef=sway_coef,
|
| 866 |
+
)
|
| 867 |
+
phys_mel = (mel_norm * self.vocoder.mel_scale + self.vocoder.mel_mean).clamp(min=-11.512925)
|
| 868 |
+
return phys_mel, frame_lengths, {"durations": durations, "prosody": prosody, "mel_norm": mel_norm}
|
| 869 |
+
|
| 870 |
+
@torch.inference_mode()
|
| 871 |
+
def synthesize(
|
| 872 |
+
self,
|
| 873 |
+
tokens,
|
| 874 |
+
stress,
|
| 875 |
+
lengths,
|
| 876 |
+
speakers,
|
| 877 |
+
speed: float = 1.0,
|
| 878 |
+
pitch_shift: float = 0.0,
|
| 879 |
+
seed: int = 0,
|
| 880 |
+
pitch_range: float | None = None,
|
| 881 |
+
n_steps: int = 8,
|
| 882 |
+
cfg_scale: float = 1.2,
|
| 883 |
+
temperature: float = 0.85,
|
| 884 |
+
solver: str = "midpoint",
|
| 885 |
+
sway_coef: float = 0.0,
|
| 886 |
+
voiced_vowels: bool = True,
|
| 887 |
+
dur_steps: int | None = None,
|
| 888 |
+
dur_temp: float | None = None,
|
| 889 |
+
prosody_steps: int | None = None,
|
| 890 |
+
prosody_temp: float | None = None,
|
| 891 |
+
):
|
| 892 |
+
_, frame_lengths, details = self.predict_physical_mel(
|
| 893 |
+
tokens, stress, lengths, speakers,
|
| 894 |
+
speed=speed, pitch_shift=pitch_shift, seed=seed, pitch_range=pitch_range,
|
| 895 |
+
n_steps=n_steps, cfg_scale=cfg_scale, temperature=temperature, solver=solver,
|
| 896 |
+
sway_coef=sway_coef, voiced_vowels=voiced_vowels,
|
| 897 |
+
dur_steps=dur_steps, dur_temp=dur_temp, prosody_steps=prosody_steps, prosody_temp=prosody_temp,
|
| 898 |
+
)
|
| 899 |
+
audio = self.vocoder.decode_mel(details["mel_norm"], frame_lengths)
|
| 900 |
+
return audio, frame_lengths * self.config.hop, details
|
code/src/lua_nova_v1/models/frontend.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lua Nova V1: feed-forward transformer with a pitch-driven source-filter head.
|
| 2 |
+
|
| 3 |
+
All weights start random. Tensor conventions: hidden [B,T,C], frame features
|
| 4 |
+
[B,T], waveform [B,S]. Acoustic frame i is centred on sample ``i * hop``.
|
| 5 |
+
|
| 6 |
+
phoneme + stress + voice -> transformer encoder -> duration predictor
|
| 7 |
+
-> repeat tokens by duration (supervised durations while training)
|
| 8 |
+
-> frame transformer A -> pitch / voicing / energy
|
| 9 |
+
-> frame transformer B -> filter parameters
|
| 10 |
+
-> harmonic pulse train (from pitch) and noise, each shaped by its
|
| 11 |
+
time-varying filter in the STFT domain -> 24 kHz waveform
|
| 12 |
+
|
| 13 |
+
The waveform head has no neural upsampling network. The oscillator supplies the
|
| 14 |
+
periodicity that a tiny decoder cannot render reliably on its own; the network
|
| 15 |
+
only has to predict slowly varying spectral envelopes (complex cepstra), which
|
| 16 |
+
is what keeps the voice from sounding buzzy or unstable at this size.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
import os
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import functional as F
|
| 24 |
+
from torch.utils.checkpoint import checkpoint
|
| 25 |
+
from ..config import Config
|
| 26 |
+
from ..text.phonemizer import PHONE_IDS, SYMBOL_TO_ID, VOWELS
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class UtteranceTooLong(ValueError):
|
| 30 |
+
"""The utterance needs more frames than ``max_frames``: split the input."""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def length_mask(lengths, size=None):
|
| 34 |
+
size = int(lengths.max()) if size is None else size
|
| 35 |
+
return torch.arange(size, device=lengths.device)[None, :] < lengths[:, None]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def rotary_table(size, width, device):
|
| 39 |
+
inverse = 1.0 / (10000 ** (torch.arange(0, width, 2, device=device, dtype=torch.float32) / width))
|
| 40 |
+
angle = torch.arange(size, device=device, dtype=torch.float32)[:, None] * inverse[None]
|
| 41 |
+
return angle.cos(), angle.sin()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def rotate(x, table):
|
| 45 |
+
cos, sin = table[0].to(x.dtype), table[1].to(x.dtype)
|
| 46 |
+
a, b = x[..., 0::2], x[..., 1::2]
|
| 47 |
+
return torch.stack((a * cos - b * sin, a * sin + b * cos), dim=-1).flatten(-2)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Attention(nn.Module):
|
| 51 |
+
"""Self-attention with rotary (relative) positions: no absolute position
|
| 52 |
+
table, so utterances longer than those seen in training stay in range."""
|
| 53 |
+
|
| 54 |
+
def __init__(self, channels, heads, dropout):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.heads, self.dropout = heads, dropout
|
| 57 |
+
self.qkv = nn.Linear(channels, 3 * channels)
|
| 58 |
+
self.out = nn.Linear(channels, channels)
|
| 59 |
+
|
| 60 |
+
def forward(self, x, mask, table):
|
| 61 |
+
b, t, c = x.shape
|
| 62 |
+
q, k, v = self.qkv(x).view(b, t, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4)
|
| 63 |
+
y = F.scaled_dot_product_attention(rotate(q, table), rotate(k, table), v, attn_mask=mask[:, None, None, :],
|
| 64 |
+
dropout_p=self.dropout if self.training else 0.0)
|
| 65 |
+
return self.out(y.transpose(1, 2).reshape(b, t, c))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class Block(nn.Module):
|
| 69 |
+
def __init__(self, c):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.norm1 = nn.LayerNorm(c.channels)
|
| 72 |
+
self.attention = Attention(c.channels, c.heads, c.dropout)
|
| 73 |
+
self.norm2 = nn.LayerNorm(c.channels)
|
| 74 |
+
self.depthwise = nn.Conv1d(c.channels, c.channels, c.kernel, padding=c.kernel // 2, groups=c.channels)
|
| 75 |
+
self.expand = nn.Linear(c.channels, c.feedforward)
|
| 76 |
+
self.project = nn.Linear(c.feedforward, c.channels)
|
| 77 |
+
self.dropout = nn.Dropout(c.dropout)
|
| 78 |
+
|
| 79 |
+
def forward(self, x, mask, table):
|
| 80 |
+
keep = mask[..., None]
|
| 81 |
+
x = (x + self.dropout(self.attention(self.norm1(x), mask, table))) * keep
|
| 82 |
+
# Mask before the convolution so padded positions cannot leak back in.
|
| 83 |
+
y = self.depthwise((self.norm2(x) * keep).transpose(1, 2)).transpose(1, 2)
|
| 84 |
+
y = self.project(self.dropout(F.gelu(self.expand(y))))
|
| 85 |
+
return (x + self.dropout(y)) * keep
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class Stack(nn.Module):
|
| 89 |
+
def __init__(self, c, layers):
|
| 90 |
+
super().__init__()
|
| 91 |
+
self.blocks = nn.ModuleList(Block(c) for _ in range(layers))
|
| 92 |
+
self.norm = nn.LayerNorm(c.channels)
|
| 93 |
+
self.width = c.channels // c.heads
|
| 94 |
+
|
| 95 |
+
def forward(self, x, mask):
|
| 96 |
+
table = rotary_table(x.shape[1], self.width, x.device)
|
| 97 |
+
for block in self.blocks:
|
| 98 |
+
x = block(x, mask, table)
|
| 99 |
+
return self.norm(x) * mask[..., None]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class Predictor(nn.Module):
|
| 103 |
+
def __init__(self, c, outputs):
|
| 104 |
+
super().__init__()
|
| 105 |
+
p = c.predictor_channels
|
| 106 |
+
self.conv1 = nn.Conv1d(c.channels, p, 3, padding=1)
|
| 107 |
+
self.conv2 = nn.Conv1d(p, p, 3, padding=1)
|
| 108 |
+
self.norm1, self.norm2 = nn.LayerNorm(p), nn.LayerNorm(p)
|
| 109 |
+
self.drop = nn.Dropout(c.dropout)
|
| 110 |
+
self.out = nn.Linear(p, outputs)
|
| 111 |
+
|
| 112 |
+
def forward(self, x, mask):
|
| 113 |
+
x = self.conv1((x * mask[..., None]).transpose(1, 2)).transpose(1, 2)
|
| 114 |
+
x = self.drop(self.norm1(F.gelu(x))) * mask[..., None]
|
| 115 |
+
x = self.conv2(x.transpose(1, 2)).transpose(1, 2)
|
| 116 |
+
x = self.drop(self.norm2(F.gelu(x)))
|
| 117 |
+
return self.out(x) * mask[..., None]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def pulse_train(f0, sample_rate, hop, limit=0.47, phase=None):
|
| 121 |
+
"""Band-limited pulse train [B, T*hop] with unit power for f0 [B, T] in Hz.
|
| 122 |
+
|
| 123 |
+
Frame values sit at samples i*hop and are interpolated in the log domain.
|
| 124 |
+
The sum of all harmonics below ``limit * sample_rate`` has the closed form
|
| 125 |
+
sin((K+1/2)x) / (2 sin(x/2)) - 1/2; the top harmonic fades in and out so the
|
| 126 |
+
signal stays continuous while the pitch glides. Float64 keeps the phase exact.
|
| 127 |
+
"""
|
| 128 |
+
frames = f0.shape[1]
|
| 129 |
+
knots = torch.log(f0.double().clamp_min(1.0))
|
| 130 |
+
knots = torch.cat((knots, knots[:, -1:]), dim=1)
|
| 131 |
+
position = torch.arange(frames * hop, device=f0.device, dtype=torch.float64) / hop
|
| 132 |
+
low = position.floor().long()
|
| 133 |
+
weight = position - low
|
| 134 |
+
frequency = torch.exp(knots[:, low] * (1 - weight) + knots[:, low + 1] * weight)
|
| 135 |
+
theta = 2 * math.pi * torch.cumsum(frequency / sample_rate, dim=1)
|
| 136 |
+
if phase is not None:
|
| 137 |
+
theta = theta + phase.double()[:, None]
|
| 138 |
+
theta = torch.remainder(theta, 2 * math.pi)
|
| 139 |
+
harmonics = (limit * sample_rate / frequency).clamp_min(1.0)
|
| 140 |
+
whole = torch.floor(harmonics)
|
| 141 |
+
denominator = 2 * torch.sin(theta / 2)
|
| 142 |
+
tiny = denominator.abs() < 1e-7
|
| 143 |
+
core = torch.where(tiny, whole, torch.sin((whole + 0.5) * theta) / torch.where(tiny, torch.ones_like(denominator), denominator) - 0.5)
|
| 144 |
+
wave = core + (harmonics - whole) * torch.cos((whole + 1) * theta)
|
| 145 |
+
return (wave * torch.sqrt(2.0 / harmonics)).float()
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def filtered(source, response, fft, hop, window):
|
| 149 |
+
"""Time-varying filtering: response [B, frames, bins] multiplies the STFT."""
|
| 150 |
+
spectrum = torch.stft(source, fft, hop, window=window, center=True, pad_mode="constant", return_complex=True)
|
| 151 |
+
if spectrum.shape[-1] != response.shape[1]:
|
| 152 |
+
raise ValueError("filter frames do not match the source")
|
| 153 |
+
return torch.istft(spectrum * response.transpose(1, 2), fft, hop, window=window, center=True, length=source.shape[-1])
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def cepstrum_response(causal, anticausal, fft):
|
| 157 |
+
"""Complex frequency response exp(FFT(cepstrum)). Causal coefficients give a
|
| 158 |
+
minimum-phase filter; anticausal ones add a maximum-phase part (glottal pulse)."""
|
| 159 |
+
buffer = causal.new_zeros(*causal.shape[:-1], fft)
|
| 160 |
+
buffer[..., :causal.shape[-1]] = causal
|
| 161 |
+
if anticausal is not None:
|
| 162 |
+
buffer[..., fft - anticausal.shape[-1]:] = anticausal.flip(-1)
|
| 163 |
+
spectrum = torch.fft.rfft(buffer, dim=-1)
|
| 164 |
+
return torch.polar(torch.exp(spectrum.real.clamp(-14, 6)), spectrum.imag)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class SourceFilter(nn.Module):
|
| 168 |
+
"""Harmonic-plus-noise synthesis controlled per frame by two linear heads."""
|
| 169 |
+
|
| 170 |
+
def __init__(self, c):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.config = c
|
| 173 |
+
self.harmonic_steps, self.noise_steps = c.hop // c.synth_hop, c.hop // c.noise_hop
|
| 174 |
+
self.harmonic = nn.Linear(c.channels, c.cep_causal + c.cep_anti + self.harmonic_steps)
|
| 175 |
+
self.noise = nn.Linear(c.channels, c.noise_cep + self.noise_steps)
|
| 176 |
+
for head, level in ((self.harmonic, -1.5), (self.noise, -2.5)): # start quiet and spectrally flat
|
| 177 |
+
nn.init.zeros_(head.weight)
|
| 178 |
+
nn.init.zeros_(head.bias)
|
| 179 |
+
head.bias.data[0] = level
|
| 180 |
+
|
| 181 |
+
def lifter(size, first):
|
| 182 |
+
scale = 1.0 / (1.0 + torch.arange(first, first + size, dtype=torch.float32) / 4)
|
| 183 |
+
if first == 0:
|
| 184 |
+
scale[0] = 2.0 # coefficient 0 is the log gain and needs range
|
| 185 |
+
return scale
|
| 186 |
+
self.register_buffer("causal_lifter", lifter(c.cep_causal, 0), persistent=False)
|
| 187 |
+
self.register_buffer("anti_lifter", lifter(c.cep_anti, 1), persistent=False)
|
| 188 |
+
self.register_buffer("noise_lifter", lifter(c.noise_cep, 0), persistent=False)
|
| 189 |
+
self.register_buffer("synth_window", torch.hann_window(c.synth_fft), persistent=False)
|
| 190 |
+
self.register_buffer("noise_window", torch.hann_window(c.noise_fft), persistent=False)
|
| 191 |
+
|
| 192 |
+
@staticmethod
|
| 193 |
+
def _take(values, index):
|
| 194 |
+
return values.gather(1, index[..., None].expand(-1, -1, values.shape[-1]))
|
| 195 |
+
|
| 196 |
+
def _subframes(self, frames, lengths, steps):
|
| 197 |
+
"""Sub-frame j uses frame j // steps; indices past an utterance's end
|
| 198 |
+
repeat its last sub-frame so padding never changes real audio. Two extra
|
| 199 |
+
sub-frames cover the half window of zeros appended to the source."""
|
| 200 |
+
sub = torch.arange(steps * frames + 3, device=lengths.device)[None].expand(len(lengths), -1)
|
| 201 |
+
return torch.minimum(sub, (steps * lengths - 1).clamp_min(0)[:, None])
|
| 202 |
+
|
| 203 |
+
@staticmethod
|
| 204 |
+
def _shape(source, response, fft, hop, window):
|
| 205 |
+
# Half a window of trailing zeros: the frames around an utterance's end are
|
| 206 |
+
# then the same whether it stands alone or is padded inside a batch.
|
| 207 |
+
return filtered(F.pad(source, (0, fft // 2)), response, fft, hop, window)[:, :source.shape[-1]]
|
| 208 |
+
|
| 209 |
+
def forward(self, hidden, f0, lengths, noise=None, phase=None):
|
| 210 |
+
c = self.config
|
| 211 |
+
frames = hidden.shape[1]
|
| 212 |
+
samples = frames * c.hop
|
| 213 |
+
with torch.autocast(device_type=hidden.device.type, enabled=False):
|
| 214 |
+
hidden = hidden.float()
|
| 215 |
+
audible = length_mask(lengths * c.hop, samples)
|
| 216 |
+
last = (lengths - 1).clamp_min(0)[:, None]
|
| 217 |
+
# Harmonic branch: envelope interpolated between frames, one gain per sub-frame.
|
| 218 |
+
h = self.harmonic(hidden)
|
| 219 |
+
split = c.cep_causal + c.cep_anti
|
| 220 |
+
sub = self._subframes(frames, lengths, self.harmonic_steps)
|
| 221 |
+
here, following = sub // self.harmonic_steps, torch.minimum((sub + 1) // self.harmonic_steps, last)
|
| 222 |
+
causal = 0.5 * (self._take(h[..., :c.cep_causal], here) + self._take(h[..., :c.cep_causal], following)) * self.causal_lifter
|
| 223 |
+
anti = 0.5 * (self._take(h[..., c.cep_causal:split], here) + self._take(h[..., c.cep_causal:split], following)) * self.anti_lifter
|
| 224 |
+
causal = torch.cat((causal[..., :1] + h[..., split:].flatten(1).gather(1, sub)[..., None], causal[..., 1:]), dim=-1)
|
| 225 |
+
harmonic_response = cepstrum_response(causal, anti, c.synth_fft)
|
| 226 |
+
# Noise branch: one envelope per frame, four gains per frame for sharp consonants.
|
| 227 |
+
n = self.noise(hidden)
|
| 228 |
+
sub = self._subframes(frames, lengths, self.noise_steps)
|
| 229 |
+
shape = self._take(n[..., :c.noise_cep], sub // self.noise_steps) * self.noise_lifter
|
| 230 |
+
shape = torch.cat((shape[..., :1] + n[..., c.noise_cep:].flatten(1).gather(1, sub)[..., None], shape[..., 1:]), dim=-1)
|
| 231 |
+
noise_response = cepstrum_response(shape, None, c.noise_fft)
|
| 232 |
+
# Hold the last real pitch value through padding: the pitch glide inside an
|
| 233 |
+
# utterance's final frame must not depend on what the batch was padded with.
|
| 234 |
+
f0 = f0.float().gather(1, torch.minimum(torch.arange(frames, device=f0.device)[None], last))
|
| 235 |
+
pulses = pulse_train(f0, c.sample_rate, c.hop, c.harmonic_limit, phase) * audible
|
| 236 |
+
if noise is None:
|
| 237 |
+
noise = torch.randn(hidden.shape[0], samples, device=hidden.device)
|
| 238 |
+
wave = (self._shape(pulses, harmonic_response, c.synth_fft, c.synth_hop, self.synth_window)
|
| 239 |
+
+ self._shape(noise * audible, noise_response, c.noise_fft, c.noise_hop, self.noise_window))
|
| 240 |
+
return wave * audible
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _load_vocos_pretrained(model_id):
|
| 244 |
+
from huggingface_hub import hf_hub_download
|
| 245 |
+
from vocos import Vocos
|
| 246 |
+
|
| 247 |
+
try:
|
| 248 |
+
cfg = hf_hub_download(repo_id=model_id, filename="config.yaml", local_files_only=True)
|
| 249 |
+
weights = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin", local_files_only=True)
|
| 250 |
+
model = Vocos.from_hparams(cfg)
|
| 251 |
+
state = torch.load(weights, map_location="cpu", weights_only=True)
|
| 252 |
+
model.load_state_dict(state)
|
| 253 |
+
return model
|
| 254 |
+
except Exception:
|
| 255 |
+
return Vocos.from_pretrained(model_id)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class VocosHead(nn.Module):
|
| 259 |
+
"""Linear mel projection followed by a pretrained 24 kHz Vocos ConvNeXt/iSTFT decoder."""
|
| 260 |
+
|
| 261 |
+
def __init__(self, c, vocos_model=None):
|
| 262 |
+
super().__init__()
|
| 263 |
+
self.config = c
|
| 264 |
+
self.frozen = False
|
| 265 |
+
self.proj = nn.Linear(c.channels, c.vocos_n_mels)
|
| 266 |
+
self.vocos = _load_vocos_pretrained(c.vocos_model) if vocos_model is None else vocos_model
|
| 267 |
+
self.register_buffer("mel_mean", torch.zeros(c.vocos_n_mels, dtype=torch.float32))
|
| 268 |
+
self.register_buffer("mel_scale", torch.ones(c.vocos_n_mels, dtype=torch.float32))
|
| 269 |
+
|
| 270 |
+
def freeze_vocoder(self, frozen=True):
|
| 271 |
+
self.frozen = frozen
|
| 272 |
+
for param in self.vocos.parameters():
|
| 273 |
+
param.requires_grad_(not frozen)
|
| 274 |
+
if frozen:
|
| 275 |
+
self.vocos.eval()
|
| 276 |
+
|
| 277 |
+
def train(self, mode=True):
|
| 278 |
+
super().train(mode)
|
| 279 |
+
if self.frozen:
|
| 280 |
+
self.vocos.eval()
|
| 281 |
+
return self
|
| 282 |
+
|
| 283 |
+
def set_mel_stats(self, mean, scale):
|
| 284 |
+
mean_t = torch.as_tensor(mean, dtype=torch.float32, device=self.mel_mean.device)
|
| 285 |
+
scale_t = torch.as_tensor(scale, dtype=torch.float32, device=self.mel_scale.device).clamp_min(1e-6)
|
| 286 |
+
if mean_t.shape != (self.config.vocos_n_mels,) or scale_t.shape != (self.config.vocos_n_mels,):
|
| 287 |
+
raise ValueError("vocos mel stats shape mismatch")
|
| 288 |
+
self.mel_mean.copy_(mean_t)
|
| 289 |
+
self.mel_scale.copy_(scale_t)
|
| 290 |
+
|
| 291 |
+
def predict_mel(self, hidden, frame_mask):
|
| 292 |
+
return self.proj(hidden.float()) * frame_mask[..., None]
|
| 293 |
+
|
| 294 |
+
def decode_mel(self, mel_norm, lengths, checkpointing=False):
|
| 295 |
+
c = self.config
|
| 296 |
+
frames = mel_norm.shape[1]
|
| 297 |
+
samples = frames * c.hop
|
| 298 |
+
if not self.training and mel_norm.shape[0] > 1:
|
| 299 |
+
waves = [
|
| 300 |
+
self.decode_mel(mel_norm[i : i + 1, : int(lengths[i])], lengths[i : i + 1])[0]
|
| 301 |
+
for i in range(mel_norm.shape[0])
|
| 302 |
+
]
|
| 303 |
+
out = nn.utils.rnn.pad_sequence(waves, batch_first=True)
|
| 304 |
+
if out.shape[1] < samples:
|
| 305 |
+
out = F.pad(out, (0, samples - out.shape[1]))
|
| 306 |
+
return out
|
| 307 |
+
with torch.autocast(device_type=mel_norm.device.type, enabled=False):
|
| 308 |
+
mel = mel_norm.float() * self.mel_scale + self.mel_mean
|
| 309 |
+
pos = torch.arange(frames + 1, device=mel.device)[None]
|
| 310 |
+
last = (lengths - 1).clamp_min(0)[:, None]
|
| 311 |
+
idx = torch.minimum(pos, last)
|
| 312 |
+
mel_bct = mel.gather(1, idx[..., None].expand(-1, -1, mel.shape[-1])).transpose(1, 2)
|
| 313 |
+
backbone = self.vocos.backbone
|
| 314 |
+
if checkpointing and self.training and mel_bct.requires_grad:
|
| 315 |
+
x = backbone.embed(mel_bct)
|
| 316 |
+
x = backbone.norm(x.transpose(1, 2)).transpose(1, 2)
|
| 317 |
+
for block in backbone.convnext:
|
| 318 |
+
x = checkpoint(block, x, use_reentrant=False)
|
| 319 |
+
x = backbone.final_layer_norm(x.transpose(1, 2))
|
| 320 |
+
else:
|
| 321 |
+
x = backbone(mel_bct)
|
| 322 |
+
wave = self.vocos.head(x)
|
| 323 |
+
audible = length_mask(lengths * c.hop, samples)
|
| 324 |
+
return wave * audible
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class LuaNovaBase(nn.Module):
|
| 328 |
+
def __init__(self, config=Config()):
|
| 329 |
+
super().__init__()
|
| 330 |
+
self.config = c = config
|
| 331 |
+
self.tokens = nn.Embedding(c.vocab_size, c.channels, padding_idx=0)
|
| 332 |
+
self.stress = nn.Embedding(3, c.channels)
|
| 333 |
+
self.voices = nn.Embedding(len(c.speakers), c.channels)
|
| 334 |
+
self.encoder = Stack(c, c.encoder_layers)
|
| 335 |
+
# Outputs per token: log(1 + frames) and, for pause-capable tokens, a
|
| 336 |
+
# "has frames at all" logit. A pause is absent more often than present, so
|
| 337 |
+
# one regression would average both cases into a pause that is too short.
|
| 338 |
+
self.duration = Predictor(c, 2)
|
| 339 |
+
self.frame_voices = nn.Embedding(len(c.speakers), c.channels)
|
| 340 |
+
self.frame_position = nn.Linear(3, c.channels)
|
| 341 |
+
self.prosody_stack = Stack(c, c.prosody_layers)
|
| 342 |
+
# Outputs: continuous log(F0/reference), voiced logit, normalized log RMS energy.
|
| 343 |
+
self.prosody_head = nn.Linear(c.channels, 3)
|
| 344 |
+
self.prosody_projection = nn.Linear(3, c.channels)
|
| 345 |
+
self.acoustic_stack = Stack(c, c.acoustic_layers)
|
| 346 |
+
self.vocoder = VocosHead(c) if c.vocoder_type == "vocos" else SourceFilter(c)
|
| 347 |
+
phones = torch.zeros(c.vocab_size, dtype=torch.bool)
|
| 348 |
+
phones[sorted(PHONE_IDS)] = True
|
| 349 |
+
self.register_buffer("phone_tokens", phones, persistent=False)
|
| 350 |
+
vowels = torch.zeros(c.vocab_size, dtype=torch.bool)
|
| 351 |
+
vowels[[SYMBOL_TO_ID[v] for v in VOWELS]] = True
|
| 352 |
+
self.register_buffer("vowel_tokens", vowels, persistent=False)
|
| 353 |
+
|
| 354 |
+
def encode(self, tokens, stress, lengths, speakers):
|
| 355 |
+
if tokens.ndim != 2 or stress.shape != tokens.shape or lengths.shape != (tokens.shape[0],) or speakers.shape != lengths.shape:
|
| 356 |
+
raise ValueError("expected tokens[B,N], stress[B,N], lengths[B], speakers[B]")
|
| 357 |
+
if tokens.shape[1] > self.config.max_tokens or bool((lengths < 1).any()) or bool((lengths > tokens.shape[1]).any()):
|
| 358 |
+
raise ValueError("invalid token length")
|
| 359 |
+
mask = length_mask(lengths, tokens.shape[1])
|
| 360 |
+
x = (self.tokens(tokens) + self.stress(stress) + self.voices(speakers)[:, None]) * mask[..., None]
|
| 361 |
+
return self.encoder(x, mask), mask
|
| 362 |
+
|
| 363 |
+
def expand(self, hidden, durations, token_mask, speakers):
|
| 364 |
+
"""Repeat token states by integer durations (zero is allowed for pause
|
| 365 |
+
tokens) and add each frame's position inside its token."""
|
| 366 |
+
if durations.shape != token_mask.shape or bool((durations < 0).any()) or bool((durations[~token_mask] != 0).any()):
|
| 367 |
+
raise ValueError("invalid durations")
|
| 368 |
+
lengths = durations.sum(1)
|
| 369 |
+
if bool((lengths < 1).any()):
|
| 370 |
+
raise ValueError("utterance has no frames")
|
| 371 |
+
if bool((lengths > self.config.max_frames).any()):
|
| 372 |
+
raise UtteranceTooLong("utterance exceeds max_frames; split the input")
|
| 373 |
+
size = int(lengths.max())
|
| 374 |
+
ends = durations.cumsum(1)
|
| 375 |
+
frame = torch.arange(size, device=hidden.device)[None].expand(hidden.shape[0], size).contiguous()
|
| 376 |
+
index = torch.searchsorted(ends, frame, right=True).clamp(max=durations.shape[1] - 1)
|
| 377 |
+
owned = durations.gather(1, index).clamp_min(1)
|
| 378 |
+
offset = frame - (ends.gather(1, index) - durations.gather(1, index))
|
| 379 |
+
relative = (offset.to(hidden.dtype) + 0.5) / owned
|
| 380 |
+
features = torch.stack((relative, 1 - relative, torch.log1p(owned.to(hidden.dtype)) / 4), dim=-1)
|
| 381 |
+
mask = frame < lengths[:, None]
|
| 382 |
+
expanded = hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1]))
|
| 383 |
+
expanded = expanded + self.frame_position(features) + self.frame_voices(speakers)[:, None]
|
| 384 |
+
return expanded * mask[..., None], mask, lengths
|
| 385 |
+
|
| 386 |
+
def predict_prosody(self, frames, frame_mask):
|
| 387 |
+
hidden = self.prosody_stack(frames, frame_mask)
|
| 388 |
+
return hidden, self.prosody_head(hidden) * frame_mask[..., None]
|
| 389 |
+
|
| 390 |
+
@staticmethod
|
| 391 |
+
def hard_prosody(prediction):
|
| 392 |
+
"""What the decoder is conditioned on when it is not teacher-forced."""
|
| 393 |
+
return torch.stack((prediction[..., 0].clamp(-2.0, 1.5), (prediction[..., 1] > 0).to(prediction.dtype),
|
| 394 |
+
prediction[..., 2].clamp(-4.5, 3.0)), dim=-1)
|
| 395 |
+
|
| 396 |
+
def decode(self, prosody_hidden, condition, frame_mask):
|
| 397 |
+
return self.acoustic_stack((prosody_hidden + self.prosody_projection(condition)) * frame_mask[..., None], frame_mask)
|
| 398 |
+
|
| 399 |
+
def frequency(self, log_f0):
|
| 400 |
+
c = self.config
|
| 401 |
+
return (c.pitch_reference_hz * torch.exp(log_f0.float())).clamp(c.f0_min, c.f0_max)
|
| 402 |
+
|
| 403 |
+
def predict_durations(self, hidden, mask, tokens, speed=1.0):
|
| 404 |
+
output = self.duration(hidden, mask).float()
|
| 405 |
+
frames = torch.round(torch.expm1(output[..., 0].clamp(0, math.log1p(400))) / speed).long().clamp_min(1)
|
| 406 |
+
# Every phoneme is audible for at least one frame. A pause-capable token
|
| 407 |
+
# (edge, punctuation, word boundary) lasts its predicted length when the
|
| 408 |
+
# presence logit says there is a pause, and vanishes otherwise.
|
| 409 |
+
present = self.phone_tokens[tokens] | (output[..., 1] > 0)
|
| 410 |
+
return torch.where(present, frames, torch.zeros_like(frames)) * mask
|
| 411 |
+
|
| 412 |
+
@staticmethod
|
| 413 |
+
def widen_pitch(prosody, frame_mask, pitch_range):
|
| 414 |
+
"""Scale the predicted pitch movement around each utterance's voiced mean.
|
| 415 |
+
Regression predicts a flatter contour than the recordings; values above 1
|
| 416 |
+
restore range (1.0 leaves the prediction untouched)."""
|
| 417 |
+
if pitch_range == 1.0:
|
| 418 |
+
return prosody
|
| 419 |
+
voiced = ((prosody[..., 1] > 0) & frame_mask).to(prosody.dtype)
|
| 420 |
+
mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1)
|
| 421 |
+
pitch = mean + (prosody[..., 0] - mean) * pitch_range
|
| 422 |
+
return torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
|
| 423 |
+
|
| 424 |
+
@staticmethod
|
| 425 |
+
def pitch_wobble(shape, semitones, seed, device):
|
| 426 |
+
"""Small random pitch movement for the oscillator only (log-F0 units).
|
| 427 |
+
Recorded pitch has cycle-to-cycle irregularity that a predicted contour
|
| 428 |
+
lacks; two thirds of the wobble is slow drift, one third frame-level."""
|
| 429 |
+
generator = torch.Generator().manual_seed(seed + 7919)
|
| 430 |
+
fast = torch.randn(shape, generator=generator)
|
| 431 |
+
slow = F.avg_pool1d(torch.randn(shape[0], 1, shape[1] + 16, generator=generator), 17, stride=1)[:, 0]
|
| 432 |
+
slow = slow / slow.std().clamp_min(1e-6)
|
| 433 |
+
return ((2 * slow + fast) / 5 ** 0.5 * semitones * math.log(2) / 12).to(device)
|
| 434 |
+
|
| 435 |
+
@torch.inference_mode()
|
| 436 |
+
def synthesize(self, tokens, stress, lengths, speakers, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0, pitch_jitter=0.0,
|
| 437 |
+
voiced_vowels=True):
|
| 438 |
+
"""Free-running synthesis: predicted durations, pitch, voicing and energy."""
|
| 439 |
+
if not math.isfinite(speed) or not 0.25 <= speed <= 4 or not math.isfinite(pitch_shift) or not 0 <= pitch_range <= 3:
|
| 440 |
+
raise ValueError("speed must be between 0.25 and 4, pitch_shift finite and pitch_range between 0 and 3")
|
| 441 |
+
hidden, mask = self.encode(tokens, stress, lengths, speakers)
|
| 442 |
+
durations = self.predict_durations(hidden, mask, tokens, speed)
|
| 443 |
+
frames, frame_mask, frame_lengths = self.expand(hidden, durations, mask, speakers)
|
| 444 |
+
prosody_hidden, prosody = self.predict_prosody(frames, frame_mask)
|
| 445 |
+
if voiced_vowels:
|
| 446 |
+
# The pitch tracker missed creaky vowels in the recordings, and the
|
| 447 |
+
# voicing predictor learned to drop whole vowels (heard as a whispered
|
| 448 |
+
# word). A vowel is voiced by definition, so its frames are kept voiced.
|
| 449 |
+
ends = durations.cumsum(1)
|
| 450 |
+
frame = torch.arange(frames.shape[1], device=tokens.device)[None].expand(len(lengths), -1).contiguous()
|
| 451 |
+
owner = torch.searchsorted(ends, frame, right=True).clamp(max=tokens.shape[1] - 1)
|
| 452 |
+
vowel = self.vowel_tokens[tokens].gather(1, owner) & frame_mask
|
| 453 |
+
prosody = torch.cat((prosody[..., :1], torch.where(vowel, prosody[..., 1].clamp_min(2.0), prosody[..., 1])[..., None],
|
| 454 |
+
prosody[..., 2:]), dim=-1)
|
| 455 |
+
prosody = self.widen_pitch(prosody, frame_mask, pitch_range)
|
| 456 |
+
if self.config.vocoder_type == "vocos":
|
| 457 |
+
pitch = prosody[..., 0] + pitch_shift
|
| 458 |
+
if pitch_jitter > 0:
|
| 459 |
+
pitch = pitch + self.pitch_wobble(pitch.shape, pitch_jitter, seed, pitch.device)
|
| 460 |
+
prosody_in = torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
|
| 461 |
+
acoustic = self.decode(prosody_hidden, self.hard_prosody(prosody_in), frame_mask)
|
| 462 |
+
mel_norm = self.vocoder.predict_mel(acoustic, frame_mask)
|
| 463 |
+
wave = self.vocoder.decode_mel(mel_norm, frame_lengths)
|
| 464 |
+
return wave, frame_lengths * self.config.hop, {"durations": durations, "prosody": prosody, "frame_mask": frame_mask}
|
| 465 |
+
acoustic = self.decode(prosody_hidden, self.hard_prosody(prosody), frame_mask)
|
| 466 |
+
# One noise stream per row, drawn at the row's own length, so batching or
|
| 467 |
+
# padding never changes a row's audio.
|
| 468 |
+
noise = nn.utils.rnn.pad_sequence([torch.randn(int(n) * self.config.hop, generator=torch.Generator().manual_seed(seed + row))
|
| 469 |
+
for row, n in enumerate(frame_lengths)], batch_first=True)
|
| 470 |
+
pitch = prosody[..., 0] + pitch_shift
|
| 471 |
+
if pitch_jitter > 0:
|
| 472 |
+
pitch = pitch + self.pitch_wobble(pitch.shape, pitch_jitter, seed, pitch.device)
|
| 473 |
+
wave = self.vocoder(acoustic, self.frequency(pitch), frame_lengths, noise=noise.to(hidden.device))
|
| 474 |
+
return wave, frame_lengths * self.config.hop, {"durations": durations, "prosody": prosody, "frame_mask": frame_mask}
|
code/src/lua_nova_v1/models/losses.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
from torch import nn
|
| 4 |
+
from torch.nn import functional as F
|
| 5 |
+
from torch.nn.utils.parametrizations import weight_norm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def masked_mean(value, mask):
|
| 9 |
+
return (value * mask).sum() / mask.sum().clamp_min(1)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def magnitude(wave, fft, hop, window):
|
| 13 |
+
spectrum = torch.stft(wave.float(), fft, hop, window=window, center=True, pad_mode="constant", return_complex=True)
|
| 14 |
+
# sqrt(re^2 + im^2 + eps): finite gradient at exact zeros (padding, silence).
|
| 15 |
+
return torch.view_as_real(spectrum).square().sum(-1).add(1e-9).sqrt()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def mel_filterbank(sample_rate, fft, n_mels):
|
| 19 |
+
"""Slaney-scale triangular filters with area normalisation, [n_mels, bins]."""
|
| 20 |
+
step, knee, slope = 200.0 / 3, 1000.0, math.log(6.4) / 27
|
| 21 |
+
|
| 22 |
+
def to_hz(mel):
|
| 23 |
+
return torch.where(mel < knee / step, mel * step, knee * torch.exp((mel - knee / step) * slope))
|
| 24 |
+
top = knee / step + math.log(sample_rate / 2 / knee) / slope if sample_rate / 2 > knee else sample_rate / 2 / step
|
| 25 |
+
points = to_hz(torch.linspace(0, top, n_mels + 2, dtype=torch.float64))
|
| 26 |
+
bins = torch.linspace(0, sample_rate / 2, fft // 2 + 1, dtype=torch.float64)
|
| 27 |
+
rising = (bins[None] - points[:-2, None]) / (points[1:-1] - points[:-2])[:, None]
|
| 28 |
+
falling = (points[2:, None] - bins[None]) / (points[2:] - points[1:-1])[:, None]
|
| 29 |
+
weights = torch.minimum(rising, falling).clamp_min(0) * (2.0 / (points[2:] - points[:-2]))[:, None]
|
| 30 |
+
return weights.float()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class SpectralLoss(nn.Module):
|
| 34 |
+
"""Multi-resolution STFT and log-mel distances over whole utterances.
|
| 35 |
+
|
| 36 |
+
Frames whose centre lies beyond an utterance's length are masked, so padded
|
| 37 |
+
batches give the same value as the utterances would alone. No parameters.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, sample_rate, resolutions=((512, 128), (1024, 256), (2048, 512)), mel=(1024, 256, 80)):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.resolutions, self.mel = tuple(resolutions), tuple(mel)
|
| 43 |
+
for fft in {fft for fft, _ in self.resolutions} | {self.mel[0]}:
|
| 44 |
+
self.register_buffer(f"window_{fft}", torch.hann_window(fft), persistent=False)
|
| 45 |
+
self.register_buffer("filters", mel_filterbank(sample_rate, self.mel[0], self.mel[2]), persistent=False)
|
| 46 |
+
|
| 47 |
+
def log_mel(self, wave):
|
| 48 |
+
fft, hop, _ = self.mel
|
| 49 |
+
return torch.log((self.filters @ magnitude(wave, fft, hop, getattr(self, f"window_{fft}"))).clamp_min(1e-5))
|
| 50 |
+
|
| 51 |
+
def forward(self, predicted, target, lengths):
|
| 52 |
+
total = predicted.new_zeros((), dtype=torch.float32)
|
| 53 |
+
for fft, hop in self.resolutions:
|
| 54 |
+
window = getattr(self, f"window_{fft}")
|
| 55 |
+
p, t = magnitude(predicted, fft, hop, window), magnitude(target, fft, hop, window)
|
| 56 |
+
mask = (torch.arange(p.shape[-1], device=p.device)[None] * hop < lengths[:, None]).float()[:, None]
|
| 57 |
+
logarithmic = ((p.clamp_min(1e-5).log() - t.clamp_min(1e-5).log()).abs() * mask).sum() / (mask.sum() * p.shape[1]).clamp_min(1)
|
| 58 |
+
# Spectral convergence per utterance; the floor keeps silent input finite.
|
| 59 |
+
convergence = (((p - t).square() * mask).sum((1, 2)) + 1e-9).sqrt() / (t.square() * mask).sum((1, 2)).sqrt().clamp_min(1.0)
|
| 60 |
+
total = total + logarithmic + convergence.mean()
|
| 61 |
+
hop = self.mel[1]
|
| 62 |
+
p, t = self.log_mel(predicted), self.log_mel(target)
|
| 63 |
+
mask = (torch.arange(p.shape[-1], device=p.device)[None] * hop < lengths[:, None]).float()[:, None]
|
| 64 |
+
mel = ((p - t).abs() * mask).sum() / (mask.sum() * p.shape[1]).clamp_min(1)
|
| 65 |
+
return total / len(self.resolutions), mel
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class PeriodDiscriminator(nn.Module):
|
| 69 |
+
def __init__(self, period, channels=(1, 32, 96, 192, 384)):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.period = period
|
| 72 |
+
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:]))
|
| 73 |
+
self.output = weight_norm(nn.Conv2d(channels[-1], 1, (3, 1), padding=(1, 0)))
|
| 74 |
+
|
| 75 |
+
def forward(self, wave):
|
| 76 |
+
wave = F.pad(wave, (0, (-wave.shape[-1]) % self.period))
|
| 77 |
+
x = wave.reshape(wave.shape[0], 1, -1, self.period)
|
| 78 |
+
features = []
|
| 79 |
+
for layer in self.layers:
|
| 80 |
+
x = F.leaky_relu(layer(x), 0.1)
|
| 81 |
+
features.append(x)
|
| 82 |
+
return self.output(x), features
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class SpectrogramDiscriminator(nn.Module):
|
| 86 |
+
def __init__(self, fft, hop, channels=32):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.fft, self.hop = fft, hop
|
| 89 |
+
self.register_buffer("window", torch.hann_window(fft), persistent=False)
|
| 90 |
+
self.layers = nn.ModuleList([
|
| 91 |
+
weight_norm(nn.Conv2d(1, channels, (3, 9), padding=(1, 4))),
|
| 92 |
+
weight_norm(nn.Conv2d(channels, channels, (3, 9), stride=(1, 2), padding=(1, 4))),
|
| 93 |
+
weight_norm(nn.Conv2d(channels, channels, (3, 9), stride=(1, 2), padding=(1, 4))),
|
| 94 |
+
weight_norm(nn.Conv2d(channels, channels, (3, 9), stride=(1, 2), padding=(1, 4))),
|
| 95 |
+
weight_norm(nn.Conv2d(channels, channels, (3, 3), padding=(1, 1))),
|
| 96 |
+
])
|
| 97 |
+
self.output = weight_norm(nn.Conv2d(channels, 1, (3, 3), padding=(1, 1)))
|
| 98 |
+
|
| 99 |
+
def forward(self, wave):
|
| 100 |
+
x = magnitude(wave, self.fft, self.hop, self.window).transpose(1, 2)[:, None] # [B,1,frames,bins]
|
| 101 |
+
features = []
|
| 102 |
+
for layer in self.layers:
|
| 103 |
+
x = F.leaky_relu(layer(x), 0.1)
|
| 104 |
+
features.append(x)
|
| 105 |
+
return self.output(x), features
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class Discriminators(nn.Module):
|
| 109 |
+
"""Training-only waveform critics. Never included in an inference export."""
|
| 110 |
+
|
| 111 |
+
def __init__(self, periods=(2, 3, 5, 7, 11), resolutions=((512, 128), (1024, 256), (2048, 512))):
|
| 112 |
+
super().__init__()
|
| 113 |
+
self.networks = nn.ModuleList([PeriodDiscriminator(p) for p in periods]
|
| 114 |
+
+ [SpectrogramDiscriminator(fft, hop) for fft, hop in resolutions])
|
| 115 |
+
|
| 116 |
+
def forward(self, wave):
|
| 117 |
+
return [network(wave) for network in self.networks]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def discriminator_loss(real, fake):
|
| 121 |
+
return sum((r-1).square().mean() + f.square().mean()
|
| 122 |
+
for (r, _), (f, _) in zip(real, fake)) / len(real)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def generator_gan_loss(real, fake):
|
| 126 |
+
adversarial = sum((f-1).square().mean() for f, _ in fake) / len(fake)
|
| 127 |
+
matching = sum(F.l1_loss(f, r.detach())
|
| 128 |
+
for (_, rs), (_, fs) in zip(real, fake) for r, f in zip(rs, fs))
|
| 129 |
+
matching = matching / sum(len(fs) for _, fs in fake)
|
| 130 |
+
return adversarial, matching
|
code/src/lua_nova_v1/text/__init__.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Brazilian Portuguese text normalization and G2P phonemization."""
|
| 2 |
+
|
| 3 |
+
from .normalizer import normalize_ptbr_text
|
| 4 |
+
from .phonemizer import (
|
| 5 |
+
ABBREVIATIONS,
|
| 6 |
+
BOS,
|
| 7 |
+
EOS,
|
| 8 |
+
ESPEAK_VOICE,
|
| 9 |
+
FALLBACK,
|
| 10 |
+
FRONTEND_VARIABLE,
|
| 11 |
+
FRONTEND_VERSION,
|
| 12 |
+
FRONTENDS,
|
| 13 |
+
PAD,
|
| 14 |
+
PHONE_IDS,
|
| 15 |
+
PHONE_SET,
|
| 16 |
+
PHONES,
|
| 17 |
+
PUNCTUATION,
|
| 18 |
+
SP,
|
| 19 |
+
SYMBOL_TO_ID,
|
| 20 |
+
SYMBOLS,
|
| 21 |
+
UNK,
|
| 22 |
+
VOICELESS,
|
| 23 |
+
VOWEL_SET,
|
| 24 |
+
VOWELS,
|
| 25 |
+
NothingToPronounce,
|
| 26 |
+
Phonemized,
|
| 27 |
+
frontend,
|
| 28 |
+
frontend_fingerprint,
|
| 29 |
+
frontend_identity,
|
| 30 |
+
frontend_runtime,
|
| 31 |
+
is_phone,
|
| 32 |
+
phonemize,
|
| 33 |
+
phonemize_ptbr,
|
| 34 |
+
set_frontend,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
__all__ = [
|
| 38 |
+
"ABBREVIATIONS",
|
| 39 |
+
"BOS",
|
| 40 |
+
"EOS",
|
| 41 |
+
"ESPEAK_VOICE",
|
| 42 |
+
"FALLBACK",
|
| 43 |
+
"FRONTEND_VARIABLE",
|
| 44 |
+
"FRONTEND_VERSION",
|
| 45 |
+
"FRONTENDS",
|
| 46 |
+
"NothingToPronounce",
|
| 47 |
+
"PAD",
|
| 48 |
+
"PHONE_IDS",
|
| 49 |
+
"PHONE_SET",
|
| 50 |
+
"PHONES",
|
| 51 |
+
"PUNCTUATION",
|
| 52 |
+
"Phonemized",
|
| 53 |
+
"SP",
|
| 54 |
+
"SYMBOLS",
|
| 55 |
+
"SYMBOL_TO_ID",
|
| 56 |
+
"UNK",
|
| 57 |
+
"VOICELESS",
|
| 58 |
+
"VOWELS",
|
| 59 |
+
"VOWEL_SET",
|
| 60 |
+
"frontend",
|
| 61 |
+
"frontend_fingerprint",
|
| 62 |
+
"frontend_identity",
|
| 63 |
+
"frontend_runtime",
|
| 64 |
+
"is_phone",
|
| 65 |
+
"normalize_ptbr_text",
|
| 66 |
+
"phonemize",
|
| 67 |
+
"phonemize_ptbr",
|
| 68 |
+
"set_frontend",
|
| 69 |
+
]
|
code/src/lua_nova_v1/text/normalizer.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Normalizador de texto PT-BR (números, moedas, horários, datas, ordinais e abreviações).
|
| 2 |
+
|
| 3 |
+
Converte expressões numéricas e abreviações comuns do português brasileiro para
|
| 4 |
+
texto por extenso antes da fonemização com eSpeak, preservando a pontuação e a
|
| 5 |
+
estrutura de frases. Sem dependências externas.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import re
|
| 10 |
+
import unicodedata
|
| 11 |
+
|
| 12 |
+
_UNITS_M = [
|
| 13 |
+
"zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito",
|
| 14 |
+
"nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis",
|
| 15 |
+
"dezessete", "dezoito", "dezenove",
|
| 16 |
+
]
|
| 17 |
+
_UNITS_F = [
|
| 18 |
+
"zero", "uma", "duas", "três", "quatro", "cinco", "seis", "sete", "oito",
|
| 19 |
+
"nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis",
|
| 20 |
+
"dezessete", "dezoito", "dezenove",
|
| 21 |
+
]
|
| 22 |
+
_TENS = [
|
| 23 |
+
"", "dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta",
|
| 24 |
+
"setenta", "oitenta", "noventa",
|
| 25 |
+
]
|
| 26 |
+
_HUNDREDS_M = [
|
| 27 |
+
"", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos",
|
| 28 |
+
"seiscentos", "setecentos", "oitocentos", "novecentos",
|
| 29 |
+
]
|
| 30 |
+
_HUNDREDS_F = [
|
| 31 |
+
"", "cento", "duzentas", "trezentas", "quatrocentas", "quinhentas",
|
| 32 |
+
"seiscentas", "setecentas", "oitocentas", "novecentas",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
_ORD_UNITS = [
|
| 36 |
+
"", "primeir", "segund", "terceir", "quart", "quint",
|
| 37 |
+
"sext", "sétim", "oitav", "non",
|
| 38 |
+
]
|
| 39 |
+
_ORD_TENS = [
|
| 40 |
+
"", "décim", "vigésim", "trigésim", "quadragésim", "quinquagésim",
|
| 41 |
+
"sexagésim", "septuagésim", "octogésim", "nonagésim",
|
| 42 |
+
]
|
| 43 |
+
_ORD_HUNDREDS = [
|
| 44 |
+
"", "centésim", "ducentésim", "trecentésim", "quadringentésim",
|
| 45 |
+
"quingentésim", "sexcentésim", "septingentésim", "octingentésim",
|
| 46 |
+
"nongentésim",
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
_MONTHS = {
|
| 50 |
+
1: "janeiro", 2: "fevereiro", 3: "março", 4: "abril",
|
| 51 |
+
5: "maio", 6: "junho", 7: "julho", 8: "agosto",
|
| 52 |
+
9: "setembro", 10: "outubro", 11: "novembro", 12: "dezembro",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _under_1000(n: int, feminine: bool = False) -> str:
|
| 57 |
+
if n == 0:
|
| 58 |
+
return "zero"
|
| 59 |
+
if n == 100:
|
| 60 |
+
return "cem"
|
| 61 |
+
units = _UNITS_F if feminine else _UNITS_M
|
| 62 |
+
hundreds_tbl = _HUNDREDS_F if feminine else _HUNDREDS_M
|
| 63 |
+
parts = []
|
| 64 |
+
hundreds, rest = divmod(n, 100)
|
| 65 |
+
if hundreds:
|
| 66 |
+
parts.append(hundreds_tbl[hundreds])
|
| 67 |
+
if rest:
|
| 68 |
+
if rest < 20:
|
| 69 |
+
parts.append(units[rest])
|
| 70 |
+
else:
|
| 71 |
+
ten, unit = divmod(rest, 10)
|
| 72 |
+
parts.append(f"{_TENS[ten]} e {units[unit]}" if unit else _TENS[ten])
|
| 73 |
+
return " e ".join(parts)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def int_to_ptbr(n: int, feminine: bool = False) -> str:
|
| 77 |
+
"""Converte inteiro (-999_999_999..999_999_999) para extenso em PT-BR."""
|
| 78 |
+
if n < 0:
|
| 79 |
+
return f"menos {int_to_ptbr(-n, feminine=feminine)}"
|
| 80 |
+
if n < 1000:
|
| 81 |
+
return _under_1000(n, feminine=feminine)
|
| 82 |
+
if n < 1_000_000:
|
| 83 |
+
thousands, rest = divmod(n, 1000)
|
| 84 |
+
t_word = "mil" if thousands == 1 else f"{_under_1000(thousands, feminine=feminine)} mil"
|
| 85 |
+
if rest == 0:
|
| 86 |
+
return t_word
|
| 87 |
+
joiner = " e " if (rest < 100 or rest % 100 == 0) else " "
|
| 88 |
+
return t_word + joiner + _under_1000(rest, feminine=feminine)
|
| 89 |
+
if n < 1_000_000_000:
|
| 90 |
+
millions, rest = divmod(n, 1_000_000)
|
| 91 |
+
m_word = "um milhão" if millions == 1 else f"{_under_1000(millions, feminine=False)} milhões"
|
| 92 |
+
if rest == 0:
|
| 93 |
+
return m_word
|
| 94 |
+
if rest < 1000 and (rest < 100 or rest % 100 == 0):
|
| 95 |
+
return f"{m_word} e {_under_1000(rest, feminine=feminine)}"
|
| 96 |
+
return f"{m_word} {int_to_ptbr(rest, feminine=feminine)}"
|
| 97 |
+
return " ".join(_UNITS_M[int(ch)] for ch in str(n))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def ordinal_to_ptbr(n: int, feminine: bool = False) -> str:
|
| 101 |
+
"""Converte ordinal (1..999) para extenso em PT-BR."""
|
| 102 |
+
if n < 1 or n > 999:
|
| 103 |
+
return int_to_ptbr(n, feminine=feminine)
|
| 104 |
+
suf = "a" if feminine else "o"
|
| 105 |
+
h, rem = divmod(n, 100)
|
| 106 |
+
t, u = divmod(rem, 10)
|
| 107 |
+
parts = []
|
| 108 |
+
if h:
|
| 109 |
+
parts.append(_ORD_HUNDREDS[h] + suf)
|
| 110 |
+
if t:
|
| 111 |
+
parts.append(_ORD_TENS[t] + suf)
|
| 112 |
+
if u:
|
| 113 |
+
parts.append(_ORD_UNITS[u] + suf)
|
| 114 |
+
return " ".join(parts)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def decimal_to_ptbr(int_str: str, frac_str: str, feminine: bool = False) -> str:
|
| 118 |
+
whole = int_to_ptbr(int(int_str.replace(".", "")), feminine=feminine)
|
| 119 |
+
if frac_str.startswith("0") and len(frac_str) > 1:
|
| 120 |
+
frac = " ".join(_UNITS_M[int(d)] for d in frac_str)
|
| 121 |
+
else:
|
| 122 |
+
frac = int_to_ptbr(int(frac_str))
|
| 123 |
+
return f"{whole} vírgula {frac}"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
_CURRENCY_RE = re.compile(
|
| 127 |
+
r"R\$\s*(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d{1,2}))?(?![\d,])"
|
| 128 |
+
)
|
| 129 |
+
_PERCENT_RE = re.compile(
|
| 130 |
+
r"(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?\s*%"
|
| 131 |
+
)
|
| 132 |
+
_DATE_RE = re.compile(
|
| 133 |
+
r"\b([0-3]?\d)/([01]?\d)(?:/(\d{2,4}))?\b"
|
| 134 |
+
)
|
| 135 |
+
_TIME_H_RE = re.compile(
|
| 136 |
+
r"\b([01]?\d|2[0-3])\s*h(?:(\d{2}))?(?:min)?\b", re.IGNORECASE
|
| 137 |
+
)
|
| 138 |
+
_TIME_COLON_RE = re.compile(
|
| 139 |
+
r"\b([01]?\d|2[0-3]):([0-5]\d)\b"
|
| 140 |
+
)
|
| 141 |
+
_ORDINAL_RE = re.compile(
|
| 142 |
+
r"\b(\d{1,3})\s*([º°ª])\b"
|
| 143 |
+
)
|
| 144 |
+
_TEMP_RE = re.compile(
|
| 145 |
+
r"(-?\d+)(?:,(\d+))?\s*°\s*C\b"
|
| 146 |
+
)
|
| 147 |
+
_UNIT_RE = re.compile(
|
| 148 |
+
r"\b(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?\s*(kHz|Hz|km|kg|cm|mm|mL|ml|GB|MB|KB)\b"
|
| 149 |
+
)
|
| 150 |
+
_THOUSANDS_RE = re.compile(
|
| 151 |
+
r"\b(\d{1,3}(?:\.\d{3})+)(?:,(\d+))?\b"
|
| 152 |
+
)
|
| 153 |
+
_DECIMAL_RE = re.compile(
|
| 154 |
+
r"\b(\d+),(\d+)\b"
|
| 155 |
+
)
|
| 156 |
+
_INT_RE = re.compile(
|
| 157 |
+
r"\b(\d+)\b"
|
| 158 |
+
)
|
| 159 |
+
_ABBREV_RULES = [
|
| 160 |
+
(re.compile(r"\bDra\.", re.IGNORECASE), "doutora"),
|
| 161 |
+
(re.compile(r"\bDr\.", re.IGNORECASE), "doutor"),
|
| 162 |
+
(re.compile(r"\bSrta\.", re.IGNORECASE), "senhorita"),
|
| 163 |
+
(re.compile(r"\bSra\.", re.IGNORECASE), "senhora"),
|
| 164 |
+
(re.compile(r"\bSr\.", re.IGNORECASE), "senhor"),
|
| 165 |
+
(re.compile(r"\bProfa\.", re.IGNORECASE), "professora"),
|
| 166 |
+
(re.compile(r"\bProf\.", re.IGNORECASE), "professor"),
|
| 167 |
+
(re.compile(r"\betc\.", re.IGNORECASE), "etcétera"),
|
| 168 |
+
]
|
| 169 |
+
_ACRONYM_MAP = {
|
| 170 |
+
"CPU": "cê pê u",
|
| 171 |
+
"GPU": "gê pê u",
|
| 172 |
+
"API": "a pê i",
|
| 173 |
+
"URL": "u érre éle",
|
| 174 |
+
"ONNX": "ônics",
|
| 175 |
+
"JSON": "jeizon",
|
| 176 |
+
"PDF": "pê dê éfe",
|
| 177 |
+
"TTS": "tê tê ésse",
|
| 178 |
+
"IA": "i a",
|
| 179 |
+
"RAM": "rã",
|
| 180 |
+
"SSD": "ésse ésse dê",
|
| 181 |
+
"USB": "u ésse bê",
|
| 182 |
+
"SQL": "ésse quê éle",
|
| 183 |
+
"HTTP": "agá tê tê pê",
|
| 184 |
+
"HTTPS": "agá tê tê pê ésse",
|
| 185 |
+
"HTML": "agá tê eme éle",
|
| 186 |
+
"RGB": "érre gê bê",
|
| 187 |
+
"CPF": "cê pê éfe",
|
| 188 |
+
"CNPJ": "cê ene pê jóta",
|
| 189 |
+
"CEP": "cépi",
|
| 190 |
+
"RG": "érre gê",
|
| 191 |
+
"IBGE": "i bê gê é",
|
| 192 |
+
"LLM": "éle éle eme",
|
| 193 |
+
"GPT": "gê pê tê",
|
| 194 |
+
"CSV": "cê ésse vê",
|
| 195 |
+
"CLI": "cê éle i",
|
| 196 |
+
"WAV": "uávi",
|
| 197 |
+
"PIX": "pics",
|
| 198 |
+
}
|
| 199 |
+
_ACRONYM_RE = re.compile(
|
| 200 |
+
r"(?<![A-Za-zÀ-ÿ])(?:"
|
| 201 |
+
+ "|".join(re.escape(k) for k in sorted(_ACRONYM_MAP, key=len, reverse=True))
|
| 202 |
+
+ r")(?![A-Za-zÀ-ÿ])"
|
| 203 |
+
)
|
| 204 |
+
_LOANWORD_RULES = [
|
| 205 |
+
(re.compile(r"(?<![A-Za-zÀ-ÿ])wi-?fi(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uái-fái"),
|
| 206 |
+
(re.compile(r"(?<![A-Za-zÀ-ÿ])bluetooth(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "blutuf"),
|
| 207 |
+
(re.compile(r"(?<![A-Za-zÀ-ÿ])python(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "páiton"),
|
| 208 |
+
(re.compile(r"(?<![A-Za-zÀ-ÿ])youtube(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "iutúbi"),
|
| 209 |
+
(re.compile(r"(?<![A-Za-zÀ-ÿ])whatsapp(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uátsápi"),
|
| 210 |
+
(re.compile(r"(?<![A-Za-zÀ-ÿ])windows(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uíndous"),
|
| 211 |
+
]
|
| 212 |
+
_SEDE_RE = re.compile(
|
| 213 |
+
r"\b(a|na|da|pela|essa|esta|sua|nossa|nova)\s+(sede)\s+"
|
| 214 |
+
r"(da|do|de|dos|das|central|principal|própria|nova|antiga|nacional|regional|local|social|administrativa)\b",
|
| 215 |
+
re.IGNORECASE,
|
| 216 |
+
)
|
| 217 |
+
_VERB_OPEN_O_RE = re.compile(
|
| 218 |
+
r"\b(não|sempre|nunca|já|ainda|também|hoje|amanhã|quando|se|só)\s+(almoço|começo)\b",
|
| 219 |
+
re.IGNORECASE,
|
| 220 |
+
)
|
| 221 |
+
_HOMOGRAPH_RULES = [
|
| 222 |
+
(_SEDE_RE, lambda m: f"{m.group(1)} {'Séde' if m.group(2)[0].isupper() else 'séde'} {m.group(3)}"),
|
| 223 |
+
(
|
| 224 |
+
_VERB_OPEN_O_RE,
|
| 225 |
+
lambda m: f"{m.group(1)} {'Almóço' if m.group(2) == 'Almoço' else 'almóço' if m.group(2).lower() == 'almoço' else 'Coméço' if m.group(2)[0].isupper() else 'coméço'}",
|
| 226 |
+
),
|
| 227 |
+
]
|
| 228 |
+
_UNIT_NAMES = {
|
| 229 |
+
"kHz": ("quilohertz", "quilohertz", False),
|
| 230 |
+
"Hz": ("hertz", "hertz", False),
|
| 231 |
+
"km": ("quilômetro", "quilômetros", False),
|
| 232 |
+
"kg": ("quilo", "quilos", False),
|
| 233 |
+
"cm": ("centímetro", "centímetros", False),
|
| 234 |
+
"mm": ("milímetro", "milímetros", False),
|
| 235 |
+
"mL": ("mililitro", "mililitros", False),
|
| 236 |
+
"ml": ("mililitro", "mililitros", False),
|
| 237 |
+
"GB": ("gigabyte", "gigabytes", False),
|
| 238 |
+
"MB": ("megabyte", "megabytes", False),
|
| 239 |
+
"KB": ("quilobyte", "quilobytes", False),
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _rep_currency(m: re.Match) -> str:
|
| 244 |
+
reais = int(m.group(1).replace(".", ""))
|
| 245 |
+
cents_raw = m.group(2)
|
| 246 |
+
cents = int(cents_raw.ljust(2, "0")) if cents_raw else 0
|
| 247 |
+
parts = []
|
| 248 |
+
if reais > 0 or cents == 0:
|
| 249 |
+
unit = "real" if reais == 1 else "reais"
|
| 250 |
+
parts.append(f"{int_to_ptbr(reais)} {unit}")
|
| 251 |
+
if cents > 0:
|
| 252 |
+
c_unit = "centavo" if cents == 1 else "centavos"
|
| 253 |
+
parts.append(f"{int_to_ptbr(cents)} {c_unit}")
|
| 254 |
+
return " e ".join(parts)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _rep_percent(m: re.Match) -> str:
|
| 258 |
+
if m.group(2):
|
| 259 |
+
return f"{decimal_to_ptbr(m.group(1), m.group(2))} por cento"
|
| 260 |
+
return f"{int_to_ptbr(int(m.group(1).replace('.', '')))} por cento"
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _rep_date(m: re.Match) -> str:
|
| 264 |
+
day, month = int(m.group(1)), int(m.group(2))
|
| 265 |
+
if not (1 <= day <= 31 and 1 <= month <= 12):
|
| 266 |
+
return m.group(0)
|
| 267 |
+
day_word = "primeiro" if day == 1 else int_to_ptbr(day)
|
| 268 |
+
out = f"{day_word} de {_MONTHS[month]}"
|
| 269 |
+
if m.group(3):
|
| 270 |
+
year = int(m.group(3))
|
| 271 |
+
if len(m.group(3)) == 2:
|
| 272 |
+
year += 2000 if year < 50 else 1900
|
| 273 |
+
out += f" de {int_to_ptbr(year)}"
|
| 274 |
+
return out
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def _format_time(hour: int, minute: int) -> str:
|
| 278 |
+
h_word = int_to_ptbr(hour, feminine=True)
|
| 279 |
+
h_unit = "hora" if hour == 1 else "horas"
|
| 280 |
+
if minute == 0:
|
| 281 |
+
return f"{h_word} {h_unit}"
|
| 282 |
+
m_unit = "minuto" if minute == 1 else "minutos"
|
| 283 |
+
return f"{h_word} {h_unit} e {int_to_ptbr(minute)} {m_unit}"
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _rep_time_h(m: re.Match) -> str:
|
| 287 |
+
hour = int(m.group(1))
|
| 288 |
+
minute = int(m.group(2)) if m.group(2) else 0
|
| 289 |
+
return _format_time(hour, minute)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def _rep_time_colon(m: re.Match) -> str:
|
| 293 |
+
return _format_time(int(m.group(1)), int(m.group(2)))
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _rep_ordinal(m: re.Match) -> str:
|
| 297 |
+
return ordinal_to_ptbr(int(m.group(1)), feminine=(m.group(2) == "ª"))
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _rep_temp(m: re.Match) -> str:
|
| 301 |
+
val_str = m.group(1)
|
| 302 |
+
neg = val_str.startswith("-")
|
| 303 |
+
num = abs(int(val_str))
|
| 304 |
+
prefix = "menos " if neg else ""
|
| 305 |
+
if m.group(2):
|
| 306 |
+
return f"{prefix}{decimal_to_ptbr(str(num), m.group(2))} graus Celsius"
|
| 307 |
+
unit = "grau Celsius" if num == 1 else "graus Celsius"
|
| 308 |
+
return f"{prefix}{int_to_ptbr(num)} {unit}"
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _rep_unit(m: re.Match) -> str:
|
| 312 |
+
sing, plur, fem = _UNIT_NAMES[m.group(3)]
|
| 313 |
+
if m.group(2):
|
| 314 |
+
return f"{decimal_to_ptbr(m.group(1), m.group(2), feminine=fem)} {plur}"
|
| 315 |
+
val = int(m.group(1).replace(".", ""))
|
| 316 |
+
return f"{int_to_ptbr(val, feminine=fem)} {sing if val == 1 else plur}"
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def normalize_ptbr_text(text: str) -> str:
|
| 320 |
+
"""Expande moedas, porcentagens, datas, horários, ordinais, números e abreviações PT-BR."""
|
| 321 |
+
s = unicodedata.normalize("NFC", text)
|
| 322 |
+
s = _CURRENCY_RE.sub(_rep_currency, s)
|
| 323 |
+
s = _TEMP_RE.sub(_rep_temp, s)
|
| 324 |
+
s = _PERCENT_RE.sub(_rep_percent, s)
|
| 325 |
+
s = _DATE_RE.sub(_rep_date, s)
|
| 326 |
+
s = _TIME_COLON_RE.sub(_rep_time_colon, s)
|
| 327 |
+
s = _TIME_H_RE.sub(_rep_time_h, s)
|
| 328 |
+
s = _ORDINAL_RE.sub(_rep_ordinal, s)
|
| 329 |
+
s = _UNIT_RE.sub(_rep_unit, s)
|
| 330 |
+
s = _THOUSANDS_RE.sub(
|
| 331 |
+
lambda m: decimal_to_ptbr(m.group(1), m.group(2)) if m.group(2) else int_to_ptbr(int(m.group(1).replace(".", ""))),
|
| 332 |
+
s,
|
| 333 |
+
)
|
| 334 |
+
s = _DECIMAL_RE.sub(lambda m: decimal_to_ptbr(m.group(1), m.group(2)), s)
|
| 335 |
+
s = _INT_RE.sub(lambda m: int_to_ptbr(int(m.group(1))), s)
|
| 336 |
+
for pattern, repl in _ABBREV_RULES:
|
| 337 |
+
s = pattern.sub(repl, s)
|
| 338 |
+
for pattern, repl in _LOANWORD_RULES:
|
| 339 |
+
s = pattern.sub(repl, s)
|
| 340 |
+
s = _ACRONYM_RE.sub(lambda m: _ACRONYM_MAP[m.group(0)], s)
|
| 341 |
+
for pattern, repl in _HOMOGRAPH_RULES:
|
| 342 |
+
s = pattern.sub(repl, s)
|
| 343 |
+
return re.sub(r"[ \t]{2,}", " ", s).strip()
|
code/src/lua_nova_v1/text/phonemizer.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Brazilian Portuguese (PT-BR) front end: text -> phoneme tokens with a stress feature.
|
| 2 |
+
|
| 3 |
+
The same code runs during annotation, training-set preparation and inference,
|
| 4 |
+
so tokens can never drift between them.
|
| 5 |
+
|
| 6 |
+
* eSpeak NG (``pt-br``) is the default pronunciation source (``espeak``).
|
| 7 |
+
* A token is one eSpeak phoneme exactly as eSpeak segments it (``--sep``), for
|
| 8 |
+
example ``t``, ``ɐ̃``, ``ɐ̃ʊ̃`` or ``tʃ``. Every phone in ``PHONE_SET`` is also
|
| 9 |
+
present in ``facebook/wav2vec2-lv-60-espeak-cv-ft``'s vocabulary for CTC
|
| 10 |
+
forced alignment.
|
| 11 |
+
* Lexical stress is a parallel feature (0 none, 1 primary, 2 secondary), not a
|
| 12 |
+
token, so it never has to be given audio frames.
|
| 13 |
+
* Punctuation, word boundaries and the utterance edges are explicit tokens that
|
| 14 |
+
may last zero frames. They carry pauses when the recording has them.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
import hashlib
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import re
|
| 22 |
+
import shutil
|
| 23 |
+
import subprocess
|
| 24 |
+
import unicodedata
|
| 25 |
+
|
| 26 |
+
FRONTEND_VERSION = 3
|
| 27 |
+
ESPEAK_VOICE = "pt-br"
|
| 28 |
+
SEPARATOR = "_"
|
| 29 |
+
FRONTENDS = ("espeak", "own")
|
| 30 |
+
FRONTEND_VARIABLE = "LUA_NOVA_FRONTEND"
|
| 31 |
+
_frontend = os.environ.get(FRONTEND_VARIABLE, "espeak")
|
| 32 |
+
if _frontend not in FRONTENDS:
|
| 33 |
+
raise ValueError(f"{FRONTEND_VARIABLE} must be one of {FRONTENDS}, not {_frontend!r}")
|
| 34 |
+
|
| 35 |
+
PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"
|
| 36 |
+
SPECIALS = (PAD, BOS, EOS, SP, UNK)
|
| 37 |
+
PUNCTUATION = (",", ".", "?", "!", ";", ":", '"', "'", "(", ")", "-", "—", "…")
|
| 38 |
+
CONSONANTS = (
|
| 39 |
+
"p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h",
|
| 40 |
+
"x", "ɣ", "m", "n", "ɲ", "ŋ", "l", "ʎ", "ɾ", "r", "ʁ", "j", "w", "tʃ", "dʒ", "ts",
|
| 41 |
+
)
|
| 42 |
+
VOWELS = (
|
| 43 |
+
"a", "ɐ", "æ", "e", "ɛ", "ə", "i", "ɪ", "y", "o", "ɔ", "u", "ʊ",
|
| 44 |
+
"aː", "eː", "iː", "oː", "uː",
|
| 45 |
+
"\u0250\u0303", "a\u0303", "e\u0303", "i\u0303", "o\u0303", "u\u0303", "\u0250\u0303\u028a\u0303",
|
| 46 |
+
"aɪ", "aʊ", "eɪ", "eʊ", "ɛɪ", "ɛʊ", "iʊ", "oɪ", "oʊ", "ɔɪ", "uɪ",
|
| 47 |
+
)
|
| 48 |
+
PHONES = CONSONANTS + VOWELS
|
| 49 |
+
# Append-only: changing the order or removing a symbol invalidates checkpoints.
|
| 50 |
+
SYMBOLS = SPECIALS + PUNCTUATION + PHONES
|
| 51 |
+
SYMBOLS_PTBR = list(SYMBOLS)
|
| 52 |
+
SYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}
|
| 53 |
+
PHONE_SET = frozenset(PHONES)
|
| 54 |
+
PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}
|
| 55 |
+
VOICELESS = frozenset(("p", "t", "k", "f", "θ", "s", "ʃ", "h", "x", "tʃ", "ts"))
|
| 56 |
+
VOWEL_SET = frozenset(VOWELS)
|
| 57 |
+
STRESS_MARKS = {"ˈ": 1, "ˌ": 2}
|
| 58 |
+
|
| 59 |
+
# eSpeak phonemes outside the inventory (foreign words, rare allophones, NFC nasals)
|
| 60 |
+
# map to the closest inventory phone(s). Anything else becomes <unk> and is reported.
|
| 61 |
+
FALLBACK = {
|
| 62 |
+
"g": ("ɡ",),
|
| 63 |
+
"\u00e3": ("\u0250\u0303",),
|
| 64 |
+
"\u1ebd": ("e\u0303",),
|
| 65 |
+
"\u0129": ("i\u0303",),
|
| 66 |
+
"\u00f5": ("o\u0303",),
|
| 67 |
+
"\u0169": ("u\u0303",),
|
| 68 |
+
"j\u0303": ("j",),
|
| 69 |
+
"w\u0303": ("w",),
|
| 70 |
+
"ɹ": ("ɾ",),
|
| 71 |
+
"ʔ": ("h",),
|
| 72 |
+
"ɻ": ("ɾ",),
|
| 73 |
+
"ç": ("ʃ",),
|
| 74 |
+
"ɬ": ("l",),
|
| 75 |
+
"ɫ": ("l",),
|
| 76 |
+
"dz": ("d", "z"),
|
| 77 |
+
"β": ("v",),
|
| 78 |
+
"ɑ": ("a",),
|
| 79 |
+
"ɑː": ("aː",),
|
| 80 |
+
"ɒ": ("ɔ",),
|
| 81 |
+
"ɑ\u0303": ("\u0250\u0303",),
|
| 82 |
+
"ɔ\u0303": ("o\u0303",),
|
| 83 |
+
"ɛ\u0303": ("e\u0303",),
|
| 84 |
+
"ʌ": ("ɐ",),
|
| 85 |
+
"ɚ": ("ə", "ɾ"),
|
| 86 |
+
"ᵻ": ("i",),
|
| 87 |
+
"ɜ": ("ɛ",),
|
| 88 |
+
"ɜː": ("ɛ",),
|
| 89 |
+
"ø": ("e",),
|
| 90 |
+
"øː": ("eː",),
|
| 91 |
+
"œ": ("ɛ",),
|
| 92 |
+
"ɛː": ("ɛ",),
|
| 93 |
+
"ɪː": ("iː",),
|
| 94 |
+
"ɔː": ("ɔ",),
|
| 95 |
+
"ʊː": ("uː",),
|
| 96 |
+
"yː": ("y",),
|
| 97 |
+
"əʊ": ("oʊ",),
|
| 98 |
+
"əl": ("ə", "l"),
|
| 99 |
+
"n̩": ("n",),
|
| 100 |
+
"l̩": ("l",),
|
| 101 |
+
"m̩": ("m",),
|
| 102 |
+
"iə": ("i", "ə"),
|
| 103 |
+
"aɪə": ("aɪ", "ə"),
|
| 104 |
+
"aʊɚ": ("aʊ", "ə", "ɾ"),
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
_QUOTES = str.maketrans({"‘": "'", "’": "'", "‚": "'", "‛": "'", "`": "'", "´": "'",
|
| 108 |
+
"“": '"', "”": '"', "„": '"', "‟": '"', "«": '"', "»": '"',
|
| 109 |
+
"–": "—", "―": "—", "[": "(", "{": "(", "]": ")", "}": ")"})
|
| 110 |
+
_PUNCTUATION_CHARS = frozenset(PUNCTUATION)
|
| 111 |
+
ABBREVIATIONS = {
|
| 112 |
+
"dr", "dra", "sr", "sra", "srta", "prof", "profa", "jr", "st", "sto", "sta",
|
| 113 |
+
"vs", "etc", "pág", "cap", "fig", "art", "inc", "ltda",
|
| 114 |
+
}
|
| 115 |
+
_LANGUAGE_TAG = re.compile(r"\((?:_?[a-z0-9]_?){2,3}(?:-(?:_?[a-z0-9]_?)+)*\)")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class NothingToPronounce(ValueError):
|
| 119 |
+
"""The text has no word, number or letter to say: only marks, emoji and the like."""
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass(frozen=True)
|
| 123 |
+
class Phonemized:
|
| 124 |
+
symbols: tuple
|
| 125 |
+
ids: tuple
|
| 126 |
+
stress: tuple
|
| 127 |
+
unknown: tuple # eSpeak phonemes that had no inventory mapping
|
| 128 |
+
|
| 129 |
+
def __len__(self):
|
| 130 |
+
return len(self.ids)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def frontend():
|
| 134 |
+
"""Name of the program that produces the phonemes: ``"espeak"`` or ``"own"``."""
|
| 135 |
+
return _frontend
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def set_frontend(name):
|
| 139 |
+
"""Select the phonemizer for this process. Tokens of the two front ends
|
| 140 |
+
must not be mixed: annotations and checkpoints record which one made them."""
|
| 141 |
+
global _frontend
|
| 142 |
+
if name not in FRONTENDS:
|
| 143 |
+
raise ValueError(f"front end must be one of {FRONTENDS}, not {name!r}")
|
| 144 |
+
_frontend = name
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _dizione():
|
| 148 |
+
try:
|
| 149 |
+
import dizione
|
| 150 |
+
except ImportError as error:
|
| 151 |
+
raise RuntimeError('the "own" front end needs the dizione package: pip install dizione') from error
|
| 152 |
+
if tuple(dizione.symbols.SYMBOLS) != SYMBOLS:
|
| 153 |
+
raise RuntimeError("dizione's symbol inventory differs from this model's")
|
| 154 |
+
return dizione
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def frontend_identity():
|
| 158 |
+
if _frontend == "own":
|
| 159 |
+
phonemizer = _dizione()
|
| 160 |
+
return {"frontend_version": phonemizer.VERSION, "phonemizer": "dizione", "symbols": list(SYMBOLS)}
|
| 161 |
+
return {"frontend_version": FRONTEND_VERSION, "voice": ESPEAK_VOICE, "separator": SEPARATOR,
|
| 162 |
+
"symbols": list(SYMBOLS), "fallback": {key: list(value) for key, value in sorted(FALLBACK.items())}}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def frontend_runtime():
|
| 166 |
+
"""What an annotation run records about the exact program behind its
|
| 167 |
+
tokens: the eSpeak version, or the fingerprint of the phonemizer build."""
|
| 168 |
+
if _frontend == "own":
|
| 169 |
+
return {"phonemizer": _dizione().identity()["fingerprint"]}
|
| 170 |
+
return {"espeak_version": espeak_version()}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def frontend_fingerprint():
|
| 174 |
+
return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def normalize_text(text):
|
| 178 |
+
text = unicodedata.normalize("NFKC", text).translate(_QUOTES)
|
| 179 |
+
text = re.sub(r"\.{3,}", "…", text)
|
| 180 |
+
text = re.sub(r"-{2,}|\s-\s", "—", text)
|
| 181 |
+
return re.sub(r"\s+", " ", text).strip()
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def chunks(text):
|
| 185 |
+
"""Yield ``(is_punctuation, piece)``. Decimals, clock times, digit groups,
|
| 186 |
+
hyphenated words, contractions, title abbreviations and initialisms stay
|
| 187 |
+
inside the text piece for eSpeak; every other punctuation mark becomes its
|
| 188 |
+
own token."""
|
| 189 |
+
start = 0
|
| 190 |
+
for i, char in enumerate(text):
|
| 191 |
+
if char not in _PUNCTUATION_CHARS:
|
| 192 |
+
continue
|
| 193 |
+
previous = text[i-1] if i else ""
|
| 194 |
+
following = text[i+1] if i+1 < len(text) else ""
|
| 195 |
+
if char == "'" and previous.isalnum() and following.isalnum():
|
| 196 |
+
continue
|
| 197 |
+
if char == "-" and previous.isalpha() and following.isalpha():
|
| 198 |
+
continue
|
| 199 |
+
if char in ".,:" and previous.isdigit() and following.isdigit():
|
| 200 |
+
continue
|
| 201 |
+
if char == ".":
|
| 202 |
+
word = re.search(r"([^\W\d_]+)$", text[:i])
|
| 203 |
+
if word and word[1].lower() in ABBREVIATIONS:
|
| 204 |
+
continue
|
| 205 |
+
if previous.isalpha() and following.isalpha():
|
| 206 |
+
continue
|
| 207 |
+
if text[start:i].strip():
|
| 208 |
+
yield False, text[start:i].strip()
|
| 209 |
+
yield True, char
|
| 210 |
+
start = i+1
|
| 211 |
+
if text[start:].strip():
|
| 212 |
+
yield False, text[start:].strip()
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def espeak_executable():
|
| 216 |
+
executable = shutil.which("espeak-ng")
|
| 217 |
+
if executable is None:
|
| 218 |
+
raise RuntimeError("Install espeak-ng and ensure it is on PATH before preprocessing/inference")
|
| 219 |
+
return executable
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def espeak_version():
|
| 223 |
+
return subprocess.run(
|
| 224 |
+
[espeak_executable(), "--version"],
|
| 225 |
+
capture_output=True, text=True, encoding="utf-8", check=True, timeout=10,
|
| 226 |
+
).stdout.strip()
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def espeak_words(piece):
|
| 230 |
+
"""Phonemize one text piece. Returns words as lists of ``(phone, stress)``.
|
| 231 |
+
|
| 232 |
+
The input must end with a newline: eSpeak NG 1.51 silently drops the last
|
| 233 |
+
character of unterminated standard input.
|
| 234 |
+
"""
|
| 235 |
+
result = subprocess.run(
|
| 236 |
+
[espeak_executable(), "-q", "--ipa", "--sep=" + SEPARATOR, "-v", ESPEAK_VOICE, "--stdin"],
|
| 237 |
+
input=piece.rstrip("\n") + "\n", text=True, encoding="utf-8", capture_output=True, check=True, timeout=30)
|
| 238 |
+
return parse_espeak(result.stdout)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def parse_espeak(output):
|
| 242 |
+
words = []
|
| 243 |
+
for word in _LANGUAGE_TAG.sub("", output).split():
|
| 244 |
+
units = []
|
| 245 |
+
for unit in word.split(SEPARATOR):
|
| 246 |
+
stress = 0
|
| 247 |
+
for mark, level in STRESS_MARKS.items():
|
| 248 |
+
if mark in unit:
|
| 249 |
+
stress = stress or level
|
| 250 |
+
unit = unit.replace(mark, "")
|
| 251 |
+
unit = "".join(c for c in unit if unicodedata.category(c) != "Cf" and c not in "()")
|
| 252 |
+
if unit:
|
| 253 |
+
units.append((unit, stress))
|
| 254 |
+
if units:
|
| 255 |
+
words.append(units)
|
| 256 |
+
return words
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def canonical(phone):
|
| 260 |
+
"""Map an eSpeak phoneme to inventory phones; ``None`` when unknown."""
|
| 261 |
+
if phone in PHONE_SET:
|
| 262 |
+
return (phone,)
|
| 263 |
+
if phone in FALLBACK:
|
| 264 |
+
return FALLBACK[phone]
|
| 265 |
+
for candidate in (unicodedata.normalize("NFD", phone), phone.replace("ː", ""), unicodedata.normalize("NFD", phone).replace("ː", "")):
|
| 266 |
+
if candidate != phone and candidate in PHONE_SET:
|
| 267 |
+
return (candidate,)
|
| 268 |
+
if candidate != phone and candidate in FALLBACK:
|
| 269 |
+
return FALLBACK[candidate]
|
| 270 |
+
stripped = "".join(c for c in unicodedata.normalize("NFD", phone) if not unicodedata.combining(c))
|
| 271 |
+
for candidate in (stripped, stripped.replace("ː", ""), stripped + "ː"):
|
| 272 |
+
if candidate != phone and candidate in PHONE_SET:
|
| 273 |
+
return (candidate,)
|
| 274 |
+
if candidate != phone and candidate in FALLBACK:
|
| 275 |
+
return FALLBACK[candidate]
|
| 276 |
+
# Decompose novel compound diphthongs/affricates into base+combining units.
|
| 277 |
+
parts = []
|
| 278 |
+
for ch in phone.replace("ː", ""):
|
| 279 |
+
if unicodedata.combining(ch) and parts:
|
| 280 |
+
parts[-1] += ch
|
| 281 |
+
else:
|
| 282 |
+
parts.append(ch)
|
| 283 |
+
if len(parts) > 1:
|
| 284 |
+
resolved = []
|
| 285 |
+
for part in parts:
|
| 286 |
+
if part in PHONE_SET:
|
| 287 |
+
resolved.append(part)
|
| 288 |
+
elif part in FALLBACK:
|
| 289 |
+
resolved.extend(FALLBACK[part])
|
| 290 |
+
else:
|
| 291 |
+
return None
|
| 292 |
+
return tuple(resolved)
|
| 293 |
+
return None
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def tokenize(pieces):
|
| 297 |
+
"""Build the token sequence from ``(is_punctuation, value)`` pieces where a
|
| 298 |
+
text piece's value is the parsed eSpeak word list. Pure function (testable
|
| 299 |
+
without eSpeak)."""
|
| 300 |
+
symbols, stress, unknown = [BOS], [0], []
|
| 301 |
+
for punctuation, value in pieces:
|
| 302 |
+
if punctuation:
|
| 303 |
+
if symbols[-1] != value: # collapse repeats such as "!!"
|
| 304 |
+
symbols.append(value)
|
| 305 |
+
stress.append(0)
|
| 306 |
+
continue
|
| 307 |
+
for word in value:
|
| 308 |
+
if symbols[-1] in PHONE_SET or symbols[-1] == UNK:
|
| 309 |
+
symbols.append(SP)
|
| 310 |
+
stress.append(0)
|
| 311 |
+
for phone, level in word:
|
| 312 |
+
mapped = canonical(phone)
|
| 313 |
+
if mapped is None:
|
| 314 |
+
unknown.append(phone)
|
| 315 |
+
mapped = (UNK,)
|
| 316 |
+
# A fallback may expand to several phones: stress goes to its first vowel.
|
| 317 |
+
carrier = next((i for i, item in enumerate(mapped) if item in VOWEL_SET), 0)
|
| 318 |
+
for index, item in enumerate(mapped):
|
| 319 |
+
symbols.append(item)
|
| 320 |
+
stress.append(level if index == carrier else 0)
|
| 321 |
+
symbols.append(EOS)
|
| 322 |
+
stress.append(0)
|
| 323 |
+
if not any(s in PHONE_SET or s == UNK for s in symbols):
|
| 324 |
+
raise NothingToPronounce("the text has nothing to pronounce")
|
| 325 |
+
return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown))
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def phonemize(text):
|
| 329 |
+
if not isinstance(text, str) or not text.strip():
|
| 330 |
+
raise ValueError("text must not be empty")
|
| 331 |
+
if _frontend == "own":
|
| 332 |
+
return tokenize(_dizione().pieces(text))
|
| 333 |
+
pieces = []
|
| 334 |
+
for punctuation, piece in chunks(normalize_text(text)):
|
| 335 |
+
pieces.append((True, piece) if punctuation else (False, espeak_words(piece)))
|
| 336 |
+
return tokenize(pieces)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def phonemize_ptbr(text: str) -> tuple[list[int], list[int]]:
|
| 340 |
+
"""Return ``(ids, stress)`` lists for Brazilian Portuguese text."""
|
| 341 |
+
result = phonemize(text)
|
| 342 |
+
return list(result.ids), list(result.stress)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def is_phone(token_ids):
|
| 346 |
+
"""Boolean list/tensor helper: tokens that must be realised as audio."""
|
| 347 |
+
return [int(i) in PHONE_IDS for i in token_ids]
|
code/src/lua_nova_v1/training/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training pipelines for Lua Nova V1 (Stage 1, ProsodyFlow, CFM v5, Option A E2E, Option B Vocoder)."""
|
| 2 |
+
|
| 3 |
+
from .common import (
|
| 4 |
+
VALIDATION_SAMPLE_TEXTS,
|
| 5 |
+
atomic_save,
|
| 6 |
+
balanced_indices,
|
| 7 |
+
cfm_loss_step,
|
| 8 |
+
check_leakage,
|
| 9 |
+
cosine_lr,
|
| 10 |
+
export_cfm_checkpoint,
|
| 11 |
+
load_cfm_model,
|
| 12 |
+
masked_std,
|
| 13 |
+
precompute_bigvgan_mels,
|
| 14 |
+
update_ema,
|
| 15 |
+
validate_cfm,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"VALIDATION_SAMPLE_TEXTS",
|
| 20 |
+
"atomic_save",
|
| 21 |
+
"balanced_indices",
|
| 22 |
+
"cfm_loss_step",
|
| 23 |
+
"check_leakage",
|
| 24 |
+
"cosine_lr",
|
| 25 |
+
"export_cfm_checkpoint",
|
| 26 |
+
"load_cfm_model",
|
| 27 |
+
"masked_std",
|
| 28 |
+
"precompute_bigvgan_mels",
|
| 29 |
+
"update_ema",
|
| 30 |
+
"validate_cfm",
|
| 31 |
+
]
|
code/src/lua_nova_v1/training/cfm.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train LuaNovaCFM in 24 kHz 100-band Slaney mel space for BigVGAN."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
import copy
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
from ..config import CFMConfig, Config
|
| 15 |
+
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
|
| 16 |
+
from ..models.bigvgan import BigVGANMelExtractor
|
| 17 |
+
from ..models.cfm import LuaNovaCFM
|
| 18 |
+
from .common import (
|
| 19 |
+
MelDatasetView,
|
| 20 |
+
atomic_save,
|
| 21 |
+
balanced_indices,
|
| 22 |
+
cfm_loss_step,
|
| 23 |
+
check_leakage,
|
| 24 |
+
cosine_lr,
|
| 25 |
+
export_cfm_checkpoint,
|
| 26 |
+
precompute_bigvgan_mels,
|
| 27 |
+
update_ema,
|
| 28 |
+
validate_cfm,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
_WARM_PREFIXES = (
|
| 32 |
+
"tokens.",
|
| 33 |
+
"stress.",
|
| 34 |
+
"voices.",
|
| 35 |
+
"encoder.",
|
| 36 |
+
"duration.",
|
| 37 |
+
"frame_voices.",
|
| 38 |
+
"frame_position.",
|
| 39 |
+
"prosody_stack.",
|
| 40 |
+
"prosody_head.",
|
| 41 |
+
"context_adapter.",
|
| 42 |
+
"frame_ctx_proj.",
|
| 43 |
+
"dur_flow.",
|
| 44 |
+
"prosody_flow.",
|
| 45 |
+
"acoustic_stack.",
|
| 46 |
+
"prosody_projection.",
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def main() -> None:
|
| 51 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 52 |
+
parser.add_argument("--train", type=Path, required=True)
|
| 53 |
+
parser.add_argument("--validation", type=Path, required=True)
|
| 54 |
+
parser.add_argument("--init-cfm", type=Path, default=None, help="Initial LuaNovaCFM checkpoint (ProsodyFlow or pretrained CFM)")
|
| 55 |
+
parser.add_argument("--init-frontend", type=Path, default=None, help="Optional Stage 1 checkpoint when starting without a CFM checkpoint")
|
| 56 |
+
parser.add_argument("--freeze-frontend", action=argparse.BooleanOptionalAction, default=True)
|
| 57 |
+
parser.add_argument("--resume", type=Path, default=None)
|
| 58 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 59 |
+
parser.add_argument("--device", default="cuda")
|
| 60 |
+
parser.add_argument("--steps", type=int, default=25000)
|
| 61 |
+
parser.add_argument("--stop-after", type=int, default=None)
|
| 62 |
+
parser.add_argument("--batch-frames", type=int, default=6000)
|
| 63 |
+
parser.add_argument("--max-batch", type=int, default=24)
|
| 64 |
+
parser.add_argument("--lr", type=float, default=3e-4)
|
| 65 |
+
parser.add_argument("--min-lr", type=float, default=1.5e-5)
|
| 66 |
+
parser.add_argument("--warmup", type=int, default=500)
|
| 67 |
+
parser.add_argument("--ema-decay", type=float, default=0.999)
|
| 68 |
+
parser.add_argument("--prior-weight", type=float, default=0.8)
|
| 69 |
+
parser.add_argument("--delta-weight", type=float, default=1.0)
|
| 70 |
+
parser.add_argument("--freq-delta-weight", type=float, default=0.50)
|
| 71 |
+
parser.add_argument("--hf-boost", type=float, default=1.40)
|
| 72 |
+
parser.add_argument("--teacher-prob", type=float, default=0.35)
|
| 73 |
+
parser.add_argument("--f0-smooth-prob", type=float, default=0.15)
|
| 74 |
+
parser.add_argument("--save-every", type=int, default=5000)
|
| 75 |
+
parser.add_argument("--val-every", type=int, default=1000)
|
| 76 |
+
parser.add_argument("--log-every", type=int, default=100)
|
| 77 |
+
parser.add_argument("--seed", type=int, default=20261121)
|
| 78 |
+
args = parser.parse_args()
|
| 79 |
+
|
| 80 |
+
if args.init_cfm is None and args.init_frontend is None:
|
| 81 |
+
parser.error("provide --init-cfm or --init-frontend")
|
| 82 |
+
|
| 83 |
+
torch.manual_seed(args.seed)
|
| 84 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 85 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 86 |
+
|
| 87 |
+
src_ckpt = torch.load(args.init_cfm or args.init_frontend, map_location="cpu", weights_only=True)
|
| 88 |
+
if args.init_cfm is not None:
|
| 89 |
+
cfg_dict = dict(src_ckpt["cfm_config"])
|
| 90 |
+
else:
|
| 91 |
+
cfg_dict = {"base": dict(src_ckpt["config"]), "acoustic_from_frames": True, "use_energy_gate": True}
|
| 92 |
+
cfg_dict.update(
|
| 93 |
+
{
|
| 94 |
+
"flow_channels": 320,
|
| 95 |
+
"flow_layers": 8,
|
| 96 |
+
"flow_heads": 8,
|
| 97 |
+
"flow_feedforward": 1024,
|
| 98 |
+
"flow_kernel": 5,
|
| 99 |
+
"flow_dropout": 0.05,
|
| 100 |
+
"prior_sigma": 0.45,
|
| 101 |
+
"cfg_dropout": 0.10,
|
| 102 |
+
"default_pitch_range": 1.05,
|
| 103 |
+
"mel_space": "bigvgan_24k_100",
|
| 104 |
+
}
|
| 105 |
+
)
|
| 106 |
+
cfm_cfg = CFMConfig.from_dict(cfg_dict)
|
| 107 |
+
base_cfg = cfm_cfg.base
|
| 108 |
+
|
| 109 |
+
train_ds = AnnotatedDataset(args.train, base_cfg, voiced_vowels=True, cache=True)
|
| 110 |
+
val_ds = AnnotatedDataset(args.validation, base_cfg, voiced_vowels=True, cache=True)
|
| 111 |
+
check_leakage(train_ds, val_ds)
|
| 112 |
+
pool = list(range(len(train_ds)))
|
| 113 |
+
val_indices = balanced_indices(val_ds, len(val_ds))
|
| 114 |
+
print(f"Preloading train ({len(pool)}) and validation ({len(val_indices)}) ...", flush=True)
|
| 115 |
+
train_ds.preload(pool, workers=8)
|
| 116 |
+
val_ds.preload(val_indices, workers=4)
|
| 117 |
+
|
| 118 |
+
t_mel = time.perf_counter()
|
| 119 |
+
extractor = BigVGANMelExtractor().to(args.device).eval()
|
| 120 |
+
train_bg, bg_mean, bg_scale = precompute_bigvgan_mels(train_ds, pool, extractor, args.device, compute_stats=True)
|
| 121 |
+
val_bg, _, _ = precompute_bigvgan_mels(val_ds, val_indices, extractor, args.device, compute_stats=False)
|
| 122 |
+
del extractor
|
| 123 |
+
print(
|
| 124 |
+
f"Precomputed BigVGAN Slaney mels in {time.perf_counter() - t_mel:.2f}s | "
|
| 125 |
+
f"mean range=[{float(bg_mean.min()):.3f}, {float(bg_mean.max()):.3f}] "
|
| 126 |
+
f"scale range=[{float(bg_scale.min()):.3f}, {float(bg_scale.max()):.3f}]",
|
| 127 |
+
flush=True,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
model = LuaNovaCFM(cfm_cfg).to(args.device)
|
| 131 |
+
loaded = []
|
| 132 |
+
if args.init_cfm is not None:
|
| 133 |
+
own = dict(model.state_dict())
|
| 134 |
+
for k, v in src_ckpt["model"].items():
|
| 135 |
+
if (args.freeze_frontend and k.startswith(_WARM_PREFIXES) or not args.freeze_frontend) and k in own and own[k].shape == v.shape:
|
| 136 |
+
if not (k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale")):
|
| 137 |
+
own[k] = v.to(own[k].device)
|
| 138 |
+
loaded.append(k)
|
| 139 |
+
model.load_state_dict(own, strict=True)
|
| 140 |
+
if not any(k == "vocoder.mel_mean" for k in loaded) or float(model.vocoder.mel_scale.std()) < 1e-6:
|
| 141 |
+
model.vocoder.set_mel_stats(bg_mean, bg_scale)
|
| 142 |
+
else:
|
| 143 |
+
s1_sd = src_ckpt.get("system", src_ckpt.get("model"))
|
| 144 |
+
loaded = model.load_frontend(s1_sd)
|
| 145 |
+
model.vocoder.set_mel_stats(bg_mean, bg_scale)
|
| 146 |
+
|
| 147 |
+
if str(src_ckpt.get("cfm_config", {}).get("mel_space")) != "bigvgan_24k_100":
|
| 148 |
+
model.vocoder.set_mel_stats(bg_mean, bg_scale)
|
| 149 |
+
model.freeze_frontend(args.freeze_frontend)
|
| 150 |
+
for p in model.vocoder.parameters():
|
| 151 |
+
p.requires_grad_(False)
|
| 152 |
+
del src_ckpt
|
| 153 |
+
|
| 154 |
+
ema_model = copy.deepcopy(model).eval()
|
| 155 |
+
for p in ema_model.parameters():
|
| 156 |
+
p.requires_grad_(False)
|
| 157 |
+
|
| 158 |
+
trainable = [p for p in model.parameters() if p.requires_grad]
|
| 159 |
+
trainable_prefixes = sorted({n.split(".")[0] for n, p in model.named_parameters() if p.requires_grad})
|
| 160 |
+
print(
|
| 161 |
+
f"CFM v5 initialized ({len(loaded)} tensors) | trainable prefixes={trainable_prefixes} | "
|
| 162 |
+
f"trainable params={sum(p.numel() for p in trainable):,} / {sum(p.numel() for p in model.parameters()):,}",
|
| 163 |
+
flush=True,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
optimizer = torch.optim.AdamW(trainable, lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
|
| 167 |
+
sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
|
| 168 |
+
step = 0
|
| 169 |
+
|
| 170 |
+
if args.resume is not None and args.resume.exists():
|
| 171 |
+
rs = torch.load(args.resume, map_location=args.device, weights_only=True)
|
| 172 |
+
model.load_state_dict(rs["model"], strict=True)
|
| 173 |
+
ema_model.load_state_dict(rs["ema_model"], strict=True)
|
| 174 |
+
optimizer.load_state_dict(rs["optimizer"])
|
| 175 |
+
sampler.generator.set_state(rs["sampler_rng"].cpu())
|
| 176 |
+
sampler.pending = list(rs["sampler_pending"])
|
| 177 |
+
step = int(rs["step"])
|
| 178 |
+
print(f"Resumed CFM from step {step}", flush=True)
|
| 179 |
+
|
| 180 |
+
train_view = MelDatasetView(train_ds, train_bg)
|
| 181 |
+
val_view = MelDatasetView(val_ds, val_bg)
|
| 182 |
+
|
| 183 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 184 |
+
(args.output / "cfm_config.json").write_text(json.dumps(cfm_cfg.to_dict(), indent=2) + "\n", encoding="utf-8")
|
| 185 |
+
|
| 186 |
+
if step == 0:
|
| 187 |
+
v0 = validate_cfm(ema_model, val_view, val_indices, args.device, args.delta_weight, args.freq_delta_weight, args.hf_boost)
|
| 188 |
+
print(f"[step 0] {json.dumps(v0)}", flush=True)
|
| 189 |
+
|
| 190 |
+
target_stop = min(args.steps, args.stop_after) if args.stop_after is not None else args.steps
|
| 191 |
+
use_amp = str(args.device).startswith("cuda")
|
| 192 |
+
model.train()
|
| 193 |
+
win: dict[str, float] = defaultdict(float)
|
| 194 |
+
win_steps = 0
|
| 195 |
+
win_t = time.monotonic()
|
| 196 |
+
|
| 197 |
+
while step < target_stop:
|
| 198 |
+
lr = cosine_lr(step, args.warmup, args.steps, args.lr, min_lr=args.min_lr)
|
| 199 |
+
for pg in optimizer.param_groups:
|
| 200 |
+
pg["lr"] = lr
|
| 201 |
+
|
| 202 |
+
batch = collate([train_view[pool[i]] for i in sampler.next()], args.device)
|
| 203 |
+
optimizer.zero_grad(set_to_none=True)
|
| 204 |
+
with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=use_amp):
|
| 205 |
+
loss, m = cfm_loss_step(
|
| 206 |
+
model,
|
| 207 |
+
batch,
|
| 208 |
+
teacher_prob=args.teacher_prob,
|
| 209 |
+
prior_weight=args.prior_weight,
|
| 210 |
+
delta_weight=args.delta_weight,
|
| 211 |
+
freq_delta_weight=args.freq_delta_weight,
|
| 212 |
+
hf_boost=args.hf_boost,
|
| 213 |
+
f0_smooth_prob=args.f0_smooth_prob,
|
| 214 |
+
training=True,
|
| 215 |
+
)
|
| 216 |
+
loss_f = loss.float()
|
| 217 |
+
if not torch.isfinite(loss_f):
|
| 218 |
+
raise RuntimeError(f"Non-finite loss at step {step}: {loss_f}")
|
| 219 |
+
loss_f.backward()
|
| 220 |
+
grad_norm = float(nn.utils.clip_grad_norm_(trainable, 1.0))
|
| 221 |
+
optimizer.step()
|
| 222 |
+
update_ema(ema_model, model, args.ema_decay)
|
| 223 |
+
|
| 224 |
+
step += 1
|
| 225 |
+
for k, v in m.items():
|
| 226 |
+
win[k] += v
|
| 227 |
+
win["grad_norm"] += grad_norm
|
| 228 |
+
win_steps += 1
|
| 229 |
+
|
| 230 |
+
do_val = (step % args.val_every == 0) or (step == target_stop)
|
| 231 |
+
do_save = (step % args.save_every == 0) or (step == target_stop)
|
| 232 |
+
do_log = (step % args.log_every == 0) or do_val or do_save
|
| 233 |
+
|
| 234 |
+
if do_log:
|
| 235 |
+
if use_amp:
|
| 236 |
+
torch.cuda.synchronize()
|
| 237 |
+
dt = max(time.monotonic() - win_t, 1e-6)
|
| 238 |
+
rec = {k: round(v / win_steps, 5) for k, v in win.items()}
|
| 239 |
+
rec.update(step=step, lr=round(lr, 7), steps_per_s=round(win_steps / dt, 2))
|
| 240 |
+
if do_val:
|
| 241 |
+
val_m = validate_cfm(
|
| 242 |
+
ema_model, val_view, val_indices, args.device, args.delta_weight, args.freq_delta_weight, args.hf_boost
|
| 243 |
+
)
|
| 244 |
+
rec.update({k: round(val, 5) for k, val in val_m.items()})
|
| 245 |
+
with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as mf:
|
| 246 |
+
mf.write(json.dumps(rec) + "\n")
|
| 247 |
+
print(f"[step {step:05d}] {json.dumps(rec)}", flush=True)
|
| 248 |
+
win = defaultdict(float)
|
| 249 |
+
win_steps = 0
|
| 250 |
+
win_t = time.monotonic()
|
| 251 |
+
|
| 252 |
+
if do_save:
|
| 253 |
+
export_cfm_checkpoint(ema_model, args.output / "inference_v5_ema.pt", step, train_ds.annotation)
|
| 254 |
+
export_cfm_checkpoint(ema_model, args.output / f"inference_v5_step-{step:06d}.pt", step, train_ds.annotation)
|
| 255 |
+
atomic_save(
|
| 256 |
+
{
|
| 257 |
+
"step": step,
|
| 258 |
+
"model": model.state_dict(),
|
| 259 |
+
"ema_model": ema_model.state_dict(),
|
| 260 |
+
"optimizer": optimizer.state_dict(),
|
| 261 |
+
"sampler_rng": sampler.generator.get_state(),
|
| 262 |
+
"sampler_pending": sampler.pending,
|
| 263 |
+
},
|
| 264 |
+
args.output / "cfm_v5_last.pt",
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
if __name__ == "__main__":
|
| 269 |
+
main()
|
code/src/lua_nova_v1/training/cfm_e2e.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Option A: E2E fine-tuning of LuaNovaCFM v5 through frozen MIT BigVGAN and frozen NVIDIA pretrained MPD/MRD."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
import copy
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
from torch.nn import functional as F
|
| 15 |
+
from torch.utils.checkpoint import checkpoint
|
| 16 |
+
|
| 17 |
+
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
|
| 18 |
+
from ..models.bigvgan import BigVGANMelExtractor, _ensure_bigvgan_importable
|
| 19 |
+
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
|
| 20 |
+
from ..models.losses import SpectralLoss, masked_mean
|
| 21 |
+
from .common import (
|
| 22 |
+
MelDatasetView,
|
| 23 |
+
balanced_indices,
|
| 24 |
+
check_leakage,
|
| 25 |
+
cosine_lr,
|
| 26 |
+
export_cfm_checkpoint,
|
| 27 |
+
load_cfm_model,
|
| 28 |
+
precompute_bigvgan_mels,
|
| 29 |
+
update_ema,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _unrolled_ode_sample(
|
| 34 |
+
model: LuaNovaCFM,
|
| 35 |
+
cond: torch.Tensor,
|
| 36 |
+
prior_mel: torch.Tensor,
|
| 37 |
+
frame_mask: torch.Tensor,
|
| 38 |
+
f0_feats: torch.Tensor | None,
|
| 39 |
+
n_steps: int,
|
| 40 |
+
cfg_scale: float,
|
| 41 |
+
temperature: float,
|
| 42 |
+
solver: str,
|
| 43 |
+
sway_coef: float,
|
| 44 |
+
use_checkpoint: bool = True,
|
| 45 |
+
noise_gate: torch.Tensor | None = None,
|
| 46 |
+
) -> torch.Tensor:
|
| 47 |
+
sigma = model.cfm_config.prior_sigma * temperature
|
| 48 |
+
eps = torch.randn_like(prior_mel)
|
| 49 |
+
noise = sigma * eps if noise_gate is None else sigma * noise_gate * eps
|
| 50 |
+
x = (prior_mel + noise) * frame_mask[..., None]
|
| 51 |
+
zero_cond = torch.zeros_like(cond)
|
| 52 |
+
zero_prior = torch.zeros_like(prior_mel)
|
| 53 |
+
zero_f0 = torch.zeros_like(f0_feats) if f0_feats is not None else None
|
| 54 |
+
|
| 55 |
+
def velocity(x_cur: torch.Tensor, t_val: float) -> torch.Tensor:
|
| 56 |
+
t_vec = torch.full((x_cur.shape[0],), t_val, device=x_cur.device, dtype=torch.float32)
|
| 57 |
+
v_c = model.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
|
| 58 |
+
if cfg_scale == 1.0:
|
| 59 |
+
return v_c
|
| 60 |
+
v_u = model.flow(x_cur, t_vec, zero_cond, zero_prior, frame_mask, f0_feats=zero_f0)
|
| 61 |
+
return v_u + cfg_scale * (v_c - v_u)
|
| 62 |
+
|
| 63 |
+
def one_step(x_in: torch.Tensor, t0_val: float, dt_val: float) -> torch.Tensor:
|
| 64 |
+
if solver == "midpoint":
|
| 65 |
+
v0 = velocity(x_in, t0_val)
|
| 66 |
+
x_mid = (x_in + 0.5 * dt_val * v0) * frame_mask[..., None]
|
| 67 |
+
v_mid = velocity(x_mid, t0_val + 0.5 * dt_val)
|
| 68 |
+
return (x_in + dt_val * v_mid) * frame_mask[..., None]
|
| 69 |
+
v0 = velocity(x_in, t0_val)
|
| 70 |
+
return (x_in + dt_val * v0) * frame_mask[..., None]
|
| 71 |
+
|
| 72 |
+
t_grid = model.sway_time_grid(n_steps, sway_coef)
|
| 73 |
+
for i in range(n_steps):
|
| 74 |
+
t0, t1 = t_grid[i], t_grid[i + 1]
|
| 75 |
+
dt_i = t1 - t0
|
| 76 |
+
if use_checkpoint and model.training and x.requires_grad:
|
| 77 |
+
x = checkpoint(lambda x_s, a=t0, d=dt_i: one_step(x_s, a, d), x, use_reentrant=False)
|
| 78 |
+
else:
|
| 79 |
+
x = one_step(x, t0, dt_i)
|
| 80 |
+
return x
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _lr_at(step: int, warmup: int, total_steps: int, base_lr: float, min_lr: float = 4e-6) -> float:
|
| 84 |
+
if step < warmup:
|
| 85 |
+
return base_lr * (step + 1) / max(warmup, 1)
|
| 86 |
+
prog = min(max((step - warmup) / max(total_steps - warmup, 1), 0.0), 1.0)
|
| 87 |
+
return min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * prog))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def option_a_micro_step(
|
| 91 |
+
model: LuaNovaCFM,
|
| 92 |
+
voc_net: nn.Module,
|
| 93 |
+
mpd: nn.Module,
|
| 94 |
+
mrd: nn.Module,
|
| 95 |
+
ext: BigVGANMelExtractor,
|
| 96 |
+
spectral: SpectralLoss,
|
| 97 |
+
feature_loss_fn,
|
| 98 |
+
generator_loss_fn,
|
| 99 |
+
batch: dict,
|
| 100 |
+
args,
|
| 101 |
+
use_bf16: bool,
|
| 102 |
+
) -> tuple[torch.Tensor, dict[str, float]]:
|
| 103 |
+
c = model.config
|
| 104 |
+
hop = int(c.hop)
|
| 105 |
+
with torch.no_grad():
|
| 106 |
+
hidden, tok_mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
|
| 107 |
+
p_tok_ctx, c_ctx_tok = model.encode_prosody_context(hidden, batch["tokens"], batch["stress"], tok_mask)
|
| 108 |
+
ac_f, pr_f, fmask, flen = model.expand_with_context(hidden, p_tok_ctx, c_ctx_tok, batch["durations"], tok_mask, batch["speakers"])
|
| 109 |
+
_, pred_pros, _ = model.sample_prosody(pr_f, fmask, seed=0)
|
| 110 |
+
|
| 111 |
+
if args.teacher_prob > 0.0:
|
| 112 |
+
teach = torch.rand(len(flen), device=flen.device) < args.teacher_prob
|
| 113 |
+
condition = torch.where(teach[:, None, None], batch["prosody"], model.hard_prosody(pred_pros))
|
| 114 |
+
else:
|
| 115 |
+
condition = model.hard_prosody(pred_pros)
|
| 116 |
+
if args.f0_smooth_prob > 0.0:
|
| 117 |
+
condition = smooth_f0_channel(condition, args.f0_smooth_prob)
|
| 118 |
+
|
| 119 |
+
base_h = ac_f if model.cfm_config.acoustic_from_frames else pr_f
|
| 120 |
+
f0_feats = f0_features(condition, fmask) if model.cfm_config.use_f0_harmonics else None
|
| 121 |
+
noise_gate = energy_noise_gate(condition, fmask) if model.cfm_config.use_energy_gate else None
|
| 122 |
+
x1 = ((batch["vocos_mel"] - model.vocoder.mel_mean) / model.vocoder.mel_scale) * fmask[..., None]
|
| 123 |
+
|
| 124 |
+
ch_w = torch.ones((1, 1, c.vocos_n_mels), device=x1.device, dtype=torch.float32)
|
| 125 |
+
ch_w[..., 60:] = args.hf_boost
|
| 126 |
+
ch_w = ch_w / ch_w.mean()
|
| 127 |
+
|
| 128 |
+
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
| 129 |
+
cond, prior_mel = model.condition_and_prior(base_h, condition, fmask)
|
| 130 |
+
mel_norm = _unrolled_ode_sample(
|
| 131 |
+
model, cond, prior_mel, fmask, f0_feats,
|
| 132 |
+
n_steps=args.ode_steps, cfg_scale=1.0, temperature=args.ode_temp,
|
| 133 |
+
solver="midpoint", sway_coef=args.sway_coef, use_checkpoint=True, noise_gate=noise_gate,
|
| 134 |
+
)
|
| 135 |
+
# Anchor CFM velocity on full sequence to preserve manifold alignment
|
| 136 |
+
t_anc = torch.sigmoid(torch.randn(x1.shape[0], device=x1.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
|
| 137 |
+
eps_anc = torch.randn_like(x1)
|
| 138 |
+
if noise_gate is not None:
|
| 139 |
+
eps_anc = eps_anc * noise_gate
|
| 140 |
+
x0_anc = (prior_mel.detach().float() + model.cfm_config.prior_sigma * eps_anc) * fmask[..., None]
|
| 141 |
+
xt_anc = ((1.0 - t_anc[:, None, None]) * x0_anc + t_anc[:, None, None] * x1) * fmask[..., None]
|
| 142 |
+
v_pred_anc = model.flow(xt_anc, t_anc, cond, prior_mel.detach(), fmask, f0_feats=f0_feats)
|
| 143 |
+
|
| 144 |
+
cfm_anchor = masked_mean(((v_pred_anc.float() - (x1 - x0_anc)).abs() * ch_w).mean(-1), fmask)
|
| 145 |
+
mel_f = mel_norm.float()
|
| 146 |
+
mel_l1 = masked_mean(((mel_f - x1).abs() * ch_w).mean(-1), fmask)
|
| 147 |
+
pair_mask = fmask[:, 1:] & fmask[:, :-1]
|
| 148 |
+
delta_l = masked_mean(((mel_f[:, 1:] - mel_f[:, :-1]) - (x1[:, 1:] - x1[:, :-1])).abs().mean(-1), pair_mask)
|
| 149 |
+
fdelta_l = masked_mean(((mel_f[..., 1:] - mel_f[..., :-1]) - (x1[..., 1:] - x1[..., :-1])).abs().mean(-1), fmask)
|
| 150 |
+
|
| 151 |
+
# Interior window crop -> frozen BigVGAN -> edge trim -> frozen STFT / Mel / MPD / MRD losses
|
| 152 |
+
b_sz = mel_f.shape[0]
|
| 153 |
+
crop_f = min(int(args.crop_frames), int(flen.min().item()))
|
| 154 |
+
starts = [
|
| 155 |
+
int(torch.randint(0, int(flen[i].item()) - crop_f + 1, (1,)).item()) if int(flen[i].item()) > crop_f else 0
|
| 156 |
+
for i in range(b_sz)
|
| 157 |
+
]
|
| 158 |
+
mel_crop = torch.stack([mel_f[i, s0 : s0 + crop_f] for i, s0 in enumerate(starts)], dim=0)
|
| 159 |
+
gt_crop = torch.stack([batch["wave"][i, s0 * hop : (s0 + crop_f) * hop] for i, s0 in enumerate(starts)], dim=0)[:, None, :]
|
| 160 |
+
|
| 161 |
+
phys_crop = (mel_crop * model.vocoder.mel_scale + model.vocoder.mel_mean).clamp(min=-11.512925)
|
| 162 |
+
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
| 163 |
+
pred_wav = voc_net(phys_crop.transpose(1, 2).contiguous())
|
| 164 |
+
|
| 165 |
+
trim = min(int(args.edge_trim), pred_wav.shape[-1] // 8)
|
| 166 |
+
pred_trim = pred_wav[:, :, trim:-trim] if trim > 0 else pred_wav
|
| 167 |
+
gt_trim = gt_crop[:, :, trim:-trim] if trim > 0 else gt_crop
|
| 168 |
+
|
| 169 |
+
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
| 170 |
+
_, y_df_g, fmap_f_r, fmap_f_g = mpd(gt_trim, pred_trim)
|
| 171 |
+
|
| 172 |
+
pred_32 = pred_trim.float()
|
| 173 |
+
gt_32 = gt_trim.float()
|
| 174 |
+
with torch.amp.autocast("cuda", enabled=False):
|
| 175 |
+
_, y_ds_g, fmap_s_r, fmap_s_g = mrd(gt_32, pred_32)
|
| 176 |
+
trim_len = torch.full((b_sz,), pred_32.shape[-1], device=x1.device, dtype=torch.long)
|
| 177 |
+
stft_l, _ = spectral(pred_32.squeeze(1), gt_32.squeeze(1), trim_len)
|
| 178 |
+
wmel_l = F.l1_loss(ext(pred_32.squeeze(1)), ext(gt_32.squeeze(1)))
|
| 179 |
+
fm_l = (
|
| 180 |
+
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])
|
| 181 |
+
+ feature_loss_fn(fmap_s_r, fmap_s_g)
|
| 182 |
+
)
|
| 183 |
+
adv_l = generator_loss_fn([t.float() for t in y_df_g])[0] + generator_loss_fn(y_ds_g)[0]
|
| 184 |
+
|
| 185 |
+
loss = (
|
| 186 |
+
args.w_cfm_anchor * cfm_anchor
|
| 187 |
+
+ args.w_mel * mel_l1
|
| 188 |
+
+ args.w_delta * delta_l
|
| 189 |
+
+ args.w_fdelta * fdelta_l
|
| 190 |
+
+ args.w_stft * stft_l
|
| 191 |
+
+ args.w_wmel * wmel_l
|
| 192 |
+
+ args.w_fm * fm_l
|
| 193 |
+
+ args.w_adv * adv_l
|
| 194 |
+
)
|
| 195 |
+
stats = {
|
| 196 |
+
"loss": float(loss.detach()),
|
| 197 |
+
"stft": float(stft_l.detach()),
|
| 198 |
+
"wmel": float(wmel_l.detach()),
|
| 199 |
+
"fm": float(fm_l.detach()),
|
| 200 |
+
"adv": float(adv_l.detach()),
|
| 201 |
+
"anc": float(cfm_anchor.detach()),
|
| 202 |
+
"mel": float(mel_l1.detach()),
|
| 203 |
+
"delta": float(delta_l.detach()),
|
| 204 |
+
}
|
| 205 |
+
return loss, stats
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@torch.no_grad()
|
| 209 |
+
def validate_option_a(
|
| 210 |
+
ema_model: LuaNovaCFM,
|
| 211 |
+
voc_net: nn.Module,
|
| 212 |
+
ext: BigVGANMelExtractor,
|
| 213 |
+
spectral: SpectralLoss,
|
| 214 |
+
val_ds: AnnotatedDataset,
|
| 215 |
+
val_gt: dict[int, torch.Tensor],
|
| 216 |
+
val_indices: list[int],
|
| 217 |
+
args,
|
| 218 |
+
) -> dict[str, float]:
|
| 219 |
+
ema_model.eval()
|
| 220 |
+
stft_tot, wmel_tot, dt_tot, n = 0.0, 0.0, 0.0, 0
|
| 221 |
+
hop = int(ema_model.config.hop)
|
| 222 |
+
for idx in val_indices:
|
| 223 |
+
it = val_ds[idx]
|
| 224 |
+
gt_wav = it["wave"][None].to(device=args.device, dtype=torch.float32)
|
| 225 |
+
gt_m = val_gt[idx][None].to(device=args.device, dtype=torch.float32)
|
| 226 |
+
tok = it["tokens"][None].to(args.device)
|
| 227 |
+
st = it["stress"][None].to(args.device)
|
| 228 |
+
tl = torch.tensor([tok.shape[1]], device=args.device)
|
| 229 |
+
sp = torch.tensor([int(it["speaker"])], device=args.device)
|
| 230 |
+
dur = it["durations"][None].to(args.device)
|
| 231 |
+
|
| 232 |
+
h, m = ema_model.encode(tok, st, tl, sp)
|
| 233 |
+
pt, ct = ema_model.encode_prosody_context(h, tok, st, m)
|
| 234 |
+
af, pr_f, fm, fl = ema_model.expand_with_context(h, pt, ct, dur, m, sp)
|
| 235 |
+
_, pred_pros, _ = ema_model.sample_prosody(pr_f, fm, seed=0)
|
| 236 |
+
cond_p = ema_model.hard_prosody(pred_pros)
|
| 237 |
+
base_h = af if ema_model.cfm_config.acoustic_from_frames else pr_f
|
| 238 |
+
cond, prior_mel = ema_model.condition_and_prior(base_h, cond_p, fm)
|
| 239 |
+
f0f = f0_features(cond_p, fm) if ema_model.cfm_config.use_f0_harmonics else None
|
| 240 |
+
ng = energy_noise_gate(cond_p, fm) if ema_model.cfm_config.use_energy_gate else None
|
| 241 |
+
mel_norm = ema_model.sample_mel(
|
| 242 |
+
cond, prior_mel, fm, n_steps=args.ode_steps, cfg_scale=1.0,
|
| 243 |
+
temperature=args.ode_temp, solver="midpoint", seed=0,
|
| 244 |
+
f0_feats=f0f, noise_gate=ng, sway_coef=args.sway_coef,
|
| 245 |
+
)
|
| 246 |
+
phys = (mel_norm.float() * ema_model.vocoder.mel_scale + ema_model.vocoder.mel_mean).clamp(min=-11.512925)
|
| 247 |
+
pred_wav = voc_net(phys.transpose(1, 2).contiguous()).squeeze(1)[:, : int(fl[0]) * hop]
|
| 248 |
+
s_len = torch.tensor([pred_wav.shape[-1]], device=args.device, dtype=torch.long)
|
| 249 |
+
stft_l, _ = spectral(pred_wav, gt_wav, s_len)
|
| 250 |
+
rec_m = ext(pred_wav)
|
| 251 |
+
n_f = min(rec_m.shape[1], gt_m.shape[1])
|
| 252 |
+
wmel_l = F.l1_loss(rec_m[:, :n_f], gt_m[:, :n_f])
|
| 253 |
+
dt_mel = (rec_m[:, 1:n_f] - rec_m[:, : n_f - 1]).abs().mean()
|
| 254 |
+
stft_tot += float(stft_l)
|
| 255 |
+
wmel_tot += float(wmel_l)
|
| 256 |
+
dt_tot += float(dt_mel)
|
| 257 |
+
n += 1
|
| 258 |
+
return {
|
| 259 |
+
"val_stft": stft_tot / max(n, 1),
|
| 260 |
+
"val_wmel": wmel_tot / max(n, 1),
|
| 261 |
+
"val_dt_mel": dt_tot / max(n, 1),
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def main() -> None:
|
| 266 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 267 |
+
parser.add_argument("--train", type=Path, required=True)
|
| 268 |
+
parser.add_argument("--validation", type=Path, required=True)
|
| 269 |
+
parser.add_argument("--init-v5", type=Path, required=True)
|
| 270 |
+
parser.add_argument("--vocoder-id", default="nvidia/bigvgan_base_24khz_100band")
|
| 271 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 272 |
+
parser.add_argument("--device", default="cuda")
|
| 273 |
+
parser.add_argument("--steps", type=int, default=4000)
|
| 274 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 275 |
+
parser.add_argument("--grad-accum", type=int, default=3)
|
| 276 |
+
parser.add_argument("--crop-frames", type=int, default=40)
|
| 277 |
+
parser.add_argument("--edge-trim", type=int, default=512)
|
| 278 |
+
parser.add_argument("--ode-steps", type=int, default=4)
|
| 279 |
+
parser.add_argument("--ode-temp", type=float, default=0.40)
|
| 280 |
+
parser.add_argument("--sway-coef", type=float, default=-0.5)
|
| 281 |
+
parser.add_argument("--lr", type=float, default=4e-5)
|
| 282 |
+
parser.add_argument("--min-lr", type=float, default=4e-6)
|
| 283 |
+
parser.add_argument("--warmup", type=int, default=200)
|
| 284 |
+
parser.add_argument("--ema-decay", type=float, default=0.995)
|
| 285 |
+
parser.add_argument("--teacher-prob", type=float, default=0.35)
|
| 286 |
+
parser.add_argument("--f0-smooth-prob", type=float, default=0.15)
|
| 287 |
+
parser.add_argument("--hf-boost", type=float, default=1.40)
|
| 288 |
+
parser.add_argument("--w-cfm-anchor", type=float, default=1.0)
|
| 289 |
+
parser.add_argument("--w-mel", type=float, default=0.5)
|
| 290 |
+
parser.add_argument("--w-delta", type=float, default=0.8)
|
| 291 |
+
parser.add_argument("--w-fdelta", type=float, default=0.4)
|
| 292 |
+
parser.add_argument("--w-stft", type=float, default=1.5)
|
| 293 |
+
parser.add_argument("--w-wmel", type=float, default=2.0)
|
| 294 |
+
parser.add_argument("--w-fm", type=float, default=0.08)
|
| 295 |
+
parser.add_argument("--w-adv", type=float, default=0.05)
|
| 296 |
+
parser.add_argument("--val-every", type=int, default=500)
|
| 297 |
+
parser.add_argument("--log-every", type=int, default=10)
|
| 298 |
+
parser.add_argument("--save-steps", nargs="+", type=int, default=[1500, 3000, 4000])
|
| 299 |
+
parser.add_argument("--seed", type=int, default=20261123)
|
| 300 |
+
args = parser.parse_args()
|
| 301 |
+
|
| 302 |
+
torch.manual_seed(args.seed)
|
| 303 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 304 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 305 |
+
|
| 306 |
+
_ensure_bigvgan_importable()
|
| 307 |
+
import bigvgan
|
| 308 |
+
from discriminators import MultiPeriodDiscriminator, MultiResolutionDiscriminator
|
| 309 |
+
from huggingface_hub import hf_hub_download
|
| 310 |
+
from loss import feature_loss, generator_loss
|
| 311 |
+
|
| 312 |
+
model = load_cfm_model(args.init_v5, args.device)
|
| 313 |
+
model.freeze_frontend(True)
|
| 314 |
+
for p in model.vocoder.parameters():
|
| 315 |
+
p.requires_grad_(False)
|
| 316 |
+
ema_model = copy.deepcopy(model).eval()
|
| 317 |
+
for p in ema_model.parameters():
|
| 318 |
+
p.requires_grad_(False)
|
| 319 |
+
|
| 320 |
+
trainable = [p for p in model.parameters() if p.requires_grad]
|
| 321 |
+
trainable_prefixes = sorted({n.split(".")[0] for n, p in model.named_parameters() if p.requires_grad})
|
| 322 |
+
|
| 323 |
+
voc_net = bigvgan.BigVGAN.from_pretrained(args.vocoder_id, use_cuda_kernel=False)
|
| 324 |
+
voc_net.remove_weight_norm()
|
| 325 |
+
voc_net = voc_net.eval().to(args.device)
|
| 326 |
+
for p in voc_net.parameters():
|
| 327 |
+
p.requires_grad_(False)
|
| 328 |
+
|
| 329 |
+
do_path = hf_hub_download(args.vocoder_id, "bigvgan_discriminator_optimizer.pt")
|
| 330 |
+
do_ckpt = torch.load(do_path, map_location="cpu", weights_only=True)
|
| 331 |
+
mpd = MultiPeriodDiscriminator(voc_net.h).to(args.device)
|
| 332 |
+
mrd = MultiResolutionDiscriminator(voc_net.h).to(args.device)
|
| 333 |
+
mpd.load_state_dict(do_ckpt["mpd"], strict=True)
|
| 334 |
+
mrd.load_state_dict(do_ckpt["mrd"], strict=True)
|
| 335 |
+
del do_ckpt
|
| 336 |
+
for mod in (mpd, mrd):
|
| 337 |
+
mod.eval()
|
| 338 |
+
for p in mod.parameters():
|
| 339 |
+
p.requires_grad_(False)
|
| 340 |
+
|
| 341 |
+
train_ds = AnnotatedDataset(args.train, model.config, voiced_vowels=True, cache=True)
|
| 342 |
+
val_ds = AnnotatedDataset(args.validation, model.config, voiced_vowels=True, cache=True)
|
| 343 |
+
check_leakage(train_ds, val_ds)
|
| 344 |
+
pool = [i for i in range(len(train_ds)) if train_ds.lengths[i] >= args.crop_frames]
|
| 345 |
+
val_indices = balanced_indices(val_ds, len(val_ds))
|
| 346 |
+
print(f"Preloading train ({len(pool)}) and validation ({len(val_indices)}) ...", flush=True)
|
| 347 |
+
train_ds.preload(pool, workers=8)
|
| 348 |
+
val_ds.preload(val_indices, workers=4)
|
| 349 |
+
|
| 350 |
+
ext = BigVGANMelExtractor().to(args.device).eval()
|
| 351 |
+
t_mel = time.perf_counter()
|
| 352 |
+
train_bg, _, _ = precompute_bigvgan_mels(train_ds, pool, ext, args.device, compute_stats=False)
|
| 353 |
+
val_bg, _, _ = precompute_bigvgan_mels(val_ds, val_indices, ext, args.device, compute_stats=False)
|
| 354 |
+
print(
|
| 355 |
+
f"Precomputed BigVGAN mels in {time.perf_counter() - t_mel:.2f}s | trainable={trainable_prefixes} "
|
| 356 |
+
f"({sum(p.numel() for p in trainable):,} params)",
|
| 357 |
+
flush=True,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
spectral = SpectralLoss(
|
| 361 |
+
model.config.sample_rate,
|
| 362 |
+
resolutions=((256, 64), (512, 128), (1024, 256), (2048, 512)),
|
| 363 |
+
mel=(1024, 256, 80),
|
| 364 |
+
).to(args.device)
|
| 365 |
+
train_view = MelDatasetView(train_ds, train_bg)
|
| 366 |
+
sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_size * 500, args.batch_size, args.seed)
|
| 367 |
+
optimizer = torch.optim.AdamW(trainable, lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
|
| 368 |
+
|
| 369 |
+
is_cuda = torch.cuda.is_available() and str(args.device).startswith("cuda")
|
| 370 |
+
use_bf16 = is_cuda
|
| 371 |
+
grad_accum = max(int(args.grad_accum), 1)
|
| 372 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 373 |
+
log_f = (args.output / "train.log").open("a", encoding="utf-8", buffering=1)
|
| 374 |
+
|
| 375 |
+
def emit(msg: str) -> None:
|
| 376 |
+
print(msg, flush=True)
|
| 377 |
+
log_f.write(msg + "\n")
|
| 378 |
+
log_f.flush()
|
| 379 |
+
|
| 380 |
+
if is_cuda:
|
| 381 |
+
torch.cuda.reset_peak_memory_stats(args.device)
|
| 382 |
+
|
| 383 |
+
v0 = validate_option_a(ema_model, voc_net, ext, spectral, val_ds, val_bg, val_indices, args)
|
| 384 |
+
emit(f"[step 0] {json.dumps(v0)}")
|
| 385 |
+
|
| 386 |
+
win = defaultdict(float)
|
| 387 |
+
win_n = 0
|
| 388 |
+
win_t = time.monotonic()
|
| 389 |
+
save_set = set(int(s) for s in args.save_steps) | {int(args.steps)}
|
| 390 |
+
|
| 391 |
+
try:
|
| 392 |
+
for step in range(args.steps):
|
| 393 |
+
lr = cosine_lr(step, args.warmup, args.steps, args.lr, min_lr=args.min_lr)
|
| 394 |
+
for pg in optimizer.param_groups:
|
| 395 |
+
pg["lr"] = lr
|
| 396 |
+
|
| 397 |
+
model.train()
|
| 398 |
+
optimizer.zero_grad(set_to_none=True)
|
| 399 |
+
acc = defaultdict(float)
|
| 400 |
+
|
| 401 |
+
for _micro in range(grad_accum):
|
| 402 |
+
batch_ids = [pool[i] for i in sampler.next()]
|
| 403 |
+
batch = collate([train_view[i] for i in batch_ids], args.device)
|
| 404 |
+
loss_mb, st_mb = option_a_micro_step(
|
| 405 |
+
model, voc_net, mpd, mrd, ext, spectral, feature_loss, generator_loss,
|
| 406 |
+
batch, args, use_bf16=use_bf16,
|
| 407 |
+
)
|
| 408 |
+
if not torch.isfinite(loss_mb):
|
| 409 |
+
raise RuntimeError(f"Non-finite loss at step {step}: {loss_mb}")
|
| 410 |
+
(loss_mb / grad_accum).backward()
|
| 411 |
+
for k, v in st_mb.items():
|
| 412 |
+
acc[k] += v / grad_accum
|
| 413 |
+
del batch, loss_mb
|
| 414 |
+
|
| 415 |
+
grad_norm = float(nn.utils.clip_grad_norm_(trainable, 1.0))
|
| 416 |
+
optimizer.step()
|
| 417 |
+
update_ema(ema_model, model, args.ema_decay)
|
| 418 |
+
|
| 419 |
+
cur = step + 1
|
| 420 |
+
for k, v in acc.items():
|
| 421 |
+
win[k] += v
|
| 422 |
+
win["grad_norm"] += grad_norm
|
| 423 |
+
win_n += 1
|
| 424 |
+
|
| 425 |
+
do_val = (cur % args.val_every == 0) or (cur == args.steps)
|
| 426 |
+
do_save = cur in save_set
|
| 427 |
+
do_log = (cur % args.log_every == 0) or (cur == 1) or do_val or do_save
|
| 428 |
+
|
| 429 |
+
if do_log:
|
| 430 |
+
if is_cuda:
|
| 431 |
+
torch.cuda.synchronize()
|
| 432 |
+
dt = max(time.monotonic() - win_t, 1e-6)
|
| 433 |
+
it_s = win_n / dt
|
| 434 |
+
eta_min = (args.steps - cur) / max(it_s, 1e-6) / 60.0
|
| 435 |
+
vram_gb = (torch.cuda.memory_allocated(args.device) / 1e9) if is_cuda else 0.0
|
| 436 |
+
vram_peak_gb = (torch.cuda.max_memory_allocated(args.device) / 1e9) if is_cuda else 0.0
|
| 437 |
+
rec = {k: round(v / win_n, 4) for k, v in win.items()}
|
| 438 |
+
rec.update(
|
| 439 |
+
step=cur,
|
| 440 |
+
lr=round(lr, 7),
|
| 441 |
+
it_s=round(it_s, 2),
|
| 442 |
+
eta_min=round(eta_min, 2),
|
| 443 |
+
vram_gb=round(vram_gb, 2),
|
| 444 |
+
vram_peak_gb=round(vram_peak_gb, 2),
|
| 445 |
+
)
|
| 446 |
+
if do_val:
|
| 447 |
+
val_m = validate_option_a(ema_model, voc_net, ext, spectral, val_ds, val_bg, val_indices, args)
|
| 448 |
+
rec.update({k: round(v, 5) for k, v in val_m.items()})
|
| 449 |
+
with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as mf:
|
| 450 |
+
mf.write(json.dumps(rec) + "\n")
|
| 451 |
+
mf.flush()
|
| 452 |
+
pct = 100.0 * cur / max(args.steps, 1)
|
| 453 |
+
msg = (
|
| 454 |
+
f"[step {cur:05d}/{args.steps:05d} | {pct:5.1f}%] "
|
| 455 |
+
f"loss={rec['loss']:.3f} stft={rec['stft']:.3f} wmel={rec['wmel']:.3f} "
|
| 456 |
+
f"fm={rec['fm']:.2f} adv={rec['adv']:.2f} anc={rec['anc']:.3f} | "
|
| 457 |
+
f"{rec['it_s']:.2f} it/s | ETA {rec['eta_min']:.1f}m | VRAM {rec['vram_gb']:.2f}/{rec['vram_peak_gb']:.2f} GB"
|
| 458 |
+
)
|
| 459 |
+
if do_val:
|
| 460 |
+
msg += f" | val_stft={rec['val_stft']:.5f} val_wmel={rec['val_wmel']:.5f} val_dt={rec['val_dt_mel']:.4f}"
|
| 461 |
+
emit(msg)
|
| 462 |
+
win = defaultdict(float)
|
| 463 |
+
win_n = 0
|
| 464 |
+
win_t = time.monotonic()
|
| 465 |
+
|
| 466 |
+
if do_save:
|
| 467 |
+
export_cfm_checkpoint(ema_model, args.output / f"inference_v5_e2e_step-{cur:06d}.pt", cur, train_ds.annotation)
|
| 468 |
+
export_cfm_checkpoint(ema_model, args.output / "inference_v5_e2e_ema.pt", cur, train_ds.annotation)
|
| 469 |
+
finally:
|
| 470 |
+
log_f.close()
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
if __name__ == "__main__":
|
| 474 |
+
main()
|
code/src/lua_nova_v1/training/common.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared training utilities for Lua Nova V1."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch import nn
|
| 11 |
+
|
| 12 |
+
from ..config import CHECKPOINT_FORMAT, CFMConfig
|
| 13 |
+
from ..data.dataset import AnnotatedDataset, collate
|
| 14 |
+
from ..models.bigvgan import BigVGANMelExtractor
|
| 15 |
+
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
|
| 16 |
+
from ..models.losses import masked_mean
|
| 17 |
+
from ..text.phonemizer import frontend_fingerprint, frontend_identity
|
| 18 |
+
from ..utils.checkpoint import atomic_save
|
| 19 |
+
|
| 20 |
+
VALIDATION_SAMPLE_TEXTS = (
|
| 21 |
+
"Amanhã de manhã eu vou pôr o pão na mesa para os irmãos.",
|
| 22 |
+
"Eu almoço cedo quando o almoço está pronto no jogo.",
|
| 23 |
+
"Dia vinte e dois de março às quatorze horas custou duzentos reais.",
|
| 24 |
+
"Você tem certeza de que ele vem hoje à tarde?",
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def masked_std(value: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
|
| 29 |
+
"""Standard deviation per row over valid masked positions, returning ``[B]``."""
|
| 30 |
+
count = mask.sum(1).clamp_min(1)
|
| 31 |
+
mean = (value * mask).sum(1) / count
|
| 32 |
+
return (((value - mean[:, None]).square() * mask).sum(1) / count + 1e-8).sqrt()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def balanced_indices(dataset: AnnotatedDataset, limit: int) -> list[int]:
|
| 36 |
+
"""Deterministic round-robin sample indices balanced across speakers."""
|
| 37 |
+
groups: dict[str, list[int]] = defaultdict(list)
|
| 38 |
+
for i, row in enumerate(dataset.rows):
|
| 39 |
+
groups[row["speaker"]].append(i)
|
| 40 |
+
limit = min(max(limit, len(groups)), len(dataset.rows))
|
| 41 |
+
selected: list[int] = []
|
| 42 |
+
for offset in range(limit):
|
| 43 |
+
for voice in sorted(groups):
|
| 44 |
+
if offset < len(groups[voice]):
|
| 45 |
+
selected.append(groups[voice][offset])
|
| 46 |
+
if len(selected) == limit:
|
| 47 |
+
return selected
|
| 48 |
+
return selected
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def check_leakage(train: AnnotatedDataset, validation: AnnotatedDataset) -> None:
|
| 52 |
+
"""Ensure zero ID or text overlap between training and validation splits."""
|
| 53 |
+
ids = {r["id"] for r in train.rows}
|
| 54 |
+
texts: dict[str, list[str]] = defaultdict(list)
|
| 55 |
+
for row in train.rows:
|
| 56 |
+
texts[row["text_hash"]].append(row["id"])
|
| 57 |
+
collisions = []
|
| 58 |
+
for row in validation.rows:
|
| 59 |
+
if row["id"] in ids or row["text_hash"] in texts:
|
| 60 |
+
collisions.append(
|
| 61 |
+
{
|
| 62 |
+
"validation_id": row["id"],
|
| 63 |
+
"train_ids": texts.get(row["text_hash"], [])[:3],
|
| 64 |
+
"text": row.get("text", "")[:160],
|
| 65 |
+
}
|
| 66 |
+
)
|
| 67 |
+
if len(collisions) == 5:
|
| 68 |
+
break
|
| 69 |
+
if collisions:
|
| 70 |
+
raise ValueError("train/validation leakage detected: " + json.dumps(collisions, ensure_ascii=False))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def cosine_lr(step: int, warmup: int, total_steps: int, base_lr: float, min_lr: float) -> float:
|
| 74 |
+
"""Linear warmup followed by cosine decay down to ``min_lr``."""
|
| 75 |
+
if step < warmup:
|
| 76 |
+
return base_lr * (step + 1) / max(warmup, 1)
|
| 77 |
+
prog = min(max((step - warmup) / max(total_steps - warmup, 1), 0.0), 1.0)
|
| 78 |
+
return min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * prog))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def update_ema(ema_model: nn.Module, model: nn.Module, decay: float, on_cpu: bool = False) -> None:
|
| 82 |
+
"""Update exponential moving average parameters matching trainable flags on GPU or CPU."""
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
for p_ema, p in zip(ema_model.parameters(), model.parameters()):
|
| 85 |
+
if p.requires_grad:
|
| 86 |
+
src = p.detach().cpu() if on_cpu else p
|
| 87 |
+
p_ema.mul_(decay).add_(src, alpha=1.0 - decay)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def export_cfm_checkpoint(model: LuaNovaCFM, path: Path | str, step: int, annotation: str | None = None) -> None:
|
| 91 |
+
"""Save a portable LuaNovaCFM checkpoint containing config, frontend identity, and state_dict."""
|
| 92 |
+
atomic_save(
|
| 93 |
+
{
|
| 94 |
+
"format_version": CHECKPOINT_FORMAT,
|
| 95 |
+
"arch": "lua_nova_v1_cfm",
|
| 96 |
+
"cfm_config": model.cfm_config.to_dict(),
|
| 97 |
+
"step": int(step),
|
| 98 |
+
"frontend": {**frontend_identity(), "fingerprint": frontend_fingerprint()},
|
| 99 |
+
"annotation": annotation,
|
| 100 |
+
"model": {k: v.detach().cpu() for k, v in model.state_dict().items()},
|
| 101 |
+
},
|
| 102 |
+
path,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def load_cfm_model(
|
| 107 |
+
path: Path | str,
|
| 108 |
+
device: str = "cpu",
|
| 109 |
+
load_vocos: bool | None = None,
|
| 110 |
+
) -> LuaNovaCFM:
|
| 111 |
+
"""Load a LuaNovaCFM checkpoint (either full or stripped of legacy Vocos buffers)."""
|
| 112 |
+
state = torch.load(path, map_location="cpu", weights_only=True)
|
| 113 |
+
cfg = CFMConfig.from_dict(state["cfm_config"])
|
| 114 |
+
use_vocos = (cfg.mel_space == "vocos") if load_vocos is None else bool(load_vocos)
|
| 115 |
+
model = LuaNovaCFM(cfg, load_vocos=use_vocos)
|
| 116 |
+
sd = state["model"]
|
| 117 |
+
if not use_vocos:
|
| 118 |
+
# Filter unused legacy Vocos weights while keeping strict validation over all active tensors.
|
| 119 |
+
sd = {
|
| 120 |
+
k: v.float()
|
| 121 |
+
for k, v in sd.items()
|
| 122 |
+
if not (k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale"))
|
| 123 |
+
}
|
| 124 |
+
model.load_state_dict(sd, strict=True)
|
| 125 |
+
return model.to(device).eval()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class MelDatasetView:
|
| 129 |
+
"""In-memory view overriding ``vocos_mel`` with precomputed BigVGAN Slaney-100 mels."""
|
| 130 |
+
|
| 131 |
+
def __init__(self, ds: AnnotatedDataset, mels: dict[int, torch.Tensor]) -> None:
|
| 132 |
+
self.ds = ds
|
| 133 |
+
self.mels = mels
|
| 134 |
+
|
| 135 |
+
def __getitem__(self, idx: int) -> dict:
|
| 136 |
+
item = dict(self.ds[idx])
|
| 137 |
+
item["vocos_mel"] = self.mels[idx].float()
|
| 138 |
+
return item
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@torch.no_grad()
|
| 142 |
+
def precompute_bigvgan_mels(
|
| 143 |
+
ds: AnnotatedDataset,
|
| 144 |
+
indices: list[int],
|
| 145 |
+
extractor: BigVGANMelExtractor,
|
| 146 |
+
device: str,
|
| 147 |
+
compute_stats: bool = False,
|
| 148 |
+
) -> tuple[dict[int, torch.Tensor], torch.Tensor | None, torch.Tensor | None]:
|
| 149 |
+
"""Extract unpadded 24 kHz 100-band Slaney log-mels in RAM without rewriting disk files."""
|
| 150 |
+
mels: dict[int, torch.Tensor] = {}
|
| 151 |
+
sum_1 = torch.zeros(extractor.n_mels, dtype=torch.float64, device=device)
|
| 152 |
+
sum_2 = torch.zeros(extractor.n_mels, dtype=torch.float64, device=device)
|
| 153 |
+
total_frames = 0
|
| 154 |
+
for idx in indices:
|
| 155 |
+
wav = ds[idx]["wave"].to(device=device, dtype=torch.float32)
|
| 156 |
+
mel = extractor(wav)[0]
|
| 157 |
+
if compute_stats:
|
| 158 |
+
mf64 = mel.double()
|
| 159 |
+
sum_1 += mf64.sum(dim=0)
|
| 160 |
+
sum_2 += mf64.square().sum(dim=0)
|
| 161 |
+
total_frames += int(mel.shape[0])
|
| 162 |
+
mels[idx] = mel.half().cpu()
|
| 163 |
+
if not compute_stats:
|
| 164 |
+
return mels, None, None
|
| 165 |
+
mean = (sum_1 / max(total_frames, 1)).float().cpu()
|
| 166 |
+
var = (sum_2 / max(total_frames, 1) - (sum_1 / max(total_frames, 1)).square()).clamp_min(1e-8)
|
| 167 |
+
scale = var.sqrt().float().clamp_min(1e-4).cpu()
|
| 168 |
+
return mels, mean, scale
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def cfm_loss_step(
|
| 172 |
+
model: LuaNovaCFM,
|
| 173 |
+
batch: dict,
|
| 174 |
+
teacher_prob: float = 0.15,
|
| 175 |
+
prior_weight: float = 1.0,
|
| 176 |
+
delta_weight: float = 0.6,
|
| 177 |
+
freq_delta_weight: float = 0.35,
|
| 178 |
+
hf_boost: float = 1.35,
|
| 179 |
+
f0_smooth_prob: float = 0.0,
|
| 180 |
+
training: bool = True,
|
| 181 |
+
) -> tuple[torch.Tensor, dict]:
|
| 182 |
+
"""Compute prior-centered OT-CFM objective plus temporal and frequency derivative losses."""
|
| 183 |
+
c = model.config
|
| 184 |
+
cfg = model.cfm_config
|
| 185 |
+
with torch.no_grad() if model._frontend_frozen else torch.enable_grad():
|
| 186 |
+
hidden, token_mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
|
| 187 |
+
prosody_token_ctx, clause_ctx_tok = model.encode_prosody_context(
|
| 188 |
+
hidden, batch["tokens"], batch["stress"], token_mask
|
| 189 |
+
)
|
| 190 |
+
acoustic_frames, prosody_frames, frame_mask, lengths = model.expand_with_context(
|
| 191 |
+
hidden, prosody_token_ctx, clause_ctx_tok, batch["durations"], token_mask, batch["speakers"]
|
| 192 |
+
)
|
| 193 |
+
if teacher_prob >= 1.0 and cfg.acoustic_from_frames:
|
| 194 |
+
prosody_hidden = None
|
| 195 |
+
prediction = None
|
| 196 |
+
else:
|
| 197 |
+
prosody_hidden, prediction, _ = model.sample_prosody(prosody_frames, frame_mask, seed=0)
|
| 198 |
+
|
| 199 |
+
target_prosody = batch["prosody"]
|
| 200 |
+
if teacher_prob >= 1.0:
|
| 201 |
+
condition = target_prosody
|
| 202 |
+
elif training and teacher_prob > 0:
|
| 203 |
+
teacher = torch.rand(len(lengths), device=lengths.device) < teacher_prob
|
| 204 |
+
condition = torch.where(teacher[:, None, None], target_prosody, model.hard_prosody(prediction.detach()))
|
| 205 |
+
else:
|
| 206 |
+
condition = model.hard_prosody(prediction.detach())
|
| 207 |
+
if training and f0_smooth_prob > 0:
|
| 208 |
+
condition = smooth_f0_channel(condition, f0_smooth_prob)
|
| 209 |
+
|
| 210 |
+
base_h = acoustic_frames if cfg.acoustic_from_frames else prosody_hidden
|
| 211 |
+
cond, prior_mel = model.condition_and_prior(base_h, condition, frame_mask)
|
| 212 |
+
f0_feats = f0_features(condition, frame_mask) if cfg.use_f0_harmonics else None
|
| 213 |
+
gate = energy_noise_gate(condition, frame_mask) if cfg.use_energy_gate else 1.0
|
| 214 |
+
x1 = ((batch["vocos_mel"] - model.vocoder.mel_mean) / model.vocoder.mel_scale) * frame_mask[..., None]
|
| 215 |
+
|
| 216 |
+
if hf_boost != 1.0:
|
| 217 |
+
ch_w = torch.ones((1, 1, c.vocos_n_mels), device=x1.device, dtype=torch.float32)
|
| 218 |
+
ch_w[..., 60:] = hf_boost
|
| 219 |
+
ch_w = ch_w / ch_w.mean()
|
| 220 |
+
else:
|
| 221 |
+
ch_w = 1.0
|
| 222 |
+
|
| 223 |
+
prior_loss = masked_mean(((prior_mel - x1).abs() * ch_w).mean(-1), frame_mask)
|
| 224 |
+
|
| 225 |
+
b = x1.shape[0]
|
| 226 |
+
if training:
|
| 227 |
+
t = torch.sigmoid(torch.randn(b, device=x1.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
|
| 228 |
+
else:
|
| 229 |
+
t = torch.full((b,), 0.5, device=x1.device, dtype=torch.float32)
|
| 230 |
+
|
| 231 |
+
eps = torch.randn_like(x1)
|
| 232 |
+
x0 = (prior_mel.detach() + cfg.prior_sigma * gate * eps) * frame_mask[..., None]
|
| 233 |
+
t_view = t[:, None, None]
|
| 234 |
+
x_t = ((1.0 - t_view) * x0 + t_view * x1) * frame_mask[..., None]
|
| 235 |
+
v_target = (x1 - x0) * frame_mask[..., None]
|
| 236 |
+
|
| 237 |
+
if training and cfg.cfg_dropout > 0:
|
| 238 |
+
drop = (torch.rand(b, device=x1.device) < cfg.cfg_dropout)[:, None, None]
|
| 239 |
+
cond_in = torch.where(drop, torch.zeros_like(cond), cond)
|
| 240 |
+
prior_in = torch.where(drop, torch.zeros_like(prior_mel), prior_mel.detach())
|
| 241 |
+
f0_in = torch.where(drop, torch.zeros_like(f0_feats), f0_feats) if f0_feats is not None else None
|
| 242 |
+
else:
|
| 243 |
+
cond_in = cond
|
| 244 |
+
prior_in = prior_mel.detach()
|
| 245 |
+
f0_in = f0_feats
|
| 246 |
+
|
| 247 |
+
v_pred = model.flow(x_t, t, cond_in, prior_in, frame_mask, f0_feats=f0_in)
|
| 248 |
+
cfm_loss = masked_mean(((v_pred - v_target).abs() * ch_w).mean(-1), frame_mask)
|
| 249 |
+
|
| 250 |
+
x1_hat = x_t + (1.0 - t_view) * v_pred
|
| 251 |
+
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
|
| 252 |
+
t_weight = t[:, None]
|
| 253 |
+
delta_err = ((x1_hat[:, 1:] - x1_hat[:, :-1]) - (x1[:, 1:] - x1[:, :-1])).abs().mean(-1)
|
| 254 |
+
delta_loss = masked_mean(delta_err * t_weight, pair_mask)
|
| 255 |
+
if freq_delta_weight > 0:
|
| 256 |
+
f_err = ((x1_hat[..., 1:] - x1_hat[..., :-1]) - (x1[..., 1:] - x1[..., :-1])).abs().mean(-1)
|
| 257 |
+
freq_delta_loss = masked_mean(f_err * t_weight, frame_mask)
|
| 258 |
+
else:
|
| 259 |
+
freq_delta_loss = x1.new_zeros(())
|
| 260 |
+
|
| 261 |
+
loss = cfm_loss + prior_weight * prior_loss + delta_weight * delta_loss + freq_delta_weight * freq_delta_loss
|
| 262 |
+
metrics = {
|
| 263 |
+
"loss": float(loss.detach()),
|
| 264 |
+
"cfm": float(cfm_loss.detach()),
|
| 265 |
+
"prior": float(prior_loss.detach()),
|
| 266 |
+
"delta": float(delta_loss.detach()),
|
| 267 |
+
"f_delta": float(freq_delta_loss.detach()),
|
| 268 |
+
}
|
| 269 |
+
return loss, metrics
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
@torch.no_grad()
|
| 273 |
+
def validate_cfm(
|
| 274 |
+
model: LuaNovaCFM,
|
| 275 |
+
dataset,
|
| 276 |
+
indices: list[int],
|
| 277 |
+
device: str,
|
| 278 |
+
delta_weight: float = 0.6,
|
| 279 |
+
freq_delta_weight: float = 0.35,
|
| 280 |
+
hf_boost: float = 1.35,
|
| 281 |
+
) -> dict:
|
| 282 |
+
"""Evaluate OT-CFM losses in both predicted-prosody and teacher-forced modes."""
|
| 283 |
+
was_training = model.training
|
| 284 |
+
model.eval()
|
| 285 |
+
totals: dict[str, float] = defaultdict(float)
|
| 286 |
+
weight = 0
|
| 287 |
+
for start in range(0, len(indices), 8):
|
| 288 |
+
batch = collate([dataset[i] for i in indices[start : start + 8]], device)
|
| 289 |
+
sz = len(batch["frame_lengths"])
|
| 290 |
+
_, m = cfm_loss_step(
|
| 291 |
+
model,
|
| 292 |
+
batch,
|
| 293 |
+
teacher_prob=0.0,
|
| 294 |
+
delta_weight=delta_weight,
|
| 295 |
+
freq_delta_weight=freq_delta_weight,
|
| 296 |
+
hf_boost=hf_boost,
|
| 297 |
+
training=False,
|
| 298 |
+
)
|
| 299 |
+
for k, v in m.items():
|
| 300 |
+
totals[f"val_{k}"] += v * sz
|
| 301 |
+
_, m_gt = cfm_loss_step(
|
| 302 |
+
model,
|
| 303 |
+
batch,
|
| 304 |
+
teacher_prob=1.0,
|
| 305 |
+
delta_weight=delta_weight,
|
| 306 |
+
freq_delta_weight=freq_delta_weight,
|
| 307 |
+
hf_boost=hf_boost,
|
| 308 |
+
training=False,
|
| 309 |
+
)
|
| 310 |
+
for k, v in m_gt.items():
|
| 311 |
+
totals[f"val_gt_{k}"] += v * sz
|
| 312 |
+
weight += sz
|
| 313 |
+
if was_training:
|
| 314 |
+
model.train()
|
| 315 |
+
return {k: v / max(weight, 1) for k, v in totals.items()}
|
code/src/lua_nova_v1/training/distill.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OT-CFM trajectory distillation (e.g. 8-step Sway Midpoint teacher -> 2-step Euler student)."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
import copy
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
|
| 15 |
+
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
|
| 16 |
+
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
|
| 17 |
+
from ..models.losses import masked_mean
|
| 18 |
+
from .common import (
|
| 19 |
+
balanced_indices,
|
| 20 |
+
check_leakage,
|
| 21 |
+
cosine_lr,
|
| 22 |
+
export_cfm_checkpoint,
|
| 23 |
+
load_cfm_model,
|
| 24 |
+
update_ema,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def make_channel_weights(n_mels: int, hf_boost: float, device: torch.device | str) -> torch.Tensor | float:
|
| 29 |
+
"""Upweight upper mel bands (bins 60..n_mels) when ``hf_boost != 1.0``."""
|
| 30 |
+
if hf_boost == 1.0:
|
| 31 |
+
return 1.0
|
| 32 |
+
ch_w = torch.ones((1, 1, n_mels), device=device, dtype=torch.float32)
|
| 33 |
+
ch_w[..., 60:] = float(hf_boost)
|
| 34 |
+
return ch_w / ch_w.mean()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _teacher_velocity(
|
| 38 |
+
teacher: LuaNovaCFM,
|
| 39 |
+
x_cur: torch.Tensor,
|
| 40 |
+
t_val: float,
|
| 41 |
+
cond: torch.Tensor,
|
| 42 |
+
prior_mel: torch.Tensor,
|
| 43 |
+
frame_mask: torch.Tensor,
|
| 44 |
+
f0_feats: torch.Tensor | None,
|
| 45 |
+
cfg_scale: float,
|
| 46 |
+
) -> torch.Tensor:
|
| 47 |
+
t_vec = torch.full((x_cur.shape[0],), float(t_val), device=x_cur.device, dtype=torch.float32)
|
| 48 |
+
v_c = teacher.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
|
| 49 |
+
if cfg_scale == 1.0:
|
| 50 |
+
return v_c
|
| 51 |
+
v_u = teacher.flow(
|
| 52 |
+
x_cur,
|
| 53 |
+
t_vec,
|
| 54 |
+
torch.zeros_like(cond),
|
| 55 |
+
torch.zeros_like(prior_mel),
|
| 56 |
+
frame_mask,
|
| 57 |
+
f0_feats=torch.zeros_like(f0_feats) if f0_feats is not None else None,
|
| 58 |
+
)
|
| 59 |
+
return v_u + cfg_scale * (v_c - v_u)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def distill_loss_step(
|
| 63 |
+
teacher: LuaNovaCFM,
|
| 64 |
+
student: LuaNovaCFM,
|
| 65 |
+
batch: dict,
|
| 66 |
+
ch_w: torch.Tensor | float,
|
| 67 |
+
teacher_steps: int = 8,
|
| 68 |
+
teacher_sway: float = -0.5,
|
| 69 |
+
teacher_temp: float = 0.35,
|
| 70 |
+
teacher_cfg: float = 1.0,
|
| 71 |
+
teacher_solver: str = "midpoint",
|
| 72 |
+
student_steps: int = 2,
|
| 73 |
+
student_sway: float = 0.0,
|
| 74 |
+
teacher_prob: float = 0.35,
|
| 75 |
+
f0_smooth_prob: float = 0.15,
|
| 76 |
+
training: bool = True,
|
| 77 |
+
) -> tuple[torch.Tensor, dict[str, float]]:
|
| 78 |
+
"""Compute trajectory distillation loss matching student Euler ODE against the teacher ODE."""
|
| 79 |
+
dev_type = "cuda" if batch["tokens"].device.type == "cuda" else "cpu"
|
| 80 |
+
use_bf16 = dev_type == "cuda"
|
| 81 |
+
|
| 82 |
+
s_grid = student.sway_time_grid(student_steps, student_sway)
|
| 83 |
+
s_mid_idx = max(1, student_steps // 2)
|
| 84 |
+
s_mid_t = s_grid[s_mid_idx]
|
| 85 |
+
t_grid = teacher.sway_time_grid(teacher_steps, teacher_sway)
|
| 86 |
+
t_mid_idx = min(range(1, len(t_grid)), key=lambda idx: abs(t_grid[idx] - s_mid_t))
|
| 87 |
+
|
| 88 |
+
with torch.no_grad():
|
| 89 |
+
hidden, token_mask = teacher.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
|
| 90 |
+
prosody_token_ctx, clause_ctx_tok = teacher.encode_prosody_context(
|
| 91 |
+
hidden, batch["tokens"], batch["stress"], token_mask
|
| 92 |
+
)
|
| 93 |
+
acoustic_frames, prosody_frames, frame_mask, flen = teacher.expand_with_context(
|
| 94 |
+
hidden, prosody_token_ctx, clause_ctx_tok, batch["durations"], token_mask, batch["speakers"]
|
| 95 |
+
)
|
| 96 |
+
if teacher.cfm_config.acoustic_from_frames and teacher_prob >= 1.0:
|
| 97 |
+
prosody_hidden = None
|
| 98 |
+
pred_pros = None
|
| 99 |
+
else:
|
| 100 |
+
prosody_hidden, pred_pros, _ = teacher.sample_prosody(prosody_frames, frame_mask, seed=0)
|
| 101 |
+
|
| 102 |
+
if pred_pros is None or teacher_prob >= 1.0:
|
| 103 |
+
condition = batch["prosody"]
|
| 104 |
+
elif training and teacher_prob > 0.0:
|
| 105 |
+
teach = torch.rand(len(flen), device=flen.device) < teacher_prob
|
| 106 |
+
condition = torch.where(teach[:, None, None], batch["prosody"], teacher.hard_prosody(pred_pros))
|
| 107 |
+
else:
|
| 108 |
+
condition = teacher.hard_prosody(pred_pros)
|
| 109 |
+
if training and f0_smooth_prob > 0.0:
|
| 110 |
+
condition = smooth_f0_channel(condition, f0_smooth_prob)
|
| 111 |
+
|
| 112 |
+
base_h = acoustic_frames if teacher.cfm_config.acoustic_from_frames else prosody_hidden
|
| 113 |
+
f0_feats = f0_features(condition, frame_mask) if teacher.cfm_config.use_f0_harmonics else None
|
| 114 |
+
gate = energy_noise_gate(condition, frame_mask) if teacher.cfm_config.use_energy_gate else 1.0
|
| 115 |
+
|
| 116 |
+
with torch.amp.autocast(device_type=dev_type, dtype=torch.bfloat16, enabled=use_bf16):
|
| 117 |
+
cond, prior_mel = teacher.condition_and_prior(base_h, condition, frame_mask)
|
| 118 |
+
sigma = float(teacher.cfm_config.prior_sigma) * float(teacher_temp)
|
| 119 |
+
eps = torch.randn_like(prior_mel) if training else torch.zeros_like(prior_mel)
|
| 120 |
+
x0 = (prior_mel.float() + sigma * gate * eps) * frame_mask[..., None]
|
| 121 |
+
|
| 122 |
+
x_t = x0
|
| 123 |
+
x_t_mid = x0
|
| 124 |
+
for i in range(teacher_steps):
|
| 125 |
+
t0, t1 = t_grid[i], t_grid[i + 1]
|
| 126 |
+
dt_i = t1 - t0
|
| 127 |
+
if teacher_solver == "midpoint":
|
| 128 |
+
v0 = _teacher_velocity(teacher, x_t, t0, cond, prior_mel, frame_mask, f0_feats, teacher_cfg)
|
| 129 |
+
x_mid = (x_t + 0.5 * dt_i * v0) * frame_mask[..., None]
|
| 130 |
+
vm = _teacher_velocity(
|
| 131 |
+
teacher, x_mid, t0 + 0.5 * dt_i, cond, prior_mel, frame_mask, f0_feats, teacher_cfg
|
| 132 |
+
)
|
| 133 |
+
x_t = (x_t + dt_i * vm) * frame_mask[..., None]
|
| 134 |
+
else:
|
| 135 |
+
v0 = _teacher_velocity(teacher, x_t, t0, cond, prior_mel, frame_mask, f0_feats, teacher_cfg)
|
| 136 |
+
x_t = (x_t + dt_i * v0) * frame_mask[..., None]
|
| 137 |
+
if i + 1 == t_mid_idx:
|
| 138 |
+
x_t_mid = x_t
|
| 139 |
+
x_t_end = x_t
|
| 140 |
+
|
| 141 |
+
with torch.amp.autocast(device_type=dev_type, dtype=torch.bfloat16, enabled=use_bf16):
|
| 142 |
+
b = x0.shape[0]
|
| 143 |
+
x_s = x0
|
| 144 |
+
x_s_mid = x0
|
| 145 |
+
for i in range(student_steps):
|
| 146 |
+
t0, t1 = s_grid[i], s_grid[i + 1]
|
| 147 |
+
dt_i = t1 - t0
|
| 148 |
+
t_vec = torch.full((b,), t0, device=x0.device, dtype=torch.float32)
|
| 149 |
+
v_s = student.flow(x_s, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
|
| 150 |
+
x_s = (x_s + dt_i * v_s) * frame_mask[..., None]
|
| 151 |
+
if i + 1 == s_mid_idx:
|
| 152 |
+
x_s_mid = x_s
|
| 153 |
+
x_s_end = x_s
|
| 154 |
+
|
| 155 |
+
xs_end_f = x_s_end.float()
|
| 156 |
+
xt_end_f = x_t_end.float()
|
| 157 |
+
end_l1 = masked_mean(((xs_end_f - xt_end_f).abs() * ch_w).mean(-1), frame_mask)
|
| 158 |
+
mid_l1 = masked_mean(((x_s_mid.float() - x_t_mid.float()).abs() * ch_w).mean(-1), frame_mask)
|
| 159 |
+
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
|
| 160 |
+
dt_l1 = masked_mean(
|
| 161 |
+
(((xs_end_f[:, 1:] - xs_end_f[:, :-1]) - (xt_end_f[:, 1:] - xt_end_f[:, :-1])).abs()).mean(-1),
|
| 162 |
+
pair_mask,
|
| 163 |
+
)
|
| 164 |
+
df_l1 = masked_mean(
|
| 165 |
+
(((xs_end_f[..., 1:] - xs_end_f[..., :-1]) - (xt_end_f[..., 1:] - xt_end_f[..., :-1])).abs()).mean(-1),
|
| 166 |
+
frame_mask,
|
| 167 |
+
)
|
| 168 |
+
loss = end_l1 + 0.5 * mid_l1 + 0.7 * dt_l1 + 0.4 * df_l1
|
| 169 |
+
metrics = {
|
| 170 |
+
"loss": float(loss.detach()),
|
| 171 |
+
"end_l1": float(end_l1.detach()),
|
| 172 |
+
"mid_l1": float(mid_l1.detach()),
|
| 173 |
+
"dt_l1": float(dt_l1.detach()),
|
| 174 |
+
"df_l1": float(df_l1.detach()),
|
| 175 |
+
}
|
| 176 |
+
return loss, metrics
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@torch.no_grad()
|
| 180 |
+
def validate_distill(
|
| 181 |
+
teacher: LuaNovaCFM,
|
| 182 |
+
student: LuaNovaCFM,
|
| 183 |
+
dataset: AnnotatedDataset,
|
| 184 |
+
indices: list[int],
|
| 185 |
+
device: str,
|
| 186 |
+
ch_w: torch.Tensor | float,
|
| 187 |
+
args: argparse.Namespace,
|
| 188 |
+
) -> dict[str, float]:
|
| 189 |
+
was_flow_training = student.flow.training
|
| 190 |
+
student.eval()
|
| 191 |
+
totals: dict[str, float] = defaultdict(float)
|
| 192 |
+
weight = 0
|
| 193 |
+
for start in range(0, len(indices), 8):
|
| 194 |
+
batch = collate([dataset[i] for i in indices[start : start + 8]], device)
|
| 195 |
+
sz = len(batch["frame_lengths"])
|
| 196 |
+
_, m = distill_loss_step(
|
| 197 |
+
teacher,
|
| 198 |
+
student,
|
| 199 |
+
batch,
|
| 200 |
+
ch_w,
|
| 201 |
+
teacher_steps=args.teacher_steps,
|
| 202 |
+
teacher_sway=args.teacher_sway,
|
| 203 |
+
teacher_temp=args.teacher_temp,
|
| 204 |
+
teacher_cfg=args.teacher_cfg,
|
| 205 |
+
teacher_solver=args.teacher_solver,
|
| 206 |
+
student_steps=args.student_steps,
|
| 207 |
+
student_sway=args.student_sway,
|
| 208 |
+
teacher_prob=args.teacher_prob,
|
| 209 |
+
f0_smooth_prob=0.0,
|
| 210 |
+
training=False,
|
| 211 |
+
)
|
| 212 |
+
for k, v in m.items():
|
| 213 |
+
totals[f"val_{k}"] += v * sz
|
| 214 |
+
weight += sz
|
| 215 |
+
if was_flow_training:
|
| 216 |
+
student.flow.train()
|
| 217 |
+
return {k: v / max(weight, 1) for k, v in totals.items()}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def main() -> None:
|
| 221 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 222 |
+
parser.add_argument("--train", type=Path, required=True)
|
| 223 |
+
parser.add_argument("--validation", type=Path, required=True)
|
| 224 |
+
parser.add_argument("--teacher", type=Path, required=True, help="Teacher CFM v5 checkpoint (.pt)")
|
| 225 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 226 |
+
parser.add_argument("--device", default="cuda")
|
| 227 |
+
parser.add_argument("--steps", type=int, default=12000)
|
| 228 |
+
parser.add_argument("--batch-frames", type=int, default=6000)
|
| 229 |
+
parser.add_argument("--max-batch", type=int, default=16)
|
| 230 |
+
parser.add_argument("--lr", type=float, default=1e-4)
|
| 231 |
+
parser.add_argument("--min-lr", type=float, default=5e-6)
|
| 232 |
+
parser.add_argument("--warmup", type=int, default=400)
|
| 233 |
+
parser.add_argument("--ema-decay", type=float, default=0.999)
|
| 234 |
+
parser.add_argument("--teacher-steps", type=int, default=8)
|
| 235 |
+
parser.add_argument("--teacher-sway", type=float, default=-0.5)
|
| 236 |
+
parser.add_argument("--teacher-temp", type=float, default=0.35)
|
| 237 |
+
parser.add_argument("--teacher-cfg", type=float, default=1.0)
|
| 238 |
+
parser.add_argument("--teacher-solver", default="midpoint", choices=["euler", "midpoint"])
|
| 239 |
+
parser.add_argument("--student-steps", type=int, default=2)
|
| 240 |
+
parser.add_argument("--student-sway", type=float, default=0.0)
|
| 241 |
+
parser.add_argument("--teacher-prob", type=float, default=0.35)
|
| 242 |
+
parser.add_argument("--hf-boost", type=float, default=1.40)
|
| 243 |
+
parser.add_argument("--f0-smooth-prob", type=float, default=0.15)
|
| 244 |
+
parser.add_argument("--save-every", type=int, default=3000)
|
| 245 |
+
parser.add_argument("--log-every", type=int, default=100)
|
| 246 |
+
parser.add_argument("--seed", type=int, default=20261121)
|
| 247 |
+
parser.add_argument("--max-seconds", type=float, default=3600.0)
|
| 248 |
+
args = parser.parse_args()
|
| 249 |
+
|
| 250 |
+
torch.manual_seed(args.seed)
|
| 251 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 252 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 253 |
+
|
| 254 |
+
teacher = load_cfm_model(args.teacher, device=args.device, load_vocos=False).eval()
|
| 255 |
+
for p in teacher.parameters():
|
| 256 |
+
p.requires_grad_(False)
|
| 257 |
+
|
| 258 |
+
student = copy.deepcopy(teacher)
|
| 259 |
+
for p in student.parameters():
|
| 260 |
+
p.requires_grad_(False)
|
| 261 |
+
for p in student.flow.parameters():
|
| 262 |
+
p.requires_grad_(True)
|
| 263 |
+
student.eval()
|
| 264 |
+
student.flow.train()
|
| 265 |
+
|
| 266 |
+
ema_model = copy.deepcopy(student).eval()
|
| 267 |
+
for p in ema_model.parameters():
|
| 268 |
+
p.requires_grad_(False)
|
| 269 |
+
|
| 270 |
+
trainable = list(student.flow.parameters())
|
| 271 |
+
optimizer = torch.optim.AdamW(trainable, lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
|
| 272 |
+
|
| 273 |
+
train_ds = AnnotatedDataset(args.train, student.config, voiced_vowels=True, cache=True)
|
| 274 |
+
val_ds = AnnotatedDataset(args.validation, student.config, voiced_vowels=True, cache=True)
|
| 275 |
+
check_leakage(train_ds, val_ds)
|
| 276 |
+
pool = list(range(len(train_ds)))
|
| 277 |
+
val_indices = balanced_indices(val_ds, min(32, len(val_ds)))
|
| 278 |
+
train_ds.preload(pool, workers=8)
|
| 279 |
+
val_ds.preload(val_indices, workers=4)
|
| 280 |
+
sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
|
| 281 |
+
ch_w = make_channel_weights(student.config.vocos_n_mels, args.hf_boost, args.device)
|
| 282 |
+
|
| 283 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 284 |
+
log_file = (args.output / "train.log").open("a", encoding="utf-8", buffering=1)
|
| 285 |
+
metrics_path = args.output / "metrics.jsonl"
|
| 286 |
+
|
| 287 |
+
def log_record(rec: dict) -> None:
|
| 288 |
+
line = json.dumps(rec, ensure_ascii=False)
|
| 289 |
+
print(line, flush=True)
|
| 290 |
+
log_file.write(line + "\n")
|
| 291 |
+
log_file.flush()
|
| 292 |
+
with metrics_path.open("a", encoding="utf-8") as mf:
|
| 293 |
+
mf.write(line + "\n")
|
| 294 |
+
|
| 295 |
+
init_val = validate_distill(teacher, ema_model, val_ds, val_indices, args.device, ch_w, args)
|
| 296 |
+
log_record(
|
| 297 |
+
{
|
| 298 |
+
"step": 0,
|
| 299 |
+
"trainable_flow_params": sum(p.numel() for p in trainable),
|
| 300 |
+
"teacher_steps": args.teacher_steps,
|
| 301 |
+
"teacher_sway": args.teacher_sway,
|
| 302 |
+
"teacher_temp": args.teacher_temp,
|
| 303 |
+
"student_steps": args.student_steps,
|
| 304 |
+
"student_sway": args.student_sway,
|
| 305 |
+
**init_val,
|
| 306 |
+
}
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
t_start = time.monotonic()
|
| 310 |
+
t_win = time.monotonic()
|
| 311 |
+
win: dict[str, float] = defaultdict(float)
|
| 312 |
+
win_steps = 0
|
| 313 |
+
|
| 314 |
+
try:
|
| 315 |
+
for step in range(1, args.steps + 1):
|
| 316 |
+
lr = cosine_lr(step - 1, args.warmup, args.steps, args.lr, args.min_lr)
|
| 317 |
+
for g in optimizer.param_groups:
|
| 318 |
+
g["lr"] = lr
|
| 319 |
+
batch = collate([train_ds[pool[i]] for i in sampler.next()], args.device)
|
| 320 |
+
optimizer.zero_grad(set_to_none=True)
|
| 321 |
+
loss, m = distill_loss_step(
|
| 322 |
+
teacher,
|
| 323 |
+
student,
|
| 324 |
+
batch,
|
| 325 |
+
ch_w,
|
| 326 |
+
teacher_steps=args.teacher_steps,
|
| 327 |
+
teacher_sway=args.teacher_sway,
|
| 328 |
+
teacher_temp=args.teacher_temp,
|
| 329 |
+
teacher_cfg=args.teacher_cfg,
|
| 330 |
+
teacher_solver=args.teacher_solver,
|
| 331 |
+
student_steps=args.student_steps,
|
| 332 |
+
student_sway=args.student_sway,
|
| 333 |
+
teacher_prob=args.teacher_prob,
|
| 334 |
+
f0_smooth_prob=args.f0_smooth_prob,
|
| 335 |
+
training=True,
|
| 336 |
+
)
|
| 337 |
+
loss.backward()
|
| 338 |
+
grad_norm = float(nn.utils.clip_grad_norm_(trainable, 5.0))
|
| 339 |
+
optimizer.step()
|
| 340 |
+
update_ema(ema_model, student, args.ema_decay)
|
| 341 |
+
|
| 342 |
+
for k, v in m.items():
|
| 343 |
+
win[k] += v
|
| 344 |
+
win["grad_norm"] += grad_norm
|
| 345 |
+
win_steps += 1
|
| 346 |
+
elapsed = time.monotonic() - t_start
|
| 347 |
+
should_stop = step == args.steps or elapsed >= args.max_seconds
|
| 348 |
+
save = step % args.save_every == 0 or should_stop
|
| 349 |
+
|
| 350 |
+
if step % args.log_every == 0 or save:
|
| 351 |
+
if str(args.device).startswith("cuda"):
|
| 352 |
+
torch.cuda.synchronize()
|
| 353 |
+
dt = max(time.monotonic() - t_win, 1e-6)
|
| 354 |
+
rec: dict[str, object] = {k: v / win_steps for k, v in win.items()}
|
| 355 |
+
rec.update(step=step, lr=lr, steps_per_s=win_steps / dt, elapsed_s=elapsed)
|
| 356 |
+
if save:
|
| 357 |
+
rec.update(validate_distill(teacher, ema_model, val_ds, val_indices, args.device, ch_w, args))
|
| 358 |
+
export_cfm_checkpoint(
|
| 359 |
+
ema_model, args.output / "inference_v5_fast2_ema.pt", step, train_ds.annotation
|
| 360 |
+
)
|
| 361 |
+
export_cfm_checkpoint(
|
| 362 |
+
ema_model, args.output / f"inference_v5_fast2_step-{step:06d}.pt", step, train_ds.annotation
|
| 363 |
+
)
|
| 364 |
+
log_record(rec)
|
| 365 |
+
win = defaultdict(float)
|
| 366 |
+
win_steps = 0
|
| 367 |
+
t_win = time.monotonic()
|
| 368 |
+
|
| 369 |
+
if should_stop:
|
| 370 |
+
break
|
| 371 |
+
finally:
|
| 372 |
+
log_file.close()
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
if __name__ == "__main__":
|
| 376 |
+
main()
|
code/src/lua_nova_v1/training/prosody_flow.py
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Item 3 (Stage 3A): Contexto linguistico + DurationFlow + ProsodyFlow generativos."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
import copy
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
from torch.nn import functional as F
|
| 15 |
+
|
| 16 |
+
from ..config import CFMConfig, Config
|
| 17 |
+
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
|
| 18 |
+
from ..models.cfm import LuaNovaCFM, smooth_prosody_noise
|
| 19 |
+
from ..models.losses import masked_mean
|
| 20 |
+
from ..text.phonemizer import phonemize
|
| 21 |
+
from ..utils.audio import limit_peak
|
| 22 |
+
from .common import VALIDATION_SAMPLE_TEXTS, check_leakage, export_cfm_checkpoint, masked_std, update_ema
|
| 23 |
+
|
| 24 |
+
SEMITONES = 12.0 / math.log(2.0)
|
| 25 |
+
|
| 26 |
+
FROZEN_FOR_ITEM3 = (
|
| 27 |
+
"tokens",
|
| 28 |
+
"stress",
|
| 29 |
+
"voices",
|
| 30 |
+
"encoder",
|
| 31 |
+
"frame_voices",
|
| 32 |
+
"frame_position",
|
| 33 |
+
"prosody_projection",
|
| 34 |
+
"acoustic_stack",
|
| 35 |
+
"prior_head",
|
| 36 |
+
"flow",
|
| 37 |
+
"vocoder",
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
TRAINABLE_ITEM3 = (
|
| 41 |
+
"context_adapter",
|
| 42 |
+
"duration",
|
| 43 |
+
"dur_flow",
|
| 44 |
+
"frame_ctx_proj",
|
| 45 |
+
"prosody_stack",
|
| 46 |
+
"prosody_head",
|
| 47 |
+
"prosody_flow",
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def set_item3_trainable(model: LuaNovaCFM) -> list[nn.Parameter]:
|
| 52 |
+
"""Congela encoder/acustico/vocoder e habilita apenas os modulos do Item 3."""
|
| 53 |
+
model._frontend_frozen = False
|
| 54 |
+
for p in model.parameters():
|
| 55 |
+
p.requires_grad_(False)
|
| 56 |
+
trainable: list[nn.Parameter] = []
|
| 57 |
+
for name in TRAINABLE_ITEM3:
|
| 58 |
+
mod = getattr(model, name, None)
|
| 59 |
+
if mod is None:
|
| 60 |
+
continue
|
| 61 |
+
for p in mod.parameters():
|
| 62 |
+
p.requires_grad_(True)
|
| 63 |
+
trainable.append(p)
|
| 64 |
+
return trainable
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def set_item3_train_mode(model: LuaNovaCFM, training: bool = True) -> None:
|
| 68 |
+
model.eval()
|
| 69 |
+
if training:
|
| 70 |
+
for name in TRAINABLE_ITEM3:
|
| 71 |
+
mod = getattr(model, name, None)
|
| 72 |
+
if mod is not None:
|
| 73 |
+
mod.train()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def build_item3_model(
|
| 77 |
+
init_cfm_path: Path | None,
|
| 78 |
+
init_stage1_path: Path | None,
|
| 79 |
+
cfg_overrides: dict | None = None,
|
| 80 |
+
device: str = "cuda",
|
| 81 |
+
vocos_model=None,
|
| 82 |
+
) -> LuaNovaCFM:
|
| 83 |
+
"""Create LuaNovaCFM with Item 3 enabled from either a CFM checkpoint or Stage-1 weights."""
|
| 84 |
+
if init_cfm_path is None and init_stage1_path is None:
|
| 85 |
+
raise ValueError("at least one of init_cfm_path or init_stage1_path is required")
|
| 86 |
+
if init_cfm_path is not None:
|
| 87 |
+
cfm_ckpt = torch.load(init_cfm_path, map_location="cpu", weights_only=True)
|
| 88 |
+
cfg = CFMConfig.from_dict(cfm_ckpt["cfm_config"])
|
| 89 |
+
else:
|
| 90 |
+
s1_tmp = torch.load(init_stage1_path, map_location="cpu", weights_only=True)
|
| 91 |
+
cfg = CFMConfig(base=Config.from_dict(s1_tmp["config"]), acoustic_from_frames=True, mel_space="bigvgan_24k_100")
|
| 92 |
+
cfm_ckpt = None
|
| 93 |
+
cfg.use_ling_context = True
|
| 94 |
+
cfg.use_duration_flow = True
|
| 95 |
+
cfg.use_prosody_flow = True
|
| 96 |
+
cfg.use_energy_gate = True
|
| 97 |
+
if cfg_overrides:
|
| 98 |
+
for k, v in cfg_overrides.items():
|
| 99 |
+
if hasattr(cfg, k):
|
| 100 |
+
setattr(cfg, k, v)
|
| 101 |
+
|
| 102 |
+
model = LuaNovaCFM(cfg, vocos_model=vocos_model)
|
| 103 |
+
if cfm_ckpt is not None:
|
| 104 |
+
own = dict(model.state_dict())
|
| 105 |
+
for k, v in cfm_ckpt["model"].items():
|
| 106 |
+
if k in own and own[k].shape == v.shape:
|
| 107 |
+
own[k] = v
|
| 108 |
+
model.load_state_dict(own, strict=True)
|
| 109 |
+
|
| 110 |
+
if init_stage1_path is not None:
|
| 111 |
+
s1_ckpt = torch.load(init_stage1_path, map_location="cpu", weights_only=True)
|
| 112 |
+
s1_sd = s1_ckpt.get("system", s1_ckpt.get("model"))
|
| 113 |
+
if cfm_ckpt is None:
|
| 114 |
+
model.load_frontend(s1_sd)
|
| 115 |
+
else:
|
| 116 |
+
own = dict(model.state_dict())
|
| 117 |
+
pref = "model." if any(k.startswith("model.") for k in s1_sd) else ""
|
| 118 |
+
for k, v in s1_sd.items():
|
| 119 |
+
if pref and not k.startswith(pref):
|
| 120 |
+
continue
|
| 121 |
+
key = k[len(pref) :] if pref else k
|
| 122 |
+
if key.startswith(("duration.", "prosody_stack.", "prosody_head.")) and key in own and own[key].shape == v.shape:
|
| 123 |
+
own[key] = v
|
| 124 |
+
model.load_state_dict(own, strict=True)
|
| 125 |
+
return model.to(device)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def prosody_flow_loss_step(
|
| 129 |
+
model: LuaNovaCFM,
|
| 130 |
+
batch: dict,
|
| 131 |
+
frame_dropout: float = 0.15,
|
| 132 |
+
weights: dict[str, float] | None = None,
|
| 133 |
+
training: bool = True,
|
| 134 |
+
) -> tuple[torch.Tensor, dict[str, float]]:
|
| 135 |
+
w = {
|
| 136 |
+
"dur_prior": 2.0,
|
| 137 |
+
"pause_bce": 1.5,
|
| 138 |
+
"dur_cfm": 2.5,
|
| 139 |
+
"dur_total": 1.0,
|
| 140 |
+
"prior_f0": 2.0,
|
| 141 |
+
"prior_f0_dt": 3.0,
|
| 142 |
+
"voicing": 2.0,
|
| 143 |
+
"prior_eng": 1.5,
|
| 144 |
+
"prior_eng_dt": 1.0,
|
| 145 |
+
"pflow_f0": 3.5,
|
| 146 |
+
"pflow_eng": 1.5,
|
| 147 |
+
"pflow_f0_dt": 4.5,
|
| 148 |
+
"pflow_f0_d2": 1.5,
|
| 149 |
+
"pflow_eng_dt": 1.5,
|
| 150 |
+
"pflow_dist": 1.0,
|
| 151 |
+
}
|
| 152 |
+
if weights:
|
| 153 |
+
w.update(weights)
|
| 154 |
+
|
| 155 |
+
cfg = model.cfm_config
|
| 156 |
+
with torch.no_grad():
|
| 157 |
+
hidden, token_mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
|
| 158 |
+
|
| 159 |
+
prosody_token_ctx, clause_ctx_tok = model.encode_prosody_context(
|
| 160 |
+
hidden, batch["tokens"], batch["stress"], token_mask
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# --- 1. Duration Prior + DurationFlow (OT-CFM sobre log1p(dur)) ---
|
| 164 |
+
gt_dur = batch["durations"]
|
| 165 |
+
present_mask = (gt_dur > 0) & token_mask
|
| 166 |
+
non_phone_mask = (~model.phone_tokens[batch["tokens"]]) & token_mask
|
| 167 |
+
raw_dur = model.duration(prosody_token_ctx, token_mask).float()
|
| 168 |
+
z1_gt = torch.log1p(gt_dur.float())
|
| 169 |
+
dur_prior_l1 = masked_mean((raw_dur[..., 0] - z1_gt).abs(), present_mask)
|
| 170 |
+
pause_bce = masked_mean(
|
| 171 |
+
F.binary_cross_entropy_with_logits(raw_dur[..., 1], (gt_dur > 0).float(), reduction="none"),
|
| 172 |
+
non_phone_mask,
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
b, l_len = batch["tokens"].shape
|
| 176 |
+
prior_z = raw_dur[..., 0].detach().clamp(0.0, math.log1p(400.0))
|
| 177 |
+
if training:
|
| 178 |
+
t_d = torch.sigmoid(torch.randn(b, device=hidden.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
|
| 179 |
+
eps_d = torch.randn((b, l_len, 1), device=hidden.device, dtype=torch.float32)
|
| 180 |
+
else:
|
| 181 |
+
t_d = torch.full((b,), 0.5, device=hidden.device, dtype=torch.float32)
|
| 182 |
+
eps_d = torch.zeros((b, l_len, 1), device=hidden.device, dtype=torch.float32)
|
| 183 |
+
z0_d = (prior_z[..., None] + cfg.dur_flow_sigma * eps_d) * token_mask[..., None].float()
|
| 184 |
+
z1_d = z1_gt[..., None]
|
| 185 |
+
td_view = t_d[:, None, None]
|
| 186 |
+
zt_d = ((1.0 - td_view) * z0_d + td_view * z1_d) * token_mask[..., None].float()
|
| 187 |
+
v_dur_pred = model.dur_flow(zt_d, t_d, prior_z[..., None], prosody_token_ctx, token_mask)
|
| 188 |
+
dur_cfm_l1 = masked_mean((v_dur_pred - (z1_d - z0_d)).abs().squeeze(-1), present_mask)
|
| 189 |
+
|
| 190 |
+
z1_d_hat = (zt_d + (1.0 - td_view) * v_dur_pred).squeeze(-1)
|
| 191 |
+
dur_hat_frames = (torch.exp(z1_d_hat.clamp(0.0, math.log1p(400.0))) - 1.0) * present_mask.float()
|
| 192 |
+
dur_gt_frames = gt_dur.float() * present_mask.float()
|
| 193 |
+
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)
|
| 194 |
+
dur_total_l1 = (tot_rel * t_d).mean()
|
| 195 |
+
|
| 196 |
+
# --- 2. Frame expansion + Prosody Prior + ProsodyFlow (OT-CFM com ruido correlacionado) ---
|
| 197 |
+
_, prosody_frames, frame_mask, _ = model.expand_with_context(
|
| 198 |
+
hidden, prosody_token_ctx, clause_ctx_tok, gt_dur, token_mask, batch["speakers"]
|
| 199 |
+
)
|
| 200 |
+
p_frames_in = F.dropout(prosody_frames, p=frame_dropout, training=True) if (training and frame_dropout > 0.0) else prosody_frames
|
| 201 |
+
prosody_hidden, prior_raw = model.predict_prosody(p_frames_in, frame_mask)
|
| 202 |
+
prior_raw = prior_raw.float()
|
| 203 |
+
|
| 204 |
+
gt_p = batch["prosody"].float()
|
| 205 |
+
trusted = batch["pitch_trusted"].float()
|
| 206 |
+
sung = frame_mask.float() * gt_p[..., 1] * trusted
|
| 207 |
+
pitch_w = frame_mask.float() * (trusted + 0.1 * (1.0 - trusted))
|
| 208 |
+
sung_pair = sung[:, 1:] * sung[:, :-1]
|
| 209 |
+
sung_tri = sung[:, 2:] * sung[:, 1:-1] * sung[:, :-2]
|
| 210 |
+
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
|
| 211 |
+
|
| 212 |
+
prior_f0_l1 = masked_mean((prior_raw[..., 0] - gt_p[..., 0]).abs(), pitch_w)
|
| 213 |
+
prior_f0_dt = masked_mean(((prior_raw[:, 1:, 0] - prior_raw[:, :-1, 0]) - (gt_p[:, 1:, 0] - gt_p[:, :-1, 0])).abs(), sung_pair)
|
| 214 |
+
voicing_bce = masked_mean(F.binary_cross_entropy_with_logits(prior_raw[..., 1], gt_p[..., 1], reduction="none"), frame_mask)
|
| 215 |
+
prior_eng_l1 = masked_mean((prior_raw[..., 2] - gt_p[..., 2]).abs(), frame_mask)
|
| 216 |
+
prior_eng_dt = masked_mean(((prior_raw[:, 1:, 2] - prior_raw[:, :-1, 2]) - (gt_p[:, 1:, 2] - gt_p[:, :-1, 2])).abs(), pair_mask)
|
| 217 |
+
|
| 218 |
+
prior_fe = torch.stack((prior_raw[..., 0], prior_raw[..., 2]), dim=-1).detach()
|
| 219 |
+
voicing_prob = torch.sigmoid(prior_raw[..., 1:2]).detach()
|
| 220 |
+
y1 = torch.stack((gt_p[..., 0], gt_p[..., 2]), dim=-1) * frame_mask[..., None].float()
|
| 221 |
+
t_len = prosody_frames.shape[1]
|
| 222 |
+
if training:
|
| 223 |
+
t_p = torch.sigmoid(torch.randn(b, device=hidden.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
|
| 224 |
+
eps_p = torch.randn((b, t_len, 2), device=hidden.device, dtype=torch.float32)
|
| 225 |
+
else:
|
| 226 |
+
t_p = torch.full((b,), 0.5, device=hidden.device, dtype=torch.float32)
|
| 227 |
+
eps_p = torch.zeros((b, t_len, 2), device=hidden.device, dtype=torch.float32)
|
| 228 |
+
eps_sm = smooth_prosody_noise(eps_p, frame_mask, model.prosody_noise_kernel)
|
| 229 |
+
y0 = (prior_fe + cfg.prosody_flow_sigma * eps_sm) * frame_mask[..., None].float()
|
| 230 |
+
tp_view = t_p[:, None, None]
|
| 231 |
+
y_t = ((1.0 - tp_view) * y0 + tp_view * y1) * frame_mask[..., None].float()
|
| 232 |
+
v_p_pred = model.prosody_flow(y_t, t_p, prior_fe, voicing_prob, prosody_hidden, frame_mask)
|
| 233 |
+
v_p_tgt = (y1 - y0) * frame_mask[..., None].float()
|
| 234 |
+
|
| 235 |
+
pflow_f0_l1 = masked_mean((v_p_pred[..., 0] - v_p_tgt[..., 0]).abs(), pitch_w)
|
| 236 |
+
pflow_eng_l1 = masked_mean((v_p_pred[..., 1] - v_p_tgt[..., 1]).abs(), frame_mask)
|
| 237 |
+
|
| 238 |
+
y1_hat = (y_t + (1.0 - tp_view) * v_p_pred) * frame_mask[..., None].float()
|
| 239 |
+
tp_w1 = t_p[:, None]
|
| 240 |
+
pflow_f0_dt = masked_mean(
|
| 241 |
+
((y1_hat[:, 1:, 0] - y1_hat[:, :-1, 0]) - (y1[:, 1:, 0] - y1[:, :-1, 0])).abs() * tp_w1,
|
| 242 |
+
sung_pair,
|
| 243 |
+
)
|
| 244 |
+
d2_p = y1_hat[:, 2:, 0] - 2.0 * y1_hat[:, 1:-1, 0] + y1_hat[:, :-2, 0]
|
| 245 |
+
d2_t = y1[:, 2:, 0] - 2.0 * y1[:, 1:-1, 0] + y1[:, :-2, 0]
|
| 246 |
+
pflow_f0_d2 = masked_mean((d2_p - d2_t).abs() * tp_w1, sung_tri)
|
| 247 |
+
pflow_eng_dt = masked_mean(
|
| 248 |
+
((y1_hat[:, 1:, 1] - y1_hat[:, :-1, 1]) - (y1[:, 1:, 1] - y1[:, :-1, 1])).abs() * tp_w1,
|
| 249 |
+
pair_mask,
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
# Distribuicao F0 por enunciado (std, P90-P10, caimento final) sem excursion_gain artificial
|
| 253 |
+
q_levels = torch.tensor([0.10, 0.90], device=hidden.device, dtype=torch.float32)
|
| 254 |
+
dist_errs = []
|
| 255 |
+
enough_dist = (sung.sum(1) >= 15) & (t_p > 0.35)
|
| 256 |
+
for i in range(b):
|
| 257 |
+
if not bool(enough_dist[i]):
|
| 258 |
+
continue
|
| 259 |
+
idx = (sung[i] > 0.5).nonzero(as_tuple=False).squeeze(-1)
|
| 260 |
+
vp = y1_hat[i, idx, 0]
|
| 261 |
+
vt = y1[i, idx, 0]
|
| 262 |
+
std_err = (vp.std() - vt.std()).abs()
|
| 263 |
+
qp = torch.quantile(vp, q_levels)
|
| 264 |
+
qt = torch.quantile(vt, q_levels)
|
| 265 |
+
span_err = ((qp[1] - qp[0]) - (qt[1] - qt[0])).abs()
|
| 266 |
+
k_tail = max(1, int(idx.numel()) // 5)
|
| 267 |
+
k_head = max(1, int(idx.numel()) // 2)
|
| 268 |
+
tail_err = ((vp[-k_tail:].mean() - vp[:k_head].mean()) - (vt[-k_tail:].mean() - vt[:k_head].mean())).abs()
|
| 269 |
+
dist_errs.append((std_err + 0.7 * span_err + 0.8 * tail_err) * t_p[i])
|
| 270 |
+
pflow_dist = torch.stack(dist_errs).mean() if dist_errs else y1_hat.new_zeros(())
|
| 271 |
+
|
| 272 |
+
terms = {
|
| 273 |
+
"dur_prior": dur_prior_l1,
|
| 274 |
+
"pause_bce": pause_bce,
|
| 275 |
+
"dur_cfm": dur_cfm_l1,
|
| 276 |
+
"dur_total": dur_total_l1,
|
| 277 |
+
"prior_f0": prior_f0_l1,
|
| 278 |
+
"prior_f0_dt": prior_f0_dt,
|
| 279 |
+
"voicing": voicing_bce,
|
| 280 |
+
"prior_eng": prior_eng_l1,
|
| 281 |
+
"prior_eng_dt": prior_eng_dt,
|
| 282 |
+
"pflow_f0": pflow_f0_l1,
|
| 283 |
+
"pflow_eng": pflow_eng_l1,
|
| 284 |
+
"pflow_f0_dt": pflow_f0_dt,
|
| 285 |
+
"pflow_f0_d2": pflow_f0_d2,
|
| 286 |
+
"pflow_eng_dt": pflow_eng_dt,
|
| 287 |
+
"pflow_dist": pflow_dist,
|
| 288 |
+
}
|
| 289 |
+
loss = sum(w[k] * v for k, v in terms.items())
|
| 290 |
+
metrics = {"loss": float(loss.detach()), **{k: float(v.detach()) for k, v in terms.items()}}
|
| 291 |
+
return loss, metrics
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@torch.no_grad()
|
| 295 |
+
def evaluate_item3(
|
| 296 |
+
model: LuaNovaCFM,
|
| 297 |
+
dataset: AnnotatedDataset,
|
| 298 |
+
device: str,
|
| 299 |
+
dur_temp: float | None = None,
|
| 300 |
+
prosody_temp: float | None = None,
|
| 301 |
+
dur_steps: int | None = None,
|
| 302 |
+
prosody_steps: int | None = None,
|
| 303 |
+
) -> dict[str, float]:
|
| 304 |
+
"""Avalia DurationFlow e ProsodyFlow em free-running na validacao/teste inteiros."""
|
| 305 |
+
model.eval()
|
| 306 |
+
dur_ph_mae, dur_all_mae, tot_len_err = [], [], []
|
| 307 |
+
f0_mae, f0_delta_mae, jit_pred, jit_gt = [], [], [], []
|
| 308 |
+
std_pred, std_gt, span95_pred, span95_gt, tail_pred, tail_gt = [], [], [], [], [], []
|
| 309 |
+
q_tail_p, q_tail_g, d_tail_p, d_tail_g = [], [], [], []
|
| 310 |
+
eng_mae, v_acc = [], []
|
| 311 |
+
sp_tp = sp_fp = sp_fn = 0
|
| 312 |
+
q95 = torch.tensor([0.05, 0.95], device=device, dtype=torch.float32)
|
| 313 |
+
|
| 314 |
+
for i, row in enumerate(dataset.rows):
|
| 315 |
+
batch = collate([dataset[i]], device)
|
| 316 |
+
hidden, mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
|
| 317 |
+
p_tok_ctx, clause_ctx = model.encode_prosody_context(hidden, batch["tokens"], batch["stress"], mask)
|
| 318 |
+
|
| 319 |
+
pred_dur, _ = model.sample_durations(
|
| 320 |
+
p_tok_ctx, mask, batch["tokens"], speed=1.0, seed=0, temperature=dur_temp, steps=dur_steps
|
| 321 |
+
)
|
| 322 |
+
pd = pred_dur[0]
|
| 323 |
+
gd = batch["durations"][0]
|
| 324 |
+
tok = batch["tokens"][0]
|
| 325 |
+
is_ph = model.phone_tokens[tok]
|
| 326 |
+
dur_ph_mae.append(float((pd[is_ph] - gd[is_ph]).abs().float().mean()))
|
| 327 |
+
dur_all_mae.append(float((pd - gd).abs().float().mean()))
|
| 328 |
+
tot_len_err.append(abs(int(pd.sum()) - int(gd.sum())) / max(int(gd.sum()), 1) * 100.0)
|
| 329 |
+
pause_tok = ~is_ph & mask[0]
|
| 330 |
+
sp_tp += int(((pd > 0) & (gd > 0) & pause_tok).sum())
|
| 331 |
+
sp_fp += int(((pd > 0) & (gd == 0) & pause_tok).sum())
|
| 332 |
+
sp_fn += int(((pd == 0) & (gd > 0) & pause_tok).sum())
|
| 333 |
+
|
| 334 |
+
_, p_frames, fmask, _ = model.expand_with_context(
|
| 335 |
+
hidden, p_tok_ctx, clause_ctx, batch["durations"], mask, batch["speakers"]
|
| 336 |
+
)
|
| 337 |
+
_, pred_p, _ = model.sample_prosody(p_frames, fmask, seed=0, temperature=prosody_temp, steps=prosody_steps)
|
| 338 |
+
gp = batch["prosody"][0].float()
|
| 339 |
+
tr = batch["pitch_trusted"][0] > 0.5
|
| 340 |
+
vp = pred_p[0, :, 0].float()
|
| 341 |
+
vt = gp[:, 0]
|
| 342 |
+
sung = (gp[:, 1] > 0.5) & tr
|
| 343 |
+
if int(sung.sum()) >= 15:
|
| 344 |
+
f0_mae.append(SEMITONES * float((vp[sung] - vt[sung]).abs().mean()))
|
| 345 |
+
pair = sung[1:] & sung[:-1]
|
| 346 |
+
if bool(pair.any()):
|
| 347 |
+
dp = (vp[1:] - vp[:-1])[pair]
|
| 348 |
+
dt = (vt[1:] - vt[:-1])[pair]
|
| 349 |
+
f0_delta_mae.append(SEMITONES * float((dp - dt).abs().mean()))
|
| 350 |
+
jit_pred.append(SEMITONES * float(dp.abs().mean()))
|
| 351 |
+
jit_gt.append(SEMITONES * float(dt.abs().mean()))
|
| 352 |
+
pv, tv = vp[sung], vt[sung]
|
| 353 |
+
std_pred.append(SEMITONES * float(pv.std()))
|
| 354 |
+
std_gt.append(SEMITONES * float(tv.std()))
|
| 355 |
+
qp = torch.quantile(pv, q95)
|
| 356 |
+
qt = torch.quantile(tv, q95)
|
| 357 |
+
span95_pred.append(SEMITONES * float(qp[1] - qp[0]))
|
| 358 |
+
span95_gt.append(SEMITONES * float(qt[1] - qt[0]))
|
| 359 |
+
kt, kh = max(1, int(pv.numel()) // 5), max(1, int(pv.numel()) // 2)
|
| 360 |
+
tp = SEMITONES * float(pv[-kt:].mean() - pv[:kh].mean())
|
| 361 |
+
tg = SEMITONES * float(tv[-kt:].mean() - tv[:kh].mean())
|
| 362 |
+
tail_pred.append(tp)
|
| 363 |
+
tail_gt.append(tg)
|
| 364 |
+
if "?" in row["text"]:
|
| 365 |
+
q_tail_p.append(tp)
|
| 366 |
+
q_tail_g.append(tg)
|
| 367 |
+
else:
|
| 368 |
+
d_tail_p.append(tp)
|
| 369 |
+
d_tail_g.append(tg)
|
| 370 |
+
eng_mae.append(float((pred_p[0, :, 2] - gp[:, 2]).abs().mean()))
|
| 371 |
+
v_acc.append(float(((pred_p[0, :, 1] > 0) == (gp[:, 1] > 0.5)).float().mean()))
|
| 372 |
+
|
| 373 |
+
pause_f1 = 2 * sp_tp / max(2 * sp_tp + sp_fp + sp_fn, 1)
|
| 374 |
+
return {
|
| 375 |
+
"val_dur_ph_mae": sum(dur_ph_mae) / len(dur_ph_mae),
|
| 376 |
+
"val_dur_all_mae": sum(dur_all_mae) / len(dur_all_mae),
|
| 377 |
+
"val_tot_len_err_pct": sum(tot_len_err) / len(tot_len_err),
|
| 378 |
+
"val_pause_f1": pause_f1,
|
| 379 |
+
"val_f0_mae_st": sum(f0_mae) / max(len(f0_mae), 1),
|
| 380 |
+
"val_f0_delta_mae_st": sum(f0_delta_mae) / max(len(f0_delta_mae), 1),
|
| 381 |
+
"val_f0_jit_pred": sum(jit_pred) / max(len(jit_pred), 1),
|
| 382 |
+
"val_f0_jit_gt": sum(jit_gt) / max(len(jit_gt), 1),
|
| 383 |
+
"val_f0_std_pred": sum(std_pred) / max(len(std_pred), 1),
|
| 384 |
+
"val_f0_std_gt": sum(std_gt) / max(len(std_gt), 1),
|
| 385 |
+
"val_span95_pred": sum(span95_pred) / max(len(span95_pred), 1),
|
| 386 |
+
"val_span95_gt": sum(span95_gt) / max(len(span95_gt), 1),
|
| 387 |
+
"val_tail_pred": sum(tail_pred) / max(len(tail_pred), 1),
|
| 388 |
+
"val_tail_gt": sum(tail_gt) / max(len(tail_gt), 1),
|
| 389 |
+
"val_q_tail_pred": sum(q_tail_p) / max(len(q_tail_p), 1),
|
| 390 |
+
"val_q_tail_gt": sum(q_tail_g) / max(len(q_tail_g), 1),
|
| 391 |
+
"val_decl_tail_pred": sum(d_tail_p) / max(len(d_tail_p), 1),
|
| 392 |
+
"val_decl_tail_gt": sum(d_tail_g) / max(len(d_tail_g), 1),
|
| 393 |
+
"val_voicing_acc": sum(v_acc) / len(v_acc),
|
| 394 |
+
"val_eng_mae": sum(eng_mae) / len(eng_mae),
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
@torch.no_grad()
|
| 399 |
+
def save_item3_samples(model: LuaNovaCFM, out_dir: Path, step: int) -> None:
|
| 400 |
+
if getattr(model.vocoder, "vocos", None) is None:
|
| 401 |
+
return
|
| 402 |
+
import soundfile as sf
|
| 403 |
+
|
| 404 |
+
model.eval()
|
| 405 |
+
device = next(model.parameters()).device
|
| 406 |
+
sample_dir = out_dir / "samples" / f"step-{step:08d}"
|
| 407 |
+
sample_dir.mkdir(parents=True, exist_ok=True)
|
| 408 |
+
for idx, text in enumerate(VALIDATION_SAMPLE_TEXTS, 1):
|
| 409 |
+
ph = phonemize(text)
|
| 410 |
+
tok = torch.tensor([ph.ids], device=device)
|
| 411 |
+
st = torch.tensor([ph.stress], device=device)
|
| 412 |
+
ln = torch.tensor([len(ph)], device=device)
|
| 413 |
+
sp = torch.tensor([0], device=device)
|
| 414 |
+
wav, wav_len, _ = model.synthesize(
|
| 415 |
+
tok, st, ln, sp, seed=0, n_steps=4, cfg_scale=1.0, temperature=0.85, solver="midpoint"
|
| 416 |
+
)
|
| 417 |
+
w = limit_peak(wav[0, : int(wav_len[0])].cpu())
|
| 418 |
+
sf.write(sample_dir / f"sample_{idx:02d}.wav", w.numpy(), model.config.sample_rate, subtype="PCM_16")
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def main() -> None:
|
| 422 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 423 |
+
parser.add_argument("--train", type=Path, required=True)
|
| 424 |
+
parser.add_argument("--validation", type=Path, required=True)
|
| 425 |
+
parser.add_argument("--init-cfm", type=Path, default=None, help="Optional LuaNovaCFM checkpoint to initialize from")
|
| 426 |
+
parser.add_argument("--init-stage1", type=Path, default=None, help="Stage 1 checkpoint for encoder, duration, and prosody")
|
| 427 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 428 |
+
parser.add_argument("--device", default="cuda")
|
| 429 |
+
parser.add_argument("--steps", type=int, default=12000)
|
| 430 |
+
parser.add_argument("--batch-frames", type=int, default=9000)
|
| 431 |
+
parser.add_argument("--max-batch", type=int, default=32)
|
| 432 |
+
parser.add_argument("--learning-rate", type=float, default=2e-4)
|
| 433 |
+
parser.add_argument("--warmup", type=int, default=600)
|
| 434 |
+
parser.add_argument("--ema-decay", type=float, default=0.997)
|
| 435 |
+
parser.add_argument("--frame-dropout", type=float, default=0.15)
|
| 436 |
+
parser.add_argument("--dur-temp", type=float, default=0.50)
|
| 437 |
+
parser.add_argument("--prosody-temp", type=float, default=0.75)
|
| 438 |
+
parser.add_argument("--log-every", type=int, default=100)
|
| 439 |
+
parser.add_argument("--eval-every", type=int, default=2000)
|
| 440 |
+
parser.add_argument("--save-every", type=int, default=3000)
|
| 441 |
+
parser.add_argument("--sample-every", type=int, default=3000)
|
| 442 |
+
parser.add_argument("--seed", type=int, default=20261120)
|
| 443 |
+
parser.add_argument("--max-seconds", type=float, default=2400)
|
| 444 |
+
args = parser.parse_args()
|
| 445 |
+
|
| 446 |
+
torch.manual_seed(args.seed)
|
| 447 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 448 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 449 |
+
|
| 450 |
+
model = build_item3_model(
|
| 451 |
+
args.init_cfm,
|
| 452 |
+
args.init_stage1,
|
| 453 |
+
cfg_overrides={"dur_flow_temp": args.dur_temp, "prosody_flow_temp": args.prosody_temp},
|
| 454 |
+
device=args.device,
|
| 455 |
+
)
|
| 456 |
+
trainable = set_item3_trainable(model)
|
| 457 |
+
ema_model = copy.deepcopy(model).eval()
|
| 458 |
+
for p in ema_model.parameters():
|
| 459 |
+
p.requires_grad_(False)
|
| 460 |
+
|
| 461 |
+
train_ds = AnnotatedDataset(args.train, model.config, voiced_vowels=True)
|
| 462 |
+
val_ds = AnnotatedDataset(args.validation, model.config, voiced_vowels=True)
|
| 463 |
+
check_leakage(train_ds, val_ds)
|
| 464 |
+
pool = list(range(len(train_ds)))
|
| 465 |
+
train_ds.preload(pool)
|
| 466 |
+
val_ds.preload(list(range(len(val_ds))))
|
| 467 |
+
|
| 468 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 469 |
+
(args.output / "cfm_config.json").write_text(json.dumps(model.cfm_config.to_dict(), indent=2) + "\n", encoding="utf-8")
|
| 470 |
+
init_eval = evaluate_item3(ema_model, val_ds, args.device)
|
| 471 |
+
print(
|
| 472 |
+
json.dumps(
|
| 473 |
+
{
|
| 474 |
+
"step": 0,
|
| 475 |
+
"total_parameters": sum(p.numel() for p in model.parameters()),
|
| 476 |
+
"trainable_item3_params": sum(p.numel() for p in trainable),
|
| 477 |
+
**init_eval,
|
| 478 |
+
}
|
| 479 |
+
),
|
| 480 |
+
flush=True,
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
optimizer = torch.optim.AdamW(trainable, lr=args.learning_rate, betas=(0.9, 0.98), weight_decay=0.01)
|
| 484 |
+
sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
|
| 485 |
+
|
| 486 |
+
def lr_at(s: int) -> float:
|
| 487 |
+
if s < args.warmup:
|
| 488 |
+
return args.learning_rate * (s + 1) / max(args.warmup, 1)
|
| 489 |
+
prog = (s - args.warmup) / max(args.steps - args.warmup, 1)
|
| 490 |
+
return args.learning_rate * (0.08 + 0.92 * 0.5 * (1.0 + math.cos(math.pi * min(prog, 1.0))))
|
| 491 |
+
|
| 492 |
+
win = defaultdict(float)
|
| 493 |
+
win_steps = 0
|
| 494 |
+
t_start = time.monotonic()
|
| 495 |
+
t_win = time.monotonic()
|
| 496 |
+
set_item3_train_mode(model, True)
|
| 497 |
+
|
| 498 |
+
for step in range(1, args.steps + 1):
|
| 499 |
+
lr = lr_at(step - 1)
|
| 500 |
+
for g in optimizer.param_groups:
|
| 501 |
+
g["lr"] = lr
|
| 502 |
+
batch = collate([train_ds[pool[i]] for i in sampler.next()], args.device)
|
| 503 |
+
optimizer.zero_grad(set_to_none=True)
|
| 504 |
+
loss, metrics = prosody_flow_loss_step(model, batch, frame_dropout=args.frame_dropout, training=True)
|
| 505 |
+
loss.backward()
|
| 506 |
+
grad_norm = float(nn.utils.clip_grad_norm_(trainable, 5.0))
|
| 507 |
+
optimizer.step()
|
| 508 |
+
update_ema(ema_model, model, args.ema_decay)
|
| 509 |
+
|
| 510 |
+
for k, v in metrics.items():
|
| 511 |
+
win[k] += v
|
| 512 |
+
win["grad_norm"] += grad_norm
|
| 513 |
+
win_steps += 1
|
| 514 |
+
elapsed = time.monotonic() - t_start
|
| 515 |
+
should_stop = step == args.steps or elapsed >= args.max_seconds
|
| 516 |
+
is_eval = step % args.eval_every == 0 or should_stop
|
| 517 |
+
is_save = step % args.save_every == 0 or should_stop
|
| 518 |
+
|
| 519 |
+
if step % args.log_every == 0 or is_eval or is_save:
|
| 520 |
+
if str(args.device).startswith("cuda"):
|
| 521 |
+
torch.cuda.synchronize()
|
| 522 |
+
dt = max(time.monotonic() - t_win, 1e-6)
|
| 523 |
+
rec = {k: v / win_steps for k, v in win.items()}
|
| 524 |
+
rec.update(step=step, lr=lr, steps_per_s=win_steps / dt, elapsed_s=elapsed)
|
| 525 |
+
if is_eval:
|
| 526 |
+
rec.update(evaluate_item3(ema_model, val_ds, args.device))
|
| 527 |
+
if is_save:
|
| 528 |
+
export_cfm_checkpoint(ema_model, args.output / "inference_prosody_flow.pt", step, train_ds.annotation)
|
| 529 |
+
export_cfm_checkpoint(
|
| 530 |
+
ema_model, args.output / f"inference_prosody_flow-step-{step:08d}.pt", step, train_ds.annotation
|
| 531 |
+
)
|
| 532 |
+
with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as f:
|
| 533 |
+
f.write(json.dumps(rec) + "\n")
|
| 534 |
+
print(json.dumps(rec), flush=True)
|
| 535 |
+
win = defaultdict(float)
|
| 536 |
+
win_steps = 0
|
| 537 |
+
t_win = time.monotonic()
|
| 538 |
+
set_item3_train_mode(model, True)
|
| 539 |
+
|
| 540 |
+
if args.sample_every > 0 and (step % args.sample_every == 0 or should_stop):
|
| 541 |
+
save_item3_samples(ema_model, args.output, step)
|
| 542 |
+
set_item3_train_mode(model, True)
|
| 543 |
+
if should_stop:
|
| 544 |
+
break
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
if __name__ == "__main__":
|
| 548 |
+
main()
|
code/src/lua_nova_v1/training/stage1.py
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""From-scratch training on validated durations. Running this starts paid compute.
|
| 2 |
+
|
| 3 |
+
There is no learned aligner and no alignment loss: token durations come from
|
| 4 |
+
the annotation layer and must cover the acoustic frames exactly. The waveform
|
| 5 |
+
discriminators and the auxiliary mel head are training-only. No model or data
|
| 6 |
+
downloads and no infrastructure management happen here.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import time
|
| 16 |
+
import torch
|
| 17 |
+
from torch import nn
|
| 18 |
+
from torch.nn import functional as F
|
| 19 |
+
from ..config import CHECKPOINT_FORMAT, Config
|
| 20 |
+
from ..data.dataset import AnnotatedDataset, BucketSampler, collate
|
| 21 |
+
from ..models.frontend import LuaNovaBase
|
| 22 |
+
from ..models.losses import Discriminators, SpectralLoss, discriminator_loss, generator_gan_loss, masked_mean
|
| 23 |
+
from ..text.phonemizer import frontend_fingerprint, frontend_identity, phonemize
|
| 24 |
+
from ..utils.audio import limit_peak
|
| 25 |
+
from ..utils.checkpoint import atomic_save
|
| 26 |
+
|
| 27 |
+
WEIGHTS = {"duration": 1.0, "pause": 1.0, "pitch": 2.0, "pitch_spread": 2.0, "voicing": 1.0, "energy": 1.0,
|
| 28 |
+
"mel_head": 2.0, "mel_delta": 5.0, "stft": 2.0, "mel": 10.0}
|
| 29 |
+
SEMITONES = 12 / math.log(2)
|
| 30 |
+
VALIDATION_SAMPLE_TEXTS = (
|
| 31 |
+
"Amanhã de manhã eu vou pôr o pão na mesa para os irmãos.",
|
| 32 |
+
"Eu almoço cedo quando o almoço está pronto no jogo.",
|
| 33 |
+
"Dia vinte e dois de março às quatorze horas custou duzentos reais.",
|
| 34 |
+
"Você tem certeza de que ele vem hoje à tarde?",
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def save_validation_samples(model, output_dir, step):
|
| 39 |
+
import soundfile as sf
|
| 40 |
+
|
| 41 |
+
was_training = model.training
|
| 42 |
+
model.eval()
|
| 43 |
+
device = next(model.parameters()).device
|
| 44 |
+
sample_dir = Path(output_dir) / "samples" / f"step-{step:08d}"
|
| 45 |
+
sample_dir.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
try:
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
for idx, text in enumerate(VALIDATION_SAMPLE_TEXTS, 1):
|
| 49 |
+
ph = phonemize(text)
|
| 50 |
+
tok = torch.tensor([ph.ids], device=device)
|
| 51 |
+
st = torch.tensor([ph.stress], device=device)
|
| 52 |
+
ln = torch.tensor([len(ph)], device=device)
|
| 53 |
+
sp = torch.tensor([0], device=device)
|
| 54 |
+
wave, lengths, _ = model.synthesize(tok, st, ln, sp, seed=0)
|
| 55 |
+
w = limit_peak(wave[0, : int(lengths[0])].cpu())
|
| 56 |
+
sf.write(sample_dir / f"sample_{idx:02d}.wav", w.numpy(), model.config.sample_rate, subtype="PCM_16")
|
| 57 |
+
finally:
|
| 58 |
+
if was_training:
|
| 59 |
+
model.train()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def masked_std(value, mask):
|
| 63 |
+
"""Standard deviation per row over the masked positions, [B]."""
|
| 64 |
+
count = mask.sum(1).clamp_min(1)
|
| 65 |
+
mean = (value * mask).sum(1) / count
|
| 66 |
+
return (((value - mean[:, None]).square() * mask).sum(1) / count + 1e-8).sqrt()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
LINGUISTIC_MODULES = (
|
| 70 |
+
"tokens", "stress", "voices", "encoder", "duration",
|
| 71 |
+
"frame_voices", "frame_position", "prosody_stack", "prosody_head",
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TrainingSystem(nn.Module):
|
| 76 |
+
def __init__(self, config, waveform_loss=True, freeze_vocoder=False, vocos_checkpointing=False,
|
| 77 |
+
freeze_linguistic=False):
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.model = LuaNovaBase(config)
|
| 80 |
+
self.mel_head = nn.Linear(config.channels, config.n_mels) if config.vocoder_type == "source_filter" else None
|
| 81 |
+
self.spectral = SpectralLoss(config.sample_rate)
|
| 82 |
+
self.waveform_loss = waveform_loss
|
| 83 |
+
self.vocos_checkpointing = vocos_checkpointing
|
| 84 |
+
self.freeze_linguistic = freeze_linguistic
|
| 85 |
+
if config.vocoder_type == "vocos" and freeze_vocoder:
|
| 86 |
+
self.model.vocoder.freeze_vocoder(True)
|
| 87 |
+
if freeze_linguistic:
|
| 88 |
+
for name in LINGUISTIC_MODULES:
|
| 89 |
+
mod = getattr(self.model, name)
|
| 90 |
+
for p in mod.parameters():
|
| 91 |
+
p.requires_grad_(False)
|
| 92 |
+
mod.eval()
|
| 93 |
+
|
| 94 |
+
def train(self, mode=True):
|
| 95 |
+
super().train(mode)
|
| 96 |
+
if self.freeze_linguistic:
|
| 97 |
+
for name in LINGUISTIC_MODULES:
|
| 98 |
+
getattr(self.model, name).eval()
|
| 99 |
+
return self
|
| 100 |
+
|
| 101 |
+
def objective(self, batch, teacher_probability, weights=WEIGHTS, random_phase=True):
|
| 102 |
+
"""Loss on full utterances. Returns ``(loss, terms, auxiliary)``.
|
| 103 |
+
|
| 104 |
+
``teacher_probability`` is the per-utterance chance that the acoustic
|
| 105 |
+
decoder is conditioned on recorded pitch/voicing/energy; otherwise it
|
| 106 |
+
gets the model's own (detached) predictions, exactly as at inference.
|
| 107 |
+
The oscillator always follows the recorded pitch here, because the
|
| 108 |
+
waveform target does.
|
| 109 |
+
"""
|
| 110 |
+
m, c = self.model, self.model.config
|
| 111 |
+
hidden, token_mask = m.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
|
| 112 |
+
output = m.duration(hidden, token_mask).float()
|
| 113 |
+
# Length is learned only where a token has frames; whether a pause-capable
|
| 114 |
+
# token has any is a separate yes/no target.
|
| 115 |
+
present = batch["durations"] > 0
|
| 116 |
+
duration = masked_mean((output[..., 0] - torch.log1p(batch["durations"].float())).square(), token_mask & present)
|
| 117 |
+
pausable = token_mask & ~m.phone_tokens[batch["tokens"]]
|
| 118 |
+
pause = masked_mean(F.binary_cross_entropy_with_logits(output[..., 1], present.float(), reduction="none"), pausable)
|
| 119 |
+
frames, frame_mask, lengths = m.expand(hidden, batch["durations"], token_mask, batch["speakers"])
|
| 120 |
+
if not torch.equal(lengths, batch["frame_lengths"]):
|
| 121 |
+
raise ValueError("durations do not sum to the acoustic frame count")
|
| 122 |
+
prosody_hidden, prediction = m.predict_prosody(frames, frame_mask)
|
| 123 |
+
prediction, target = prediction.float(), batch["prosody"]
|
| 124 |
+
trusted = batch["pitch_trusted"]
|
| 125 |
+
# Recorded pitch counts fully; interpolated stretches only keep the curve continuous.
|
| 126 |
+
pitch = masked_mean((prediction[..., 0] - target[..., 0]).abs(), frame_mask * (trusted + 0.1 * (1 - trusted)))
|
| 127 |
+
# An absolute-error fit alone predicts a flatter contour than people speak
|
| 128 |
+
# (about three quarters of the recorded spread on held-out text). Match each
|
| 129 |
+
# utterance's pitch spread as well, the classic global-variance correction.
|
| 130 |
+
sung = frame_mask * target[..., 1] * trusted
|
| 131 |
+
enough = (sung.sum(1) >= 10).float()
|
| 132 |
+
predicted_spread, recorded_spread = masked_std(prediction[..., 0], sung), masked_std(target[..., 0], sung)
|
| 133 |
+
pitch_spread = masked_mean((predicted_spread - recorded_spread).abs(), enough)
|
| 134 |
+
voicing = masked_mean(F.binary_cross_entropy_with_logits(prediction[..., 1], target[..., 1], reduction="none"), frame_mask)
|
| 135 |
+
energy = masked_mean((prediction[..., 2] - target[..., 2]).abs(), frame_mask)
|
| 136 |
+
teacher = torch.rand(len(lengths), device=lengths.device) < teacher_probability
|
| 137 |
+
condition = torch.where(teacher[:, None, None], target, m.hard_prosody(prediction.detach()))
|
| 138 |
+
acoustic = m.decode(prosody_hidden, condition.to(prosody_hidden.dtype), frame_mask)
|
| 139 |
+
if c.vocoder_type == "vocos":
|
| 140 |
+
mel_norm = m.vocoder.predict_mel(acoustic, frame_mask)
|
| 141 |
+
mel_target = (batch["vocos_mel"] - m.vocoder.mel_mean) / m.vocoder.mel_scale
|
| 142 |
+
mel_pred = masked_mean((mel_norm.float() - mel_target).abs().mean(-1), frame_mask)
|
| 143 |
+
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
|
| 144 |
+
mel_delta = masked_mean(
|
| 145 |
+
((mel_norm[:, 1:] - mel_norm[:, :-1]) - (mel_target[:, 1:] - mel_target[:, :-1])).abs().mean(-1),
|
| 146 |
+
pair_mask,
|
| 147 |
+
)
|
| 148 |
+
if self.waveform_loss:
|
| 149 |
+
wave = m.vocoder.decode_mel(mel_norm, lengths, checkpointing=self.vocos_checkpointing)
|
| 150 |
+
stft, mel = self.spectral(wave, batch["wave"], lengths * c.hop)
|
| 151 |
+
mel_head = mel_pred
|
| 152 |
+
reconstruction = weights["stft"] * stft + weights["mel"] * mel
|
| 153 |
+
else:
|
| 154 |
+
wave = None
|
| 155 |
+
stft = mel_pred.new_zeros(())
|
| 156 |
+
mel = mel_pred
|
| 157 |
+
mel_head = mel_pred.new_zeros(())
|
| 158 |
+
reconstruction = None
|
| 159 |
+
terms = dict(duration=duration, pause=pause, pitch=pitch, pitch_spread=pitch_spread, voicing=voicing,
|
| 160 |
+
energy=energy, mel_head=mel_head, mel_delta=mel_delta, stft=stft, mel=mel)
|
| 161 |
+
else:
|
| 162 |
+
mel_target = (batch["mel"] - c.mel_mean) / c.mel_scale
|
| 163 |
+
mel_head = masked_mean((self.mel_head(acoustic).float() - mel_target).abs().mean(-1), frame_mask)
|
| 164 |
+
phase = 2 * math.pi * torch.rand(len(lengths), device=lengths.device) if random_phase else None
|
| 165 |
+
wave = m.vocoder(acoustic, m.frequency(target[..., 0]), lengths, phase=phase)
|
| 166 |
+
stft, mel = self.spectral(wave, batch["wave"], lengths * c.hop)
|
| 167 |
+
reconstruction = weights["stft"] * stft + weights["mel"] * mel
|
| 168 |
+
terms = dict(duration=duration, pause=pause, pitch=pitch, pitch_spread=pitch_spread, voicing=voicing,
|
| 169 |
+
energy=energy, mel_head=mel_head, stft=stft, mel=mel)
|
| 170 |
+
loss = sum(weights[name] * value for name, value in terms.items())
|
| 171 |
+
with torch.no_grad():
|
| 172 |
+
voiced = sung
|
| 173 |
+
predicted = m.predict_durations(hidden, token_mask, batch["tokens"])
|
| 174 |
+
predicted_frames = predicted.sum(1)
|
| 175 |
+
pause_frames = (batch["durations"] * pausable).sum().clamp_min(1)
|
| 176 |
+
terms.update(
|
| 177 |
+
base_loss=loss.detach(), teacher_fraction=teacher.float().mean(),
|
| 178 |
+
pitch_error_semitones=SEMITONES * masked_mean((prediction[..., 0] - target[..., 0]).abs(), voiced),
|
| 179 |
+
pitch_spread_ratio=masked_mean(predicted_spread / recorded_spread.clamp_min(1e-3), enough),
|
| 180 |
+
voicing_accuracy=masked_mean(((prediction[..., 1] > 0) == target[..., 1].bool()).float(), frame_mask),
|
| 181 |
+
pause_accuracy=masked_mean(((output[..., 1] > 0) == present).float(), pausable),
|
| 182 |
+
pause_length_ratio=(predicted * pausable).sum() / pause_frames,
|
| 183 |
+
duration_length_ratio=(predicted_frames / lengths).mean(),
|
| 184 |
+
duration_length_error=((predicted_frames - lengths).abs() / lengths).mean())
|
| 185 |
+
return loss, terms, {"wave": wave, "reconstruction": reconstruction}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def crops(fake, real, lengths, size, count):
|
| 189 |
+
"""Aligned random windows [B*count, size] from generated and recorded audio,
|
| 190 |
+
plus the sample indices they cover ([B, count*size])."""
|
| 191 |
+
size = min(size, int(lengths.min()))
|
| 192 |
+
start = (torch.rand(len(lengths), count, device=fake.device) * (lengths[:, None] - size + 1)).long()
|
| 193 |
+
index = (start[..., None] + torch.arange(size, device=fake.device)).flatten(1)
|
| 194 |
+
return fake.gather(1, index).view(-1, size), real.gather(1, index).view(-1, size), index
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def learning_rate(step, base, warmup, half_life, start=0):
|
| 198 |
+
"""Linear warm-up from ``start`` (0, or the step a run was branched at),
|
| 199 |
+
then halving every ``half_life`` steps."""
|
| 200 |
+
return base * min(1.0, (step - start + 1) / max(warmup, 1)) * 0.5 ** (step / half_life)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def teacher_probability(step, hold, ramp, final):
|
| 204 |
+
"""1 while the prosody predictor is still poor, then down to ``final``."""
|
| 205 |
+
return 1.0 if step < hold else max(final, 1.0 - (1.0 - final) * (step - hold) / max(ramp, 1))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def optimize_step(system, critics, optimizer, critic_optimizer, batch, step, recipe):
|
| 209 |
+
weights = recipe["weights"]
|
| 210 |
+
start = (recipe.get("branched_from") or {}).get("step", 0)
|
| 211 |
+
for group in optimizer.param_groups:
|
| 212 |
+
group["lr"] = learning_rate(step, recipe["learning_rate"], recipe["warmup"], recipe["lr_half_life"], start)
|
| 213 |
+
for group in critic_optimizer.param_groups:
|
| 214 |
+
group["lr"] = learning_rate(step, recipe["learning_rate"], 1, recipe["lr_half_life"], start)
|
| 215 |
+
optimizer.zero_grad(set_to_none=True)
|
| 216 |
+
probability = teacher_probability(step, recipe["teacher_hold"], recipe["teacher_ramp"], recipe["teacher_final"])
|
| 217 |
+
loss, metrics, auxiliary = system.objective(batch, probability, weights)
|
| 218 |
+
if step >= recipe["gan_start"]:
|
| 219 |
+
wave = auxiliary["wave"]
|
| 220 |
+
fake, real, index = crops(wave, batch["wave"], batch["frame_lengths"] * system.model.config.hop, recipe["crop_samples"], recipe["crops"])
|
| 221 |
+
critic_optimizer.zero_grad(set_to_none=True)
|
| 222 |
+
d_loss = discriminator_loss(critics(real), critics(fake.detach()))
|
| 223 |
+
d_loss.backward()
|
| 224 |
+
nn.utils.clip_grad_norm_(critics.parameters(), 10, error_if_nonfinite=True)
|
| 225 |
+
critic_optimizer.step()
|
| 226 |
+
critics.requires_grad_(False)
|
| 227 |
+
try:
|
| 228 |
+
with torch.no_grad():
|
| 229 |
+
real_features = critics(real)
|
| 230 |
+
adversarial, matching = generator_gan_loss(real_features, critics(fake))
|
| 231 |
+
gan = adversarial + recipe["feature_matching"] * matching
|
| 232 |
+
# Fixed weights cannot balance these terms: measured at the waveform, the
|
| 233 |
+
# adversarial gradient was under 1% of the spectral one, i.e. switched off.
|
| 234 |
+
# Scale the GAN term so that, inside the windows the critics saw, its
|
| 235 |
+
# gradient is ``gan_ratio`` times the reconstruction gradient.
|
| 236 |
+
reconstruction_gradient = torch.autograd.grad(auxiliary["reconstruction"], wave, retain_graph=True)[0].gather(1, index)
|
| 237 |
+
gan_gradient = torch.autograd.grad(gan, wave, retain_graph=True)[0].gather(1, index)
|
| 238 |
+
ramp = min(1.0, (step - recipe["gan_start"] + 1) / max(recipe["gan_ramp"], 1))
|
| 239 |
+
scale = (recipe["gan_ratio"] * ramp * reconstruction_gradient.norm() / gan_gradient.norm().clamp_min(1e-12))
|
| 240 |
+
scale = scale.clamp(max=recipe["gan_scale_max"]).detach()
|
| 241 |
+
loss = loss + scale * gan
|
| 242 |
+
metrics.update(discriminator=d_loss, adversarial=adversarial, feature_matching=matching, gan_scale=scale)
|
| 243 |
+
loss.backward()
|
| 244 |
+
finally:
|
| 245 |
+
critics.requires_grad_(True)
|
| 246 |
+
else:
|
| 247 |
+
loss.backward()
|
| 248 |
+
grad = nn.utils.clip_grad_norm_(system.parameters(), recipe["grad_clip"], error_if_nonfinite=True)
|
| 249 |
+
optimizer.step()
|
| 250 |
+
return {**{k: float(v.detach()) for k, v in metrics.items()}, "loss": float(loss.detach()), "grad_norm": float(grad),
|
| 251 |
+
"frames": int(batch["frame_lengths"].sum()), "utterances": len(batch["frame_lengths"])}
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def export_model(model, path, step, annotation=None):
|
| 255 |
+
atomic_save({"format_version": CHECKPOINT_FORMAT, "config": model.config.to_dict(), "step": step,
|
| 256 |
+
"frontend": {**frontend_identity(), "fingerprint": frontend_fingerprint()}, "annotation": annotation,
|
| 257 |
+
"model": {k: v.detach().cpu() for k, v in model.state_dict().items()}}, path)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def load_compatible(module, state):
|
| 261 |
+
"""Load weights for a branched run. A tensor that grew (same rank, every
|
| 262 |
+
dimension at least as large) keeps the old values in its leading block and
|
| 263 |
+
its fresh initialisation elsewhere. Returns what was not an exact copy."""
|
| 264 |
+
current = module.state_dict()
|
| 265 |
+
report = {"grown": [], "new": [], "dropped": sorted(set(state) - set(current))}
|
| 266 |
+
for name, tensor in current.items():
|
| 267 |
+
if name not in state:
|
| 268 |
+
report["new"].append(name)
|
| 269 |
+
elif state[name].shape == tensor.shape:
|
| 270 |
+
current[name] = state[name]
|
| 271 |
+
elif state[name].ndim == tensor.ndim and all(a <= b for a, b in zip(state[name].shape, tensor.shape)):
|
| 272 |
+
merged = tensor.clone()
|
| 273 |
+
merged[tuple(slice(0, size) for size in state[name].shape)] = state[name]
|
| 274 |
+
current[name] = merged
|
| 275 |
+
report["grown"].append(name)
|
| 276 |
+
else:
|
| 277 |
+
raise ValueError(f"cannot branch: {name} changed shape from {tuple(state[name].shape)} to {tuple(tensor.shape)}")
|
| 278 |
+
module.load_state_dict(current)
|
| 279 |
+
return report
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def balanced_indices(dataset, limit):
|
| 283 |
+
"""Stable round-robin over voices, independent of manifest order."""
|
| 284 |
+
groups = defaultdict(list)
|
| 285 |
+
for i, row in enumerate(dataset.rows):
|
| 286 |
+
groups[row["speaker"]].append(i)
|
| 287 |
+
limit = min(max(limit, len(groups)), len(dataset.rows))
|
| 288 |
+
selected = []
|
| 289 |
+
for offset in range(limit):
|
| 290 |
+
for voice in sorted(groups):
|
| 291 |
+
if offset < len(groups[voice]):
|
| 292 |
+
selected.append(groups[voice][offset])
|
| 293 |
+
if len(selected) == limit:
|
| 294 |
+
return selected
|
| 295 |
+
return selected
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def check_leakage(train, validation):
|
| 299 |
+
ids = {r["id"] for r in train.rows}
|
| 300 |
+
texts = defaultdict(list)
|
| 301 |
+
for row in train.rows:
|
| 302 |
+
texts[row["text_hash"]].append(row["id"])
|
| 303 |
+
collisions = []
|
| 304 |
+
for row in validation.rows:
|
| 305 |
+
if row["id"] in ids or row["text_hash"] in texts:
|
| 306 |
+
collisions.append({"validation_id": row["id"], "train_ids": texts.get(row["text_hash"], [])[:3], "text": row.get("text", "")[:160]})
|
| 307 |
+
if len(collisions) == 5:
|
| 308 |
+
break
|
| 309 |
+
if collisions:
|
| 310 |
+
raise ValueError("train/validation leakage; split by sentence/text_id across BOTH voices. Examples: " + json.dumps(collisions, ensure_ascii=False))
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@torch.no_grad()
|
| 314 |
+
def validate(system, dataset, indices, device, weights=WEIGHTS, batch_size=8):
|
| 315 |
+
"""Held-out metrics on a fixed balanced subset.
|
| 316 |
+
|
| 317 |
+
``teacher_forced`` conditions the decoder on recorded prosody, ``predicted``
|
| 318 |
+
on the model's own; both use recorded durations and pitch for the oscillator
|
| 319 |
+
so the spectra are comparable with the recording. Durations, pauses, pitch
|
| 320 |
+
and voicing errors are those of the free-running predictors. This is a
|
| 321 |
+
training monitor; pronunciation is judged separately with ASR and by listening.
|
| 322 |
+
"""
|
| 323 |
+
system.eval()
|
| 324 |
+
order = sorted(indices, key=lambda i: dataset.lengths[i])
|
| 325 |
+
totals, weight = defaultdict(float), 0
|
| 326 |
+
for start in range(0, len(order), batch_size):
|
| 327 |
+
batch = collate([dataset[i] for i in order[start:start + batch_size]], device)
|
| 328 |
+
size = len(batch["frame_lengths"])
|
| 329 |
+
for name, probability in (("teacher_forced", 1.0), ("predicted", 0.0)):
|
| 330 |
+
_, metrics, _ = system.objective(batch, probability, weights, random_phase=False)
|
| 331 |
+
totals[f"validation_{name}_mel"] += float(metrics["mel"]) * size
|
| 332 |
+
totals[f"validation_{name}_stft"] += float(metrics["stft"]) * size
|
| 333 |
+
for key in ("duration", "pause_accuracy", "pause_length_ratio", "pitch_error_semitones", "pitch_spread_ratio", "voicing_accuracy",
|
| 334 |
+
"duration_length_ratio", "duration_length_error"):
|
| 335 |
+
totals["validation_" + key] += float(metrics[key]) * size
|
| 336 |
+
weight += size
|
| 337 |
+
system.train()
|
| 338 |
+
return {key: value / weight for key, value in totals.items()}
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def main():
|
| 342 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 343 |
+
parser.add_argument("--train", type=Path, required=True, help="Annotation manifest (train.jsonl)")
|
| 344 |
+
parser.add_argument("--validation", type=Path, required=True)
|
| 345 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 346 |
+
parser.add_argument("--config", type=Path)
|
| 347 |
+
parser.add_argument("--device", default="cuda")
|
| 348 |
+
parser.add_argument("--steps", type=int, default=100000)
|
| 349 |
+
parser.add_argument("--batch-frames", type=int, default=9000, help="Padded acoustic frames per batch")
|
| 350 |
+
parser.add_argument("--max-batch", type=int, default=32)
|
| 351 |
+
parser.add_argument("--learning-rate", type=float, default=3e-4)
|
| 352 |
+
parser.add_argument("--warmup", type=int, default=1000)
|
| 353 |
+
parser.add_argument("--lr-half-life", type=float, default=100000)
|
| 354 |
+
parser.add_argument("--grad-clip", type=float, default=10.0)
|
| 355 |
+
parser.add_argument("--weights", type=json.loads, default={}, help="JSON overrides for the loss weights, e.g. '{\"mel\": 5}'")
|
| 356 |
+
parser.add_argument("--gan-start", type=int, default=8000)
|
| 357 |
+
parser.add_argument("--gan-ratio", type=float, default=0.7, help="Adversarial gradient as a fraction of the reconstruction gradient at the waveform")
|
| 358 |
+
parser.add_argument("--gan-ramp", type=int, default=3000, help="Steps over which the adversarial term fades in while the critics warm up")
|
| 359 |
+
parser.add_argument("--feature-matching", type=float, default=30.0, help="Feature-matching weight inside the adversarial term")
|
| 360 |
+
parser.add_argument("--gan-scale-max", type=float, default=2000.0)
|
| 361 |
+
parser.add_argument("--crop-samples", type=int, default=8192)
|
| 362 |
+
parser.add_argument("--crops", type=int, default=2, help="Discriminator windows per utterance")
|
| 363 |
+
parser.add_argument("--teacher-hold", type=int, default=3000, help="Steps with recorded prosody conditioning only")
|
| 364 |
+
parser.add_argument("--teacher-ramp", type=int, default=7000)
|
| 365 |
+
parser.add_argument("--teacher-final", type=float, default=0.0, help="Share of utterances still conditioned on recorded prosody "
|
| 366 |
+
"after the ramp (0 = the decoder sees only what it gets at inference)")
|
| 367 |
+
parser.add_argument("--subset", type=int, help="Train on the first N utterances (balanced by voice): memorisation check")
|
| 368 |
+
parser.add_argument("--validation-size", type=int, default=32)
|
| 369 |
+
parser.add_argument("--save-every", type=int, default=1000)
|
| 370 |
+
parser.add_argument("--keep-every", type=int, default=10000, help="Keep a numbered checkpoint at this interval and at the GAN boundary")
|
| 371 |
+
parser.add_argument("--sample-every", type=int, default=5000, help="Generate validation audio samples every N steps (0 to disable)")
|
| 372 |
+
parser.add_argument("--log-every", type=int, default=10)
|
| 373 |
+
parser.add_argument("--seed", type=int, default=20261113)
|
| 374 |
+
parser.add_argument("--max-seconds", type=float, default=3600, help="Wall-time cap per invocation; save and exit at a step boundary")
|
| 375 |
+
parser.add_argument("--deadline-file", type=Path, help="Budget JSON with an absolute 'deadline'; training saves and exits before it")
|
| 376 |
+
parser.add_argument("--deadline-margin", type=float, default=300)
|
| 377 |
+
parser.add_argument("--resume", type=Path, help="Continue the same run exactly (same recipe, data and configuration)")
|
| 378 |
+
parser.add_argument("--init-from", type=Path, help="Start a NEW run from another run's checkpoint with a changed recipe: "
|
| 379 |
+
"weights, step counter and already-trained critics are taken over; the data order starts fresh")
|
| 380 |
+
parser.add_argument("--new-data", action="store_true", help="With --init-from: the checkpoint comes from a different annotation "
|
| 381 |
+
"run or front end (same symbol inventory)")
|
| 382 |
+
parser.add_argument("--stop-file", type=Path, help="Save and exit after a step when this file appears")
|
| 383 |
+
parser.add_argument("--recorded-voicing", action="store_true", help="Use the pitch tracker's voicing as it is, "
|
| 384 |
+
"without marking vowel frames voiced")
|
| 385 |
+
parser.add_argument("--no-preload", action="store_true", help="Load feature files lazily instead of before the first step")
|
| 386 |
+
parser.add_argument("--vocoder", choices=("source_filter", "vocos"), default=None, help="Vocoder architecture")
|
| 387 |
+
parser.add_argument("--vocos-stats", type=Path, default=None, help="JSON with Vocos per-channel mel mean and scale")
|
| 388 |
+
parser.add_argument("--freeze-vocoder", action="store_true", help="Keep pretrained Vocos weights frozen")
|
| 389 |
+
parser.add_argument("--freeze-linguistic", action="store_true",
|
| 390 |
+
help="Freeze encoder, duration and prosody predictors (refine only acoustic stack + vocoder)")
|
| 391 |
+
parser.add_argument("--no-waveform-loss", action="store_true", help="Skip waveform decode and STFT loss (mel-only Stage 1)")
|
| 392 |
+
parser.add_argument("--vocos-checkpointing", action="store_true", help="Gradient checkpoint Vocos ConvNeXt blocks")
|
| 393 |
+
args = parser.parse_args()
|
| 394 |
+
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:
|
| 395 |
+
parser.error("steps, batch limits and intervals must be positive")
|
| 396 |
+
if args.max_seconds <= 0 or args.learning_rate <= 0 or args.lr_half_life <= 0 or not 0 <= args.teacher_final <= 1:
|
| 397 |
+
parser.error("time cap, learning rate and half life must be positive; teacher_final in [0, 1]")
|
| 398 |
+
if set(args.weights) - set(WEIGHTS) or min(args.gan_ratio, args.feature_matching, args.gan_scale_max) < 0:
|
| 399 |
+
parser.error(f"--weights may only override {sorted(WEIGHTS)}; GAN settings must be non-negative")
|
| 400 |
+
if args.resume and args.init_from:
|
| 401 |
+
parser.error("--init-from starts a new run; --resume continues one")
|
| 402 |
+
if args.no_waveform_loss and args.gan_start < args.steps:
|
| 403 |
+
parser.error("--no-waveform-loss requires --gan-start >= --steps")
|
| 404 |
+
|
| 405 |
+
# The budget file is re-read while training so a deliberate extension (or cut) takes effect.
|
| 406 |
+
budget = {"deadline": math.inf, "checked": time.time()}
|
| 407 |
+
if args.deadline_file:
|
| 408 |
+
budget["deadline"] = float(json.loads(args.deadline_file.read_text())["deadline"]) - args.deadline_margin
|
| 409 |
+
|
| 410 |
+
def deadline():
|
| 411 |
+
if args.deadline_file and time.time() - budget["checked"] > 30:
|
| 412 |
+
budget["checked"] = time.time()
|
| 413 |
+
try:
|
| 414 |
+
budget["deadline"] = float(json.loads(args.deadline_file.read_text())["deadline"]) - args.deadline_margin
|
| 415 |
+
except (OSError, ValueError, KeyError):
|
| 416 |
+
pass # keep the last valid deadline while the file is being rewritten
|
| 417 |
+
return budget["deadline"]
|
| 418 |
+
if time.time() >= deadline():
|
| 419 |
+
raise SystemExit("the cloud budget deadline has passed (or is too close); not starting")
|
| 420 |
+
if args.config:
|
| 421 |
+
c = Config.from_dict(json.loads(args.config.read_text()))
|
| 422 |
+
elif args.vocoder is not None:
|
| 423 |
+
c = Config(vocoder_type=args.vocoder)
|
| 424 |
+
elif args.resume or args.init_from:
|
| 425 |
+
ckpt_state = torch.load(args.resume or args.init_from, map_location="cpu", weights_only=True)
|
| 426 |
+
c = Config.from_dict(ckpt_state["config"])
|
| 427 |
+
del ckpt_state
|
| 428 |
+
else:
|
| 429 |
+
c = Config()
|
| 430 |
+
torch.manual_seed(args.seed)
|
| 431 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 432 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 433 |
+
train = AnnotatedDataset(args.train, c, voiced_vowels=not args.recorded_voicing)
|
| 434 |
+
validation = AnnotatedDataset(args.validation, c, voiced_vowels=not args.recorded_voicing)
|
| 435 |
+
check_leakage(train, validation)
|
| 436 |
+
if train.annotation != validation.annotation:
|
| 437 |
+
raise ValueError("train and validation manifests come from different annotation runs")
|
| 438 |
+
if args.output.exists() and any(args.output.iterdir()) and not args.resume:
|
| 439 |
+
raise FileExistsError("output directory is not empty; use --resume or a new directory")
|
| 440 |
+
pool = balanced_indices(train, args.subset) if args.subset else list(range(len(train)))
|
| 441 |
+
validation_indices = balanced_indices(validation, args.validation_size)
|
| 442 |
+
if not args.no_preload:
|
| 443 |
+
train.preload(pool)
|
| 444 |
+
validation.preload(validation_indices)
|
| 445 |
+
system = TrainingSystem(
|
| 446 |
+
c,
|
| 447 |
+
waveform_loss=not args.no_waveform_loss,
|
| 448 |
+
freeze_vocoder=args.freeze_vocoder,
|
| 449 |
+
vocos_checkpointing=args.vocos_checkpointing,
|
| 450 |
+
freeze_linguistic=args.freeze_linguistic,
|
| 451 |
+
).to(args.device)
|
| 452 |
+
if c.vocoder_type == "vocos" and args.vocos_stats:
|
| 453 |
+
stats = json.loads(args.vocos_stats.read_text(encoding="utf-8"))
|
| 454 |
+
system.model.vocoder.set_mel_stats(stats["mean"], stats["scale"])
|
| 455 |
+
critics = Discriminators().to(args.device)
|
| 456 |
+
count = sum(p.numel() for p in system.model.parameters())
|
| 457 |
+
budget_limit = 25_000_000 if c.vocoder_type == "vocos" else 5_000_000
|
| 458 |
+
if count > budget_limit:
|
| 459 |
+
raise ValueError(f"inference parameter budget exceeded: {count:,}")
|
| 460 |
+
trainable_params = [p for p in system.parameters() if p.requires_grad] if args.freeze_linguistic else list(system.parameters())
|
| 461 |
+
optimizer = torch.optim.AdamW(trainable_params, lr=args.learning_rate, betas=(0.8, 0.99), weight_decay=0.01)
|
| 462 |
+
critic_optimizer = torch.optim.AdamW(critics.parameters(), lr=args.learning_rate, betas=(0.8, 0.99), weight_decay=0.0)
|
| 463 |
+
sampler = BucketSampler([train.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
|
| 464 |
+
fingerprints = [train.fingerprint, validation.fingerprint]
|
| 465 |
+
recipe = {key: getattr(args, key) for key in ("batch_frames", "max_batch", "learning_rate", "warmup", "lr_half_life", "grad_clip",
|
| 466 |
+
"gan_start", "gan_ratio", "gan_ramp", "feature_matching", "gan_scale_max",
|
| 467 |
+
"crop_samples", "crops", "teacher_hold", "teacher_ramp", "teacher_final",
|
| 468 |
+
"subset", "validation_size", "seed")}
|
| 469 |
+
recipe["voiced_vowel_targets"] = not args.recorded_voicing
|
| 470 |
+
recipe["vocoder_type"] = c.vocoder_type
|
| 471 |
+
recipe["freeze_vocoder"] = bool(args.freeze_vocoder)
|
| 472 |
+
recipe["freeze_linguistic"] = bool(args.freeze_linguistic)
|
| 473 |
+
recipe["waveform_loss"] = not args.no_waveform_loss
|
| 474 |
+
recipe["weights"] = {**WEIGHTS, **{key: float(value) for key, value in args.weights.items()}}
|
| 475 |
+
recipe["branched_from"] = None
|
| 476 |
+
step = 0
|
| 477 |
+
|
| 478 |
+
def compatible(state, what, same_data=True):
|
| 479 |
+
if state.get("format_version") != CHECKPOINT_FORMAT:
|
| 480 |
+
raise ValueError(f"checkpoint predates phoneme tokens and supervised durations (format < 4); it cannot be {what}")
|
| 481 |
+
if same_data and (state["frontend"] != frontend_fingerprint() or state["annotation"] != train.annotation):
|
| 482 |
+
raise ValueError("checkpoint was trained with a different front end or annotation run "
|
| 483 |
+
"(branch with --init-from and --new-data to fine-tune on new annotations)")
|
| 484 |
+
if state["config"] != c.to_dict():
|
| 485 |
+
raise ValueError("checkpoint was trained with a different model configuration")
|
| 486 |
+
if args.resume:
|
| 487 |
+
state = torch.load(args.resume, map_location=args.device, weights_only=True)
|
| 488 |
+
compatible(state, "resumed")
|
| 489 |
+
recipe["branched_from"] = state["recipe"].get("branched_from")
|
| 490 |
+
if state["datasets"] != fingerprints or state["recipe"] != recipe:
|
| 491 |
+
raise ValueError("resume recipe or dataset mismatch (use --init-from to branch a new run with a changed recipe)")
|
| 492 |
+
system.load_state_dict(state["system"])
|
| 493 |
+
critics.load_state_dict(state["critics"])
|
| 494 |
+
optimizer.load_state_dict(state["optimizer"])
|
| 495 |
+
critic_optimizer.load_state_dict(state["critic_optimizer"])
|
| 496 |
+
sampler.load_state(state["sampler"])
|
| 497 |
+
torch.set_rng_state(state["torch_rng"].cpu())
|
| 498 |
+
if str(args.device).startswith("cuda") and state["cuda_rng"] is not None:
|
| 499 |
+
torch.cuda.set_rng_state_all([x.cpu() for x in state["cuda_rng"]])
|
| 500 |
+
step = state["step"]
|
| 501 |
+
elif args.init_from:
|
| 502 |
+
state = torch.load(args.init_from, map_location=args.device, weights_only=True)
|
| 503 |
+
# The symbol inventory is fixed (vocabulary size is part of the configuration),
|
| 504 |
+
# so a checkpoint can be fine-tuned on another annotation run or front end.
|
| 505 |
+
compatible(state, "branched", same_data=not args.new_data)
|
| 506 |
+
step = state["step"]
|
| 507 |
+
loaded = load_compatible(system, state["system"])
|
| 508 |
+
# Critics that have already been trained are taken over, otherwise a branch
|
| 509 |
+
# in the adversarial phase would hand full-strength gradients from untrained
|
| 510 |
+
# critics to the generator. Optimizer moments are kept when no tensor changed.
|
| 511 |
+
loaded["critics"] = step > state["recipe"]["gan_start"]
|
| 512 |
+
if loaded["critics"]:
|
| 513 |
+
critics.load_state_dict(state["critics"])
|
| 514 |
+
critic_optimizer.load_state_dict(state["critic_optimizer"])
|
| 515 |
+
loaded["optimizer"] = (
|
| 516 |
+
not loaded["grown"] and not loaded["new"] and not loaded["dropped"]
|
| 517 |
+
and not args.freeze_linguistic
|
| 518 |
+
)
|
| 519 |
+
if loaded["optimizer"]:
|
| 520 |
+
optimizer.load_state_dict(state["optimizer"])
|
| 521 |
+
recipe["branched_from"] = {"step": step, "recipe": state["recipe"], "datasets": state["datasets"], "loaded": loaded}
|
| 522 |
+
if args.new_data:
|
| 523 |
+
recipe["branched_from"].update(frontend=state["frontend"], annotation=state["annotation"])
|
| 524 |
+
if step >= args.steps:
|
| 525 |
+
raise ValueError("checkpoint already reached requested total steps")
|
| 526 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 527 |
+
(args.output / "config.json").write_text(json.dumps(c.to_dict(), indent=2) + "\n")
|
| 528 |
+
(args.output / "recipe.json").write_text(json.dumps({**recipe, "annotation": train.annotation, "frontend": frontend_fingerprint(),
|
| 529 |
+
"train_utterances": len(pool), "datasets": fingerprints}, indent=2) + "\n")
|
| 530 |
+
mel_head_params = sum(p.numel() for p in system.mel_head.parameters()) if system.mel_head is not None else 0
|
| 531 |
+
print(json.dumps({"inference_parameters": count, "training_only_parameters": mel_head_params
|
| 532 |
+
+ sum(p.numel() for p in critics.parameters()), "train_utterances": len(pool), "start_step": step,
|
| 533 |
+
"branched": bool(args.init_from), "resumed": bool(args.resume)}), flush=True)
|
| 534 |
+
start = time.monotonic()
|
| 535 |
+
system.train()
|
| 536 |
+
|
| 537 |
+
def snapshot():
|
| 538 |
+
return {"format_version": CHECKPOINT_FORMAT, "config": c.to_dict(), "frontend": frontend_fingerprint(), "annotation": train.annotation,
|
| 539 |
+
"step": step, "datasets": fingerprints, "recipe": recipe, "system": system.state_dict(), "critics": critics.state_dict(),
|
| 540 |
+
"optimizer": optimizer.state_dict(), "critic_optimizer": critic_optimizer.state_dict(), "sampler": sampler.state(),
|
| 541 |
+
"torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state_all() if str(args.device).startswith("cuda") else None}
|
| 542 |
+
if step == args.gan_start and not args.resume:
|
| 543 |
+
atomic_save(snapshot(), args.output / f"step-{step:08d}.pt")
|
| 544 |
+
window, window_steps, window_start = defaultdict(float), 0, time.monotonic()
|
| 545 |
+
while step < args.steps:
|
| 546 |
+
batch = collate([train[pool[i]] for i in sampler.next()], args.device)
|
| 547 |
+
metrics = optimize_step(system, critics, optimizer, critic_optimizer, batch, step, recipe)
|
| 548 |
+
step += 1
|
| 549 |
+
for key, value in metrics.items():
|
| 550 |
+
window[key] += value
|
| 551 |
+
window_steps += 1
|
| 552 |
+
elapsed = time.monotonic() - start
|
| 553 |
+
should_stop = (elapsed >= args.max_seconds or step == args.steps or time.time() >= deadline()
|
| 554 |
+
or (args.stop_file is not None and args.stop_file.exists()))
|
| 555 |
+
retain = step == args.gan_start or step % args.keep_every == 0
|
| 556 |
+
save = step % args.save_every == 0 or should_stop or retain
|
| 557 |
+
if step % args.log_every == 0 or save:
|
| 558 |
+
if str(args.device).startswith("cuda"):
|
| 559 |
+
torch.cuda.synchronize()
|
| 560 |
+
seconds = time.monotonic() - window_start
|
| 561 |
+
record = {key: (value if key in ("frames", "utterances") else value / window_steps) for key, value in window.items()}
|
| 562 |
+
record.update(step=step, elapsed_seconds=elapsed, steps_per_second=window_steps / max(seconds, 1e-9),
|
| 563 |
+
audio_seconds_per_second=window["frames"] * c.hop / c.sample_rate / max(seconds, 1e-9),
|
| 564 |
+
learning_rate=optimizer.param_groups[0]["lr"])
|
| 565 |
+
if save:
|
| 566 |
+
record.update(validate(system, validation, validation_indices, args.device, recipe["weights"]))
|
| 567 |
+
state = snapshot()
|
| 568 |
+
atomic_save(state, args.output / "last.pt")
|
| 569 |
+
export_model(system.model, args.output / "inference.pt", step, train.annotation)
|
| 570 |
+
if retain:
|
| 571 |
+
atomic_save(state, args.output / f"step-{step:08d}.pt")
|
| 572 |
+
with (args.output / "metrics.jsonl").open("a") as stream:
|
| 573 |
+
stream.write(json.dumps(record) + "\n")
|
| 574 |
+
print(json.dumps(record), flush=True)
|
| 575 |
+
window, window_steps, window_start = defaultdict(float), 0, time.monotonic()
|
| 576 |
+
if args.sample_every > 0 and (step % args.sample_every == 0 or step == args.steps):
|
| 577 |
+
save_validation_samples(system.model, args.output, step)
|
| 578 |
+
if should_stop:
|
| 579 |
+
break
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
if __name__ == "__main__":
|
| 583 |
+
main()
|
code/src/lua_nova_v1/training/vocoder_ft.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Anti-forgetting fine-tuning of MIT BigVGAN (base or v1 Large) on F1 real + CFM v5 predicted mels."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
import copy
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
from torch.nn import functional as F
|
| 15 |
+
|
| 16 |
+
from ..data.dataset import AnnotatedDataset, collate
|
| 17 |
+
from ..models.bigvgan import BigVGANMelExtractor, _ensure_bigvgan_importable
|
| 18 |
+
from ..models.cfm import energy_noise_gate, f0_features
|
| 19 |
+
from .common import atomic_save, balanced_indices, check_leakage, load_cfm_model, update_ema
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@torch.inference_mode()
|
| 23 |
+
def precompute_gt_and_cfm_mels(
|
| 24 |
+
ds: AnnotatedDataset,
|
| 25 |
+
indices: list[int],
|
| 26 |
+
cfm,
|
| 27 |
+
extractor: BigVGANMelExtractor,
|
| 28 |
+
device: str,
|
| 29 |
+
seed: int = 0,
|
| 30 |
+
cfm_steps: int = 8,
|
| 31 |
+
cfm_temp: float = 0.35,
|
| 32 |
+
sway_coef: float = -0.5,
|
| 33 |
+
) -> tuple[dict[int, torch.Tensor], dict[int, torch.Tensor]]:
|
| 34 |
+
"""Precompute exact ``gt_mel`` and ``CFM v5`` predicted ``cfm_mel`` (``all_gt``) in RAM."""
|
| 35 |
+
gt_mels: dict[int, torch.Tensor] = {}
|
| 36 |
+
cfm_mels: dict[int, torch.Tensor] = {}
|
| 37 |
+
|
| 38 |
+
for idx in indices:
|
| 39 |
+
wav = ds[idx]["wave"].to(device=device, dtype=torch.float32)
|
| 40 |
+
gt_mels[idx] = extractor(wav)[0].half().cpu()
|
| 41 |
+
|
| 42 |
+
sorted_idx = sorted(indices, key=lambda i: ds.lengths[i])
|
| 43 |
+
use_amp = str(device).startswith("cuda")
|
| 44 |
+
for start in range(0, len(sorted_idx), 16):
|
| 45 |
+
chunk = sorted_idx[start : start + 16]
|
| 46 |
+
batch = collate([ds[i] for i in chunk], device)
|
| 47 |
+
with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=use_amp):
|
| 48 |
+
h, m = cfm.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
|
| 49 |
+
pt, ct = cfm.encode_prosody_context(h, batch["tokens"], batch["stress"], m)
|
| 50 |
+
af, _, fm, fl = cfm.expand_with_context(h, pt, ct, batch["durations"], m, batch["speakers"])
|
| 51 |
+
hp = cfm.hard_prosody(batch["prosody"])
|
| 52 |
+
cond, prior = cfm.condition_and_prior(af, hp, fm)
|
| 53 |
+
f0f = f0_features(hp, fm) if cfm.cfm_config.use_f0_harmonics else None
|
| 54 |
+
ng = energy_noise_gate(hp, fm) if cfm.cfm_config.use_energy_gate else None
|
| 55 |
+
mel_norm = cfm.sample_mel(
|
| 56 |
+
cond, prior, fm, n_steps=cfm_steps, cfg_scale=1.0, temperature=cfm_temp,
|
| 57 |
+
solver="midpoint", seed=seed, f0_feats=f0f, noise_gate=ng, sway_coef=sway_coef,
|
| 58 |
+
)
|
| 59 |
+
phys = (mel_norm.float() * cfm.vocoder.mel_scale + cfm.vocoder.mel_mean).clamp(min=-11.512925)
|
| 60 |
+
for b_i, ds_i in enumerate(chunk):
|
| 61 |
+
cfm_mels[ds_i] = phys[b_i, : int(fl[b_i])].half().cpu()
|
| 62 |
+
return gt_mels, cfm_mels
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def sample_ft_crops(
|
| 66 |
+
ds: AnnotatedDataset,
|
| 67 |
+
indices: list[int],
|
| 68 |
+
gt_mels: dict[int, torch.Tensor],
|
| 69 |
+
cfm_mels: dict[int, torch.Tensor],
|
| 70 |
+
batch_size: int,
|
| 71 |
+
crop_frames: int,
|
| 72 |
+
cfm_prob: float,
|
| 73 |
+
hop: int,
|
| 74 |
+
rng: torch.Generator,
|
| 75 |
+
device: str,
|
| 76 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 77 |
+
"""Sample aligned ``[B, 100, crop_frames]`` mel crops (gt/cfm mix) and ``[B, 1, crop_frames*hop]`` real wave."""
|
| 78 |
+
eligible = [i for i in indices if ds.lengths[i] >= crop_frames]
|
| 79 |
+
pick = torch.randint(len(eligible), (batch_size,), generator=rng).tolist()
|
| 80 |
+
mels = torch.zeros((batch_size, 100, crop_frames), dtype=torch.float32)
|
| 81 |
+
waves = torch.zeros((batch_size, 1, crop_frames * hop), dtype=torch.float32)
|
| 82 |
+
use_cfm = torch.rand((batch_size,), generator=rng).tolist()
|
| 83 |
+
|
| 84 |
+
for b, e_idx in enumerate(pick):
|
| 85 |
+
ds_i = eligible[e_idx]
|
| 86 |
+
t_tot = int(gt_mels[ds_i].shape[0])
|
| 87 |
+
s0 = int(torch.randint(0, t_tot - crop_frames + 1, (1,), generator=rng).item())
|
| 88 |
+
src = cfm_mels[ds_i] if use_cfm[b] < cfm_prob else gt_mels[ds_i]
|
| 89 |
+
mels[b] = src[s0 : s0 + crop_frames].float().transpose(0, 1)
|
| 90 |
+
waves[b, 0] = ds[ds_i]["wave"][s0 * hop : (s0 + crop_frames) * hop]
|
| 91 |
+
return mels.to(device), waves.to(device)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _update_ema(ema_gen: nn.Module, gen: nn.Module, decay: float, on_cpu: bool) -> None:
|
| 95 |
+
if not on_cpu:
|
| 96 |
+
update_ema(ema_gen, gen, decay)
|
| 97 |
+
return
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
for p_ema, p in zip(ema_gen.parameters(), gen.parameters()):
|
| 100 |
+
if p.requires_grad:
|
| 101 |
+
p_ema.mul_(decay).add_(p.detach().cpu(), alpha=1.0 - decay)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@torch.no_grad()
|
| 105 |
+
def validate_bigvgan(
|
| 106 |
+
gen,
|
| 107 |
+
ext: BigVGANMelExtractor,
|
| 108 |
+
ds: AnnotatedDataset,
|
| 109 |
+
indices: list[int],
|
| 110 |
+
gt_mels: dict[int, torch.Tensor],
|
| 111 |
+
cfm_mels: dict[int, torch.Tensor],
|
| 112 |
+
device: str,
|
| 113 |
+
ema_on_cpu: bool = False,
|
| 114 |
+
) -> dict[str, float]:
|
| 115 |
+
was_training = gen.training
|
| 116 |
+
if ema_on_cpu:
|
| 117 |
+
gen.to(device)
|
| 118 |
+
gen.eval()
|
| 119 |
+
gt_tot, cfm_tot, n = 0.0, 0.0, 0
|
| 120 |
+
try:
|
| 121 |
+
for idx in indices:
|
| 122 |
+
gt_m = gt_mels[idx][None].to(device=device, dtype=torch.float32)
|
| 123 |
+
t_len = int(gt_m.shape[1])
|
| 124 |
+
cfm_m = cfm_mels[idx][None].to(device=device, dtype=torch.float32)
|
| 125 |
+
w_from_gt = gen(gt_m.transpose(1, 2)).squeeze(1)[:, : t_len * 256]
|
| 126 |
+
w_from_cfm = gen(cfm_m.transpose(1, 2)).squeeze(1)[:, : t_len * 256]
|
| 127 |
+
gt_tot += float(F.l1_loss(ext(w_from_gt), gt_m))
|
| 128 |
+
cfm_tot += float(F.l1_loss(ext(w_from_cfm), gt_m))
|
| 129 |
+
n += 1
|
| 130 |
+
finally:
|
| 131 |
+
if was_training:
|
| 132 |
+
gen.train()
|
| 133 |
+
if ema_on_cpu:
|
| 134 |
+
gen.to("cpu")
|
| 135 |
+
if str(device).startswith("cuda") and torch.cuda.is_available():
|
| 136 |
+
torch.cuda.empty_cache()
|
| 137 |
+
return {"val_gt_mel_l1": gt_tot / max(n, 1), "val_cfm_mel_l1": cfm_tot / max(n, 1)}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _lr_g_at(step: int, disc_warmup: int, warmup_g: int, total_steps: int, lr_g: float, min_lr_g: float) -> float:
|
| 141 |
+
if step < disc_warmup:
|
| 142 |
+
return 0.0
|
| 143 |
+
gs = step - disc_warmup
|
| 144 |
+
g_tot = max(total_steps - disc_warmup, 1)
|
| 145 |
+
if gs < warmup_g:
|
| 146 |
+
return lr_g * (gs + 1) / max(warmup_g, 1)
|
| 147 |
+
prog = min(max((gs - warmup_g) / max(g_tot - warmup_g, 1), 0.0), 1.0)
|
| 148 |
+
return min_lr_g + 0.5 * (lr_g - min_lr_g) * (1.0 + math.cos(math.pi * prog))
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _lr_d_at(step: int, disc_warmup: int, total_steps: int, lr_d: float, lr_d_post: float, min_lr_d: float) -> float:
|
| 152 |
+
if step < disc_warmup:
|
| 153 |
+
return lr_d
|
| 154 |
+
prog = min(max((step - disc_warmup) / max(total_steps - disc_warmup, 1), 0.0), 1.0)
|
| 155 |
+
return min_lr_d + 0.5 * (lr_d_post - min_lr_d) * (1.0 + math.cos(math.pi * prog))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _save_bigvgan_ckpt(gen, model_id: str, step: int, path: Path) -> None:
|
| 159 |
+
atomic_save(
|
| 160 |
+
{
|
| 161 |
+
"format": "bigvgan_ft_v1",
|
| 162 |
+
"model_id": model_id,
|
| 163 |
+
"step": int(step),
|
| 164 |
+
"weight_norm_removed": False,
|
| 165 |
+
"h": dict(gen.h),
|
| 166 |
+
"state_dict": {k: v.detach().cpu() for k, v in gen.state_dict().items()},
|
| 167 |
+
},
|
| 168 |
+
path,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def main() -> None:
|
| 173 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 174 |
+
parser.add_argument("--train", type=Path, required=True)
|
| 175 |
+
parser.add_argument("--validation", type=Path, required=True)
|
| 176 |
+
parser.add_argument("--cfm-ckpt", type=Path, required=True)
|
| 177 |
+
parser.add_argument("--model-id", default="nvidia/bigvgan_base_24khz_100band")
|
| 178 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 179 |
+
parser.add_argument("--device", default="cuda")
|
| 180 |
+
parser.add_argument("--steps", type=int, default=3500)
|
| 181 |
+
parser.add_argument("--disc-warmup", type=int, default=500)
|
| 182 |
+
parser.add_argument("--batch-size", type=int, default=6)
|
| 183 |
+
parser.add_argument("--grad-accum", type=int, default=2)
|
| 184 |
+
parser.add_argument("--crop-frames", type=int, default=32)
|
| 185 |
+
parser.add_argument("--cfm-prob", type=float, default=0.50)
|
| 186 |
+
parser.add_argument("--bf16", action=argparse.BooleanOptionalAction, default=True)
|
| 187 |
+
parser.add_argument("--lr-g", type=float, default=2e-5)
|
| 188 |
+
parser.add_argument("--min-lr-g", type=float, default=2e-6)
|
| 189 |
+
parser.add_argument("--warmup-g", type=int, default=300)
|
| 190 |
+
parser.add_argument("--lr-d", type=float, default=1e-4)
|
| 191 |
+
parser.add_argument("--lr-d-post", type=float, default=5e-5)
|
| 192 |
+
parser.add_argument("--min-lr-d", type=float, default=5e-6)
|
| 193 |
+
parser.add_argument("--ema-decay", type=float, default=0.995)
|
| 194 |
+
parser.add_argument("--val-every", type=int, default=500)
|
| 195 |
+
parser.add_argument("--log-every", type=int, default=10)
|
| 196 |
+
parser.add_argument("--save-steps", nargs="+", type=int, default=[2000, 3500])
|
| 197 |
+
parser.add_argument("--pretrained-disc", action=argparse.BooleanOptionalAction, default=True)
|
| 198 |
+
parser.add_argument("--cfm-steps", type=int, default=8)
|
| 199 |
+
parser.add_argument("--cfm-temp", type=float, default=0.35)
|
| 200 |
+
parser.add_argument("--sway-coef", type=float, default=-0.5)
|
| 201 |
+
parser.add_argument("--ema-on-cpu", action=argparse.BooleanOptionalAction, default=False)
|
| 202 |
+
parser.add_argument("--seed", type=int, default=20261122)
|
| 203 |
+
args = parser.parse_args()
|
| 204 |
+
|
| 205 |
+
torch.manual_seed(args.seed)
|
| 206 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 207 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 208 |
+
|
| 209 |
+
_ensure_bigvgan_importable()
|
| 210 |
+
import bigvgan
|
| 211 |
+
from discriminators import MultiPeriodDiscriminator, MultiResolutionDiscriminator
|
| 212 |
+
from loss import discriminator_loss, feature_loss, generator_loss
|
| 213 |
+
|
| 214 |
+
cfm = load_cfm_model(args.cfm_ckpt, args.device)
|
| 215 |
+
train_ds = AnnotatedDataset(args.train, cfm.config, voiced_vowels=True, cache=True)
|
| 216 |
+
val_ds = AnnotatedDataset(args.validation, cfm.config, voiced_vowels=True, cache=True)
|
| 217 |
+
check_leakage(train_ds, val_ds)
|
| 218 |
+
pool = [i for i in range(len(train_ds)) if train_ds.lengths[i] >= args.crop_frames]
|
| 219 |
+
val_indices = balanced_indices(val_ds, len(val_ds))
|
| 220 |
+
print(f"Preloading train ({len(pool)}) and validation ({len(val_indices)}) ...", flush=True)
|
| 221 |
+
train_ds.preload(pool, workers=8)
|
| 222 |
+
val_ds.preload(val_indices, workers=4)
|
| 223 |
+
|
| 224 |
+
ext = BigVGANMelExtractor().to(args.device).eval()
|
| 225 |
+
t0_pre = time.perf_counter()
|
| 226 |
+
train_gt, train_cfm = precompute_gt_and_cfm_mels(
|
| 227 |
+
train_ds, pool, cfm, ext, args.device, seed=0,
|
| 228 |
+
cfm_steps=args.cfm_steps, cfm_temp=args.cfm_temp, sway_coef=args.sway_coef,
|
| 229 |
+
)
|
| 230 |
+
val_gt, val_cfm = precompute_gt_and_cfm_mels(
|
| 231 |
+
val_ds, val_indices, cfm, ext, args.device, seed=0,
|
| 232 |
+
cfm_steps=args.cfm_steps, cfm_temp=args.cfm_temp, sway_coef=args.sway_coef,
|
| 233 |
+
)
|
| 234 |
+
del cfm
|
| 235 |
+
torch.cuda.empty_cache()
|
| 236 |
+
print(
|
| 237 |
+
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",
|
| 238 |
+
flush=True,
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
gen = bigvgan.BigVGAN.from_pretrained(args.model_id, use_cuda_kernel=False).to(args.device)
|
| 242 |
+
ema_device = "cpu" if args.ema_on_cpu else args.device
|
| 243 |
+
ema_gen = bigvgan.BigVGAN(gen.h, use_cuda_kernel=False).to(ema_device)
|
| 244 |
+
ema_gen.load_state_dict({k: v.detach().to(ema_device).clone() for k, v in gen.state_dict().items()}, strict=True)
|
| 245 |
+
ema_gen.eval()
|
| 246 |
+
for p in ema_gen.parameters():
|
| 247 |
+
p.requires_grad_(False)
|
| 248 |
+
|
| 249 |
+
mpd = MultiPeriodDiscriminator(gen.h).to(args.device)
|
| 250 |
+
mrd = MultiResolutionDiscriminator(gen.h).to(args.device)
|
| 251 |
+
disc_msg = "Discriminators initialized randomly"
|
| 252 |
+
if args.pretrained_disc:
|
| 253 |
+
from huggingface_hub import hf_hub_download
|
| 254 |
+
|
| 255 |
+
do_path = hf_hub_download(args.model_id, "bigvgan_discriminator_optimizer.pt")
|
| 256 |
+
do_ckpt = torch.load(do_path, map_location="cpu", weights_only=True)
|
| 257 |
+
mpd.load_state_dict(do_ckpt["mpd"], strict=True)
|
| 258 |
+
mrd.load_state_dict(do_ckpt["mrd"], strict=True)
|
| 259 |
+
disc_msg = f"Loaded pretrained NVIDIA MPD/MRD from {args.model_id} (steps={do_ckpt.get('steps')})"
|
| 260 |
+
del do_ckpt
|
| 261 |
+
disc_params = list(mpd.parameters()) + list(mrd.parameters())
|
| 262 |
+
|
| 263 |
+
for p in gen.parameters():
|
| 264 |
+
p.requires_grad_(False)
|
| 265 |
+
opt_g = torch.optim.AdamW(list(gen.parameters()), lr=args.lr_g, betas=(0.8, 0.99), weight_decay=0.0)
|
| 266 |
+
opt_d = torch.optim.AdamW(disc_params, lr=args.lr_d, betas=(0.8, 0.99), weight_decay=0.0)
|
| 267 |
+
|
| 268 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 269 |
+
log_f = (args.output / "train.log").open("a", encoding="utf-8", buffering=1)
|
| 270 |
+
|
| 271 |
+
def emit(msg: str) -> None:
|
| 272 |
+
print(msg, flush=True)
|
| 273 |
+
log_f.write(msg + "\n")
|
| 274 |
+
log_f.flush()
|
| 275 |
+
|
| 276 |
+
emit(f"{disc_msg} | ema_on_cpu={args.ema_on_cpu}")
|
| 277 |
+
|
| 278 |
+
is_cuda = torch.cuda.is_available() and str(args.device).startswith("cuda")
|
| 279 |
+
use_bf16 = bool(args.bf16 and is_cuda)
|
| 280 |
+
grad_accum = max(int(args.grad_accum), 1)
|
| 281 |
+
if is_cuda:
|
| 282 |
+
torch.cuda.reset_peak_memory_stats(args.device)
|
| 283 |
+
|
| 284 |
+
v0 = validate_bigvgan(ema_gen, ext, val_ds, val_indices, val_gt, val_cfm, args.device, ema_on_cpu=args.ema_on_cpu)
|
| 285 |
+
emit(f"[step 0] {json.dumps(v0)}")
|
| 286 |
+
|
| 287 |
+
rng = torch.Generator().manual_seed(args.seed + 31)
|
| 288 |
+
hop = int(gen.h.hop_size)
|
| 289 |
+
win = defaultdict(float)
|
| 290 |
+
win_n = 0
|
| 291 |
+
win_t = time.monotonic()
|
| 292 |
+
save_set = set(int(s) for s in args.save_steps) | {int(args.steps)}
|
| 293 |
+
|
| 294 |
+
try:
|
| 295 |
+
for step in range(args.steps):
|
| 296 |
+
if step == args.disc_warmup:
|
| 297 |
+
for p in gen.parameters():
|
| 298 |
+
p.requires_grad_(True)
|
| 299 |
+
if is_cuda:
|
| 300 |
+
torch.cuda.reset_peak_memory_stats(args.device)
|
| 301 |
+
emit(f"[step {step}] Generator unfrozen (lr_g -> {args.lr_g}, bf16={use_bf16}, bs={args.batch_size}x{grad_accum})")
|
| 302 |
+
|
| 303 |
+
lr_d = _lr_d_at(step, args.disc_warmup, args.steps, args.lr_d, args.lr_d_post, args.min_lr_d)
|
| 304 |
+
for pg in opt_d.param_groups:
|
| 305 |
+
pg["lr"] = lr_d
|
| 306 |
+
lr_g = _lr_g_at(step, args.disc_warmup, args.warmup_g, args.steps, args.lr_g, args.min_lr_g)
|
| 307 |
+
for pg in opt_g.param_groups:
|
| 308 |
+
pg["lr"] = lr_g
|
| 309 |
+
|
| 310 |
+
opt_d.zero_grad(set_to_none=True)
|
| 311 |
+
if step >= args.disc_warmup:
|
| 312 |
+
opt_g.zero_grad(set_to_none=True)
|
| 313 |
+
|
| 314 |
+
acc_loss_d = 0.0
|
| 315 |
+
acc_loss_g = 0.0
|
| 316 |
+
acc_mel = 0.0
|
| 317 |
+
acc_fm = 0.0
|
| 318 |
+
acc_adv = 0.0
|
| 319 |
+
|
| 320 |
+
for _micro in range(grad_accum):
|
| 321 |
+
mel_crop, y = sample_ft_crops(
|
| 322 |
+
train_ds, pool, train_gt, train_cfm, args.batch_size, args.crop_frames, args.cfm_prob, hop, rng, args.device
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
# Forward generator
|
| 326 |
+
if step < args.disc_warmup:
|
| 327 |
+
gen.eval()
|
| 328 |
+
with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
| 329 |
+
y_g_hat = gen(mel_crop)
|
| 330 |
+
else:
|
| 331 |
+
gen.train()
|
| 332 |
+
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
| 333 |
+
y_g_hat = gen(mel_crop)
|
| 334 |
+
|
| 335 |
+
y_g_det_bf = y_g_hat.detach()
|
| 336 |
+
y_g_det_32 = y_g_det_bf.float()
|
| 337 |
+
y_32 = y.float()
|
| 338 |
+
|
| 339 |
+
# Discriminator micro-step
|
| 340 |
+
mpd.train()
|
| 341 |
+
mrd.train()
|
| 342 |
+
for p in disc_params:
|
| 343 |
+
p.requires_grad_(True)
|
| 344 |
+
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
| 345 |
+
y_df_r, y_df_g, _, _ = mpd(y, y_g_det_bf)
|
| 346 |
+
with torch.amp.autocast("cuda", enabled=False):
|
| 347 |
+
loss_df, _, _ = discriminator_loss([t.float() for t in y_df_r], [t.float() for t in y_df_g])
|
| 348 |
+
y_ds_r, y_ds_g, _, _ = mrd(y_32, y_g_det_32)
|
| 349 |
+
loss_ds, _, _ = discriminator_loss(y_ds_r, y_ds_g)
|
| 350 |
+
loss_d_mb = loss_df + loss_ds
|
| 351 |
+
if not torch.isfinite(loss_d_mb):
|
| 352 |
+
raise RuntimeError(f"Non-finite loss_d at step {step}: {loss_d_mb}")
|
| 353 |
+
(loss_d_mb / grad_accum).backward()
|
| 354 |
+
acc_loss_d += float(loss_d_mb.detach()) / grad_accum
|
| 355 |
+
del y_df_r, y_df_g, y_ds_r, y_ds_g, y_g_det_bf, y_g_det_32
|
| 356 |
+
|
| 357 |
+
# Generator micro-step after disc warmup
|
| 358 |
+
if step >= args.disc_warmup:
|
| 359 |
+
for p in disc_params:
|
| 360 |
+
p.requires_grad_(False)
|
| 361 |
+
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
| 362 |
+
y_df_r, y_df_g, fmap_f_r, fmap_f_g = mpd(y, y_g_hat)
|
| 363 |
+
y_g_hat_32 = y_g_hat.float()
|
| 364 |
+
with torch.amp.autocast("cuda", enabled=False):
|
| 365 |
+
y_ds_r, y_ds_g, fmap_s_r, fmap_s_g = mrd(y_32, y_g_hat_32)
|
| 366 |
+
loss_mel_mb = F.l1_loss(ext(y_g_hat_32.squeeze(1)), ext(y_32.squeeze(1))) * 45.0
|
| 367 |
+
loss_fm_mb = (
|
| 368 |
+
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])
|
| 369 |
+
+ feature_loss(fmap_s_r, fmap_s_g)
|
| 370 |
+
)
|
| 371 |
+
loss_gen_mb = generator_loss([t.float() for t in y_df_g])[0] + generator_loss(y_ds_g)[0]
|
| 372 |
+
loss_g_mb = loss_gen_mb + loss_fm_mb + loss_mel_mb
|
| 373 |
+
if not torch.isfinite(loss_g_mb):
|
| 374 |
+
raise RuntimeError(f"Non-finite loss_g at step {step}: {loss_g_mb}")
|
| 375 |
+
(loss_g_mb / grad_accum).backward()
|
| 376 |
+
acc_loss_g += float(loss_g_mb.detach()) / grad_accum
|
| 377 |
+
acc_mel += float(loss_mel_mb.detach()) / grad_accum
|
| 378 |
+
acc_fm += float(loss_fm_mb.detach()) / grad_accum
|
| 379 |
+
acc_adv += float(loss_gen_mb.detach()) / grad_accum
|
| 380 |
+
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
|
| 381 |
+
else:
|
| 382 |
+
with torch.no_grad(), torch.amp.autocast("cuda", enabled=False):
|
| 383 |
+
loss_mel_mb = F.l1_loss(ext(y_g_hat.float().squeeze(1)), ext(y_32.squeeze(1))) * 45.0
|
| 384 |
+
acc_mel += float(loss_mel_mb.detach()) / grad_accum
|
| 385 |
+
acc_loss_g += float(loss_mel_mb.detach()) / grad_accum
|
| 386 |
+
del y_g_hat, mel_crop, y, y_32
|
| 387 |
+
|
| 388 |
+
for p in disc_params:
|
| 389 |
+
p.requires_grad_(True)
|
| 390 |
+
nn.utils.clip_grad_norm_(disc_params, 1.0)
|
| 391 |
+
opt_d.step()
|
| 392 |
+
|
| 393 |
+
if step >= args.disc_warmup:
|
| 394 |
+
grad_g = float(nn.utils.clip_grad_norm_(gen.parameters(), 1.0))
|
| 395 |
+
opt_g.step()
|
| 396 |
+
_update_ema(ema_gen, gen, args.ema_decay, args.ema_on_cpu)
|
| 397 |
+
else:
|
| 398 |
+
grad_g = 0.0
|
| 399 |
+
|
| 400 |
+
cur = step + 1
|
| 401 |
+
win["loss_g"] += acc_loss_g
|
| 402 |
+
win["loss_d"] += acc_loss_d
|
| 403 |
+
win["mel"] += acc_mel
|
| 404 |
+
win["fm"] += acc_fm
|
| 405 |
+
win["adv"] += acc_adv
|
| 406 |
+
win["grad_g"] += grad_g
|
| 407 |
+
win_n += 1
|
| 408 |
+
|
| 409 |
+
do_val = (cur % args.val_every == 0) or (cur == args.steps)
|
| 410 |
+
do_save = cur in save_set
|
| 411 |
+
do_log = (cur % args.log_every == 0) or (cur == args.disc_warmup + 1) or do_val or do_save
|
| 412 |
+
|
| 413 |
+
if do_log:
|
| 414 |
+
if is_cuda:
|
| 415 |
+
torch.cuda.synchronize()
|
| 416 |
+
dt = max(time.monotonic() - win_t, 1e-6)
|
| 417 |
+
it_s = win_n / dt
|
| 418 |
+
eta_min = (args.steps - cur) / max(it_s, 1e-6) / 60.0
|
| 419 |
+
vram_gb = (torch.cuda.memory_allocated(args.device) / 1e9) if is_cuda else 0.0
|
| 420 |
+
vram_peak_gb = (torch.cuda.max_memory_allocated(args.device) / 1e9) if is_cuda else 0.0
|
| 421 |
+
rec = {k: round(v / win_n, 4) for k, v in win.items()}
|
| 422 |
+
rec.update(
|
| 423 |
+
step=cur,
|
| 424 |
+
lr_g=round(lr_g, 7),
|
| 425 |
+
lr_d=round(lr_d, 7),
|
| 426 |
+
it_s=round(it_s, 2),
|
| 427 |
+
eta_min=round(eta_min, 2),
|
| 428 |
+
vram_gb=round(vram_gb, 2),
|
| 429 |
+
vram_peak_gb=round(vram_peak_gb, 2),
|
| 430 |
+
)
|
| 431 |
+
if do_val:
|
| 432 |
+
rec.update(
|
| 433 |
+
{
|
| 434 |
+
k: round(v, 5)
|
| 435 |
+
for k, v in validate_bigvgan(
|
| 436 |
+
ema_gen, ext, val_ds, val_indices, val_gt, val_cfm, args.device, ema_on_cpu=args.ema_on_cpu
|
| 437 |
+
).items()
|
| 438 |
+
}
|
| 439 |
+
)
|
| 440 |
+
with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as mf:
|
| 441 |
+
mf.write(json.dumps(rec) + "\n")
|
| 442 |
+
mf.flush()
|
| 443 |
+
pct = 100.0 * cur / max(args.steps, 1)
|
| 444 |
+
msg = (
|
| 445 |
+
f"[step {cur:05d}/{args.steps:05d} | {pct:5.1f}%] "
|
| 446 |
+
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} | "
|
| 447 |
+
f"{rec['it_s']:.2f} it/s | ETA {rec['eta_min']:.1f}m | VRAM {rec['vram_gb']:.2f}/{rec['vram_peak_gb']:.2f} GB"
|
| 448 |
+
)
|
| 449 |
+
if do_val:
|
| 450 |
+
msg += f" | val_gt={rec['val_gt_mel_l1']:.5f} val_cfm={rec['val_cfm_mel_l1']:.5f}"
|
| 451 |
+
emit(msg)
|
| 452 |
+
win = defaultdict(float)
|
| 453 |
+
win_n = 0
|
| 454 |
+
win_t = time.monotonic()
|
| 455 |
+
|
| 456 |
+
if do_save:
|
| 457 |
+
_save_bigvgan_ckpt(ema_gen, args.model_id, cur, args.output / f"bigvgan_ft_step-{cur:06d}.pt")
|
| 458 |
+
_save_bigvgan_ckpt(ema_gen, args.model_id, cur, args.output / "bigvgan_ft_ema.pt")
|
| 459 |
+
finally:
|
| 460 |
+
log_f.close()
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
if __name__ == "__main__":
|
| 464 |
+
main()
|
code/src/lua_nova_v1/utils/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared audio and checkpoint utilities."""
|
| 2 |
+
|
| 3 |
+
from .audio import (
|
| 4 |
+
DEFAULT_FADE_MS,
|
| 5 |
+
DEFAULT_TARGET_RMS_DB,
|
| 6 |
+
PEAK,
|
| 7 |
+
finished,
|
| 8 |
+
limit_peak,
|
| 9 |
+
pcm16,
|
| 10 |
+
postprocess_audio,
|
| 11 |
+
sentences,
|
| 12 |
+
shorter,
|
| 13 |
+
split_clauses,
|
| 14 |
+
)
|
| 15 |
+
from .checkpoint import atomic_save, soup_checkpoints, strip_legacy_vocoder
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"DEFAULT_FADE_MS",
|
| 19 |
+
"DEFAULT_TARGET_RMS_DB",
|
| 20 |
+
"PEAK",
|
| 21 |
+
"atomic_save",
|
| 22 |
+
"finished",
|
| 23 |
+
"limit_peak",
|
| 24 |
+
"pcm16",
|
| 25 |
+
"postprocess_audio",
|
| 26 |
+
"sentences",
|
| 27 |
+
"shorter",
|
| 28 |
+
"soup_checkpoints",
|
| 29 |
+
"split_clauses",
|
| 30 |
+
"strip_legacy_vocoder",
|
| 31 |
+
]
|
code/src/lua_nova_v1/utils/audio.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audio post-processing, PCM16 conversion, and text segmentation helpers."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import math
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
PEAK = 0.99
|
| 11 |
+
DEFAULT_TARGET_RMS_DB = -14.5
|
| 12 |
+
DEFAULT_FADE_MS = 5.0
|
| 13 |
+
|
| 14 |
+
_SPACE = re.compile(r"[\s\ufeff]+")
|
| 15 |
+
_SENTENCE_END = re.compile(r"""(?:(?<=[.!?…])|(?<=[.!?…]["')\]]))\s+(?=["'(\[]?[A-ZÀ-Ý0-9])""")
|
| 16 |
+
_NOT_AN_END = re.compile(
|
| 17 |
+
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À-Ý])\.$",
|
| 18 |
+
re.IGNORECASE,
|
| 19 |
+
)
|
| 20 |
+
_CLAUSE_END = re.compile(r"(?<=[,;:—])\s+")
|
| 21 |
+
_TEXT_END = re.compile(r"[\s\ufeff]+$")
|
| 22 |
+
_CLOSING = "\"'”’)]»"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def pcm16(wave: np.ndarray | torch.Tensor) -> tuple[np.ndarray, float]:
|
| 26 |
+
"""Scale samples into [-1, 1] when peak > 1.0 and return ``(samples, attenuation_db)``."""
|
| 27 |
+
arr = wave.detach().cpu().numpy() if isinstance(wave, torch.Tensor) else wave
|
| 28 |
+
arr = np.asarray(arr, dtype=np.float64)
|
| 29 |
+
peak = float(np.abs(arr).max()) if arr.size else 0.0
|
| 30 |
+
if peak <= 1.0:
|
| 31 |
+
return arr, 0.0
|
| 32 |
+
return arr / peak, round(20.0 * float(np.log10(peak)), 2)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def limit_peak(wave: torch.Tensor, peak: float = PEAK) -> torch.Tensor:
|
| 36 |
+
"""Scale ``wave`` down as a whole only when its peak amplitude exceeds ``peak``."""
|
| 37 |
+
loudest = float(wave.abs().max()) if wave.numel() else 0.0
|
| 38 |
+
return wave * (peak / loudest) if loudest > peak else wave
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _postprocess_numpy(
|
| 42 |
+
arr: np.ndarray,
|
| 43 |
+
sample_rate: int,
|
| 44 |
+
target_rms_db: float | None,
|
| 45 |
+
peak: float | None,
|
| 46 |
+
fade_ms: float,
|
| 47 |
+
) -> np.ndarray:
|
| 48 |
+
if not arr.size:
|
| 49 |
+
return arr
|
| 50 |
+
out = np.asarray(arr, dtype=np.float32)
|
| 51 |
+
if target_rms_db is not None:
|
| 52 |
+
loudest = float(np.abs(out).max())
|
| 53 |
+
if loudest > 1e-7:
|
| 54 |
+
frame_len = max(1, int(round(sample_rate * 0.02)))
|
| 55 |
+
usable = (out.size // frame_len) * frame_len
|
| 56 |
+
if usable >= frame_len:
|
| 57 |
+
f_rms = np.sqrt((out[:usable].reshape(-1, frame_len) ** 2).mean(axis=1))
|
| 58 |
+
active = f_rms[f_rms > loudest * (10.0 ** (-35.0 / 20.0))]
|
| 59 |
+
rms = float(np.sqrt((active ** 2).mean())) if active.size else float(np.sqrt((out ** 2).mean()))
|
| 60 |
+
else:
|
| 61 |
+
rms = float(np.sqrt((out ** 2).mean()))
|
| 62 |
+
target_rms = 10.0 ** (float(target_rms_db) / 20.0)
|
| 63 |
+
gain = max(0.25, min(4.0, target_rms / max(rms, 1e-8)))
|
| 64 |
+
out = out * np.float32(gain)
|
| 65 |
+
if fade_ms and fade_ms > 0:
|
| 66 |
+
n = min(int(round(sample_rate * fade_ms / 1000.0)), out.size // 2)
|
| 67 |
+
if n > 1:
|
| 68 |
+
out = out.copy()
|
| 69 |
+
ramp = (0.5 * (1.0 - np.cos(np.linspace(0.0, math.pi, n, dtype=np.float32)))).astype(np.float32)
|
| 70 |
+
out[:n] *= ramp
|
| 71 |
+
out[-n:] *= ramp[::-1]
|
| 72 |
+
if peak is not None:
|
| 73 |
+
loudest = float(np.abs(out).max())
|
| 74 |
+
if loudest > peak:
|
| 75 |
+
out = out * np.float32(peak / loudest)
|
| 76 |
+
return out
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def postprocess_audio(
|
| 80 |
+
wave: np.ndarray | torch.Tensor,
|
| 81 |
+
sample_rate: int = 24000,
|
| 82 |
+
target_rms_db: float | None = DEFAULT_TARGET_RMS_DB,
|
| 83 |
+
peak: float | None = PEAK,
|
| 84 |
+
fade_ms: float = DEFAULT_FADE_MS,
|
| 85 |
+
) -> np.ndarray | torch.Tensor:
|
| 86 |
+
"""Normalize active-speech RMS, apply short cosine edge fades, and limit peaks."""
|
| 87 |
+
if isinstance(wave, torch.Tensor):
|
| 88 |
+
if not wave.numel():
|
| 89 |
+
return wave
|
| 90 |
+
processed = _postprocess_numpy(wave.detach().cpu().numpy(), sample_rate, target_rms_db, peak, fade_ms)
|
| 91 |
+
return torch.from_numpy(processed).to(device=wave.device, dtype=wave.dtype)
|
| 92 |
+
return _postprocess_numpy(np.asarray(wave, dtype=np.float32), sample_rate, target_rms_db, peak, fade_ms)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def sentences(text: str) -> list[str]:
|
| 96 |
+
"""Split text into natural sentences without breaking on common abbreviations."""
|
| 97 |
+
parts, current = [], ""
|
| 98 |
+
for piece in _SENTENCE_END.split(_SPACE.sub(" ", text).strip()):
|
| 99 |
+
current = f"{current} {piece}" if current else piece
|
| 100 |
+
if not _NOT_AN_END.search(current):
|
| 101 |
+
parts.append(current)
|
| 102 |
+
current = ""
|
| 103 |
+
if current:
|
| 104 |
+
parts.append(current)
|
| 105 |
+
return [part for part in parts if any(ch.isalnum() for ch in part)]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def finished(text: str) -> str:
|
| 109 |
+
"""Append a final period when text ends without terminal or clause punctuation."""
|
| 110 |
+
body = _TEXT_END.sub("", text)
|
| 111 |
+
if not body:
|
| 112 |
+
return text
|
| 113 |
+
last = _SPACE.split(body)[-1]
|
| 114 |
+
if any(ch.isalnum() for ch in last):
|
| 115 |
+
marked = last.rstrip(_CLOSING)[-1:] in tuple(".!?…,;:")
|
| 116 |
+
else:
|
| 117 |
+
marked = any(ch in ".!?…" for ch in last) or last in (",", ";", ":")
|
| 118 |
+
return text if marked else body + "."
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def shorter(text: str) -> list[str]:
|
| 122 |
+
"""Split an overly long sentence on clause punctuation, or at its middle word."""
|
| 123 |
+
pieces = _CLAUSE_END.split(text)
|
| 124 |
+
if len(pieces) > 1:
|
| 125 |
+
return pieces
|
| 126 |
+
words = text.split(" ")
|
| 127 |
+
if len(words) < 2:
|
| 128 |
+
return []
|
| 129 |
+
half = (len(words) + 1) // 2
|
| 130 |
+
return [" ".join(words[:half]), " ".join(words[half:])]
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def split_clauses(text: str) -> list[str]:
|
| 134 |
+
"""Split text into sentences and clause-level chunks with terminal punctuation."""
|
| 135 |
+
chunks: list[str] = []
|
| 136 |
+
for sent in sentences(text):
|
| 137 |
+
for clause in _CLAUSE_END.split(finished(sent)):
|
| 138 |
+
clean = clause.strip()
|
| 139 |
+
if clean:
|
| 140 |
+
chunks.append(clean)
|
| 141 |
+
return chunks or ([text.strip()] if text.strip() else [])
|
code/src/lua_nova_v1/utils/checkpoint.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Checkpoint I/O, weight-soup interpolation, and lightweight inference stripping."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def atomic_save(value: object, path: Path | str) -> None:
|
| 11 |
+
"""Write a torch object safely using a temporary sibling file and atomic replace."""
|
| 12 |
+
target = Path(path)
|
| 13 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
temporary = target.with_suffix(target.suffix + ".tmp")
|
| 15 |
+
torch.save(value, temporary)
|
| 16 |
+
os.replace(temporary, target)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def soup_checkpoints(
|
| 20 |
+
ckpt_a: Path | str,
|
| 21 |
+
ckpt_b: Path | str,
|
| 22 |
+
out_path: Path | str,
|
| 23 |
+
alpha: float = 0.5,
|
| 24 |
+
) -> Path:
|
| 25 |
+
"""Interpolate ``(1 - alpha) * a + alpha * b`` across all floating-point ``model`` weights."""
|
| 26 |
+
a = torch.load(ckpt_a, map_location="cpu", weights_only=True)
|
| 27 |
+
b = torch.load(ckpt_b, map_location="cpu", weights_only=True)
|
| 28 |
+
sd_a, sd_b = a["model"], b["model"]
|
| 29 |
+
if set(sd_a.keys()) != set(sd_b.keys()):
|
| 30 |
+
raise ValueError("checkpoints do not have identical model keys for souping")
|
| 31 |
+
|
| 32 |
+
w_a = 1.0 - float(alpha)
|
| 33 |
+
w_b = float(alpha)
|
| 34 |
+
merged = {}
|
| 35 |
+
for k in sd_a:
|
| 36 |
+
ta, tb = sd_a[k], sd_b[k]
|
| 37 |
+
if torch.is_floating_point(ta):
|
| 38 |
+
merged[k] = (w_a * ta.float() + w_b * tb.float()).to(ta.dtype)
|
| 39 |
+
else:
|
| 40 |
+
merged[k] = ta.clone()
|
| 41 |
+
|
| 42 |
+
out = dict(a)
|
| 43 |
+
out["model"] = merged
|
| 44 |
+
out["soup"] = {"alpha": float(alpha), "source_a": Path(ckpt_a).name, "source_b": Path(ckpt_b).name}
|
| 45 |
+
atomic_save(out, out_path)
|
| 46 |
+
return Path(out_path)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def strip_legacy_vocoder(
|
| 50 |
+
ckpt_path: Path | str,
|
| 51 |
+
out_path: Path | str,
|
| 52 |
+
fp16: bool = False,
|
| 53 |
+
) -> Path:
|
| 54 |
+
"""Strip unused legacy Vocos weights from a BigVGAN-space CFM checkpoint for distribution."""
|
| 55 |
+
state = torch.load(ckpt_path, map_location="cpu", weights_only=True)
|
| 56 |
+
sd = state["model"]
|
| 57 |
+
cleaned = {}
|
| 58 |
+
for k, v in sd.items():
|
| 59 |
+
if k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale"):
|
| 60 |
+
continue
|
| 61 |
+
cleaned[k] = v.half() if (fp16 and torch.is_floating_point(v)) else v.clone()
|
| 62 |
+
|
| 63 |
+
out = dict(state)
|
| 64 |
+
out["model"] = cleaned
|
| 65 |
+
out["stripped_legacy_vocoder"] = True
|
| 66 |
+
atomic_save(out, out_path)
|
| 67 |
+
return Path(out_path)
|
code/tests/test_model.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for CFMConfig, LuaNovaCFM, Sway Sampling, BigVGAN mel extractor, and checkpoint helpers."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import tempfile
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from lua_nova_v1.config import CFMConfig, Config
|
| 11 |
+
from lua_nova_v1.models import BigVGANMelExtractor, MelStatsHead, LuaNovaCFM
|
| 12 |
+
from lua_nova_v1.training.common import export_cfm_checkpoint, load_cfm_model
|
| 13 |
+
from lua_nova_v1.utils.checkpoint import soup_checkpoints, strip_legacy_vocoder
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ModelTests(unittest.TestCase):
|
| 17 |
+
def _tiny_cfg(self) -> CFMConfig:
|
| 18 |
+
base = Config(
|
| 19 |
+
channels=32,
|
| 20 |
+
heads=2,
|
| 21 |
+
feedforward=64,
|
| 22 |
+
encoder_layers=1,
|
| 23 |
+
prosody_layers=1,
|
| 24 |
+
acoustic_layers=1,
|
| 25 |
+
predictor_channels=16,
|
| 26 |
+
vocos_n_mels=100,
|
| 27 |
+
)
|
| 28 |
+
return CFMConfig(
|
| 29 |
+
base=base,
|
| 30 |
+
flow_channels=32,
|
| 31 |
+
flow_layers=2,
|
| 32 |
+
flow_heads=2,
|
| 33 |
+
flow_feedforward=64,
|
| 34 |
+
flow_kernel=3,
|
| 35 |
+
use_acoustic_prior=True,
|
| 36 |
+
use_f0_harmonics=True,
|
| 37 |
+
acoustic_from_frames=True,
|
| 38 |
+
use_energy_gate=True,
|
| 39 |
+
use_ling_context=True,
|
| 40 |
+
use_duration_flow=True,
|
| 41 |
+
use_prosody_flow=True,
|
| 42 |
+
prosody_context_layers=1,
|
| 43 |
+
dur_flow_channels=16,
|
| 44 |
+
dur_flow_layers=1,
|
| 45 |
+
dur_flow_heads=2,
|
| 46 |
+
dur_flow_feedforward=32,
|
| 47 |
+
prosody_flow_channels=16,
|
| 48 |
+
prosody_flow_layers=1,
|
| 49 |
+
prosody_flow_heads=2,
|
| 50 |
+
prosody_flow_feedforward=32,
|
| 51 |
+
mel_space="bigvgan_24k_100",
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def test_mel_stats_head_requires_no_external_vocos(self) -> None:
|
| 55 |
+
model = LuaNovaCFM(self._tiny_cfg())
|
| 56 |
+
self.assertIsInstance(model.vocoder, MelStatsHead)
|
| 57 |
+
self.assertIsNone(model.vocoder.vocos)
|
| 58 |
+
|
| 59 |
+
def test_sway_schedule_and_parity(self) -> None:
|
| 60 |
+
uniform = LuaNovaCFM.sway_time_grid(8, sway_coef=0.0)
|
| 61 |
+
self.assertEqual(uniform, [i / 8 for i in range(9)])
|
| 62 |
+
swayed = LuaNovaCFM.sway_time_grid(8, sway_coef=-0.5)
|
| 63 |
+
self.assertAlmostEqual(swayed[0], 0.0, places=6)
|
| 64 |
+
self.assertAlmostEqual(swayed[-1], 1.0, places=6)
|
| 65 |
+
self.assertTrue(all(a < b for a, b in zip(swayed[:-1], swayed[1:])))
|
| 66 |
+
self.assertLess(swayed[4], 0.5)
|
| 67 |
+
|
| 68 |
+
model = LuaNovaCFM(self._tiny_cfg()).eval()
|
| 69 |
+
cond = torch.randn(1, 12, 32)
|
| 70 |
+
prior = torch.randn(1, 12, 100)
|
| 71 |
+
fmask = torch.ones(1, 12, dtype=torch.bool)
|
| 72 |
+
f0_f = torch.randn(1, 12, 12)
|
| 73 |
+
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)
|
| 74 |
+
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)
|
| 75 |
+
self.assertEqual(m1.shape, (1, 12, 100))
|
| 76 |
+
self.assertTrue(torch.isfinite(m1).all() and torch.isfinite(m2).all())
|
| 77 |
+
|
| 78 |
+
def test_bigvgan_mel_extractor_shapes_and_finiteness(self) -> None:
|
| 79 |
+
ext = BigVGANMelExtractor().eval()
|
| 80 |
+
wave = torch.randn(2, 256 * 20) * 0.1
|
| 81 |
+
mel = ext(wave)
|
| 82 |
+
self.assertEqual(mel.shape, (2, 20, 100))
|
| 83 |
+
self.assertTrue(torch.isfinite(mel).all())
|
| 84 |
+
mel_1d = ext(wave[0])
|
| 85 |
+
self.assertTrue(torch.allclose(mel[0], mel_1d[0], atol=1e-5))
|
| 86 |
+
|
| 87 |
+
def test_checkpoint_strip_soup_and_load_roundtrip(self) -> None:
|
| 88 |
+
m_a = LuaNovaCFM(self._tiny_cfg()).eval()
|
| 89 |
+
m_b = LuaNovaCFM(self._tiny_cfg()).eval()
|
| 90 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 91 |
+
p_a = Path(tmp) / "a.pt"
|
| 92 |
+
p_b = Path(tmp) / "b.pt"
|
| 93 |
+
p_soup = Path(tmp) / "soup.pt"
|
| 94 |
+
p_strip = Path(tmp) / "stripped.pt"
|
| 95 |
+
export_cfm_checkpoint(m_a, p_a, step=10)
|
| 96 |
+
export_cfm_checkpoint(m_b, p_b, step=20)
|
| 97 |
+
soup_checkpoints(p_a, p_b, p_soup, alpha=0.5)
|
| 98 |
+
strip_legacy_vocoder(p_soup, p_strip, fp16=True)
|
| 99 |
+
|
| 100 |
+
loaded = load_cfm_model(p_strip, device="cpu")
|
| 101 |
+
for k in m_a.state_dict():
|
| 102 |
+
if not (k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale")):
|
| 103 |
+
expected = 0.5 * m_a.state_dict()[k] + 0.5 * m_b.state_dict()[k]
|
| 104 |
+
if torch.is_floating_point(expected):
|
| 105 |
+
self.assertLess((loaded.state_dict()[k] - expected).abs().max().item(), 1e-2)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
unittest.main()
|