Spaces:
Sleeping
Sleeping
Add Hugging Face Space demo
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +70 -0
- .gitattributes +3 -0
- .gitignore +163 -0
- .pre-commit-config.yaml +14 -0
- Dockerfile +29 -0
- LICENSE +21 -0
- README.md +172 -9
- app.py +121 -4
- data/librispeech_pc_test_clean_cross_sentence.lst +0 -0
- data/ljspeech_inset_test_9s.lst +0 -0
- docs/static/images/wavtts_pipeline.png +3 -0
- packages.txt +1 -0
- pyproject.toml +69 -0
- requirements.txt +1 -0
- ruff.toml +11 -0
- src/wavtts/__init__.py +1 -0
- src/wavtts/configs/WavTTS.yaml +65 -0
- src/wavtts/eval/README.md +67 -0
- src/wavtts/eval/ecapa_tdnn.py +331 -0
- src/wavtts/eval/eval_infer_batch.py +349 -0
- src/wavtts/eval/eval_infer_batch.sh +201 -0
- src/wavtts/eval/eval_infer_batch_example.sh +20 -0
- src/wavtts/eval/eval_librispeech_test_clean.py +119 -0
- src/wavtts/eval/eval_seedtts.sh +70 -0
- src/wavtts/eval/eval_seedtts_testset.py +120 -0
- src/wavtts/eval/eval_utmos.py +42 -0
- src/wavtts/eval/utils_eval.py +422 -0
- src/wavtts/infer/README.md +87 -0
- src/wavtts/infer/examples/basic.toml +23 -0
- src/wavtts/infer/examples/basic_ref_en.wav +3 -0
- src/wavtts/infer/examples/basic_ref_zh.wav +3 -0
- src/wavtts/infer/examples/vocab.txt +2556 -0
- src/wavtts/infer/infer.sh +43 -0
- src/wavtts/infer/infer_cli.py +383 -0
- src/wavtts/infer/utils_infer.py +598 -0
- src/wavtts/model/__init__.py +7 -0
- src/wavtts/model/backbones/dit.py +440 -0
- src/wavtts/model/backbones/mmdit.py +213 -0
- src/wavtts/model/cfm.py +461 -0
- src/wavtts/model/dataset.py +229 -0
- src/wavtts/model/modules.py +876 -0
- src/wavtts/model/trainer.py +487 -0
- src/wavtts/model/utils.py +221 -0
- src/wavtts/scripts/count_max_epoch.py +33 -0
- src/wavtts/scripts/count_max_epoch_precise.py +32 -0
- src/wavtts/scripts/count_params_gflops.py +36 -0
- src/wavtts/train/README.md +95 -0
- src/wavtts/train/datasets/prepare_csv_wavs.py +283 -0
- src/wavtts/train/datasets/prepare_emilia.py +260 -0
- src/wavtts/train/datasets/prepare_emilia_v2.py +94 -0
.dockerignore
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# VCS and local tooling
|
| 2 |
+
.git
|
| 3 |
+
.gitignore
|
| 4 |
+
.github
|
| 5 |
+
.claude
|
| 6 |
+
.codex
|
| 7 |
+
.vscode
|
| 8 |
+
.idea
|
| 9 |
+
.history
|
| 10 |
+
|
| 11 |
+
# Python caches and virtual environments
|
| 12 |
+
__pycache__/
|
| 13 |
+
*.py[cod]
|
| 14 |
+
.pytest_cache/
|
| 15 |
+
.mypy_cache/
|
| 16 |
+
.ruff_cache/
|
| 17 |
+
.ipynb_checkpoints/
|
| 18 |
+
.venv/
|
| 19 |
+
venv/
|
| 20 |
+
env/
|
| 21 |
+
|
| 22 |
+
# Build and packaging artifacts
|
| 23 |
+
build/
|
| 24 |
+
dist/
|
| 25 |
+
.eggs/
|
| 26 |
+
*.egg-info/
|
| 27 |
+
wheels/
|
| 28 |
+
|
| 29 |
+
# Local datasets and generated outputs
|
| 30 |
+
/data/
|
| 31 |
+
/exp/
|
| 32 |
+
/results/
|
| 33 |
+
/output/
|
| 34 |
+
/generated_output/
|
| 35 |
+
/log/
|
| 36 |
+
/logs/
|
| 37 |
+
/runs/
|
| 38 |
+
/wandb/
|
| 39 |
+
/tensorboard/
|
| 40 |
+
/assets/
|
| 41 |
+
|
| 42 |
+
# Model checkpoints and generated media
|
| 43 |
+
*.ckpt
|
| 44 |
+
*.pt
|
| 45 |
+
*.pth
|
| 46 |
+
*.onnx
|
| 47 |
+
*.bin
|
| 48 |
+
*.safetensors
|
| 49 |
+
*.data
|
| 50 |
+
*.index
|
| 51 |
+
*.wav
|
| 52 |
+
*.mp3
|
| 53 |
+
*.flac
|
| 54 |
+
|
| 55 |
+
# Keep packaged inference examples
|
| 56 |
+
!src/wavtts/infer/examples/*.wav
|
| 57 |
+
!src/wavtts/infer/examples/vocab.txt
|
| 58 |
+
|
| 59 |
+
# Archives and temporary files
|
| 60 |
+
*.zip
|
| 61 |
+
*.tar
|
| 62 |
+
*.tar.gz
|
| 63 |
+
*.tgz
|
| 64 |
+
*.rar
|
| 65 |
+
*.7z
|
| 66 |
+
*.log
|
| 67 |
+
*.tmp
|
| 68 |
+
*.swp
|
| 69 |
+
*.swo
|
| 70 |
+
.DS_Store
|
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ 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 |
+
docs/static/images/wavt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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Visual Studio Code files
|
| 2 |
+
.vs
|
| 3 |
+
/.vscode/*
|
| 4 |
+
!/.vscode/extensions.json
|
| 5 |
+
!/.vscode/settings_recommended.json
|
| 6 |
+
|
| 7 |
+
# Editor temporaries
|
| 8 |
+
*.swn
|
| 9 |
+
*.swo
|
| 10 |
+
*.swp
|
| 11 |
+
*.swm
|
| 12 |
+
*~
|
| 13 |
+
|
| 14 |
+
# Dolphin runtime info
|
| 15 |
+
reorder.dict
|
| 16 |
+
tmp/
|
| 17 |
+
total.code
|
| 18 |
+
total_bpe.dict
|
| 19 |
+
fbank_80dim_cmvn.kaldi
|
| 20 |
+
datum_pb2.py
|
| 21 |
+
lmdb_shard*/
|
| 22 |
+
char_bpe.dict
|
| 23 |
+
rank*cer*txt*
|
| 24 |
+
cer_*txt*
|
| 25 |
+
*.workspace.xml
|
| 26 |
+
|
| 27 |
+
# Dolphin runtime template dirs
|
| 28 |
+
demo/
|
| 29 |
+
voxceleb2_train/
|
| 30 |
+
stress_prediction/
|
| 31 |
+
nnlm_ez/
|
| 32 |
+
kws_rnnt_train/
|
| 33 |
+
kws_ce_train/
|
| 34 |
+
endpoints/
|
| 35 |
+
dfsmnln_online/
|
| 36 |
+
dfsmnln_online_pretrain/
|
| 37 |
+
exp/
|
| 38 |
+
runs/
|
| 39 |
+
stress_eval/
|
| 40 |
+
tensorboard/
|
| 41 |
+
falconclaw-data/
|
| 42 |
+
dist_init_file*
|
| 43 |
+
|
| 44 |
+
# Distribution / packaging
|
| 45 |
+
build/
|
| 46 |
+
eggs/
|
| 47 |
+
.eggs/
|
| 48 |
+
*.egg-info/
|
| 49 |
+
lib/
|
| 50 |
+
lib64/
|
| 51 |
+
wheels/
|
| 52 |
+
|
| 53 |
+
# Compiled Object files
|
| 54 |
+
*.so
|
| 55 |
+
*.o
|
| 56 |
+
|
| 57 |
+
# Compiled python
|
| 58 |
+
*.pyc
|
| 59 |
+
*.pyd
|
| 60 |
+
__pycache__
|
| 61 |
+
|
| 62 |
+
# macOS dir files
|
| 63 |
+
.DS_Store
|
| 64 |
+
|
| 65 |
+
# Idea settings
|
| 66 |
+
.idea
|
| 67 |
+
|
| 68 |
+
# Binary files
|
| 69 |
+
*.pth
|
| 70 |
+
*.pt
|
| 71 |
+
*.data
|
| 72 |
+
*.index
|
| 73 |
+
*.onnx
|
| 74 |
+
*.wav
|
| 75 |
+
*.jsonl
|
| 76 |
+
*.zip
|
| 77 |
+
*.bin
|
| 78 |
+
*.txt
|
| 79 |
+
!requirements.txt
|
| 80 |
+
!packages.txt
|
| 81 |
+
!doc/*.txt
|
| 82 |
+
!src/wavtts/infer/examples/*.wav
|
| 83 |
+
!src/wavtts/infer/examples/vocab.txt
|
| 84 |
+
|
| 85 |
+
# logs
|
| 86 |
+
/**/cruise_logs
|
| 87 |
+
/**/wandb
|
| 88 |
+
/**/lightning_logs
|
| 89 |
+
|
| 90 |
+
# ipynb ckpts
|
| 91 |
+
.ipynb_checkpoints
|
| 92 |
+
|
| 93 |
+
# ignore the weekly_test reports
|
| 94 |
+
scripts/weekly_test/report/
|
| 95 |
+
scripts/weekly_test/report_json/
|
| 96 |
+
scripts/weekly_test/Dolphin*.md
|
| 97 |
+
|
| 98 |
+
# module cache
|
| 99 |
+
.module_cache/
|
| 100 |
+
|
| 101 |
+
# data directory
|
| 102 |
+
assets/
|
| 103 |
+
# data/
|
| 104 |
+
video/
|
| 105 |
+
seedtts_testset/
|
| 106 |
+
test-clean/
|
| 107 |
+
|
| 108 |
+
# log directory
|
| 109 |
+
log/
|
| 110 |
+
logs/
|
| 111 |
+
cruise_logs/
|
| 112 |
+
lyrics2song_test/
|
| 113 |
+
|
| 114 |
+
.history/
|
| 115 |
+
|
| 116 |
+
span.log
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
durator
|
| 120 |
+
durator2
|
| 121 |
+
recipes/voicebox/testset
|
| 122 |
+
events.*
|
| 123 |
+
|
| 124 |
+
recipes/text2semantic/custom_scripts/run.sh
|
| 125 |
+
*.log
|
| 126 |
+
resource/
|
| 127 |
+
*.ckpt
|
| 128 |
+
*.csv
|
| 129 |
+
libs/
|
| 130 |
+
generated_output/
|
| 131 |
+
pypetrel.1.0.0.129/
|
| 132 |
+
bm_inference.pstats
|
| 133 |
+
recipes/bigmusic/tests/data/
|
| 134 |
+
recipes/leadsheet
|
| 135 |
+
.attach_*
|
| 136 |
+
*.ipynb
|
| 137 |
+
scripts_usr
|
| 138 |
+
.deploy_cache
|
| 139 |
+
output
|
| 140 |
+
# src/wavtts/train/runs_emilia/
|
| 141 |
+
.venv/
|
| 142 |
+
.codex
|
| 143 |
+
.claude
|
| 144 |
+
|
| 145 |
+
stats_*
|
| 146 |
+
|
| 147 |
+
Emilia_ZH_EN_pinyin/
|
| 148 |
+
LibriSpeech-test-clean/
|
| 149 |
+
data/LibriTTS_100_360_500_char/duration.json
|
| 150 |
+
data/LibriTTS_100_360_500_char/raw.arrow
|
| 151 |
+
|
| 152 |
+
# local dataset symlinks
|
| 153 |
+
/data/Emilia_ZH_EN_pinyin
|
| 154 |
+
/data/LibriSpeech
|
| 155 |
+
/data/LibriTTS_100_360_500_char
|
| 156 |
+
/data/seedtts_testset
|
| 157 |
+
|
| 158 |
+
# local dataset symlinks
|
| 159 |
+
/data/Emilia_ZH_EN_pinyin
|
| 160 |
+
/data/Emilia_ZH_EN_hdfs_pinyin
|
| 161 |
+
/data/LibriSpeech
|
| 162 |
+
/data/LibriTTS_100_360_500_char
|
| 163 |
+
/data/seedtts_testset
|
.pre-commit-config.yaml
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
repos:
|
| 2 |
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
| 3 |
+
# Ruff version.
|
| 4 |
+
rev: v0.11.2
|
| 5 |
+
hooks:
|
| 6 |
+
- id: ruff
|
| 7 |
+
name: ruff linter
|
| 8 |
+
args: [--fix]
|
| 9 |
+
- id: ruff-format
|
| 10 |
+
name: ruff formatter
|
| 11 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
| 12 |
+
rev: v5.0.0
|
| 13 |
+
hooks:
|
| 14 |
+
- id: check-yaml
|
Dockerfile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel
|
| 2 |
+
|
| 3 |
+
USER root
|
| 4 |
+
|
| 5 |
+
ARG DEBIAN_FRONTEND=noninteractive
|
| 6 |
+
|
| 7 |
+
LABEL github_repo="https://github.com/cwx-worst-one/WavTTS"
|
| 8 |
+
|
| 9 |
+
RUN set -x \
|
| 10 |
+
&& apt-get update \
|
| 11 |
+
&& apt-get -y install wget curl man git less openssl libssl-dev unzip unar build-essential aria2 tmux vim \
|
| 12 |
+
&& apt-get install -y openssh-server sox libsox-fmt-all libsox-fmt-mp3 libsndfile1-dev ffmpeg \
|
| 13 |
+
&& apt-get install -y librdmacm1 libibumad3 librdmacm-dev libibverbs1 libibverbs-dev ibverbs-utils ibverbs-providers \
|
| 14 |
+
&& rm -rf /var/lib/apt/lists/* \
|
| 15 |
+
&& apt-get clean
|
| 16 |
+
|
| 17 |
+
WORKDIR /workspace/WavTTS
|
| 18 |
+
|
| 19 |
+
COPY . /workspace/WavTTS
|
| 20 |
+
|
| 21 |
+
RUN pip install -e . --no-cache-dir
|
| 22 |
+
|
| 23 |
+
ENV SHELL=/bin/bash
|
| 24 |
+
|
| 25 |
+
VOLUME /root/.cache/huggingface/hub/
|
| 26 |
+
|
| 27 |
+
EXPOSE 7860
|
| 28 |
+
|
| 29 |
+
WORKDIR /workspace/WavTTS
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Wenxi Chen
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWAR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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: WavTTS
|
| 3 |
+
emoji: 🗣️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.39.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
pinned: true
|
| 10 |
+
short_description: Zero-shot TTS with raw waveform generation
|
| 11 |
+
preload_from_hub:
|
| 12 |
+
- worstchan/WavTTS
|
| 13 |
+
- openai/whisper-large-v3-turbo
|
| 14 |
---
|
| 15 |
|
| 16 |
+
<div align="center">
|
| 17 |
+
<h1>
|
| 18 |
+
WavTTS: Towards High-Quality Zero-Shot TTS via Direct Raw Waveform Modeling
|
| 19 |
+
</h1>
|
| 20 |
+
|
| 21 |
+
<p align="center">
|
| 22 |
+
<a href="#installation"><img src="https://img.shields.io/badge/Python-3.10-brightgreen.svg?logo=python&logoColor=white" alt="Python"></a>
|
| 23 |
+
<a href="https://arxiv.org/abs/2606.03455"><img src="https://img.shields.io/badge/Arxiv-2606.03455-b31b1b.svg?logo=arXiv" alt="arXiv"></a>
|
| 24 |
+
<a href="https://wavtts.github.io/"><img src="https://img.shields.io/badge/🌐%20Demo-Page-orange.svg" alt="Demo"></a>
|
| 25 |
+
<a href="https://huggingface.co/worstchan/WavTTS"><img src="https://img.shields.io/badge/🤗%20HuggingFace-Models-yellow.svg" alt="HuggingFace"></a>
|
| 26 |
+
</p>
|
| 27 |
+
|
| 28 |
+
<p align="center">
|
| 29 |
+
<i>End-to-end zero-shot TTS directly in the raw waveform space.</i>
|
| 30 |
+
</p>
|
| 31 |
+
|
| 32 |
+
</div>
|
| 33 |
+
|
| 34 |
+
## 📖 Introduction
|
| 35 |
+
|
| 36 |
+
WavTTS is an end-to-end zero-shot TTS framework that generates speech directly in the raw waveform space, without relying on intermediate acoustic representations such as mel-spectrograms, VAE latents, or codec tokens. Built on flow matching with DiT, WavTTS combines waveform patchification, multi-scale mel-spectrogram supervision, and optimized noise scheduling to achieve high-quality waveform generation. For more details, please refer to our paper: [WavTTS: Towards High-Quality Zero-Shot TTS via Direct Raw Waveform Modeling](https://arxiv.org/abs/2606.03455).
|
| 37 |
+
|
| 38 |
+
<div align="center">
|
| 39 |
+
<img src="docs/static/images/wavtts_pipeline.png" alt="WavTTS pipeline" width="85%">
|
| 40 |
+
</div>
|
| 41 |
+
|
| 42 |
+
**Note:** This repository is based on [F5-TTS](https://github.com/SWivid/F5-TTS). For general usage, troubleshooting, and basic guidance, please refer to the original F5-TTS repository. The sections below outline workflows specific to WavTTS.
|
| 43 |
+
|
| 44 |
+
## 🚀 News
|
| 45 |
+
|
| 46 |
+
- **[2026-06-03]**: We have released the WavTTS codebase along with the official 16 kHz checkpoint. Please note that this project is still under active development, and we will continue to roll out updates and improvements.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
## ⚙️ Installation
|
| 51 |
+
|
| 52 |
+
We recommend using Conda to manage the environment and dependencies.
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
# 1. Clone the repository
|
| 56 |
+
git clone https://github.com/cwx-worst-one/WavTTS
|
| 57 |
+
cd WavTTS
|
| 58 |
+
|
| 59 |
+
# 2. Create and activate a virtual environment
|
| 60 |
+
conda create -n wavtts python=3.10
|
| 61 |
+
conda activate wavtts
|
| 62 |
+
|
| 63 |
+
# 3. Install PyTorch (>=2.2.0) with CUDA support, e.g.,
|
| 64 |
+
pip install torch==2.6.0 torchaudio==2.6.0 --index-url https://download.pytorch.org/whl/cu124
|
| 65 |
+
|
| 66 |
+
# 4. Install WavTTS in editable mode
|
| 67 |
+
pip install -e .
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
## 📦 Model Checkpoints
|
| 71 |
+
|
| 72 |
+
The official WavTTS checkpoint is available on Hugging Face: [WavTTS 🤗](https://huggingface.co/worstchan/WavTTS). The default checkpoint supports 16 kHz zero-shot TTS inference and will be downloaded automatically the first time you run the inference script.
|
| 73 |
+
|
| 74 |
+
## 🚀 Inference
|
| 75 |
+
|
| 76 |
+
WavTTS supports both command-line inference and a minimal Hugging Face Space demo. For the Space demo, upload a short reference clip, provide the reference transcript, and enter the text to synthesize. Providing `ref_text` is recommended because leaving it blank triggers automatic ASR and can make the first run slower.
|
| 77 |
+
|
| 78 |
+
For more details about command-line and script-based inference, please refer to the [Inference Guide](src/wavtts/infer/README.md).
|
| 79 |
+
|
| 80 |
+
### CLI Inference
|
| 81 |
+
|
| 82 |
+
Generate speech using a short reference audio prompt. CLI arguments will automatically override values defined in the TOML config.
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
wavtts_infer-cli \
|
| 86 |
+
--model WavTTS \
|
| 87 |
+
--ref_audio "provide_prompt_wav_path_here.wav" \
|
| 88 |
+
--ref_text "The content, subtitle, or transcription of the reference audio." \
|
| 89 |
+
--gen_text "The text you want WavTTS to synthesize."
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Alternatively, manage your parameters cleanly using a TOML configuration file:
|
| 93 |
+
|
| 94 |
+
```bash
|
| 95 |
+
# Use the provided default config
|
| 96 |
+
wavtts_infer-cli -c src/wavtts/infer/examples/basic.toml
|
| 97 |
+
|
| 98 |
+
# Use a custom config (with an inline text override)
|
| 99 |
+
wavtts_infer-cli -c custom.toml --gen_text "Override text here."
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
### Script-based Inference
|
| 103 |
+
|
| 104 |
+
For customized pipelines, you can directly modify the paths and texts in `src/wavtts/infer/infer.sh` and execute:
|
| 105 |
+
|
| 106 |
+
```bash
|
| 107 |
+
bash src/wavtts/infer/infer.sh
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
## 🏋️ Training
|
| 112 |
+
|
| 113 |
+
Training WavTTS requires preprocessed dataset metadata. For a complete walkthrough of data preparation, training, and fine-tuning, please refer to the [Training Guide](src/wavtts/train/README.md).
|
| 114 |
+
|
| 115 |
+
### Data Preparation
|
| 116 |
+
|
| 117 |
+
We use [Emilia](https://huggingface.co/datasets/amphion/Emilia-Dataset) as the training dataset in our main experiments. After downloading Emilia, update the paths in the preparation script and run:
|
| 118 |
+
|
| 119 |
+
```bash
|
| 120 |
+
# Prepare training metadata for the Emilia dataset
|
| 121 |
+
python src/wavtts/train/datasets/prepare_emilia.py
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Preparation scripts for other datasets like LibriTTS are available under `src/wavtts/train/datasets/`. To use a custom dataset, please adapt the loading logic in `src/wavtts/model/dataset.py`.
|
| 125 |
+
|
| 126 |
+
### Launching Training
|
| 127 |
+
|
| 128 |
+
WavTTS can be trained directly with `accelerate`:
|
| 129 |
+
|
| 130 |
+
```bash
|
| 131 |
+
# Step 1: Configure Accelerate (e.g., multi-GPU DDP, mixed precision)
|
| 132 |
+
accelerate config
|
| 133 |
+
|
| 134 |
+
# Step 2: Launch training using a Hydra config
|
| 135 |
+
# YAML configuration files are located under the src/wavtts/configs/ directory.
|
| 136 |
+
accelerate launch src/wavtts/train/train.py --config-name WavTTS.yaml
|
| 137 |
+
|
| 138 |
+
# Example with inline overrides:
|
| 139 |
+
accelerate launch --mixed_precision=bf16 src/wavtts/train/train.py --config-name WavTTS.yaml ++datasets.batch_size_per_gpu=19200
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
For our main experiments, we provide a unified launcher script. Remember to edit the default environment variables at the top of the script before running:
|
| 143 |
+
|
| 144 |
+
```bash
|
| 145 |
+
bash src/wavtts/train/run_main_train.sh
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
## 📊 Evaluation
|
| 150 |
+
|
| 151 |
+
For evaluation setup, dataset preparation, and objective metric scripts, please refer to the [Evaluation Guide](src/wavtts/eval/README.md).
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
## 🙏 Acknowledgements
|
| 155 |
+
|
| 156 |
+
WavTTS is built upon the awesome [F5-TTS](https://github.com/SWivid/F5-TTS) codebase, with references to the implementations of [DAC](https://github.com/descriptinc/descript-audio-codec) and [JiT](https://github.com/LTH14/JiT). We sincerely thank the authors for their invaluable open-source contributions.
|
| 157 |
+
|
| 158 |
+
If you encounter general pipeline or environment issues, we recommend first checking the [F5-TTS issue tracker](https://github.com/SWivid/F5-TTS/issues), where many common questions may have already been discussed or resolved.
|
| 159 |
+
|
| 160 |
+
## 📝 Citation
|
| 161 |
+
|
| 162 |
+
If you find this work useful in your research, please consider citing our paper:
|
| 163 |
+
|
| 164 |
+
```bibtex
|
| 165 |
+
@misc{chen2026wavttshighqualityzeroshottts,
|
| 166 |
+
title={WavTTS: Towards High-Quality Zero-Shot TTS via Direct Raw Waveform Modeling},
|
| 167 |
+
author={Wenxi Chen and Dongya Jia and Yushen Chen and Zhikang Niu and Yuzhe Liang and Xiquan Li and Ruiqi Yan and Ziyang Ma and Guanrou Yang and Sanyuan Chen and Yue Wang and Zhuo Chen and Kai Yu and Xie Chen},
|
| 168 |
+
year={2026},
|
| 169 |
+
eprint={2606.03455},
|
| 170 |
+
archivePrefix={arXiv},
|
| 171 |
+
primaryClass={eess.AS},
|
| 172 |
+
url={https://arxiv.org/abs/2606.03455},
|
| 173 |
+
}
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
## 📜 License
|
| 177 |
+
|
| 178 |
+
The codebase of this repository is released under the MIT License. Due to the license restrictions of the Emilia training dataset, the released pre-trained model weights are licensed under CC BY-NC 4.0.
|
app.py
CHANGED
|
@@ -1,7 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
def greet(name):
|
| 4 |
-
return "Hello " + name + "!!"
|
| 5 |
|
| 6 |
-
|
| 7 |
-
demo.launch()
|
|
|
|
| 1 |
+
import tempfile
|
| 2 |
+
from importlib.resources import files
|
| 3 |
+
|
| 4 |
import gradio as gr
|
| 5 |
+
import soundfile as sf
|
| 6 |
+
import spaces
|
| 7 |
+
from cached_path import cached_path
|
| 8 |
+
from hydra.utils import get_class
|
| 9 |
+
from omegaconf import OmegaConf
|
| 10 |
+
|
| 11 |
+
from wavtts.infer.utils_infer import (
|
| 12 |
+
cfg_strength,
|
| 13 |
+
cross_fade_duration,
|
| 14 |
+
device,
|
| 15 |
+
fix_duration,
|
| 16 |
+
infer_process,
|
| 17 |
+
load_model,
|
| 18 |
+
nfe_step,
|
| 19 |
+
preprocess_ref_audio_text,
|
| 20 |
+
remove_silence_for_generated_wav,
|
| 21 |
+
shift,
|
| 22 |
+
speed,
|
| 23 |
+
sway_sampling_coef,
|
| 24 |
+
target_rms,
|
| 25 |
+
timestep_mapping,
|
| 26 |
+
timestep_power,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
DEFAULT_MODEL = "WavTTS"
|
| 30 |
+
DEFAULT_CKPT_FILE = "hf://worstchan/WavTTS/model_1200000.pt"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load_wavtts_model():
|
| 34 |
+
model_cfg = OmegaConf.load(str(files("wavtts").joinpath(f"configs/{DEFAULT_MODEL}.yaml")))
|
| 35 |
+
model_cls = get_class(f"wavtts.model.{model_cfg.model.backbone}")
|
| 36 |
+
ckpt_file = str(cached_path(DEFAULT_CKPT_FILE))
|
| 37 |
+
|
| 38 |
+
print(f"Using config {model_cfg.model.name} with checkpoint {ckpt_file}...")
|
| 39 |
+
return load_model(
|
| 40 |
+
model_cls,
|
| 41 |
+
model_cfg.model.arch,
|
| 42 |
+
ckpt_file,
|
| 43 |
+
device=device,
|
| 44 |
+
cfm_kwargs=getattr(model_cfg.model, "cfm", {}) or {},
|
| 45 |
+
waveform_kwargs=model_cfg.model.waveform,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
ema_model = load_wavtts_model()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@spaces.GPU
|
| 53 |
+
def run_tts(ref_audio, ref_text, gen_text, remove_silence=False):
|
| 54 |
+
if not ref_audio:
|
| 55 |
+
raise gr.Error("Please upload a reference audio file.")
|
| 56 |
+
if not gen_text or not gen_text.strip():
|
| 57 |
+
raise gr.Error("Please enter the text to synthesize.")
|
| 58 |
+
|
| 59 |
+
ref_audio, ref_text = preprocess_ref_audio_text(ref_audio, ref_text or "")
|
| 60 |
+
audio_segment, final_sample_rate, _ = infer_process(
|
| 61 |
+
ref_audio,
|
| 62 |
+
ref_text,
|
| 63 |
+
gen_text.strip(),
|
| 64 |
+
ema_model,
|
| 65 |
+
target_rms=target_rms,
|
| 66 |
+
cross_fade_duration=cross_fade_duration,
|
| 67 |
+
nfe_step=nfe_step,
|
| 68 |
+
cfg_strength=cfg_strength,
|
| 69 |
+
sway_sampling_coef=sway_sampling_coef,
|
| 70 |
+
timestep_mapping=timestep_mapping,
|
| 71 |
+
timestep_power=timestep_power,
|
| 72 |
+
shift=shift,
|
| 73 |
+
speed=speed,
|
| 74 |
+
fix_duration=fix_duration,
|
| 75 |
+
device=device,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
if audio_segment is None:
|
| 79 |
+
raise gr.Error("No audio was generated. Please try a shorter text or a different reference audio.")
|
| 80 |
+
|
| 81 |
+
output_wav_path = tempfile.mktemp(suffix=".wav")
|
| 82 |
+
sf.write(output_wav_path, audio_segment, final_sample_rate)
|
| 83 |
+
|
| 84 |
+
if remove_silence:
|
| 85 |
+
remove_silence_for_generated_wav(output_wav_path)
|
| 86 |
+
|
| 87 |
+
return output_wav_path
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
demo = gr.Interface(
|
| 91 |
+
fn=run_tts,
|
| 92 |
+
inputs=[
|
| 93 |
+
gr.Audio(label="Reference Audio", type="filepath"),
|
| 94 |
+
gr.Textbox(
|
| 95 |
+
label="Reference Text",
|
| 96 |
+
placeholder="Some call me nature, others call me mother nature.",
|
| 97 |
+
lines=2,
|
| 98 |
+
),
|
| 99 |
+
gr.Textbox(
|
| 100 |
+
label="Generation Text",
|
| 101 |
+
placeholder="The text you want WavTTS to synthesize.",
|
| 102 |
+
lines=4,
|
| 103 |
+
),
|
| 104 |
+
gr.Checkbox(label="Remove Silence from Output?", value=False),
|
| 105 |
+
],
|
| 106 |
+
outputs=gr.Audio(label="Generated Speech", type="filepath"),
|
| 107 |
+
title="🗣️ WavTTS Demo",
|
| 108 |
+
description=(
|
| 109 |
+
"Upload a short reference voice clip, provide its transcript, and generate speech in the same voice. "
|
| 110 |
+
"Reference text is recommended; leaving it blank triggers automatic ASR and may be slower on first use."
|
| 111 |
+
),
|
| 112 |
+
examples=[
|
| 113 |
+
[
|
| 114 |
+
str(files("wavtts").joinpath("infer/examples/basic_ref_en.wav")),
|
| 115 |
+
"Some call me nature, others call me mother nature.",
|
| 116 |
+
"WavTTS generates speech directly in raw waveform space.",
|
| 117 |
+
False,
|
| 118 |
+
],
|
| 119 |
+
],
|
| 120 |
+
)
|
| 121 |
|
|
|
|
|
|
|
| 122 |
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
demo.launch()
|
data/librispeech_pc_test_clean_cross_sentence.lst
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/ljspeech_inset_test_9s.lst
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
docs/static/images/wavtts_pipeline.png
ADDED
|
Git LFS Details
|
packages.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
pyproject.toml
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools >= 61.0", "setuptools-scm>=8.0"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "wavtts"
|
| 7 |
+
version = "1.1.10"
|
| 8 |
+
description = "WavTTS: Towards High-Quality Zero-Shot TTS via Direct Raw Waveform Modeling"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
license = {text = "MIT License"}
|
| 11 |
+
classifiers = [
|
| 12 |
+
"License :: OSI Approved :: MIT License",
|
| 13 |
+
"Operating System :: OS Independent",
|
| 14 |
+
"Programming Language :: Python :: 3",
|
| 15 |
+
]
|
| 16 |
+
dependencies = [
|
| 17 |
+
"accelerate>=0.33.0",
|
| 18 |
+
"bitsandbytes>0.37.0; platform_machine!='arm64' and platform_system!='Darwin'",
|
| 19 |
+
"cached_path",
|
| 20 |
+
"click",
|
| 21 |
+
"datasets",
|
| 22 |
+
"einops>=0.8.2",
|
| 23 |
+
"ema_pytorch>=0.5.2",
|
| 24 |
+
"hydra-core>=1.3.2",
|
| 25 |
+
"huggingface-hub>=0.26.0,<1.0",
|
| 26 |
+
"librosa",
|
| 27 |
+
"matplotlib",
|
| 28 |
+
"numpy<2.0.0",
|
| 29 |
+
"pydantic<=2.10.6",
|
| 30 |
+
"pydub",
|
| 31 |
+
"pypinyin",
|
| 32 |
+
"rjieba",
|
| 33 |
+
"safetensors",
|
| 34 |
+
"soundfile>=0.13.1",
|
| 35 |
+
"tomli",
|
| 36 |
+
"torch>=2.0.0",
|
| 37 |
+
"torchaudio>=2.0.0",
|
| 38 |
+
"torchcodec",
|
| 39 |
+
"torchdiffeq",
|
| 40 |
+
"tqdm",
|
| 41 |
+
"transformers",
|
| 42 |
+
"transformers-stream-generator",
|
| 43 |
+
"unidecode",
|
| 44 |
+
"wandb",
|
| 45 |
+
"x-transformers>=1.31.14",
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
[project.optional-dependencies]
|
| 49 |
+
space = [
|
| 50 |
+
"gradio",
|
| 51 |
+
"spaces",
|
| 52 |
+
]
|
| 53 |
+
dev = [
|
| 54 |
+
"pytest",
|
| 55 |
+
]
|
| 56 |
+
eval = [
|
| 57 |
+
"faster_whisper==0.10.1",
|
| 58 |
+
"funasr",
|
| 59 |
+
"jiwer==3.1.0",
|
| 60 |
+
"modelscope",
|
| 61 |
+
"zhconv",
|
| 62 |
+
"zhon",
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
[project.urls]
|
| 66 |
+
Homepage = "https://github.com/cwx-worst-one/WavTTS"
|
| 67 |
+
|
| 68 |
+
[project.scripts]
|
| 69 |
+
"wavtts_infer-cli" = "wavtts.infer.infer_cli:main"
|
requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
-e .[space]
|
ruff.toml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
line-length = 120
|
| 2 |
+
target-version = "py310"
|
| 3 |
+
|
| 4 |
+
[lint]
|
| 5 |
+
extend-select = ["I"]
|
| 6 |
+
# Only ignore variables with names starting with "_".
|
| 7 |
+
dummy-variable-rgx = "^_.*$"
|
| 8 |
+
|
| 9 |
+
[lint.isort]
|
| 10 |
+
force-single-line = false
|
| 11 |
+
lines-after-imports = 2
|
src/wavtts/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""WavTTS package."""
|
src/wavtts/configs/WavTTS.yaml
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
hydra:
|
| 2 |
+
run:
|
| 3 |
+
dir: ckpts/${model.name}_${model.tokenizer}_${datasets.name}/${now:%Y-%m-%d}/${now:%H-%M-%S}
|
| 4 |
+
|
| 5 |
+
datasets:
|
| 6 |
+
name: Emilia_ZH_EN # dataset name
|
| 7 |
+
batch_size_per_gpu: 19200 # 8 GPUs, 8 * 19200 = 153,600
|
| 8 |
+
batch_size_type: frame # frame | sample
|
| 9 |
+
max_samples: 64 # max sequences per batch if use frame-wise batch_size. we set 32 for small models, 64 for base models
|
| 10 |
+
num_workers: 16
|
| 11 |
+
|
| 12 |
+
optim:
|
| 13 |
+
epochs: 686
|
| 14 |
+
learning_rate: 7.5e-5
|
| 15 |
+
num_warmup_updates: 20000 # warmup updates
|
| 16 |
+
grad_accumulation_steps: 1 # note: updates = steps / grad_accumulation_steps
|
| 17 |
+
max_grad_norm: 1.0 # gradient clipping
|
| 18 |
+
bnb_optimizer: False # use bnb 8bit AdamW optimizer or not
|
| 19 |
+
|
| 20 |
+
model:
|
| 21 |
+
name: WavTTS_Large # model name
|
| 22 |
+
tokenizer: pinyin # tokenizer type (pinyin for bilingual, char for English only)
|
| 23 |
+
tokenizer_path: null # if 'custom' tokenizer, define the path want to use (should be vocab.txt)
|
| 24 |
+
backbone: DiT
|
| 25 |
+
cfm:
|
| 26 |
+
prediction: x_pred # flow | x_pred
|
| 27 |
+
loss_space: v # flow | v (v is typical for x_pred mode)
|
| 28 |
+
t_sampling: logistic_normal # uniform | logistic_normal
|
| 29 |
+
P_mean: -0.8
|
| 30 |
+
P_std: 0.8
|
| 31 |
+
t_eps: 0.02
|
| 32 |
+
latents_scale: 9.0
|
| 33 |
+
use_aux_mel_loss: True
|
| 34 |
+
aux_mel_loss_weight: 0.05
|
| 35 |
+
sample_rate: 16000
|
| 36 |
+
joint_cond_drop_prob: 0.1
|
| 37 |
+
arch:
|
| 38 |
+
dim: 1152
|
| 39 |
+
depth: 28
|
| 40 |
+
heads: 16
|
| 41 |
+
dropout: 0.0
|
| 42 |
+
ff_mult: 4
|
| 43 |
+
text_dim: 512
|
| 44 |
+
text_mask_padding: True
|
| 45 |
+
qk_norm: null # null | rms_norm
|
| 46 |
+
conv_layers: 4
|
| 47 |
+
pe_attn_head: null
|
| 48 |
+
attn_backend: torch # torch | flash_attn
|
| 49 |
+
attn_mask_enabled: False
|
| 50 |
+
checkpoint_activations: False # recompute activations and save memory for extra compute
|
| 51 |
+
use_audio_proj: True
|
| 52 |
+
audio_proj_dim: 1024
|
| 53 |
+
audio_proj_hidden: 768
|
| 54 |
+
waveform:
|
| 55 |
+
target_sample_rate: 16000
|
| 56 |
+
wav_frame_len: 160 # 160 @16k = 100Hz
|
| 57 |
+
|
| 58 |
+
ckpts:
|
| 59 |
+
logger: wandb # wandb | tensorboard | null
|
| 60 |
+
log_samples: True # infer random sample per save checkpoint. wip, normal to fail with extra long samples
|
| 61 |
+
save_per_updates: 50000 # save checkpoint per updates 50000
|
| 62 |
+
keep_last_n_checkpoints: -1 # -1 to keep all, 0 to not save intermediate, > 0 to keep last N checkpoints
|
| 63 |
+
last_per_updates: 5000 # save last checkpoint per updates 5000
|
| 64 |
+
exp_name: ${model.name}_${model.tokenizer}_${datasets.name}
|
| 65 |
+
save_dir: ckpts/${model.name}_${model.tokenizer}_${datasets.name}
|
src/wavtts/eval/README.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluation
|
| 2 |
+
|
| 3 |
+
## 1. Installation
|
| 4 |
+
|
| 5 |
+
First, install the optional evaluation dependencies from the WavTTS root directory:
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
pip install -e .[eval]
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## 2. Prepare Evaluation Models
|
| 12 |
+
|
| 13 |
+
Objective evaluation requires ASR models and a speaker similarity model.
|
| 14 |
+
|
| 15 |
+
1. Chinese ASR Model: [Paraformer-zh](https://huggingface.co/funasr/paraformer-zh)
|
| 16 |
+
2. English ASR Model: [Faster-Whisper](https://huggingface.co/Systran/faster-whisper-large-v3)
|
| 17 |
+
3. Speaker Similarity Model: WavLM (download `wavlm_large_finetune.pth` from [Google Drive](https://drive.google.com/file/d/1-aE1NfzpRCLxA4GUxX9ITI3F9LlbtEGP/view))
|
| 18 |
+
|
| 19 |
+
> **⚠️ Important Checkpoint Setup:**
|
| 20 |
+
> - **ASR Models:** By default, the ASR models will be downloaded automatically from Hugging Face. If you are running in an offline environment with the `--local` flag, download them manually and update `asr_ckpt_dir` in `eval_librispeech_test_clean.py` and `eval_seedtts_testset.py`.
|
| 21 |
+
> - **WavLM Model:** This model **MUST** be downloaded manually. Pass the downloaded `wavlm_large_finetune.pth` path with `--wavlm_ckpt_dir` for SIM metric scripts.
|
| 22 |
+
|
| 23 |
+
## 3. Prepare Test Datasets
|
| 24 |
+
|
| 25 |
+
We recommend using the following standard datasets for evaluation:
|
| 26 |
+
|
| 27 |
+
1. Seed-TTS Testset (ZH/EN): Download from [seed-tts-eval](https://github.com/BytedanceSpeech/seed-tts-eval).
|
| 28 |
+
2. LibriSpeech test-clean (EN): Download from [OpenSLR](http://www.openslr.org/12/).
|
| 29 |
+
|
| 30 |
+
Unzip the downloaded datasets and place them into your local `data/` directory.
|
| 31 |
+
|
| 32 |
+
## 4. Running Evaluations
|
| 33 |
+
|
| 34 |
+
You can either run the full generation and evaluation pipeline automatically, or compute metrics step by step on existing audio files.
|
| 35 |
+
|
| 36 |
+
### A. All-in-One Batch Inference & Evaluation
|
| 37 |
+
|
| 38 |
+
To run batch inference and evaluation, execute the following commands:
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
# Set up Accelerate if you have not configured it yet.
|
| 42 |
+
accelerate config
|
| 43 |
+
|
| 44 |
+
# Generate audio only, skipping metric calculation.
|
| 45 |
+
bash src/wavtts/eval/eval_infer_batch.sh --infer-only
|
| 46 |
+
|
| 47 |
+
# Generate audio and calculate objective metrics automatically.
|
| 48 |
+
bash src/wavtts/eval/eval_infer_batch.sh --full-eval --wavlm-ckpt-dir "<WAVLM_CKPT_PATH>"
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### B. Calculate Metrics Manually
|
| 52 |
+
|
| 53 |
+
If you have already generated `.wav` files via batch inference, you can evaluate them independently by pointing the scripts to your `<GEN_WAV_DIR>`.
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
# Evaluation [WER] for Seed-TTS test [ZH] set
|
| 57 |
+
python src/wavtts/eval/eval_seedtts_testset.py --eval_task wer --lang zh --gen_wav_dir "<GEN_WAV_DIR>" --gpu_nums 8
|
| 58 |
+
|
| 59 |
+
# Evaluation [SIM] for LibriSpeech-PC test-clean (cross-sentence)
|
| 60 |
+
python src/wavtts/eval/eval_librispeech_test_clean.py --eval_task sim --gen_wav_dir "<GEN_WAV_DIR>" --librispeech_test_clean_path "<TEST_CLEAN_PATH>" --wavlm_ckpt_dir "<WAVLM_CKPT_PATH>"
|
| 61 |
+
|
| 62 |
+
# Evaluation [UTMOS] for any directory containing audio files
|
| 63 |
+
python src/wavtts/eval/eval_utmos.py --audio_dir "<GEN_WAV_DIR>" --ext wav
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
> **💡 Tip:**
|
| 67 |
+
> Once evaluation is completed, detailed results will be saved as `_*_results.jsonl` files directly within your `<GEN_WAV_DIR>` directory.
|
src/wavtts/eval/ecapa_tdnn.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# just for speaker similarity evaluation, third-party code
|
| 2 |
+
|
| 3 |
+
# From https://github.com/microsoft/UniSpeech/blob/main/downstreams/speaker_verification/models/
|
| 4 |
+
# part of the code is borrowed from https://github.com/lawlict/ECAPA-TDNN
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
""" Res2Conv1d + BatchNorm1d + ReLU
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Res2Conv1dReluBn(nn.Module):
|
| 18 |
+
"""
|
| 19 |
+
in_channels == out_channels == channels
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True, scale=4):
|
| 23 |
+
super().__init__()
|
| 24 |
+
assert channels % scale == 0, "{} % {} != 0".format(channels, scale)
|
| 25 |
+
self.scale = scale
|
| 26 |
+
self.width = channels // scale
|
| 27 |
+
self.nums = scale if scale == 1 else scale - 1
|
| 28 |
+
|
| 29 |
+
self.convs = []
|
| 30 |
+
self.bns = []
|
| 31 |
+
for i in range(self.nums):
|
| 32 |
+
self.convs.append(nn.Conv1d(self.width, self.width, kernel_size, stride, padding, dilation, bias=bias))
|
| 33 |
+
self.bns.append(nn.BatchNorm1d(self.width))
|
| 34 |
+
self.convs = nn.ModuleList(self.convs)
|
| 35 |
+
self.bns = nn.ModuleList(self.bns)
|
| 36 |
+
|
| 37 |
+
def forward(self, x):
|
| 38 |
+
out = []
|
| 39 |
+
spx = torch.split(x, self.width, 1)
|
| 40 |
+
for i in range(self.nums):
|
| 41 |
+
if i == 0:
|
| 42 |
+
sp = spx[i]
|
| 43 |
+
else:
|
| 44 |
+
sp = sp + spx[i]
|
| 45 |
+
# Order: conv -> relu -> bn
|
| 46 |
+
sp = self.convs[i](sp)
|
| 47 |
+
sp = self.bns[i](F.relu(sp))
|
| 48 |
+
out.append(sp)
|
| 49 |
+
if self.scale != 1:
|
| 50 |
+
out.append(spx[self.nums])
|
| 51 |
+
out = torch.cat(out, dim=1)
|
| 52 |
+
|
| 53 |
+
return out
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
""" Conv1d + BatchNorm1d + ReLU
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Conv1dReluBn(nn.Module):
|
| 61 |
+
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True):
|
| 62 |
+
super().__init__()
|
| 63 |
+
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias)
|
| 64 |
+
self.bn = nn.BatchNorm1d(out_channels)
|
| 65 |
+
|
| 66 |
+
def forward(self, x):
|
| 67 |
+
return self.bn(F.relu(self.conv(x)))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
""" The SE connection of 1D case.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class SE_Connect(nn.Module):
|
| 75 |
+
def __init__(self, channels, se_bottleneck_dim=128):
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.linear1 = nn.Linear(channels, se_bottleneck_dim)
|
| 78 |
+
self.linear2 = nn.Linear(se_bottleneck_dim, channels)
|
| 79 |
+
|
| 80 |
+
def forward(self, x):
|
| 81 |
+
out = x.mean(dim=2)
|
| 82 |
+
out = F.relu(self.linear1(out))
|
| 83 |
+
out = torch.sigmoid(self.linear2(out))
|
| 84 |
+
out = x * out.unsqueeze(2)
|
| 85 |
+
|
| 86 |
+
return out
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
""" SE-Res2Block of the ECAPA-TDNN architecture.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
# def SE_Res2Block(channels, kernel_size, stride, padding, dilation, scale):
|
| 93 |
+
# return nn.Sequential(
|
| 94 |
+
# Conv1dReluBn(channels, 512, kernel_size=1, stride=1, padding=0),
|
| 95 |
+
# Res2Conv1dReluBn(512, kernel_size, stride, padding, dilation, scale=scale),
|
| 96 |
+
# Conv1dReluBn(512, channels, kernel_size=1, stride=1, padding=0),
|
| 97 |
+
# SE_Connect(channels)
|
| 98 |
+
# )
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class SE_Res2Block(nn.Module):
|
| 102 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, scale, se_bottleneck_dim):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.Conv1dReluBn1 = Conv1dReluBn(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
| 105 |
+
self.Res2Conv1dReluBn = Res2Conv1dReluBn(out_channels, kernel_size, stride, padding, dilation, scale=scale)
|
| 106 |
+
self.Conv1dReluBn2 = Conv1dReluBn(out_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
| 107 |
+
self.SE_Connect = SE_Connect(out_channels, se_bottleneck_dim)
|
| 108 |
+
|
| 109 |
+
self.shortcut = None
|
| 110 |
+
if in_channels != out_channels:
|
| 111 |
+
self.shortcut = nn.Conv1d(
|
| 112 |
+
in_channels=in_channels,
|
| 113 |
+
out_channels=out_channels,
|
| 114 |
+
kernel_size=1,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def forward(self, x):
|
| 118 |
+
residual = x
|
| 119 |
+
if self.shortcut:
|
| 120 |
+
residual = self.shortcut(x)
|
| 121 |
+
|
| 122 |
+
x = self.Conv1dReluBn1(x)
|
| 123 |
+
x = self.Res2Conv1dReluBn(x)
|
| 124 |
+
x = self.Conv1dReluBn2(x)
|
| 125 |
+
x = self.SE_Connect(x)
|
| 126 |
+
|
| 127 |
+
return x + residual
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
""" Attentive weighted mean and standard deviation pooling.
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class AttentiveStatsPool(nn.Module):
|
| 135 |
+
def __init__(self, in_dim, attention_channels=128, global_context_att=False):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.global_context_att = global_context_att
|
| 138 |
+
|
| 139 |
+
# Use Conv1d with stride == 1 rather than Linear, then we don't need to transpose inputs.
|
| 140 |
+
if global_context_att:
|
| 141 |
+
self.linear1 = nn.Conv1d(in_dim * 3, attention_channels, kernel_size=1) # equals W and b in the paper
|
| 142 |
+
else:
|
| 143 |
+
self.linear1 = nn.Conv1d(in_dim, attention_channels, kernel_size=1) # equals W and b in the paper
|
| 144 |
+
self.linear2 = nn.Conv1d(attention_channels, in_dim, kernel_size=1) # equals V and k in the paper
|
| 145 |
+
|
| 146 |
+
def forward(self, x):
|
| 147 |
+
if self.global_context_att:
|
| 148 |
+
context_mean = torch.mean(x, dim=-1, keepdim=True).expand_as(x)
|
| 149 |
+
context_std = torch.sqrt(torch.var(x, dim=-1, keepdim=True) + 1e-10).expand_as(x)
|
| 150 |
+
x_in = torch.cat((x, context_mean, context_std), dim=1)
|
| 151 |
+
else:
|
| 152 |
+
x_in = x
|
| 153 |
+
|
| 154 |
+
# DON'T use ReLU here! In experiments, I find ReLU hard to converge.
|
| 155 |
+
alpha = torch.tanh(self.linear1(x_in))
|
| 156 |
+
# alpha = F.relu(self.linear1(x_in))
|
| 157 |
+
alpha = torch.softmax(self.linear2(alpha), dim=2)
|
| 158 |
+
mean = torch.sum(alpha * x, dim=2)
|
| 159 |
+
residuals = torch.sum(alpha * (x**2), dim=2) - mean**2
|
| 160 |
+
std = torch.sqrt(residuals.clamp(min=1e-9))
|
| 161 |
+
return torch.cat([mean, std], dim=1)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class ECAPA_TDNN(nn.Module):
|
| 165 |
+
def __init__(
|
| 166 |
+
self,
|
| 167 |
+
feat_dim=80,
|
| 168 |
+
channels=512,
|
| 169 |
+
emb_dim=192,
|
| 170 |
+
global_context_att=False,
|
| 171 |
+
feat_type="wavlm_large",
|
| 172 |
+
sr=16000,
|
| 173 |
+
feature_selection="hidden_states",
|
| 174 |
+
update_extract=False,
|
| 175 |
+
config_path=None,
|
| 176 |
+
):
|
| 177 |
+
super().__init__()
|
| 178 |
+
|
| 179 |
+
self.feat_type = feat_type
|
| 180 |
+
self.feature_selection = feature_selection
|
| 181 |
+
self.update_extract = update_extract
|
| 182 |
+
self.sr = sr
|
| 183 |
+
|
| 184 |
+
torch.hub._validate_not_a_forked_repo = lambda a, b, c: True
|
| 185 |
+
try:
|
| 186 |
+
local_s3prl_path = os.path.expanduser("~/.cache/torch/hub/s3prl_s3prl_main")
|
| 187 |
+
self.feature_extract = torch.hub.load(local_s3prl_path, feat_type, source="local", config_path=config_path)
|
| 188 |
+
except: # noqa: E722
|
| 189 |
+
self.feature_extract = torch.hub.load("s3prl/s3prl", feat_type)
|
| 190 |
+
|
| 191 |
+
if len(self.feature_extract.model.encoder.layers) == 24 and hasattr(
|
| 192 |
+
self.feature_extract.model.encoder.layers[23].self_attn, "fp32_attention"
|
| 193 |
+
):
|
| 194 |
+
self.feature_extract.model.encoder.layers[23].self_attn.fp32_attention = False
|
| 195 |
+
if len(self.feature_extract.model.encoder.layers) == 24 and hasattr(
|
| 196 |
+
self.feature_extract.model.encoder.layers[11].self_attn, "fp32_attention"
|
| 197 |
+
):
|
| 198 |
+
self.feature_extract.model.encoder.layers[11].self_attn.fp32_attention = False
|
| 199 |
+
|
| 200 |
+
self.feat_num = self.get_feat_num()
|
| 201 |
+
self.feature_weight = nn.Parameter(torch.zeros(self.feat_num))
|
| 202 |
+
|
| 203 |
+
if feat_type != "fbank" and feat_type != "mfcc":
|
| 204 |
+
freeze_list = ["final_proj", "label_embs_concat", "mask_emb", "project_q", "quantizer"]
|
| 205 |
+
for name, param in self.feature_extract.named_parameters():
|
| 206 |
+
for freeze_val in freeze_list:
|
| 207 |
+
if freeze_val in name:
|
| 208 |
+
param.requires_grad = False
|
| 209 |
+
break
|
| 210 |
+
|
| 211 |
+
if not self.update_extract:
|
| 212 |
+
for param in self.feature_extract.parameters():
|
| 213 |
+
param.requires_grad = False
|
| 214 |
+
|
| 215 |
+
self.instance_norm = nn.InstanceNorm1d(feat_dim)
|
| 216 |
+
# self.channels = [channels] * 4 + [channels * 3]
|
| 217 |
+
self.channels = [channels] * 4 + [1536]
|
| 218 |
+
|
| 219 |
+
self.layer1 = Conv1dReluBn(feat_dim, self.channels[0], kernel_size=5, padding=2)
|
| 220 |
+
self.layer2 = SE_Res2Block(
|
| 221 |
+
self.channels[0],
|
| 222 |
+
self.channels[1],
|
| 223 |
+
kernel_size=3,
|
| 224 |
+
stride=1,
|
| 225 |
+
padding=2,
|
| 226 |
+
dilation=2,
|
| 227 |
+
scale=8,
|
| 228 |
+
se_bottleneck_dim=128,
|
| 229 |
+
)
|
| 230 |
+
self.layer3 = SE_Res2Block(
|
| 231 |
+
self.channels[1],
|
| 232 |
+
self.channels[2],
|
| 233 |
+
kernel_size=3,
|
| 234 |
+
stride=1,
|
| 235 |
+
padding=3,
|
| 236 |
+
dilation=3,
|
| 237 |
+
scale=8,
|
| 238 |
+
se_bottleneck_dim=128,
|
| 239 |
+
)
|
| 240 |
+
self.layer4 = SE_Res2Block(
|
| 241 |
+
self.channels[2],
|
| 242 |
+
self.channels[3],
|
| 243 |
+
kernel_size=3,
|
| 244 |
+
stride=1,
|
| 245 |
+
padding=4,
|
| 246 |
+
dilation=4,
|
| 247 |
+
scale=8,
|
| 248 |
+
se_bottleneck_dim=128,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# self.conv = nn.Conv1d(self.channels[-1], self.channels[-1], kernel_size=1)
|
| 252 |
+
cat_channels = channels * 3
|
| 253 |
+
self.conv = nn.Conv1d(cat_channels, self.channels[-1], kernel_size=1)
|
| 254 |
+
self.pooling = AttentiveStatsPool(
|
| 255 |
+
self.channels[-1], attention_channels=128, global_context_att=global_context_att
|
| 256 |
+
)
|
| 257 |
+
self.bn = nn.BatchNorm1d(self.channels[-1] * 2)
|
| 258 |
+
self.linear = nn.Linear(self.channels[-1] * 2, emb_dim)
|
| 259 |
+
|
| 260 |
+
def get_feat_num(self):
|
| 261 |
+
self.feature_extract.eval()
|
| 262 |
+
wav = [torch.randn(self.sr).to(next(self.feature_extract.parameters()).device)]
|
| 263 |
+
with torch.no_grad():
|
| 264 |
+
features = self.feature_extract(wav)
|
| 265 |
+
select_feature = features[self.feature_selection]
|
| 266 |
+
if isinstance(select_feature, (list, tuple)):
|
| 267 |
+
return len(select_feature)
|
| 268 |
+
else:
|
| 269 |
+
return 1
|
| 270 |
+
|
| 271 |
+
def get_feat(self, x):
|
| 272 |
+
if self.update_extract:
|
| 273 |
+
x = self.feature_extract([sample for sample in x])
|
| 274 |
+
else:
|
| 275 |
+
with torch.no_grad():
|
| 276 |
+
if self.feat_type == "fbank" or self.feat_type == "mfcc":
|
| 277 |
+
x = self.feature_extract(x) + 1e-6 # B x feat_dim x time_len
|
| 278 |
+
else:
|
| 279 |
+
x = self.feature_extract([sample for sample in x])
|
| 280 |
+
|
| 281 |
+
if self.feat_type == "fbank":
|
| 282 |
+
x = x.log()
|
| 283 |
+
|
| 284 |
+
if self.feat_type != "fbank" and self.feat_type != "mfcc":
|
| 285 |
+
x = x[self.feature_selection]
|
| 286 |
+
if isinstance(x, (list, tuple)):
|
| 287 |
+
x = torch.stack(x, dim=0)
|
| 288 |
+
else:
|
| 289 |
+
x = x.unsqueeze(0)
|
| 290 |
+
norm_weights = F.softmax(self.feature_weight, dim=-1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
|
| 291 |
+
x = (norm_weights * x).sum(dim=0)
|
| 292 |
+
x = torch.transpose(x, 1, 2) + 1e-6
|
| 293 |
+
|
| 294 |
+
x = self.instance_norm(x)
|
| 295 |
+
return x
|
| 296 |
+
|
| 297 |
+
def forward(self, x):
|
| 298 |
+
x = self.get_feat(x)
|
| 299 |
+
|
| 300 |
+
out1 = self.layer1(x)
|
| 301 |
+
out2 = self.layer2(out1)
|
| 302 |
+
out3 = self.layer3(out2)
|
| 303 |
+
out4 = self.layer4(out3)
|
| 304 |
+
|
| 305 |
+
out = torch.cat([out2, out3, out4], dim=1)
|
| 306 |
+
out = F.relu(self.conv(out))
|
| 307 |
+
out = self.bn(self.pooling(out))
|
| 308 |
+
out = self.linear(out)
|
| 309 |
+
|
| 310 |
+
return out
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def ECAPA_TDNN_SMALL(
|
| 314 |
+
feat_dim,
|
| 315 |
+
emb_dim=256,
|
| 316 |
+
feat_type="wavlm_large",
|
| 317 |
+
sr=16000,
|
| 318 |
+
feature_selection="hidden_states",
|
| 319 |
+
update_extract=False,
|
| 320 |
+
config_path=None,
|
| 321 |
+
):
|
| 322 |
+
return ECAPA_TDNN(
|
| 323 |
+
feat_dim=feat_dim,
|
| 324 |
+
channels=512,
|
| 325 |
+
emb_dim=emb_dim,
|
| 326 |
+
feat_type=feat_type,
|
| 327 |
+
sr=sr,
|
| 328 |
+
feature_selection=feature_selection,
|
| 329 |
+
update_extract=update_extract,
|
| 330 |
+
config_path=config_path,
|
| 331 |
+
)
|
src/wavtts/eval/eval_infer_batch.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import time
|
| 9 |
+
from importlib.resources import files
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torchaudio
|
| 13 |
+
from accelerate import Accelerator
|
| 14 |
+
from cached_path import cached_path
|
| 15 |
+
from hydra.utils import get_class
|
| 16 |
+
from omegaconf import OmegaConf
|
| 17 |
+
from tqdm import tqdm
|
| 18 |
+
|
| 19 |
+
from wavtts.eval.utils_eval import (
|
| 20 |
+
get_inference_prompt,
|
| 21 |
+
get_librispeech_test_clean_metainfo,
|
| 22 |
+
get_seedtts_testset_metainfo,
|
| 23 |
+
)
|
| 24 |
+
from wavtts.infer.utils_infer import load_checkpoint
|
| 25 |
+
from wavtts.model import CFM
|
| 26 |
+
from wavtts.model.utils import get_tokenizer
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
accelerator = Accelerator()
|
| 30 |
+
device = f"cuda:{accelerator.process_index}"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
target_rms = 0.1 # 0.1, 0.12
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
rel_path = str(files("wavtts").joinpath("../../"))
|
| 37 |
+
DEFAULT_CKPT_FILE = "hf://worstchan/WavTTS/model_1200000.pt"
|
| 38 |
+
DEFAULT_VOCAB_FILE = str(files("wavtts").joinpath("infer/examples/vocab.txt"))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
parser = argparse.ArgumentParser(description="batch inference")
|
| 43 |
+
|
| 44 |
+
parser.add_argument("-s", "--seed", default=None, type=int)
|
| 45 |
+
parser.add_argument("-n", "--expname", required=True)
|
| 46 |
+
parser.add_argument("-c", "--ckptstep", default=1250000, type=int)
|
| 47 |
+
|
| 48 |
+
parser.add_argument("-nfe", "--nfe_step", default=50, type=int)
|
| 49 |
+
parser.add_argument("-ss", "--swaysampling", default=-1, type=float)
|
| 50 |
+
parser.add_argument("--timestep_mapping", default="power", choices=["uniform", "sway_sampling", "power"])
|
| 51 |
+
parser.add_argument("--timestep_power", default=2.0, type=float)
|
| 52 |
+
parser.add_argument("--shift", default=3.0, type=float)
|
| 53 |
+
|
| 54 |
+
parser.add_argument("-t", "--testset", required=True)
|
| 55 |
+
parser.add_argument(
|
| 56 |
+
"-p",
|
| 57 |
+
"--librispeech_test_clean_path",
|
| 58 |
+
default=f"{rel_path}/data/LibriSpeech/test-clean",
|
| 59 |
+
type=str,
|
| 60 |
+
)
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"--ljspeech_inset_meta",
|
| 63 |
+
default=f"{rel_path}/data/ljspeech_inset_test_9s.lst",
|
| 64 |
+
type=str,
|
| 65 |
+
help="Metadata list for ljspeech_inset_test_9s. Format: ref_utt ref_dur ref_txt gen_utt gen_dur gen_txt.",
|
| 66 |
+
)
|
| 67 |
+
parser.add_argument(
|
| 68 |
+
"--ljspeech_wav_dir",
|
| 69 |
+
default=f"{rel_path}/data/ljspeech/LJSpeech-1.1/wavs",
|
| 70 |
+
type=str,
|
| 71 |
+
help="Directory containing original LJSpeech wavs. Only used when truth duration is enabled.",
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
parser.add_argument("--ckpt_path", default=DEFAULT_CKPT_FILE, type=str)
|
| 75 |
+
parser.add_argument(
|
| 76 |
+
"--vocab_file",
|
| 77 |
+
default=DEFAULT_VOCAB_FILE,
|
| 78 |
+
type=str,
|
| 79 |
+
help="Path to vocab.txt used to build the model tokenizer.",
|
| 80 |
+
)
|
| 81 |
+
parser.add_argument(
|
| 82 |
+
"--output_dir",
|
| 83 |
+
default=None,
|
| 84 |
+
type=str,
|
| 85 |
+
help="Optional directory to save generated wavs. Defaults to the standard results/... directory.",
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--fixed_prompt_wav",
|
| 89 |
+
default=None,
|
| 90 |
+
type=str,
|
| 91 |
+
help="Use one fixed prompt wav for all samples instead of each test sample's prompt wav.",
|
| 92 |
+
)
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--fixed_prompt_text",
|
| 95 |
+
default=None,
|
| 96 |
+
type=str,
|
| 97 |
+
help="Text corresponding to --fixed_prompt_wav. Required when --fixed_prompt_wav is set.",
|
| 98 |
+
)
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--result_expname",
|
| 101 |
+
default=None,
|
| 102 |
+
type=str,
|
| 103 |
+
help="Optional result directory name override. Defaults to --expname.",
|
| 104 |
+
)
|
| 105 |
+
parser.add_argument("--cfg_strength", default=3.0, type=float)
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--load_dtype",
|
| 108 |
+
default="fp32",
|
| 109 |
+
choices=["bf16", "fp16", "fp32"],
|
| 110 |
+
help="Model checkpoint load precision. Default fp32 for more stable weight loading.",
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--infer_dtype",
|
| 114 |
+
default="bf16",
|
| 115 |
+
choices=["bf16", "fp16", "fp32"],
|
| 116 |
+
help="Inference precision: bf16/fp16 for autocast mixed precision, fp32 to disable autocast.",
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
args = parser.parse_args()
|
| 120 |
+
|
| 121 |
+
seed = args.seed
|
| 122 |
+
exp_name = args.expname
|
| 123 |
+
result_exp_name = args.result_expname or exp_name
|
| 124 |
+
ckpt_step = args.ckptstep
|
| 125 |
+
|
| 126 |
+
nfe_step = args.nfe_step
|
| 127 |
+
sway_sampling_coef = args.swaysampling
|
| 128 |
+
timestep_mapping = args.timestep_mapping
|
| 129 |
+
timestep_power = args.timestep_power
|
| 130 |
+
shift = args.shift
|
| 131 |
+
|
| 132 |
+
if timestep_mapping == "power" and timestep_power is None:
|
| 133 |
+
raise ValueError("--timestep_power must be provided when --timestep_mapping power is used")
|
| 134 |
+
|
| 135 |
+
testset = args.testset
|
| 136 |
+
load_dtype_name = args.load_dtype
|
| 137 |
+
infer_dtype_name = args.infer_dtype
|
| 138 |
+
|
| 139 |
+
infer_batch_size = 1 # max frames. 1 for ddp single inference (recommended)
|
| 140 |
+
cfg_strength = args.cfg_strength
|
| 141 |
+
speed = 1.0
|
| 142 |
+
use_truth_duration = False
|
| 143 |
+
no_ref_audio = False
|
| 144 |
+
|
| 145 |
+
amp_dtype_map = {
|
| 146 |
+
"bf16": torch.bfloat16,
|
| 147 |
+
"fp16": torch.float16,
|
| 148 |
+
}
|
| 149 |
+
autocast_dtype = amp_dtype_map.get(infer_dtype_name)
|
| 150 |
+
|
| 151 |
+
model_cfg = OmegaConf.load(str(files("wavtts").joinpath(f"configs/{exp_name}.yaml")))
|
| 152 |
+
model_cls = get_class(f"wavtts.model.{model_cfg.model.backbone}")
|
| 153 |
+
model_arc = model_cfg.model.arch
|
| 154 |
+
|
| 155 |
+
dataset_name = model_cfg.datasets.name
|
| 156 |
+
tokenizer = model_cfg.model.tokenizer
|
| 157 |
+
|
| 158 |
+
target_sample_rate = model_cfg.model.waveform.target_sample_rate
|
| 159 |
+
wav_frame_len = model_cfg.model.waveform.wav_frame_len
|
| 160 |
+
|
| 161 |
+
if testset == "ls_pc_test_clean":
|
| 162 |
+
metalst = rel_path + "/data/librispeech_pc_test_clean_cross_sentence.lst"
|
| 163 |
+
librispeech_test_clean_path = args.librispeech_test_clean_path
|
| 164 |
+
metainfo = get_librispeech_test_clean_metainfo(metalst, librispeech_test_clean_path)
|
| 165 |
+
|
| 166 |
+
elif testset == "seedtts_test_zh":
|
| 167 |
+
metalst = rel_path + "/data/seedtts_testset/zh/meta.lst"
|
| 168 |
+
metainfo = get_seedtts_testset_metainfo(metalst)
|
| 169 |
+
|
| 170 |
+
elif testset == "seedtts_test_zh_hard":
|
| 171 |
+
metalst = rel_path + "/data/seedtts_testset/zh/hardcase.lst"
|
| 172 |
+
metainfo = get_seedtts_testset_metainfo(metalst)
|
| 173 |
+
|
| 174 |
+
elif testset == "seedtts_test_en":
|
| 175 |
+
metalst = rel_path + "/data/seedtts_testset/en/meta.lst"
|
| 176 |
+
metainfo = get_seedtts_testset_metainfo(metalst)
|
| 177 |
+
|
| 178 |
+
elif testset == "ljspeech_inset_test_9s":
|
| 179 |
+
metalst = args.ljspeech_inset_meta
|
| 180 |
+
if not os.path.exists(metalst):
|
| 181 |
+
raise FileNotFoundError(f"LJSpeech inset metadata not found: {metalst}")
|
| 182 |
+
|
| 183 |
+
metainfo = []
|
| 184 |
+
with open(metalst, "r", encoding="utf-8") as f:
|
| 185 |
+
for line in f:
|
| 186 |
+
parts = line.rstrip("\n").split("\t")
|
| 187 |
+
if len(parts) < 6:
|
| 188 |
+
continue
|
| 189 |
+
ref_utt, _ref_dur, ref_txt, gen_utt, _gen_dur, gen_txt = parts[:6]
|
| 190 |
+
ref_wav = os.path.join(args.ljspeech_wav_dir, ref_utt + ".wav")
|
| 191 |
+
gen_wav = os.path.join(args.ljspeech_wav_dir, gen_utt + ".wav")
|
| 192 |
+
metainfo.append((gen_utt, ref_txt, ref_wav, " " + gen_txt, gen_wav))
|
| 193 |
+
|
| 194 |
+
else:
|
| 195 |
+
raise ValueError(f"Unknown testset: {testset}")
|
| 196 |
+
|
| 197 |
+
if (args.fixed_prompt_wav is None) != (args.fixed_prompt_text is None):
|
| 198 |
+
raise ValueError("--fixed_prompt_wav and --fixed_prompt_text must be set together")
|
| 199 |
+
|
| 200 |
+
if args.fixed_prompt_wav is not None:
|
| 201 |
+
if not os.path.exists(args.fixed_prompt_wav):
|
| 202 |
+
raise FileNotFoundError(f"Fixed prompt wav not found: {args.fixed_prompt_wav}")
|
| 203 |
+
fixed_prompt_wav = args.fixed_prompt_wav
|
| 204 |
+
fixed_prompt_text = args.fixed_prompt_text
|
| 205 |
+
metainfo = [
|
| 206 |
+
(utt, fixed_prompt_text, fixed_prompt_wav, gt_text, gt_wav)
|
| 207 |
+
for utt, _prompt_text, _prompt_wav, gt_text, gt_wav in metainfo
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# path to save genereted wavs
|
| 212 |
+
if args.output_dir is not None:
|
| 213 |
+
output_dir = args.output_dir
|
| 214 |
+
else:
|
| 215 |
+
output_dir = (
|
| 216 |
+
f"{rel_path}/"
|
| 217 |
+
f"results/{result_exp_name}/{ckpt_step}/{testset}/"
|
| 218 |
+
f"seed{seed}_nfe{nfe_step}_wav"
|
| 219 |
+
f"{'_uniform' if timestep_mapping == 'uniform' else ''}"
|
| 220 |
+
f"{f'_ss{sway_sampling_coef}' if timestep_mapping == 'sway_sampling' and sway_sampling_coef else ''}"
|
| 221 |
+
f"{f'_power{timestep_power}' if timestep_mapping == 'power' else ''}"
|
| 222 |
+
f"{f'_shift{shift}' if shift != 1.0 else ''}"
|
| 223 |
+
f"_cfg{cfg_strength}"
|
| 224 |
+
f"{'_gt-dur' if use_truth_duration else ''}"
|
| 225 |
+
f"{'_no-ref-audio' if no_ref_audio else ''}"
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# -------------------------------------------------#
|
| 229 |
+
wav_frame_len = int(model_cfg.model.waveform.get("wav_frame_len", 160))
|
| 230 |
+
|
| 231 |
+
prompts_all = get_inference_prompt(
|
| 232 |
+
metainfo,
|
| 233 |
+
speed=speed,
|
| 234 |
+
tokenizer=tokenizer,
|
| 235 |
+
target_sample_rate=target_sample_rate,
|
| 236 |
+
target_rms=target_rms,
|
| 237 |
+
use_truth_duration=use_truth_duration,
|
| 238 |
+
infer_batch_size=infer_batch_size,
|
| 239 |
+
wav_frame_len=wav_frame_len,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# Tokenizer
|
| 243 |
+
if args.vocab_file:
|
| 244 |
+
vocab_char_map, vocab_size = get_tokenizer(args.vocab_file, "custom")
|
| 245 |
+
else:
|
| 246 |
+
vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
|
| 247 |
+
|
| 248 |
+
# waveform geometry
|
| 249 |
+
waveform_kwargs = model_cfg.model.waveform
|
| 250 |
+
if waveform_kwargs is None:
|
| 251 |
+
waveform_kwargs = dict(
|
| 252 |
+
wav_frame_len=wav_frame_len,
|
| 253 |
+
target_sample_rate=target_sample_rate,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
# CFM kwargs
|
| 257 |
+
cfm_kwargs = getattr(model_cfg.model, "cfm", {}) or {}
|
| 258 |
+
|
| 259 |
+
# Model
|
| 260 |
+
model = CFM(
|
| 261 |
+
transformer=model_cls(**model_arc, text_num_embeds=vocab_size, wav_frame_len=wav_frame_len),
|
| 262 |
+
waveform_kwargs=waveform_kwargs,
|
| 263 |
+
odeint_kwargs=dict(
|
| 264 |
+
method="euler",
|
| 265 |
+
),
|
| 266 |
+
vocab_char_map=vocab_char_map,
|
| 267 |
+
**cfm_kwargs,
|
| 268 |
+
).to(device)
|
| 269 |
+
|
| 270 |
+
# ckpt_prefix = rel_path + f"/ckpts/{exp_name}/model_{ckpt_step}"
|
| 271 |
+
# if os.path.exists(ckpt_prefix + ".pt"):
|
| 272 |
+
# ckpt_path = ckpt_prefix + ".pt"
|
| 273 |
+
# elif os.path.exists(ckpt_prefix + ".safetensors"):
|
| 274 |
+
# ckpt_path = ckpt_prefix + ".safetensors"
|
| 275 |
+
# else:
|
| 276 |
+
# print("Loading from self-organized training checkpoints rather than released pretrained.")
|
| 277 |
+
# ckpt_prefix = rel_path + f"/{model_cfg.ckpts.save_dir}/model_{ckpt_step}"
|
| 278 |
+
# if os.path.exists(ckpt_prefix + ".pt"):
|
| 279 |
+
# ckpt_path = ckpt_prefix + ".pt"
|
| 280 |
+
# elif os.path.exists(ckpt_prefix + ".safetensors"):
|
| 281 |
+
# ckpt_path = ckpt_prefix + ".safetensors"
|
| 282 |
+
# else:
|
| 283 |
+
# raise ValueError("The checkpoint does not exist or cannot be found in given location.")
|
| 284 |
+
ckpt_path = args.ckpt_path or DEFAULT_CKPT_FILE
|
| 285 |
+
if ckpt_path.startswith(("hf://", "http://", "https://")):
|
| 286 |
+
ckpt_path = str(cached_path(ckpt_path))
|
| 287 |
+
|
| 288 |
+
load_dtype = amp_dtype_map.get(load_dtype_name, torch.float32)
|
| 289 |
+
model = load_checkpoint(model, ckpt_path, device, dtype=load_dtype, use_ema=True)
|
| 290 |
+
|
| 291 |
+
if not os.path.exists(output_dir) and accelerator.is_main_process:
|
| 292 |
+
os.makedirs(output_dir)
|
| 293 |
+
|
| 294 |
+
# start batch inference
|
| 295 |
+
accelerator.wait_for_everyone()
|
| 296 |
+
start = time.time()
|
| 297 |
+
|
| 298 |
+
with accelerator.split_between_processes(prompts_all) as prompts:
|
| 299 |
+
for prompt in tqdm(prompts, disable=not accelerator.is_local_main_process):
|
| 300 |
+
utts, ref_rms_list, ref_wavs, ref_wav_lens, total_wav_lens, final_text_list = prompt
|
| 301 |
+
ref_wavs = ref_wavs.to(device)
|
| 302 |
+
ref_wav_lens = torch.tensor(ref_wav_lens, dtype=torch.long).to(device)
|
| 303 |
+
total_wav_lens = torch.tensor(total_wav_lens, dtype=torch.long).to(device)
|
| 304 |
+
|
| 305 |
+
# Inference
|
| 306 |
+
with torch.inference_mode():
|
| 307 |
+
with torch.autocast("cuda", dtype=autocast_dtype, enabled=autocast_dtype is not None):
|
| 308 |
+
generated, _ = model.sample(
|
| 309 |
+
cond=ref_wavs,
|
| 310 |
+
text=final_text_list,
|
| 311 |
+
duration=total_wav_lens,
|
| 312 |
+
steps=nfe_step,
|
| 313 |
+
cfg_strength=cfg_strength,
|
| 314 |
+
sway_sampling_coef=sway_sampling_coef,
|
| 315 |
+
timestep_mapping=timestep_mapping,
|
| 316 |
+
timestep_power=timestep_power,
|
| 317 |
+
shift=shift,
|
| 318 |
+
use_epss=timestep_mapping == "sway_sampling",
|
| 319 |
+
no_ref_audio=no_ref_audio,
|
| 320 |
+
seed=seed,
|
| 321 |
+
)
|
| 322 |
+
# Final result
|
| 323 |
+
for i, gen in enumerate(generated):
|
| 324 |
+
start_idx = ref_wav_lens[i].item()
|
| 325 |
+
end_idx = total_wav_lens[i].item()
|
| 326 |
+
generated_wave = gen[start_idx:end_idx].cpu()
|
| 327 |
+
|
| 328 |
+
if ref_rms_list[i] < target_rms:
|
| 329 |
+
generated_wave = generated_wave * ref_rms_list[i] / target_rms
|
| 330 |
+
|
| 331 |
+
wave_to_save = generated_wave.to(torch.float32).cpu()
|
| 332 |
+
|
| 333 |
+
if wave_to_save.ndim == 1:
|
| 334 |
+
wave_to_save = wave_to_save.unsqueeze(0)
|
| 335 |
+
elif wave_to_save.ndim > 2:
|
| 336 |
+
wave_to_save = wave_to_save.squeeze()
|
| 337 |
+
if wave_to_save.ndim == 1:
|
| 338 |
+
wave_to_save = wave_to_save.unsqueeze(0)
|
| 339 |
+
|
| 340 |
+
torchaudio.save(f"{output_dir}/{utts[i]}.wav", wave_to_save, target_sample_rate)
|
| 341 |
+
|
| 342 |
+
accelerator.wait_for_everyone()
|
| 343 |
+
if accelerator.is_main_process:
|
| 344 |
+
timediff = time.time() - start
|
| 345 |
+
print(f"Done batch inference in {timediff / 60:.2f} minutes.")
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
if __name__ == "__main__":
|
| 349 |
+
main()
|
src/wavtts/eval/eval_infer_batch.sh
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
export PYTHONWARNINGS="ignore::UserWarning,ignore::FutureWarning"
|
| 4 |
+
export MASTER_PORT=53721
|
| 5 |
+
export CUDA_VISIBLE_DEVICES="0,1,2,3,4,5,6,7"
|
| 6 |
+
|
| 7 |
+
# Configuration parameters
|
| 8 |
+
MODEL_NAME=WavTTS
|
| 9 |
+
RESULT_MODEL_NAME="${MODEL_NAME}"
|
| 10 |
+
SEEDS=(0)
|
| 11 |
+
CKPTSTEPS=(1200000)
|
| 12 |
+
TASKS=("seedtts_test_en" "seedtts_test_zh")
|
| 13 |
+
GPUS="[0,1,2,3,4,5,6,7]"
|
| 14 |
+
TRAIN_GPU_TAG="8gpus"
|
| 15 |
+
CKPT_FILE="hf://worstchan/WavTTS/model_1200000.pt"
|
| 16 |
+
WAVLM_CKPT_DIR=""
|
| 17 |
+
LS_TEST_CLEAN_PATH="data/LibriSpeech/test-clean"
|
| 18 |
+
|
| 19 |
+
cfg_strength=3.0
|
| 20 |
+
nfe_step=50
|
| 21 |
+
timestep_mapping="power" # power, sway_sampling, uniform
|
| 22 |
+
swaysampling=-1
|
| 23 |
+
timestep_power=2.0
|
| 24 |
+
shift="3.0" # 1.0, 3.0
|
| 25 |
+
|
| 26 |
+
# Parse arguments
|
| 27 |
+
INFER_ONLY=true # true, false
|
| 28 |
+
while [[ $# -gt 0 ]]; do
|
| 29 |
+
case $1 in
|
| 30 |
+
--full-eval)
|
| 31 |
+
INFER_ONLY=false
|
| 32 |
+
shift
|
| 33 |
+
;;
|
| 34 |
+
--infer-only)
|
| 35 |
+
INFER_ONLY=true
|
| 36 |
+
shift
|
| 37 |
+
;;
|
| 38 |
+
--result-model-name)
|
| 39 |
+
RESULT_MODEL_NAME="$2"
|
| 40 |
+
shift 2
|
| 41 |
+
;;
|
| 42 |
+
--timestep-mapping)
|
| 43 |
+
timestep_mapping="$2"
|
| 44 |
+
shift 2
|
| 45 |
+
;;
|
| 46 |
+
--timestep-power)
|
| 47 |
+
timestep_power="$2"
|
| 48 |
+
shift 2
|
| 49 |
+
;;
|
| 50 |
+
--shift)
|
| 51 |
+
shift="$2"
|
| 52 |
+
shift 2
|
| 53 |
+
;;
|
| 54 |
+
--train-gpu-tag)
|
| 55 |
+
TRAIN_GPU_TAG="$2"
|
| 56 |
+
shift 2
|
| 57 |
+
;;
|
| 58 |
+
--wavlm-ckpt-dir)
|
| 59 |
+
WAVLM_CKPT_DIR="$2"
|
| 60 |
+
shift 2
|
| 61 |
+
;;
|
| 62 |
+
--librispeech-test-clean-path)
|
| 63 |
+
LS_TEST_CLEAN_PATH="$2"
|
| 64 |
+
shift 2
|
| 65 |
+
;;
|
| 66 |
+
*)
|
| 67 |
+
echo "======== Unknown parameter: $1"
|
| 68 |
+
exit 1
|
| 69 |
+
;;
|
| 70 |
+
esac
|
| 71 |
+
done
|
| 72 |
+
|
| 73 |
+
echo "======== Starting WavTTS batch evaluation task..."
|
| 74 |
+
echo "======== Result model name: ${RESULT_MODEL_NAME}"
|
| 75 |
+
echo "======== Timestep mapping: ${timestep_mapping}"
|
| 76 |
+
echo "======== Train GPU tag: ${TRAIN_GPU_TAG}"
|
| 77 |
+
if [ -n "${WAVLM_CKPT_DIR}" ]; then
|
| 78 |
+
echo "======== WavLM checkpoint: ${WAVLM_CKPT_DIR}"
|
| 79 |
+
fi
|
| 80 |
+
RESULT_EXP_SUFFIX=""
|
| 81 |
+
if [ "${TRAIN_GPU_TAG}" != "8gpus" ]; then
|
| 82 |
+
RESULT_EXP_SUFFIX="_${TRAIN_GPU_TAG}"
|
| 83 |
+
fi
|
| 84 |
+
RESULT_EXPNAME="${RESULT_MODEL_NAME}${RESULT_EXP_SUFFIX}"
|
| 85 |
+
|
| 86 |
+
if [ "${timestep_mapping}" = "power" ]; then
|
| 87 |
+
echo "======== Timestep power: ${timestep_power}"
|
| 88 |
+
fi
|
| 89 |
+
if [ "${shift}" != "1.0" ]; then
|
| 90 |
+
echo "======== Shift: ${shift}"
|
| 91 |
+
fi
|
| 92 |
+
if [ "$INFER_ONLY" = true ]; then
|
| 93 |
+
echo "======== Mode: Execute infer tasks only"
|
| 94 |
+
else
|
| 95 |
+
echo "======== Mode: Execute full pipeline (infer + eval)"
|
| 96 |
+
if [ -z "${WAVLM_CKPT_DIR}" ]; then
|
| 97 |
+
echo "======== WavLM checkpoint is required for SIM evaluation. Pass --wavlm-ckpt-dir <path>."
|
| 98 |
+
exit 1
|
| 99 |
+
fi
|
| 100 |
+
fi
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# Function: Execute eval tasks
|
| 104 |
+
execute_eval_tasks() {
|
| 105 |
+
local ckptstep=$1
|
| 106 |
+
local seed=$2
|
| 107 |
+
local task_name=$3
|
| 108 |
+
|
| 109 |
+
local gen_wav_dir="results/${RESULT_EXPNAME}/${ckptstep}/${task_name}/seed${seed}_nfe${nfe_step}_wav"
|
| 110 |
+
if [ "${timestep_mapping}" = "uniform" ]; then
|
| 111 |
+
gen_wav_dir+="_uniform"
|
| 112 |
+
fi
|
| 113 |
+
if [ "${timestep_mapping}" = "sway_sampling" ] && [ "${swaysampling}" != "0" ]; then
|
| 114 |
+
gen_wav_dir+="_ss${swaysampling}"
|
| 115 |
+
fi
|
| 116 |
+
if [ "${timestep_mapping}" = "power" ]; then
|
| 117 |
+
gen_wav_dir+="_power${timestep_power}"
|
| 118 |
+
fi
|
| 119 |
+
if [ "${shift}" != "1.0" ]; then
|
| 120 |
+
gen_wav_dir+="_shift${shift}"
|
| 121 |
+
fi
|
| 122 |
+
gen_wav_dir+="_cfg${cfg_strength}"
|
| 123 |
+
|
| 124 |
+
echo ">>>>>>>> Starting eval task: ckptstep=${ckptstep}, seed=${seed}, task=${task_name}, gen_wav_dir=${gen_wav_dir}"
|
| 125 |
+
|
| 126 |
+
local wavlm_ckpt_args=()
|
| 127 |
+
if [ -n "${WAVLM_CKPT_DIR}" ]; then
|
| 128 |
+
wavlm_ckpt_args=(--wavlm_ckpt_dir "${WAVLM_CKPT_DIR}")
|
| 129 |
+
fi
|
| 130 |
+
|
| 131 |
+
case $task_name in
|
| 132 |
+
"seedtts_test_zh")
|
| 133 |
+
python src/wavtts/eval/eval_seedtts_testset.py -e wer -l zh -g "$gen_wav_dir" -n "$GPUS"
|
| 134 |
+
python src/wavtts/eval/eval_seedtts_testset.py -e sim -l zh -g "$gen_wav_dir" -n "$GPUS" "${wavlm_ckpt_args[@]}"
|
| 135 |
+
python src/wavtts/eval/eval_utmos.py --audio_dir "$gen_wav_dir"
|
| 136 |
+
;;
|
| 137 |
+
"seedtts_test_en")
|
| 138 |
+
python src/wavtts/eval/eval_seedtts_testset.py -e wer -l en -g "$gen_wav_dir" -n "$GPUS"
|
| 139 |
+
python src/wavtts/eval/eval_seedtts_testset.py -e sim -l en -g "$gen_wav_dir" -n "$GPUS" "${wavlm_ckpt_args[@]}"
|
| 140 |
+
python src/wavtts/eval/eval_utmos.py --audio_dir "$gen_wav_dir"
|
| 141 |
+
;;
|
| 142 |
+
"ls_pc_test_clean")
|
| 143 |
+
python src/wavtts/eval/eval_librispeech_test_clean.py -e wer -g "$gen_wav_dir" -n "$GPUS" -p "$LS_TEST_CLEAN_PATH"
|
| 144 |
+
python src/wavtts/eval/eval_librispeech_test_clean.py -e sim -g "$gen_wav_dir" -n "$GPUS" -p "$LS_TEST_CLEAN_PATH" "${wavlm_ckpt_args[@]}"
|
| 145 |
+
python src/wavtts/eval/eval_utmos.py --audio_dir "$gen_wav_dir"
|
| 146 |
+
;;
|
| 147 |
+
esac
|
| 148 |
+
|
| 149 |
+
echo ">>>>>>>> Completed eval task: ckptstep=${ckptstep}, seed=${seed}, task=${task_name}"
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
# Main execution loop
|
| 153 |
+
for ckptstep in "${CKPTSTEPS[@]}"; do
|
| 154 |
+
CKPT_PATH="${CKPT_FILE}"
|
| 155 |
+
|
| 156 |
+
echo "======== Processing ckptstep: ${ckptstep}"
|
| 157 |
+
echo "======== Using checkpoint: ${CKPT_PATH}"
|
| 158 |
+
|
| 159 |
+
for seed in "${SEEDS[@]}"; do
|
| 160 |
+
echo "-------- Processing seed: ${seed}"
|
| 161 |
+
|
| 162 |
+
# Store eval task PIDs for current seed (if not infer-only mode)
|
| 163 |
+
if [ "$INFER_ONLY" = false ]; then
|
| 164 |
+
declare -a eval_pids
|
| 165 |
+
fi
|
| 166 |
+
|
| 167 |
+
# Execute each infer task sequentially
|
| 168 |
+
for task in "${TASKS[@]}"; do
|
| 169 |
+
echo ">>>>>>>> Executing infer task: accelerate launch src/wavtts/eval/eval_infer_batch.py -s ${seed} -n \"${MODEL_NAME}\" -t \"${task}\" -c ${ckptstep} --ckpt_path \"${CKPT_PATH}\" --result_expname \"${RESULT_EXPNAME}\" --cfg_strength ${cfg_strength} --nfe_step ${nfe_step} --swaysampling ${swaysampling} --timestep_mapping ${timestep_mapping} --timestep_power ${timestep_power} --shift ${shift} -p \"${LS_TEST_CLEAN_PATH}\""
|
| 170 |
+
|
| 171 |
+
# Execute infer task
|
| 172 |
+
accelerate launch --main_process_port ${MASTER_PORT} src/wavtts/eval/eval_infer_batch.py -s ${seed} -n "${MODEL_NAME}" -t "${task}" -c ${ckptstep} --ckpt_path "${CKPT_PATH}" --result_expname "${RESULT_EXPNAME}" --nfe_step ${nfe_step} --swaysampling ${swaysampling} --timestep_mapping ${timestep_mapping} --timestep_power ${timestep_power} --shift ${shift} --cfg_strength ${cfg_strength} -p "${LS_TEST_CLEAN_PATH}"
|
| 173 |
+
|
| 174 |
+
# If not infer-only mode, launch corresponding eval task
|
| 175 |
+
if [ "$INFER_ONLY" = false ]; then
|
| 176 |
+
# Launch corresponding eval task (background execution, non-blocking for next infer)
|
| 177 |
+
execute_eval_tasks $ckptstep $seed $task &
|
| 178 |
+
eval_pids+=($!)
|
| 179 |
+
fi
|
| 180 |
+
done
|
| 181 |
+
|
| 182 |
+
# If not infer-only mode, wait for all eval tasks of current seed to complete
|
| 183 |
+
if [ "$INFER_ONLY" = false ]; then
|
| 184 |
+
echo ">>>>>>>> All infer tasks for seed ${seed} completed, waiting for corresponding eval tasks to finish..."
|
| 185 |
+
|
| 186 |
+
for pid in "${eval_pids[@]}"; do
|
| 187 |
+
wait $pid
|
| 188 |
+
done
|
| 189 |
+
|
| 190 |
+
unset eval_pids # Clean up array
|
| 191 |
+
fi
|
| 192 |
+
echo "-------- All eval tasks for seed ${seed} completed"
|
| 193 |
+
done
|
| 194 |
+
|
| 195 |
+
echo "======== Completed ckptstep: ${ckptstep}"
|
| 196 |
+
echo
|
| 197 |
+
done
|
| 198 |
+
|
| 199 |
+
echo "======== All tasks completed!"
|
| 200 |
+
|
| 201 |
+
# bash src/wavtts/eval/eval_infer_batch.sh
|
src/wavtts/eval/eval_infer_batch_example.sh
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# WavTTS batch inference examples.
|
| 4 |
+
# Use an explicit checkpoint path because WavTTS configs no longer include legacy model fallbacks.
|
| 5 |
+
|
| 6 |
+
CKPT_PATH="hf://worstchan/WavTTS/model_1200000.pt"
|
| 7 |
+
MODEL_NAME=WavTTS
|
| 8 |
+
GPU_NUMS=8
|
| 9 |
+
WAVLM_CKPT_DIR="<PATH_TO_WAVLM_LARGE_FINETUNE_PTH>"
|
| 10 |
+
|
| 11 |
+
# e.g. WavTTS, 50 NFE
|
| 12 |
+
accelerate launch --num_processes "${GPU_NUMS}" src/wavtts/eval/eval_infer_batch.py -s 0 -n "${MODEL_NAME}" -t "seedtts_test_zh" -c 1200000 -nfe 50 --ckpt_path "${CKPT_PATH}"
|
| 13 |
+
accelerate launch --num_processes "${GPU_NUMS}" src/wavtts/eval/eval_infer_batch.py -s 0 -n "${MODEL_NAME}" -t "seedtts_test_en" -c 1200000 -nfe 50 --ckpt_path "${CKPT_PATH}"
|
| 14 |
+
accelerate launch --num_processes "${GPU_NUMS}" src/wavtts/eval/eval_infer_batch.py -s 0 -n "${MODEL_NAME}" -t "ls_pc_test_clean" -c 1200000 -nfe 50 -p data/LibriSpeech/test-clean --ckpt_path "${CKPT_PATH}"
|
| 15 |
+
|
| 16 |
+
# e.g. evaluate WavTTS 50 NFE result on Seed-TTS test-zh
|
| 17 |
+
GEN_WAV_DIR=results/WavTTS/1200000/seedtts_test_zh/seed0_nfe50_wav_power2.0_shift3.0_cfg3.0
|
| 18 |
+
python src/wavtts/eval/eval_seedtts_testset.py -e wer -l zh --gen_wav_dir "${GEN_WAV_DIR}" --gpu_nums "${GPU_NUMS}"
|
| 19 |
+
python src/wavtts/eval/eval_seedtts_testset.py -e sim -l zh --gen_wav_dir "${GEN_WAV_DIR}" --gpu_nums "${GPU_NUMS}" --wavlm_ckpt_dir "$WAVLM_CKPT_DIR"
|
| 20 |
+
python src/wavtts/eval/eval_utmos.py --audio_dir "${GEN_WAV_DIR}"
|
src/wavtts/eval/eval_librispeech_test_clean.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluate with Librispeech test-clean, ~3s prompt to generate 4-10s audio (the way of valle/voicebox evaluation)
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import ast
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
sys.path.append(os.getcwd())
|
| 11 |
+
|
| 12 |
+
import multiprocessing as mp
|
| 13 |
+
from importlib.resources import files
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from wavtts.eval.utils_eval import get_librispeech_test, run_asr_wer, run_sim
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
rel_path = str(files("wavtts").joinpath("../../"))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_args():
|
| 24 |
+
parser = argparse.ArgumentParser()
|
| 25 |
+
parser.add_argument("-e", "--eval_task", type=str, default="wer", choices=["sim", "wer"])
|
| 26 |
+
parser.add_argument("-l", "--lang", type=str, default="en")
|
| 27 |
+
parser.add_argument("-g", "--gen_wav_dir", type=str, required=True)
|
| 28 |
+
parser.add_argument("-p", "--librispeech_test_clean_path", type=str, required=True)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"-n", "--gpu_nums", type=str, default="8", help="Number of GPUs to use (e.g., 8) or GPU list (e.g., [0,1,2,3])"
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument("-t", "--task", type=str, default="ls_pc_test_clean", choices=["ls_pc_test_clean"])
|
| 33 |
+
parser.add_argument(
|
| 34 |
+
"--wavlm_ckpt_dir",
|
| 35 |
+
type=str,
|
| 36 |
+
default="",
|
| 37 |
+
help="Path to wavlm_large_finetune.pth for SIM evaluation.",
|
| 38 |
+
)
|
| 39 |
+
parser.add_argument("--local", action="store_true", help="Use local custom checkpoint directory")
|
| 40 |
+
return parser.parse_args()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_gpu_nums(gpu_nums_str):
|
| 44 |
+
try:
|
| 45 |
+
if gpu_nums_str.startswith("[") and gpu_nums_str.endswith("]"):
|
| 46 |
+
gpu_list = ast.literal_eval(gpu_nums_str)
|
| 47 |
+
if isinstance(gpu_list, list):
|
| 48 |
+
return gpu_list
|
| 49 |
+
return list(range(int(gpu_nums_str)))
|
| 50 |
+
except (ValueError, SyntaxError):
|
| 51 |
+
raise argparse.ArgumentTypeError(
|
| 52 |
+
f"Invalid GPU specification: {gpu_nums_str}. Use a number (e.g., 8) or a list (e.g., [0,1,2,3])"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
args = get_args()
|
| 58 |
+
eval_task = args.eval_task
|
| 59 |
+
lang = args.lang
|
| 60 |
+
librispeech_test_clean_path = args.librispeech_test_clean_path # test-clean path
|
| 61 |
+
gen_wav_dir = args.gen_wav_dir
|
| 62 |
+
|
| 63 |
+
metalst = rel_path + "/data/librispeech_pc_test_clean_cross_sentence.lst"
|
| 64 |
+
|
| 65 |
+
gpus = parse_gpu_nums(args.gpu_nums)
|
| 66 |
+
test_set = get_librispeech_test(metalst, gen_wav_dir, gpus, librispeech_test_clean_path)
|
| 67 |
+
|
| 68 |
+
## In LibriSpeech, some speakers utilized varying voice characteristics for different characters in the book,
|
| 69 |
+
## leading to a low similarity for the ground truth in some cases.
|
| 70 |
+
# test_set = get_librispeech_test(metalst, gen_wav_dir, gpus, librispeech_test_clean_path, eval_ground_truth = True) # eval ground truth
|
| 71 |
+
|
| 72 |
+
wavlm_ckpt_dir = args.wavlm_ckpt_dir
|
| 73 |
+
if eval_task == "sim" and not wavlm_ckpt_dir:
|
| 74 |
+
raise ValueError(
|
| 75 |
+
"--wavlm_ckpt_dir is required for SIM evaluation. "
|
| 76 |
+
"Download wavlm_large_finetune.pth and pass its path."
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
local = args.local
|
| 80 |
+
if local: # use local custom checkpoint dir
|
| 81 |
+
asr_ckpt_dir = "../checkpoints/Systran/faster-whisper-large-v3"
|
| 82 |
+
else:
|
| 83 |
+
asr_ckpt_dir = "" # auto download to cache dir
|
| 84 |
+
|
| 85 |
+
# --------------------------------------------------------------------------
|
| 86 |
+
|
| 87 |
+
full_results = []
|
| 88 |
+
metrics = []
|
| 89 |
+
|
| 90 |
+
if eval_task == "wer":
|
| 91 |
+
with mp.Pool(processes=len(gpus)) as pool:
|
| 92 |
+
args = [(rank, lang, sub_test_set, asr_ckpt_dir) for (rank, sub_test_set) in test_set]
|
| 93 |
+
results = pool.map(run_asr_wer, args)
|
| 94 |
+
for r in results:
|
| 95 |
+
full_results.extend(r)
|
| 96 |
+
elif eval_task == "sim":
|
| 97 |
+
with mp.Pool(processes=len(gpus)) as pool:
|
| 98 |
+
args = [(rank, sub_test_set, wavlm_ckpt_dir) for (rank, sub_test_set) in test_set]
|
| 99 |
+
results = pool.map(run_sim, args)
|
| 100 |
+
for r in results:
|
| 101 |
+
full_results.extend(r)
|
| 102 |
+
else:
|
| 103 |
+
raise ValueError(f"Unknown metric type: {eval_task}")
|
| 104 |
+
|
| 105 |
+
result_path = f"{gen_wav_dir}/_{eval_task}_results.jsonl"
|
| 106 |
+
with open(result_path, "w") as f:
|
| 107 |
+
for line in full_results:
|
| 108 |
+
metrics.append(line[eval_task])
|
| 109 |
+
f.write(json.dumps(line, ensure_ascii=False) + "\n")
|
| 110 |
+
metric = round(np.mean(metrics), 5)
|
| 111 |
+
f.write(f"\n{eval_task.upper()}: {metric}\n")
|
| 112 |
+
|
| 113 |
+
print(f"\nTotal {len(metrics)} samples")
|
| 114 |
+
print(f"{eval_task.upper()}: {metric}")
|
| 115 |
+
print(f"{eval_task.upper()} results saved to {result_path}")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
main()
|
src/wavtts/eval/eval_seedtts.sh
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
# Environment variables; adjust as needed.
|
| 5 |
+
export PYTHONWARNINGS="ignore::UserWarning,ignore::FutureWarning"
|
| 6 |
+
export OMP_NUM_THREADS=1
|
| 7 |
+
|
| 8 |
+
eval_metric=("wer sim utmos")
|
| 9 |
+
|
| 10 |
+
langs=("zh" "en")
|
| 11 |
+
ckpt_steps=(1200000)
|
| 12 |
+
seed=0
|
| 13 |
+
nfe_step=50
|
| 14 |
+
cfg_strength=3.0
|
| 15 |
+
timestep_mapping="power"
|
| 16 |
+
timestep_power=2.0
|
| 17 |
+
shift="3.0"
|
| 18 |
+
RESULTS_ROOT=./results/WavTTS
|
| 19 |
+
GPUS="[0,1,2,3,4,5,6,7]"
|
| 20 |
+
|
| 21 |
+
LOCAL=""
|
| 22 |
+
WAVLM_CKPT_DIR="<PATH_TO_WAVLM_LARGE_FINETUNE_PTH>"
|
| 23 |
+
|
| 24 |
+
gen_wav_subdir=seed${seed}_nfe${nfe_step}_wav
|
| 25 |
+
if [[ "${timestep_mapping}" == "uniform" ]]; then
|
| 26 |
+
gen_wav_subdir+="_uniform"
|
| 27 |
+
fi
|
| 28 |
+
if [[ "${timestep_mapping}" == "sway_sampling" && "${swaysampling}" != "0" ]]; then
|
| 29 |
+
gen_wav_subdir+="_ss${swaysampling}"
|
| 30 |
+
fi
|
| 31 |
+
if [[ "${timestep_mapping}" == "power" ]]; then
|
| 32 |
+
gen_wav_subdir+="_power${timestep_power}"
|
| 33 |
+
fi
|
| 34 |
+
if [[ "${shift}" != "1.0" ]]; then
|
| 35 |
+
gen_wav_subdir+="_shift${shift}"
|
| 36 |
+
fi
|
| 37 |
+
gen_wav_subdir+="_cfg${cfg_strength}"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
for ckpt_step in "${ckpt_steps[@]}"; do
|
| 41 |
+
output_dir=${RESULTS_ROOT}/${ckpt_step}
|
| 42 |
+
echo "[INFO] processing ckpt_step=${ckpt_step}"
|
| 43 |
+
|
| 44 |
+
for lang in "${langs[@]}"; do
|
| 45 |
+
gen_wav_dir=${output_dir}/seedtts_test_${lang}/${gen_wav_subdir}
|
| 46 |
+
echo "[INFO] evaluating ${gen_wav_dir}"
|
| 47 |
+
|
| 48 |
+
if [[ ! -d "${gen_wav_dir}" ]]; then
|
| 49 |
+
echo "[ERROR] generated wav dir not found: ${gen_wav_dir}" >&2
|
| 50 |
+
exit 1
|
| 51 |
+
fi
|
| 52 |
+
|
| 53 |
+
if [[ " ${eval_metric[@]} " =~ " wer " ]]; then
|
| 54 |
+
python src/wavtts/eval/eval_seedtts_testset.py \
|
| 55 |
+
-e wer -l "$lang" -g "$gen_wav_dir" -n "$GPUS" $LOCAL
|
| 56 |
+
fi
|
| 57 |
+
|
| 58 |
+
if [[ " ${eval_metric[@]} " =~ " sim " ]]; then
|
| 59 |
+
python src/wavtts/eval/eval_seedtts_testset.py \
|
| 60 |
+
-e sim -l "$lang" -g "$gen_wav_dir" -n "$GPUS" $LOCAL --wavlm_ckpt_dir "$WAVLM_CKPT_DIR"
|
| 61 |
+
fi
|
| 62 |
+
|
| 63 |
+
if [[ " ${eval_metric[@]} " =~ " utmos " ]]; then
|
| 64 |
+
python src/wavtts/eval/eval_utmos.py \
|
| 65 |
+
--audio_dir "$gen_wav_dir"
|
| 66 |
+
fi
|
| 67 |
+
done
|
| 68 |
+
done
|
| 69 |
+
|
| 70 |
+
# bash src/wavtts/eval/eval_seedtts.sh
|
src/wavtts/eval/eval_seedtts_testset.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluate with Seed-TTS testset
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import ast
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
sys.path.append(os.getcwd())
|
| 11 |
+
|
| 12 |
+
import multiprocessing as mp
|
| 13 |
+
from importlib.resources import files
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from wavtts.eval.utils_eval import get_seed_tts_test, run_asr_wer, run_sim
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
rel_path = str(files("wavtts").joinpath("../../"))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_args():
|
| 24 |
+
parser = argparse.ArgumentParser()
|
| 25 |
+
parser.add_argument("-e", "--eval_task", type=str, default="wer", choices=["sim", "wer"])
|
| 26 |
+
parser.add_argument("-l", "--lang", type=str, default="en", choices=["zh", "zh_hard", "en"])
|
| 27 |
+
parser.add_argument("-g", "--gen_wav_dir", type=str, required=True)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
"-n", "--gpu_nums", type=str, default="8", help="Number of GPUs to use (e.g., 8) or GPU list (e.g., [0,1,2,3])"
|
| 30 |
+
)
|
| 31 |
+
parser.add_argument(
|
| 32 |
+
"--wavlm_ckpt_dir",
|
| 33 |
+
type=str,
|
| 34 |
+
default="",
|
| 35 |
+
help="Path to wavlm_large_finetune.pth for SIM evaluation.",
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument("--local", action="store_true", help="Use local custom checkpoint directory")
|
| 38 |
+
return parser.parse_args()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def parse_gpu_nums(gpu_nums_str):
|
| 42 |
+
try:
|
| 43 |
+
if gpu_nums_str.startswith("[") and gpu_nums_str.endswith("]"):
|
| 44 |
+
gpu_list = ast.literal_eval(gpu_nums_str)
|
| 45 |
+
if isinstance(gpu_list, list):
|
| 46 |
+
return gpu_list
|
| 47 |
+
return list(range(int(gpu_nums_str)))
|
| 48 |
+
except (ValueError, SyntaxError):
|
| 49 |
+
raise argparse.ArgumentTypeError(
|
| 50 |
+
f"Invalid GPU specification: {gpu_nums_str}. Use a number (e.g., 8) or a list (e.g., [0,1,2,3])"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main():
|
| 55 |
+
args = get_args()
|
| 56 |
+
eval_task = args.eval_task
|
| 57 |
+
lang = args.lang
|
| 58 |
+
asr_lang = "zh" if lang == "zh_hard" else lang
|
| 59 |
+
gen_wav_dir = args.gen_wav_dir
|
| 60 |
+
if lang == "zh_hard":
|
| 61 |
+
metalst = rel_path + "/data/seedtts_testset/zh/hardcase.lst"
|
| 62 |
+
else:
|
| 63 |
+
metalst = rel_path + f"/data/seedtts_testset/{lang}/meta.lst" # seed-tts testset
|
| 64 |
+
|
| 65 |
+
# NOTE. paraformer-zh result will be slightly different according to the number of gpus, cuz batchsize is different
|
| 66 |
+
# zh 1.254 seems a result of 4 workers wer_seed_tts
|
| 67 |
+
gpus = parse_gpu_nums(args.gpu_nums)
|
| 68 |
+
test_set = get_seed_tts_test(metalst, gen_wav_dir, gpus)
|
| 69 |
+
|
| 70 |
+
wavlm_ckpt_dir = args.wavlm_ckpt_dir
|
| 71 |
+
if eval_task == "sim" and not wavlm_ckpt_dir:
|
| 72 |
+
raise ValueError(
|
| 73 |
+
"--wavlm_ckpt_dir is required for SIM evaluation. "
|
| 74 |
+
"Download wavlm_large_finetune.pth and pass its path."
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
local = args.local
|
| 78 |
+
if local: # use local custom checkpoint dir
|
| 79 |
+
if asr_lang == "zh":
|
| 80 |
+
asr_ckpt_dir = "../checkpoints/funasr" # paraformer-zh dir under funasr
|
| 81 |
+
elif asr_lang == "en":
|
| 82 |
+
asr_ckpt_dir = "../checkpoints/Systran/faster-whisper-large-v3"
|
| 83 |
+
else:
|
| 84 |
+
asr_ckpt_dir = "" # auto download to cache dir
|
| 85 |
+
|
| 86 |
+
# --------------------------------------------------------------------------
|
| 87 |
+
|
| 88 |
+
full_results = []
|
| 89 |
+
metrics = []
|
| 90 |
+
|
| 91 |
+
if eval_task == "wer":
|
| 92 |
+
with mp.Pool(processes=len(gpus)) as pool:
|
| 93 |
+
args = [(rank, asr_lang, sub_test_set, asr_ckpt_dir) for (rank, sub_test_set) in test_set]
|
| 94 |
+
results = pool.map(run_asr_wer, args)
|
| 95 |
+
for r in results:
|
| 96 |
+
full_results.extend(r)
|
| 97 |
+
elif eval_task == "sim":
|
| 98 |
+
with mp.Pool(processes=len(gpus)) as pool:
|
| 99 |
+
args = [(rank, sub_test_set, wavlm_ckpt_dir) for (rank, sub_test_set) in test_set]
|
| 100 |
+
results = pool.map(run_sim, args)
|
| 101 |
+
for r in results:
|
| 102 |
+
full_results.extend(r)
|
| 103 |
+
else:
|
| 104 |
+
raise ValueError(f"Unknown metric type: {eval_task}")
|
| 105 |
+
|
| 106 |
+
result_path = f"{gen_wav_dir}/_{eval_task}_results.jsonl"
|
| 107 |
+
with open(result_path, "w") as f:
|
| 108 |
+
for line in full_results:
|
| 109 |
+
metrics.append(line[eval_task])
|
| 110 |
+
f.write(json.dumps(line, ensure_ascii=False) + "\n")
|
| 111 |
+
metric = round(np.mean(metrics), 5)
|
| 112 |
+
f.write(f"\n{eval_task.upper()}: {metric}\n")
|
| 113 |
+
|
| 114 |
+
print(f"\nTotal {len(metrics)} samples")
|
| 115 |
+
print(f"{eval_task.upper()}: {metric}")
|
| 116 |
+
print(f"{eval_task.upper()} results saved to {result_path}")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
main()
|
src/wavtts/eval/eval_utmos.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import librosa
|
| 6 |
+
import torch
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
parser = argparse.ArgumentParser(description="UTMOS Evaluation")
|
| 12 |
+
parser.add_argument("--audio_dir", type=str, required=True, help="Audio file path.")
|
| 13 |
+
parser.add_argument("--ext", type=str, default="wav", help="Audio extension.")
|
| 14 |
+
args = parser.parse_args()
|
| 15 |
+
|
| 16 |
+
device = "cuda" if torch.cuda.is_available() else "xpu" if torch.xpu.is_available() else "cpu"
|
| 17 |
+
|
| 18 |
+
predictor = torch.hub.load("tarepan/SpeechMOS:v1.2.0", "utmos22_strong", trust_repo=True)
|
| 19 |
+
predictor = predictor.to(device)
|
| 20 |
+
|
| 21 |
+
audio_paths = list(Path(args.audio_dir).rglob(f"*.{args.ext}"))
|
| 22 |
+
utmos_score = 0
|
| 23 |
+
|
| 24 |
+
utmos_result_path = Path(args.audio_dir) / "_utmos_results.jsonl"
|
| 25 |
+
with open(utmos_result_path, "w", encoding="utf-8") as f:
|
| 26 |
+
for audio_path in tqdm(audio_paths, desc="Processing"):
|
| 27 |
+
wav, sr = librosa.load(audio_path, sr=None, mono=True)
|
| 28 |
+
wav_tensor = torch.from_numpy(wav).to(device).unsqueeze(0)
|
| 29 |
+
score = predictor(wav_tensor, sr)
|
| 30 |
+
line = {}
|
| 31 |
+
line["wav"], line["utmos"] = str(audio_path.stem), score.item()
|
| 32 |
+
utmos_score += score.item()
|
| 33 |
+
f.write(json.dumps(line, ensure_ascii=False) + "\n")
|
| 34 |
+
avg_score = utmos_score / len(audio_paths) if len(audio_paths) > 0 else 0
|
| 35 |
+
f.write(f"\nUTMOS: {avg_score:.4f}\n")
|
| 36 |
+
|
| 37 |
+
print(f"UTMOS: {avg_score:.4f}")
|
| 38 |
+
print(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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
import string
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import torchaudio
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
|
| 12 |
+
from wavtts.eval.ecapa_tdnn import ECAPA_TDNN_SMALL
|
| 13 |
+
from wavtts.model.utils import convert_char_to_pinyin
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# seedtts testset metainfo: utt, prompt_text, prompt_wav, gt_text, gt_wav
|
| 17 |
+
def get_seedtts_testset_metainfo(metalst):
|
| 18 |
+
f = open(metalst)
|
| 19 |
+
lines = f.readlines()
|
| 20 |
+
f.close()
|
| 21 |
+
metainfo = []
|
| 22 |
+
for line in lines:
|
| 23 |
+
if len(line.strip().split("|")) == 5:
|
| 24 |
+
utt, prompt_text, prompt_wav, gt_text, gt_wav = line.strip().split("|")
|
| 25 |
+
elif len(line.strip().split("|")) == 4:
|
| 26 |
+
utt, prompt_text, prompt_wav, gt_text = line.strip().split("|")
|
| 27 |
+
gt_wav = os.path.join(os.path.dirname(metalst), "wavs", utt + ".wav")
|
| 28 |
+
if not os.path.isabs(prompt_wav):
|
| 29 |
+
prompt_wav = os.path.join(os.path.dirname(metalst), prompt_wav)
|
| 30 |
+
metainfo.append((utt, prompt_text, prompt_wav, gt_text, gt_wav))
|
| 31 |
+
return metainfo
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# librispeech test-clean metainfo: gen_utt, ref_txt, ref_wav, gen_txt, gen_wav
|
| 35 |
+
def get_librispeech_test_clean_metainfo(metalst, librispeech_test_clean_path):
|
| 36 |
+
f = open(metalst)
|
| 37 |
+
lines = f.readlines()
|
| 38 |
+
f.close()
|
| 39 |
+
metainfo = []
|
| 40 |
+
for line in lines:
|
| 41 |
+
ref_utt, ref_dur, ref_txt, gen_utt, gen_dur, gen_txt = line.strip().split("\t")
|
| 42 |
+
|
| 43 |
+
# ref_txt = ref_txt[0] + ref_txt[1:].lower() + '.' # if use librispeech test-clean (no-pc)
|
| 44 |
+
ref_spk_id, ref_chaptr_id, _ = ref_utt.split("-")
|
| 45 |
+
ref_wav = os.path.join(librispeech_test_clean_path, ref_spk_id, ref_chaptr_id, ref_utt + ".flac")
|
| 46 |
+
|
| 47 |
+
# gen_txt = gen_txt[0] + gen_txt[1:].lower() + '.' # if use librispeech test-clean (no-pc)
|
| 48 |
+
gen_spk_id, gen_chaptr_id, _ = gen_utt.split("-")
|
| 49 |
+
gen_wav = os.path.join(librispeech_test_clean_path, gen_spk_id, gen_chaptr_id, gen_utt + ".flac")
|
| 50 |
+
|
| 51 |
+
metainfo.append((gen_utt, ref_txt, ref_wav, " " + gen_txt, gen_wav))
|
| 52 |
+
|
| 53 |
+
return metainfo
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def padded_wav_batch(wavs):
|
| 57 |
+
"""
|
| 58 |
+
wavs: list[Tensor], each [1, T]
|
| 59 |
+
return: Tensor [B, 1, T_max]
|
| 60 |
+
"""
|
| 61 |
+
assert len(wavs) > 0
|
| 62 |
+
max_len = max(x.shape[-1] for x in wavs)
|
| 63 |
+
out = wavs[0].new_zeros(len(wavs), 1, max_len)
|
| 64 |
+
for i, x in enumerate(wavs):
|
| 65 |
+
out[i, 0, : x.shape[-1]] = x[0]
|
| 66 |
+
return out.squeeze(1)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# get prompts from metainfo containing: utt, prompt_text, prompt_wav, gt_text, gt_wav
|
| 70 |
+
|
| 71 |
+
def get_inference_prompt(
|
| 72 |
+
metainfo,
|
| 73 |
+
speed=1.0,
|
| 74 |
+
tokenizer="pinyin",
|
| 75 |
+
polyphone=True,
|
| 76 |
+
target_sample_rate=24000,
|
| 77 |
+
target_rms=0.1,
|
| 78 |
+
use_truth_duration=False,
|
| 79 |
+
infer_batch_size=1,
|
| 80 |
+
num_buckets=200,
|
| 81 |
+
min_secs=3,
|
| 82 |
+
max_secs=40,
|
| 83 |
+
wav_frame_len=160,
|
| 84 |
+
):
|
| 85 |
+
prompts_all = []
|
| 86 |
+
|
| 87 |
+
frame_len = wav_frame_len
|
| 88 |
+
min_tokens = min_secs * target_sample_rate
|
| 89 |
+
max_tokens = max_secs * target_sample_rate
|
| 90 |
+
|
| 91 |
+
batch_accum = [0] * num_buckets
|
| 92 |
+
utts, ref_rms_list, ref_feats, ref_feat_lens, total_feat_lens, final_text_list = (
|
| 93 |
+
[[] for _ in range(num_buckets)] for _ in range(6)
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
for utt, prompt_text, prompt_wav, gt_text, gt_wav in tqdm(metainfo, desc="Processing prompts..."):
|
| 98 |
+
# Audio
|
| 99 |
+
ref_audio, ref_sr = torchaudio.load(prompt_wav)
|
| 100 |
+
if ref_audio.shape[0] > 1:
|
| 101 |
+
ref_audio = ref_audio.mean(dim=0, keepdim=True)
|
| 102 |
+
|
| 103 |
+
ref_rms = torch.sqrt(torch.mean(torch.square(ref_audio)))
|
| 104 |
+
if ref_rms < target_rms:
|
| 105 |
+
ref_audio = ref_audio * target_rms / ref_rms
|
| 106 |
+
|
| 107 |
+
assert ref_audio.shape[-1] > 5000, f"Empty prompt wav: {prompt_wav}, or torchaudio backend issue."
|
| 108 |
+
if ref_sr != target_sample_rate:
|
| 109 |
+
resampler = torchaudio.transforms.Resample(ref_sr, target_sample_rate)
|
| 110 |
+
ref_audio = resampler(ref_audio)
|
| 111 |
+
|
| 112 |
+
# Text
|
| 113 |
+
if len(prompt_text[-1].encode("utf-8")) == 1:
|
| 114 |
+
prompt_text = prompt_text + " "
|
| 115 |
+
text = [prompt_text + gt_text]
|
| 116 |
+
if tokenizer == "pinyin":
|
| 117 |
+
text_list = convert_char_to_pinyin(text, polyphone=polyphone)
|
| 118 |
+
else:
|
| 119 |
+
text_list = text
|
| 120 |
+
|
| 121 |
+
ref_len_samples = ref_audio.shape[-1]
|
| 122 |
+
ref_full_frames = ref_len_samples // frame_len
|
| 123 |
+
ref_len_aligned = max(ref_full_frames * frame_len, frame_len)
|
| 124 |
+
ref_audio = ref_audio[..., :ref_len_aligned]
|
| 125 |
+
|
| 126 |
+
ref_feat = ref_audio # [1, T_aligned]
|
| 127 |
+
ref_feat_len = ref_len_aligned # prompt samples
|
| 128 |
+
|
| 129 |
+
if use_truth_duration:
|
| 130 |
+
gt_audio, gt_sr = torchaudio.load(gt_wav)
|
| 131 |
+
if gt_audio.shape[0] > 1:
|
| 132 |
+
gt_audio = torch.mean(gt_audio, dim=0, keepdim=True)
|
| 133 |
+
if gt_sr != target_sample_rate:
|
| 134 |
+
resampler = torchaudio.transforms.Resample(gt_sr, target_sample_rate)
|
| 135 |
+
gt_audio = resampler(gt_audio)
|
| 136 |
+
|
| 137 |
+
total_len = ref_feat_len + int(gt_audio.shape[-1] / speed)
|
| 138 |
+
else:
|
| 139 |
+
ref_text_len = len(prompt_text.encode("utf-8"))
|
| 140 |
+
gen_text_len = len(gt_text.encode("utf-8"))
|
| 141 |
+
total_len = ref_feat_len + int(ref_feat_len / ref_text_len * gen_text_len / speed)
|
| 142 |
+
|
| 143 |
+
# deal with batch
|
| 144 |
+
assert infer_batch_size > 0, "infer_batch_size should be greater than 0."
|
| 145 |
+
|
| 146 |
+
approx_secs = total_len // target_sample_rate
|
| 147 |
+
|
| 148 |
+
assert min_secs <= approx_secs <= max_secs, (
|
| 149 |
+
f"Audio {utt} has duration {approx_secs}s out of range [{min_secs}, {max_secs}]."
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
bucket_i = math.floor((total_len - min_tokens) / (max_tokens - min_tokens + 1) * num_buckets)
|
| 153 |
+
|
| 154 |
+
utts[bucket_i].append(utt)
|
| 155 |
+
ref_rms_list[bucket_i].append(ref_rms)
|
| 156 |
+
ref_feats[bucket_i].append(ref_feat)
|
| 157 |
+
ref_feat_lens[bucket_i].append(ref_feat_len)
|
| 158 |
+
total_feat_lens[bucket_i].append(total_len)
|
| 159 |
+
final_text_list[bucket_i].extend(text_list)
|
| 160 |
+
|
| 161 |
+
batch_accum[bucket_i] += total_len
|
| 162 |
+
|
| 163 |
+
if batch_accum[bucket_i] >= infer_batch_size:
|
| 164 |
+
# print(f"\n{len(ref_feats[bucket_i][0][0])}\n{ref_feat_len[bucket_i]}\n{total_feat_lens[bucket_i]}")
|
| 165 |
+
prompts_all.append(
|
| 166 |
+
(
|
| 167 |
+
utts[bucket_i],
|
| 168 |
+
ref_rms_list[bucket_i],
|
| 169 |
+
padded_wav_batch(ref_feats[bucket_i]),
|
| 170 |
+
ref_feat_lens[bucket_i],
|
| 171 |
+
total_feat_lens[bucket_i],
|
| 172 |
+
final_text_list[bucket_i],
|
| 173 |
+
)
|
| 174 |
+
)
|
| 175 |
+
batch_accum[bucket_i] = 0
|
| 176 |
+
(
|
| 177 |
+
utts[bucket_i],
|
| 178 |
+
ref_rms_list[bucket_i],
|
| 179 |
+
ref_feats[bucket_i],
|
| 180 |
+
ref_feat_lens[bucket_i],
|
| 181 |
+
total_feat_lens[bucket_i],
|
| 182 |
+
final_text_list[bucket_i],
|
| 183 |
+
) = [], [], [], [], [], []
|
| 184 |
+
|
| 185 |
+
# add residual
|
| 186 |
+
for bucket_i, bucket_frames in enumerate(batch_accum):
|
| 187 |
+
if bucket_frames > 0:
|
| 188 |
+
prompts_all.append(
|
| 189 |
+
(
|
| 190 |
+
utts[bucket_i],
|
| 191 |
+
ref_rms_list[bucket_i],
|
| 192 |
+
padded_wav_batch(ref_feats[bucket_i]),
|
| 193 |
+
ref_feat_lens[bucket_i],
|
| 194 |
+
total_feat_lens[bucket_i],
|
| 195 |
+
final_text_list[bucket_i],
|
| 196 |
+
)
|
| 197 |
+
)
|
| 198 |
+
# not only leave easy work for last workers
|
| 199 |
+
random.seed(666)
|
| 200 |
+
random.shuffle(prompts_all)
|
| 201 |
+
|
| 202 |
+
return prompts_all
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# get wav_res_ref_text of seed-tts test metalst
|
| 206 |
+
# https://github.com/BytedanceSpeech/seed-tts-eval
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def get_seed_tts_test(metalst, gen_wav_dir, gpus):
|
| 210 |
+
f = open(metalst)
|
| 211 |
+
lines = f.readlines()
|
| 212 |
+
f.close()
|
| 213 |
+
|
| 214 |
+
test_set_ = []
|
| 215 |
+
for line in tqdm(lines):
|
| 216 |
+
if len(line.strip().split("|")) == 5:
|
| 217 |
+
utt, prompt_text, prompt_wav, gt_text, gt_wav = line.strip().split("|")
|
| 218 |
+
elif len(line.strip().split("|")) == 4:
|
| 219 |
+
utt, prompt_text, prompt_wav, gt_text = line.strip().split("|")
|
| 220 |
+
|
| 221 |
+
if not os.path.exists(os.path.join(gen_wav_dir, utt + ".wav")):
|
| 222 |
+
continue
|
| 223 |
+
gen_wav = os.path.join(gen_wav_dir, utt + ".wav")
|
| 224 |
+
if not os.path.isabs(prompt_wav):
|
| 225 |
+
prompt_wav = os.path.join(os.path.dirname(metalst), prompt_wav)
|
| 226 |
+
|
| 227 |
+
test_set_.append((gen_wav, prompt_wav, gt_text))
|
| 228 |
+
|
| 229 |
+
num_jobs = len(gpus)
|
| 230 |
+
if num_jobs == 1:
|
| 231 |
+
return [(gpus[0], test_set_)]
|
| 232 |
+
|
| 233 |
+
wav_per_job = len(test_set_) // num_jobs + 1
|
| 234 |
+
test_set = []
|
| 235 |
+
for i in range(num_jobs):
|
| 236 |
+
test_set.append((gpus[i], test_set_[i * wav_per_job : (i + 1) * wav_per_job]))
|
| 237 |
+
|
| 238 |
+
return test_set
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
# get librispeech test-clean cross sentence test
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def get_librispeech_test(metalst, gen_wav_dir, gpus, librispeech_test_clean_path, eval_ground_truth=False):
|
| 245 |
+
f = open(metalst)
|
| 246 |
+
lines = f.readlines()
|
| 247 |
+
f.close()
|
| 248 |
+
|
| 249 |
+
test_set_ = []
|
| 250 |
+
for line in tqdm(lines):
|
| 251 |
+
ref_utt, ref_dur, ref_txt, gen_utt, gen_dur, gen_txt = line.strip().split("\t")
|
| 252 |
+
|
| 253 |
+
if eval_ground_truth:
|
| 254 |
+
gen_spk_id, gen_chaptr_id, _ = gen_utt.split("-")
|
| 255 |
+
gen_wav = os.path.join(librispeech_test_clean_path, gen_spk_id, gen_chaptr_id, gen_utt + ".flac")
|
| 256 |
+
else:
|
| 257 |
+
if not os.path.exists(os.path.join(gen_wav_dir, gen_utt + ".wav")):
|
| 258 |
+
raise FileNotFoundError(f"Generated wav not found: {gen_utt}")
|
| 259 |
+
gen_wav = os.path.join(gen_wav_dir, gen_utt + ".wav")
|
| 260 |
+
|
| 261 |
+
ref_spk_id, ref_chaptr_id, _ = ref_utt.split("-")
|
| 262 |
+
ref_wav = os.path.join(librispeech_test_clean_path, ref_spk_id, ref_chaptr_id, ref_utt + ".flac")
|
| 263 |
+
|
| 264 |
+
test_set_.append((gen_wav, ref_wav, gen_txt))
|
| 265 |
+
|
| 266 |
+
num_jobs = len(gpus)
|
| 267 |
+
if num_jobs == 1:
|
| 268 |
+
return [(gpus[0], test_set_)]
|
| 269 |
+
|
| 270 |
+
wav_per_job = len(test_set_) // num_jobs + 1
|
| 271 |
+
test_set = []
|
| 272 |
+
for i in range(num_jobs):
|
| 273 |
+
test_set.append((gpus[i], test_set_[i * wav_per_job : (i + 1) * wav_per_job]))
|
| 274 |
+
|
| 275 |
+
return test_set
|
| 276 |
+
|
| 277 |
+
# load asr model
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def load_asr_model(lang, ckpt_dir=""):
|
| 281 |
+
if lang == "zh":
|
| 282 |
+
from funasr import AutoModel
|
| 283 |
+
|
| 284 |
+
model = AutoModel(
|
| 285 |
+
model=os.path.join(ckpt_dir, "paraformer-zh"),
|
| 286 |
+
# vad_model = os.path.join(ckpt_dir, "fsmn-vad"),
|
| 287 |
+
# punc_model = os.path.join(ckpt_dir, "ct-punc"),
|
| 288 |
+
# spk_model = os.path.join(ckpt_dir, "cam++"),
|
| 289 |
+
disable_update=True,
|
| 290 |
+
) # following seed-tts setting
|
| 291 |
+
elif lang == "en":
|
| 292 |
+
from faster_whisper import WhisperModel
|
| 293 |
+
|
| 294 |
+
model_size = "large-v3" if ckpt_dir == "" else ckpt_dir
|
| 295 |
+
model = WhisperModel(model_size, device="cuda", compute_type="float16")
|
| 296 |
+
return model
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# WER Evaluation, the way Seed-TTS does
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def run_asr_wer(args):
|
| 303 |
+
rank, lang, test_set, ckpt_dir = args
|
| 304 |
+
|
| 305 |
+
if lang == "zh":
|
| 306 |
+
import zhconv
|
| 307 |
+
|
| 308 |
+
torch.cuda.set_device(rank)
|
| 309 |
+
elif lang == "en":
|
| 310 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = str(rank)
|
| 311 |
+
else:
|
| 312 |
+
raise NotImplementedError(
|
| 313 |
+
"lang support only 'zh' (funasr paraformer-zh), 'en' (faster-whisper-large-v3), for now."
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
asr_model = load_asr_model(lang, ckpt_dir=ckpt_dir)
|
| 317 |
+
|
| 318 |
+
from zhon.hanzi import punctuation
|
| 319 |
+
|
| 320 |
+
punctuation_all = punctuation + string.punctuation
|
| 321 |
+
wer_results = []
|
| 322 |
+
|
| 323 |
+
from jiwer import compute_measures
|
| 324 |
+
|
| 325 |
+
for gen_wav, prompt_wav, truth in tqdm(test_set):
|
| 326 |
+
if lang == "zh":
|
| 327 |
+
res = asr_model.generate(input=gen_wav, batch_size_s=300, disable_pbar=True)
|
| 328 |
+
hypo = res[0]["text"]
|
| 329 |
+
hypo = zhconv.convert(hypo, "zh-cn")
|
| 330 |
+
elif lang == "en":
|
| 331 |
+
segments, _ = asr_model.transcribe(gen_wav, beam_size=5, language="en")
|
| 332 |
+
hypo = ""
|
| 333 |
+
for segment in segments:
|
| 334 |
+
hypo = hypo + " " + segment.text
|
| 335 |
+
|
| 336 |
+
raw_truth = truth
|
| 337 |
+
raw_hypo = hypo
|
| 338 |
+
|
| 339 |
+
for x in punctuation_all:
|
| 340 |
+
truth = truth.replace(x, "")
|
| 341 |
+
hypo = hypo.replace(x, "")
|
| 342 |
+
|
| 343 |
+
truth = truth.replace(" ", " ")
|
| 344 |
+
hypo = hypo.replace(" ", " ")
|
| 345 |
+
|
| 346 |
+
if lang == "zh":
|
| 347 |
+
truth = " ".join([x for x in truth])
|
| 348 |
+
hypo = " ".join([x for x in hypo])
|
| 349 |
+
elif lang == "en":
|
| 350 |
+
truth = truth.lower()
|
| 351 |
+
hypo = hypo.lower()
|
| 352 |
+
|
| 353 |
+
measures = compute_measures(truth, hypo)
|
| 354 |
+
wer = measures["wer"]
|
| 355 |
+
|
| 356 |
+
# ref_list = truth.split(" ")
|
| 357 |
+
# subs = measures["substitutions"] / len(ref_list)
|
| 358 |
+
# dele = measures["deletions"] / len(ref_list)
|
| 359 |
+
# inse = measures["insertions"] / len(ref_list)
|
| 360 |
+
|
| 361 |
+
wer_results.append(
|
| 362 |
+
{
|
| 363 |
+
"wav": Path(gen_wav).stem,
|
| 364 |
+
"truth": raw_truth,
|
| 365 |
+
"hypo": raw_hypo,
|
| 366 |
+
"wer": wer,
|
| 367 |
+
}
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
return wer_results
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# SIM Evaluation
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def run_sim(args):
|
| 377 |
+
rank, test_set, ckpt_dir = args
|
| 378 |
+
device = f"cuda:{rank}"
|
| 379 |
+
|
| 380 |
+
model = ECAPA_TDNN_SMALL(feat_dim=1024, feat_type="wavlm_large", config_path=None)
|
| 381 |
+
state_dict = torch.load(ckpt_dir, weights_only=True, map_location=lambda storage, loc: storage)
|
| 382 |
+
model.load_state_dict(state_dict["model"], strict=False)
|
| 383 |
+
|
| 384 |
+
use_gpu = True if torch.cuda.is_available() else False
|
| 385 |
+
if use_gpu:
|
| 386 |
+
model = model.cuda(device)
|
| 387 |
+
model.eval()
|
| 388 |
+
|
| 389 |
+
sim_results = []
|
| 390 |
+
for gen_wav, prompt_wav, truth in tqdm(test_set):
|
| 391 |
+
wav1, sr1 = torchaudio.load(gen_wav)
|
| 392 |
+
wav2, sr2 = torchaudio.load(prompt_wav)
|
| 393 |
+
|
| 394 |
+
if use_gpu:
|
| 395 |
+
wav1 = wav1.cuda(device)
|
| 396 |
+
wav2 = wav2.cuda(device)
|
| 397 |
+
|
| 398 |
+
if sr1 != 16000:
|
| 399 |
+
resample1 = torchaudio.transforms.Resample(orig_freq=sr1, new_freq=16000)
|
| 400 |
+
if use_gpu:
|
| 401 |
+
resample1 = resample1.cuda(device)
|
| 402 |
+
wav1 = resample1(wav1)
|
| 403 |
+
if sr2 != 16000:
|
| 404 |
+
resample2 = torchaudio.transforms.Resample(orig_freq=sr2, new_freq=16000)
|
| 405 |
+
if use_gpu:
|
| 406 |
+
resample2 = resample2.cuda(device)
|
| 407 |
+
wav2 = resample2(wav2)
|
| 408 |
+
|
| 409 |
+
with torch.no_grad():
|
| 410 |
+
emb1 = model(wav1)
|
| 411 |
+
emb2 = model(wav2)
|
| 412 |
+
|
| 413 |
+
sim = F.cosine_similarity(emb1, emb2)[0].item()
|
| 414 |
+
# print(f"VSim score between two audios: {sim:.4f} (-1.0, 1.0).")
|
| 415 |
+
sim_results.append(
|
| 416 |
+
{
|
| 417 |
+
"wav": Path(gen_wav).stem,
|
| 418 |
+
"sim": sim,
|
| 419 |
+
}
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
return sim_results
|
src/wavtts/infer/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Inference
|
| 2 |
+
|
| 3 |
+
WavTTS supports zero-shot TTS from a reference audio prompt via either command-line or script-based inference.
|
| 4 |
+
|
| 5 |
+
> **💡 Tip for Reference Audio:**
|
| 6 |
+
> For optimal results, use a short reference clip, preferably under 12 seconds. We also recommend leaving a brief silence at the end of the clip to avoid truncating the prompt mid-word.
|
| 7 |
+
|
| 8 |
+
The pretrained checkpoint and matching vocabulary are available on [🤗 Hugging Face](https://huggingface.co/worstchan/WavTTS) and the checkpoint will be downloaded automatically when using the default configuration. To use a local checkpoint, specify its path with the `ckpt_file` parameter.
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
## CLI Inference
|
| 12 |
+
|
| 13 |
+
> **Note:** `wavtts_infer-cli` is an alias for `python src/wavtts/infer/infer_cli.py`. You can use either command interchangeably.
|
| 14 |
+
|
| 15 |
+
CLI inference can be run either with direct arguments or with a TOML configuration file. Command-line arguments always override values defined in the TOML config.
|
| 16 |
+
|
| 17 |
+
### A. Direct Arguments
|
| 18 |
+
|
| 19 |
+
Run inference by passing the required arguments directly:
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
wavtts_infer-cli \
|
| 23 |
+
--model WavTTS \
|
| 24 |
+
--ref_audio "infer/examples/basic_ref_en.wav" \
|
| 25 |
+
--ref_text "Some call me nature, others call me mother nature." \
|
| 26 |
+
--gen_text "The text you want WavTTS to synthesize."
|
| 27 |
+
```
|
| 28 |
+
*(Optional: Use `--model_cfg` instead of `--model` to provide an explicit YAML model config path.)*
|
| 29 |
+
|
| 30 |
+
### B. TOML Configuration
|
| 31 |
+
|
| 32 |
+
For reproducible runs, we recommend storing inference settings in a `.toml` file. If no config is provided, `wavtts_infer-cli` uses the default example config at `src/wavtts/infer/examples/basic.toml`.
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
# Use the default example config
|
| 36 |
+
wavtts_infer-cli -c src/wavtts/infer/examples/basic.toml
|
| 37 |
+
|
| 38 |
+
# Use a custom config with optional argument overrides
|
| 39 |
+
wavtts_infer-cli -c custom.toml --gen_text "Override text here."
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
**Example `custom.toml`:**
|
| 43 |
+
```toml
|
| 44 |
+
# Model settings
|
| 45 |
+
model = "WavTTS"
|
| 46 |
+
ckpt_file = "" # Leave empty to use the Hugging Face default
|
| 47 |
+
vocab_file = "infer/examples/vocab.txt"
|
| 48 |
+
|
| 49 |
+
# Prompt and generation
|
| 50 |
+
ref_audio = "infer/examples/basic_ref_en.wav"
|
| 51 |
+
ref_text = "Some call me nature, others call me mother nature."
|
| 52 |
+
gen_text = "The text you want WavTTS to synthesize."
|
| 53 |
+
|
| 54 |
+
# Output settings
|
| 55 |
+
output_dir = "output"
|
| 56 |
+
output_file = "infer_cli_basic.wav"
|
| 57 |
+
remove_silence = false
|
| 58 |
+
|
| 59 |
+
# Generation hyperparameters
|
| 60 |
+
nfe_step = 50
|
| 61 |
+
cfg_strength = 3.0
|
| 62 |
+
timestep_mapping = "power"
|
| 63 |
+
timestep_power = 2.0
|
| 64 |
+
shift = 3.0
|
| 65 |
+
speed = 1.0
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
## Script-based Inference
|
| 69 |
+
|
| 70 |
+
For customized pipelines or evaluation, you can modify and run the provided bash scripts.
|
| 71 |
+
|
| 72 |
+
### Single-sample Inference
|
| 73 |
+
Edit the paths and text in `src/wavtts/infer/infer.sh`, then execute:
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
bash src/wavtts/infer/infer.sh
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
### Batch Inference
|
| 80 |
+
For batch inference, configure the task and dataset paths in `src/wavtts/eval/eval_infer_batch.sh`, then run:
|
| 81 |
+
|
| 82 |
+
```bash
|
| 83 |
+
bash src/wavtts/eval/eval_infer_batch.sh --infer-only
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
> **💡 Tip:**
|
| 87 |
+
> If you notice obvious background noise in the synthesized speech, try lowering the `shift` value to mitigate it (e.g., set `shift = 1.0`).
|
src/wavtts/infer/examples/basic.toml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Model and checkpoint
|
| 2 |
+
model = "WavTTS"
|
| 3 |
+
ckpt_file = "" # Leave empty to download the default Hugging Face checkpoint.
|
| 4 |
+
vocab_file = "infer/examples/vocab.txt"
|
| 5 |
+
|
| 6 |
+
# Reference prompt and generation text
|
| 7 |
+
ref_audio = "infer/examples/basic_ref_en.wav"
|
| 8 |
+
ref_text = "Some call me nature, others call me mother nature."
|
| 9 |
+
gen_text = "I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall."
|
| 10 |
+
gen_file = "" # If set, this file is used instead of gen_text.
|
| 11 |
+
|
| 12 |
+
# Output
|
| 13 |
+
output_dir = "output"
|
| 14 |
+
output_file = "infer_cli_basic.wav"
|
| 15 |
+
remove_silence = false
|
| 16 |
+
|
| 17 |
+
# Sampling
|
| 18 |
+
nfe_step = 50
|
| 19 |
+
cfg_strength = 3.0
|
| 20 |
+
timestep_mapping = "power"
|
| 21 |
+
timestep_power = 2.0
|
| 22 |
+
shift = 3.0
|
| 23 |
+
speed = 1.0
|
src/wavtts/infer/examples/basic_ref_en.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b0e22048e72414fcc1e6b6342e47a774d748a195ed34e4a5b3fcf416707f2b71
|
| 3 |
+
size 256018
|
src/wavtts/infer/examples/basic_ref_zh.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git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
|
| 75 |
+
ao2
|
| 76 |
+
ao3
|
| 77 |
+
ao4
|
| 78 |
+
b
|
| 79 |
+
ba
|
| 80 |
+
ba1
|
| 81 |
+
ba2
|
| 82 |
+
ba3
|
| 83 |
+
ba4
|
| 84 |
+
bai1
|
| 85 |
+
bai2
|
| 86 |
+
bai3
|
| 87 |
+
bai4
|
| 88 |
+
ban1
|
| 89 |
+
ban2
|
| 90 |
+
ban3
|
| 91 |
+
ban4
|
| 92 |
+
bang1
|
| 93 |
+
bang2
|
| 94 |
+
bang3
|
| 95 |
+
bang4
|
| 96 |
+
bao1
|
| 97 |
+
bao2
|
| 98 |
+
bao3
|
| 99 |
+
bao4
|
| 100 |
+
bei
|
| 101 |
+
bei1
|
| 102 |
+
bei2
|
| 103 |
+
bei3
|
| 104 |
+
bei4
|
| 105 |
+
ben1
|
| 106 |
+
ben2
|
| 107 |
+
ben3
|
| 108 |
+
ben4
|
| 109 |
+
beng
|
| 110 |
+
beng1
|
| 111 |
+
beng2
|
| 112 |
+
beng3
|
| 113 |
+
beng4
|
| 114 |
+
bi1
|
| 115 |
+
bi2
|
| 116 |
+
bi3
|
| 117 |
+
bi4
|
| 118 |
+
bian1
|
| 119 |
+
bian2
|
| 120 |
+
bian3
|
| 121 |
+
bian4
|
| 122 |
+
biao1
|
| 123 |
+
biao2
|
| 124 |
+
biao3
|
| 125 |
+
bie1
|
| 126 |
+
bie2
|
| 127 |
+
bie3
|
| 128 |
+
bie4
|
| 129 |
+
bin1
|
| 130 |
+
bin4
|
| 131 |
+
bing1
|
| 132 |
+
bing2
|
| 133 |
+
bing3
|
| 134 |
+
bing4
|
| 135 |
+
bo
|
| 136 |
+
bo1
|
| 137 |
+
bo2
|
| 138 |
+
bo3
|
| 139 |
+
bo4
|
| 140 |
+
bu
|
| 141 |
+
bu2
|
| 142 |
+
bu3
|
| 143 |
+
bu4
|
| 144 |
+
c
|
| 145 |
+
ca1
|
| 146 |
+
cai1
|
| 147 |
+
cai2
|
| 148 |
+
cai3
|
| 149 |
+
cai4
|
| 150 |
+
can1
|
| 151 |
+
can2
|
| 152 |
+
can3
|
| 153 |
+
can4
|
| 154 |
+
cang1
|
| 155 |
+
cang2
|
| 156 |
+
cao1
|
| 157 |
+
cao2
|
| 158 |
+
cao3
|
| 159 |
+
ce4
|
| 160 |
+
cen1
|
| 161 |
+
cen2
|
| 162 |
+
ceng1
|
| 163 |
+
ceng2
|
| 164 |
+
ceng4
|
| 165 |
+
cha1
|
| 166 |
+
cha2
|
| 167 |
+
cha3
|
| 168 |
+
cha4
|
| 169 |
+
chai1
|
| 170 |
+
chai2
|
| 171 |
+
chan1
|
| 172 |
+
chan2
|
| 173 |
+
chan3
|
| 174 |
+
chan4
|
| 175 |
+
chang1
|
| 176 |
+
chang2
|
| 177 |
+
chang3
|
| 178 |
+
chang4
|
| 179 |
+
chao1
|
| 180 |
+
chao2
|
| 181 |
+
chao3
|
| 182 |
+
che1
|
| 183 |
+
che2
|
| 184 |
+
che3
|
| 185 |
+
che4
|
| 186 |
+
chen1
|
| 187 |
+
chen2
|
| 188 |
+
chen3
|
| 189 |
+
chen4
|
| 190 |
+
cheng1
|
| 191 |
+
cheng2
|
| 192 |
+
cheng3
|
| 193 |
+
cheng4
|
| 194 |
+
chi1
|
| 195 |
+
chi2
|
| 196 |
+
chi3
|
| 197 |
+
chi4
|
| 198 |
+
chong1
|
| 199 |
+
chong2
|
| 200 |
+
chong3
|
| 201 |
+
chong4
|
| 202 |
+
chou1
|
| 203 |
+
chou2
|
| 204 |
+
chou3
|
| 205 |
+
chou4
|
| 206 |
+
chu1
|
| 207 |
+
chu2
|
| 208 |
+
chu3
|
| 209 |
+
chu4
|
| 210 |
+
chua1
|
| 211 |
+
chuai1
|
| 212 |
+
chuai2
|
| 213 |
+
chuai3
|
| 214 |
+
chuai4
|
| 215 |
+
chuan1
|
| 216 |
+
chuan2
|
| 217 |
+
chuan3
|
| 218 |
+
chuan4
|
| 219 |
+
chuang1
|
| 220 |
+
chuang2
|
| 221 |
+
chuang3
|
| 222 |
+
chuang4
|
| 223 |
+
chui1
|
| 224 |
+
chui2
|
| 225 |
+
chun1
|
| 226 |
+
chun2
|
| 227 |
+
chun3
|
| 228 |
+
chuo1
|
| 229 |
+
chuo4
|
| 230 |
+
ci1
|
| 231 |
+
ci2
|
| 232 |
+
ci3
|
| 233 |
+
ci4
|
| 234 |
+
cong1
|
| 235 |
+
cong2
|
| 236 |
+
cou4
|
| 237 |
+
cu1
|
| 238 |
+
cu4
|
| 239 |
+
cuan1
|
| 240 |
+
cuan2
|
| 241 |
+
cuan4
|
| 242 |
+
cui1
|
| 243 |
+
cui3
|
| 244 |
+
cui4
|
| 245 |
+
cun1
|
| 246 |
+
cun2
|
| 247 |
+
cun4
|
| 248 |
+
cuo1
|
| 249 |
+
cuo2
|
| 250 |
+
cuo4
|
| 251 |
+
d
|
| 252 |
+
da
|
| 253 |
+
da1
|
| 254 |
+
da2
|
| 255 |
+
da3
|
| 256 |
+
da4
|
| 257 |
+
dai1
|
| 258 |
+
dai2
|
| 259 |
+
dai3
|
| 260 |
+
dai4
|
| 261 |
+
dan1
|
| 262 |
+
dan2
|
| 263 |
+
dan3
|
| 264 |
+
dan4
|
| 265 |
+
dang1
|
| 266 |
+
dang2
|
| 267 |
+
dang3
|
| 268 |
+
dang4
|
| 269 |
+
dao1
|
| 270 |
+
dao2
|
| 271 |
+
dao3
|
| 272 |
+
dao4
|
| 273 |
+
de
|
| 274 |
+
de1
|
| 275 |
+
de2
|
| 276 |
+
dei3
|
| 277 |
+
den4
|
| 278 |
+
deng1
|
| 279 |
+
deng2
|
| 280 |
+
deng3
|
| 281 |
+
deng4
|
| 282 |
+
di
|
| 283 |
+
di1
|
| 284 |
+
di2
|
| 285 |
+
di3
|
| 286 |
+
di4
|
| 287 |
+
dia3
|
| 288 |
+
dian1
|
| 289 |
+
dian2
|
| 290 |
+
dian3
|
| 291 |
+
dian4
|
| 292 |
+
diao1
|
| 293 |
+
diao3
|
| 294 |
+
diao4
|
| 295 |
+
die1
|
| 296 |
+
die2
|
| 297 |
+
die4
|
| 298 |
+
ding1
|
| 299 |
+
ding2
|
| 300 |
+
ding3
|
| 301 |
+
ding4
|
| 302 |
+
diu1
|
| 303 |
+
dong1
|
| 304 |
+
dong3
|
| 305 |
+
dong4
|
| 306 |
+
dou1
|
| 307 |
+
dou2
|
| 308 |
+
dou3
|
| 309 |
+
dou4
|
| 310 |
+
du1
|
| 311 |
+
du2
|
| 312 |
+
du3
|
| 313 |
+
du4
|
| 314 |
+
duan1
|
| 315 |
+
duan2
|
| 316 |
+
duan3
|
| 317 |
+
duan4
|
| 318 |
+
dui1
|
| 319 |
+
dui4
|
| 320 |
+
dun1
|
| 321 |
+
dun3
|
| 322 |
+
dun4
|
| 323 |
+
duo
|
| 324 |
+
duo1
|
| 325 |
+
duo2
|
| 326 |
+
duo3
|
| 327 |
+
duo4
|
| 328 |
+
e
|
| 329 |
+
e1
|
| 330 |
+
e2
|
| 331 |
+
e3
|
| 332 |
+
e4
|
| 333 |
+
ei2
|
| 334 |
+
en1
|
| 335 |
+
en4
|
| 336 |
+
er
|
| 337 |
+
er2
|
| 338 |
+
er3
|
| 339 |
+
er4
|
| 340 |
+
f
|
| 341 |
+
fa1
|
| 342 |
+
fa2
|
| 343 |
+
fa3
|
| 344 |
+
fa4
|
| 345 |
+
fan1
|
| 346 |
+
fan2
|
| 347 |
+
fan3
|
| 348 |
+
fan4
|
| 349 |
+
fang
|
| 350 |
+
fang1
|
| 351 |
+
fang2
|
| 352 |
+
fang3
|
| 353 |
+
fang4
|
| 354 |
+
fei1
|
| 355 |
+
fei2
|
| 356 |
+
fei3
|
| 357 |
+
fei4
|
| 358 |
+
fen1
|
| 359 |
+
fen2
|
| 360 |
+
fen3
|
| 361 |
+
fen4
|
| 362 |
+
feng1
|
| 363 |
+
feng2
|
| 364 |
+
feng3
|
| 365 |
+
feng4
|
| 366 |
+
fo2
|
| 367 |
+
fou2
|
| 368 |
+
fou3
|
| 369 |
+
fu
|
| 370 |
+
fu1
|
| 371 |
+
fu2
|
| 372 |
+
fu3
|
| 373 |
+
fu4
|
| 374 |
+
g
|
| 375 |
+
ga1
|
| 376 |
+
ga2
|
| 377 |
+
ga3
|
| 378 |
+
ga4
|
| 379 |
+
gai1
|
| 380 |
+
gai2
|
| 381 |
+
gai3
|
| 382 |
+
gai4
|
| 383 |
+
gan1
|
| 384 |
+
gan2
|
| 385 |
+
gan3
|
| 386 |
+
gan4
|
| 387 |
+
gang1
|
| 388 |
+
gang2
|
| 389 |
+
gang3
|
| 390 |
+
gang4
|
| 391 |
+
gao1
|
| 392 |
+
gao2
|
| 393 |
+
gao3
|
| 394 |
+
gao4
|
| 395 |
+
ge
|
| 396 |
+
ge1
|
| 397 |
+
ge2
|
| 398 |
+
ge3
|
| 399 |
+
ge4
|
| 400 |
+
gei2
|
| 401 |
+
gei3
|
| 402 |
+
gen1
|
| 403 |
+
gen2
|
| 404 |
+
gen3
|
| 405 |
+
gen4
|
| 406 |
+
geng1
|
| 407 |
+
geng3
|
| 408 |
+
geng4
|
| 409 |
+
gong1
|
| 410 |
+
gong3
|
| 411 |
+
gong4
|
| 412 |
+
gou1
|
| 413 |
+
gou2
|
| 414 |
+
gou3
|
| 415 |
+
gou4
|
| 416 |
+
gu
|
| 417 |
+
gu1
|
| 418 |
+
gu2
|
| 419 |
+
gu3
|
| 420 |
+
gu4
|
| 421 |
+
gua1
|
| 422 |
+
gua2
|
| 423 |
+
gua3
|
| 424 |
+
gua4
|
| 425 |
+
guai1
|
| 426 |
+
guai2
|
| 427 |
+
guai3
|
| 428 |
+
guai4
|
| 429 |
+
guan1
|
| 430 |
+
guan2
|
| 431 |
+
guan3
|
| 432 |
+
guan4
|
| 433 |
+
guang1
|
| 434 |
+
guang2
|
| 435 |
+
guang3
|
| 436 |
+
guang4
|
| 437 |
+
gui1
|
| 438 |
+
gui2
|
| 439 |
+
gui3
|
| 440 |
+
gui4
|
| 441 |
+
gun3
|
| 442 |
+
gun4
|
| 443 |
+
guo1
|
| 444 |
+
guo2
|
| 445 |
+
guo3
|
| 446 |
+
guo4
|
| 447 |
+
h
|
| 448 |
+
ha1
|
| 449 |
+
ha2
|
| 450 |
+
ha3
|
| 451 |
+
hai1
|
| 452 |
+
hai2
|
| 453 |
+
hai3
|
| 454 |
+
hai4
|
| 455 |
+
han1
|
| 456 |
+
han2
|
| 457 |
+
han3
|
| 458 |
+
han4
|
| 459 |
+
hang1
|
| 460 |
+
hang2
|
| 461 |
+
hang4
|
| 462 |
+
hao1
|
| 463 |
+
hao2
|
| 464 |
+
hao3
|
| 465 |
+
hao4
|
| 466 |
+
he1
|
| 467 |
+
he2
|
| 468 |
+
he4
|
| 469 |
+
hei1
|
| 470 |
+
hen2
|
| 471 |
+
hen3
|
| 472 |
+
hen4
|
| 473 |
+
heng1
|
| 474 |
+
heng2
|
| 475 |
+
heng4
|
| 476 |
+
hong1
|
| 477 |
+
hong2
|
| 478 |
+
hong3
|
| 479 |
+
hong4
|
| 480 |
+
hou1
|
| 481 |
+
hou2
|
| 482 |
+
hou3
|
| 483 |
+
hou4
|
| 484 |
+
hu1
|
| 485 |
+
hu2
|
| 486 |
+
hu3
|
| 487 |
+
hu4
|
| 488 |
+
hua1
|
| 489 |
+
hua2
|
| 490 |
+
hua4
|
| 491 |
+
huai2
|
| 492 |
+
huai4
|
| 493 |
+
huan1
|
| 494 |
+
huan2
|
| 495 |
+
huan3
|
| 496 |
+
huan4
|
| 497 |
+
huang1
|
| 498 |
+
huang2
|
| 499 |
+
huang3
|
| 500 |
+
huang4
|
| 501 |
+
hui1
|
| 502 |
+
hui2
|
| 503 |
+
hui3
|
| 504 |
+
hui4
|
| 505 |
+
hun1
|
| 506 |
+
hun2
|
| 507 |
+
hun4
|
| 508 |
+
huo
|
| 509 |
+
huo1
|
| 510 |
+
huo2
|
| 511 |
+
huo3
|
| 512 |
+
huo4
|
| 513 |
+
i
|
| 514 |
+
j
|
| 515 |
+
ji1
|
| 516 |
+
ji2
|
| 517 |
+
ji3
|
| 518 |
+
ji4
|
| 519 |
+
jia
|
| 520 |
+
jia1
|
| 521 |
+
jia2
|
| 522 |
+
jia3
|
| 523 |
+
jia4
|
| 524 |
+
jian1
|
| 525 |
+
jian2
|
| 526 |
+
jian3
|
| 527 |
+
jian4
|
| 528 |
+
jiang1
|
| 529 |
+
jiang2
|
| 530 |
+
jiang3
|
| 531 |
+
jiang4
|
| 532 |
+
jiao1
|
| 533 |
+
jiao2
|
| 534 |
+
jiao3
|
| 535 |
+
jiao4
|
| 536 |
+
jie1
|
| 537 |
+
jie2
|
| 538 |
+
jie3
|
| 539 |
+
jie4
|
| 540 |
+
jin1
|
| 541 |
+
jin2
|
| 542 |
+
jin3
|
| 543 |
+
jin4
|
| 544 |
+
jing1
|
| 545 |
+
jing2
|
| 546 |
+
jing3
|
| 547 |
+
jing4
|
| 548 |
+
jiong3
|
| 549 |
+
jiu1
|
| 550 |
+
jiu2
|
| 551 |
+
jiu3
|
| 552 |
+
jiu4
|
| 553 |
+
ju1
|
| 554 |
+
ju2
|
| 555 |
+
ju3
|
| 556 |
+
ju4
|
| 557 |
+
juan1
|
| 558 |
+
juan2
|
| 559 |
+
juan3
|
| 560 |
+
juan4
|
| 561 |
+
jue1
|
| 562 |
+
jue2
|
| 563 |
+
jue4
|
| 564 |
+
jun1
|
| 565 |
+
jun4
|
| 566 |
+
k
|
| 567 |
+
ka1
|
| 568 |
+
ka2
|
| 569 |
+
ka3
|
| 570 |
+
kai1
|
| 571 |
+
kai2
|
| 572 |
+
kai3
|
| 573 |
+
kai4
|
| 574 |
+
kan1
|
| 575 |
+
kan2
|
| 576 |
+
kan3
|
| 577 |
+
kan4
|
| 578 |
+
kang1
|
| 579 |
+
kang2
|
| 580 |
+
kang4
|
| 581 |
+
kao1
|
| 582 |
+
kao2
|
| 583 |
+
kao3
|
| 584 |
+
kao4
|
| 585 |
+
ke1
|
| 586 |
+
ke2
|
| 587 |
+
ke3
|
| 588 |
+
ke4
|
| 589 |
+
ken3
|
| 590 |
+
keng1
|
| 591 |
+
kong1
|
| 592 |
+
kong3
|
| 593 |
+
kong4
|
| 594 |
+
kou1
|
| 595 |
+
kou2
|
| 596 |
+
kou3
|
| 597 |
+
kou4
|
| 598 |
+
ku1
|
| 599 |
+
ku2
|
| 600 |
+
ku3
|
| 601 |
+
ku4
|
| 602 |
+
kua1
|
| 603 |
+
kua3
|
| 604 |
+
kua4
|
| 605 |
+
kuai3
|
| 606 |
+
kuai4
|
| 607 |
+
kuan1
|
| 608 |
+
kuan3
|
| 609 |
+
kuang1
|
| 610 |
+
kuang2
|
| 611 |
+
kuang4
|
| 612 |
+
kui1
|
| 613 |
+
kui2
|
| 614 |
+
kui3
|
| 615 |
+
kui4
|
| 616 |
+
kun1
|
| 617 |
+
kun3
|
| 618 |
+
kun4
|
| 619 |
+
kuo4
|
| 620 |
+
l
|
| 621 |
+
la
|
| 622 |
+
la1
|
| 623 |
+
la2
|
| 624 |
+
la3
|
| 625 |
+
la4
|
| 626 |
+
lai2
|
| 627 |
+
lai4
|
| 628 |
+
lan2
|
| 629 |
+
lan3
|
| 630 |
+
lan4
|
| 631 |
+
lang1
|
| 632 |
+
lang2
|
| 633 |
+
lang3
|
| 634 |
+
lang4
|
| 635 |
+
lao
|
| 636 |
+
lao1
|
| 637 |
+
lao2
|
| 638 |
+
lao3
|
| 639 |
+
lao4
|
| 640 |
+
le
|
| 641 |
+
le1
|
| 642 |
+
le4
|
| 643 |
+
lei
|
| 644 |
+
lei1
|
| 645 |
+
lei2
|
| 646 |
+
lei3
|
| 647 |
+
lei4
|
| 648 |
+
leng1
|
| 649 |
+
leng2
|
| 650 |
+
leng3
|
| 651 |
+
leng4
|
| 652 |
+
li
|
| 653 |
+
li1
|
| 654 |
+
li2
|
| 655 |
+
li3
|
| 656 |
+
li4
|
| 657 |
+
lia3
|
| 658 |
+
lian2
|
| 659 |
+
lian3
|
| 660 |
+
lian4
|
| 661 |
+
liang2
|
| 662 |
+
liang3
|
| 663 |
+
liang4
|
| 664 |
+
liao1
|
| 665 |
+
liao2
|
| 666 |
+
liao3
|
| 667 |
+
liao4
|
| 668 |
+
lie1
|
| 669 |
+
lie2
|
| 670 |
+
lie3
|
| 671 |
+
lie4
|
| 672 |
+
lin1
|
| 673 |
+
lin2
|
| 674 |
+
lin3
|
| 675 |
+
lin4
|
| 676 |
+
ling2
|
| 677 |
+
ling3
|
| 678 |
+
ling4
|
| 679 |
+
liu1
|
| 680 |
+
liu2
|
| 681 |
+
liu3
|
| 682 |
+
liu4
|
| 683 |
+
long1
|
| 684 |
+
long2
|
| 685 |
+
long3
|
| 686 |
+
long4
|
| 687 |
+
lou1
|
| 688 |
+
lou2
|
| 689 |
+
lou3
|
| 690 |
+
lou4
|
| 691 |
+
lu1
|
| 692 |
+
lu2
|
| 693 |
+
lu3
|
| 694 |
+
lu4
|
| 695 |
+
luan2
|
| 696 |
+
luan3
|
| 697 |
+
luan4
|
| 698 |
+
lun1
|
| 699 |
+
lun2
|
| 700 |
+
lun4
|
| 701 |
+
luo1
|
| 702 |
+
luo2
|
| 703 |
+
luo3
|
| 704 |
+
luo4
|
| 705 |
+
lv2
|
| 706 |
+
lv3
|
| 707 |
+
lv4
|
| 708 |
+
lve4
|
| 709 |
+
m
|
| 710 |
+
ma
|
| 711 |
+
ma1
|
| 712 |
+
ma2
|
| 713 |
+
ma3
|
| 714 |
+
ma4
|
| 715 |
+
mai2
|
| 716 |
+
mai3
|
| 717 |
+
mai4
|
| 718 |
+
man1
|
| 719 |
+
man2
|
| 720 |
+
man3
|
| 721 |
+
man4
|
| 722 |
+
mang2
|
| 723 |
+
mang3
|
| 724 |
+
mao1
|
| 725 |
+
mao2
|
| 726 |
+
mao3
|
| 727 |
+
mao4
|
| 728 |
+
me
|
| 729 |
+
mei2
|
| 730 |
+
mei3
|
| 731 |
+
mei4
|
| 732 |
+
men
|
| 733 |
+
men1
|
| 734 |
+
men2
|
| 735 |
+
men4
|
| 736 |
+
meng
|
| 737 |
+
meng1
|
| 738 |
+
meng2
|
| 739 |
+
meng3
|
| 740 |
+
meng4
|
| 741 |
+
mi1
|
| 742 |
+
mi2
|
| 743 |
+
mi3
|
| 744 |
+
mi4
|
| 745 |
+
mian2
|
| 746 |
+
mian3
|
| 747 |
+
mian4
|
| 748 |
+
miao1
|
| 749 |
+
miao2
|
| 750 |
+
miao3
|
| 751 |
+
miao4
|
| 752 |
+
mie1
|
| 753 |
+
mie4
|
| 754 |
+
min2
|
| 755 |
+
min3
|
| 756 |
+
ming2
|
| 757 |
+
ming3
|
| 758 |
+
ming4
|
| 759 |
+
miu4
|
| 760 |
+
mo1
|
| 761 |
+
mo2
|
| 762 |
+
mo3
|
| 763 |
+
mo4
|
| 764 |
+
mou1
|
| 765 |
+
mou2
|
| 766 |
+
mou3
|
| 767 |
+
mu2
|
| 768 |
+
mu3
|
| 769 |
+
mu4
|
| 770 |
+
n
|
| 771 |
+
n2
|
| 772 |
+
na1
|
| 773 |
+
na2
|
| 774 |
+
na3
|
| 775 |
+
na4
|
| 776 |
+
nai
|
| 777 |
+
nai3
|
| 778 |
+
nai4
|
| 779 |
+
nan1
|
| 780 |
+
nan2
|
| 781 |
+
nan3
|
| 782 |
+
nan4
|
| 783 |
+
nang1
|
| 784 |
+
nang2
|
| 785 |
+
nang3
|
| 786 |
+
nao1
|
| 787 |
+
nao2
|
| 788 |
+
nao3
|
| 789 |
+
nao4
|
| 790 |
+
ne
|
| 791 |
+
ne2
|
| 792 |
+
ne4
|
| 793 |
+
nei3
|
| 794 |
+
nei4
|
| 795 |
+
nen4
|
| 796 |
+
neng2
|
| 797 |
+
ni1
|
| 798 |
+
ni2
|
| 799 |
+
ni3
|
| 800 |
+
ni4
|
| 801 |
+
nian1
|
| 802 |
+
nian2
|
| 803 |
+
nian3
|
| 804 |
+
nian4
|
| 805 |
+
niang2
|
| 806 |
+
niang4
|
| 807 |
+
niao2
|
| 808 |
+
niao3
|
| 809 |
+
niao4
|
| 810 |
+
nie1
|
| 811 |
+
nie4
|
| 812 |
+
nin2
|
| 813 |
+
ning2
|
| 814 |
+
ning3
|
| 815 |
+
ning4
|
| 816 |
+
niu1
|
| 817 |
+
niu2
|
| 818 |
+
niu3
|
| 819 |
+
niu4
|
| 820 |
+
nong2
|
| 821 |
+
nong4
|
| 822 |
+
nou4
|
| 823 |
+
nu2
|
| 824 |
+
nu3
|
| 825 |
+
nu4
|
| 826 |
+
nuan3
|
| 827 |
+
nuo2
|
| 828 |
+
nuo4
|
| 829 |
+
nv2
|
| 830 |
+
nv3
|
| 831 |
+
nve4
|
| 832 |
+
o
|
| 833 |
+
o1
|
| 834 |
+
o2
|
| 835 |
+
ou1
|
| 836 |
+
ou2
|
| 837 |
+
ou3
|
| 838 |
+
ou4
|
| 839 |
+
p
|
| 840 |
+
pa1
|
| 841 |
+
pa2
|
| 842 |
+
pa4
|
| 843 |
+
pai1
|
| 844 |
+
pai2
|
| 845 |
+
pai3
|
| 846 |
+
pai4
|
| 847 |
+
pan1
|
| 848 |
+
pan2
|
| 849 |
+
pan4
|
| 850 |
+
pang1
|
| 851 |
+
pang2
|
| 852 |
+
pang4
|
| 853 |
+
pao1
|
| 854 |
+
pao2
|
| 855 |
+
pao3
|
| 856 |
+
pao4
|
| 857 |
+
pei1
|
| 858 |
+
pei2
|
| 859 |
+
pei4
|
| 860 |
+
pen1
|
| 861 |
+
pen2
|
| 862 |
+
pen4
|
| 863 |
+
peng1
|
| 864 |
+
peng2
|
| 865 |
+
peng3
|
| 866 |
+
peng4
|
| 867 |
+
pi1
|
| 868 |
+
pi2
|
| 869 |
+
pi3
|
| 870 |
+
pi4
|
| 871 |
+
pian1
|
| 872 |
+
pian2
|
| 873 |
+
pian4
|
| 874 |
+
piao1
|
| 875 |
+
piao2
|
| 876 |
+
piao3
|
| 877 |
+
piao4
|
| 878 |
+
pie1
|
| 879 |
+
pie2
|
| 880 |
+
pie3
|
| 881 |
+
pin1
|
| 882 |
+
pin2
|
| 883 |
+
pin3
|
| 884 |
+
pin4
|
| 885 |
+
ping1
|
| 886 |
+
ping2
|
| 887 |
+
po
|
| 888 |
+
po1
|
| 889 |
+
po2
|
| 890 |
+
po3
|
| 891 |
+
po4
|
| 892 |
+
pou1
|
| 893 |
+
pu1
|
| 894 |
+
pu2
|
| 895 |
+
pu3
|
| 896 |
+
pu4
|
| 897 |
+
q
|
| 898 |
+
qi1
|
| 899 |
+
qi2
|
| 900 |
+
qi3
|
| 901 |
+
qi4
|
| 902 |
+
qia1
|
| 903 |
+
qia3
|
| 904 |
+
qia4
|
| 905 |
+
qian1
|
| 906 |
+
qian2
|
| 907 |
+
qian3
|
| 908 |
+
qian4
|
| 909 |
+
qiang1
|
| 910 |
+
qiang2
|
| 911 |
+
qiang3
|
| 912 |
+
qiang4
|
| 913 |
+
qiao1
|
| 914 |
+
qiao2
|
| 915 |
+
qiao3
|
| 916 |
+
qiao4
|
| 917 |
+
qie1
|
| 918 |
+
qie2
|
| 919 |
+
qie3
|
| 920 |
+
qie4
|
| 921 |
+
qin1
|
| 922 |
+
qin2
|
| 923 |
+
qin3
|
| 924 |
+
qin4
|
| 925 |
+
qing1
|
| 926 |
+
qing2
|
| 927 |
+
qing3
|
| 928 |
+
qing4
|
| 929 |
+
qiong1
|
| 930 |
+
qiong2
|
| 931 |
+
qiu1
|
| 932 |
+
qiu2
|
| 933 |
+
qiu3
|
| 934 |
+
qu1
|
| 935 |
+
qu2
|
| 936 |
+
qu3
|
| 937 |
+
qu4
|
| 938 |
+
quan1
|
| 939 |
+
quan2
|
| 940 |
+
quan3
|
| 941 |
+
quan4
|
| 942 |
+
que1
|
| 943 |
+
que2
|
| 944 |
+
que4
|
| 945 |
+
qun2
|
| 946 |
+
r
|
| 947 |
+
ran2
|
| 948 |
+
ran3
|
| 949 |
+
rang
|
| 950 |
+
rang1
|
| 951 |
+
rang2
|
| 952 |
+
rang3
|
| 953 |
+
rang4
|
| 954 |
+
rao2
|
| 955 |
+
rao3
|
| 956 |
+
rao4
|
| 957 |
+
re2
|
| 958 |
+
re3
|
| 959 |
+
re4
|
| 960 |
+
ren2
|
| 961 |
+
ren3
|
| 962 |
+
ren4
|
| 963 |
+
reng1
|
| 964 |
+
reng2
|
| 965 |
+
ri4
|
| 966 |
+
rong1
|
| 967 |
+
rong2
|
| 968 |
+
rong3
|
| 969 |
+
rou2
|
| 970 |
+
rou4
|
| 971 |
+
ru2
|
| 972 |
+
ru3
|
| 973 |
+
ru4
|
| 974 |
+
ruan2
|
| 975 |
+
ruan3
|
| 976 |
+
rui3
|
| 977 |
+
rui4
|
| 978 |
+
run4
|
| 979 |
+
ruo4
|
| 980 |
+
s
|
| 981 |
+
sa1
|
| 982 |
+
sa2
|
| 983 |
+
sa3
|
| 984 |
+
sa4
|
| 985 |
+
sai1
|
| 986 |
+
sai4
|
| 987 |
+
san1
|
| 988 |
+
san2
|
| 989 |
+
san3
|
| 990 |
+
san4
|
| 991 |
+
sang1
|
| 992 |
+
sang3
|
| 993 |
+
sang4
|
| 994 |
+
sao1
|
| 995 |
+
sao2
|
| 996 |
+
sao3
|
| 997 |
+
sao4
|
| 998 |
+
se4
|
| 999 |
+
sen1
|
| 1000 |
+
seng1
|
| 1001 |
+
sha1
|
| 1002 |
+
sha2
|
| 1003 |
+
sha3
|
| 1004 |
+
sha4
|
| 1005 |
+
shai1
|
| 1006 |
+
shai2
|
| 1007 |
+
shai3
|
| 1008 |
+
shai4
|
| 1009 |
+
shan1
|
| 1010 |
+
shan3
|
| 1011 |
+
shan4
|
| 1012 |
+
shang
|
| 1013 |
+
shang1
|
| 1014 |
+
shang3
|
| 1015 |
+
shang4
|
| 1016 |
+
shao1
|
| 1017 |
+
shao2
|
| 1018 |
+
shao3
|
| 1019 |
+
shao4
|
| 1020 |
+
she1
|
| 1021 |
+
she2
|
| 1022 |
+
she3
|
| 1023 |
+
she4
|
| 1024 |
+
shei2
|
| 1025 |
+
shen1
|
| 1026 |
+
shen2
|
| 1027 |
+
shen3
|
| 1028 |
+
shen4
|
| 1029 |
+
sheng
|
| 1030 |
+
sheng1
|
| 1031 |
+
sheng2
|
| 1032 |
+
sheng3
|
| 1033 |
+
sheng4
|
| 1034 |
+
shi
|
| 1035 |
+
shi1
|
| 1036 |
+
shi2
|
| 1037 |
+
shi3
|
| 1038 |
+
shi4
|
| 1039 |
+
shou1
|
| 1040 |
+
shou2
|
| 1041 |
+
shou3
|
| 1042 |
+
shou4
|
| 1043 |
+
shu1
|
| 1044 |
+
shu2
|
| 1045 |
+
shu3
|
| 1046 |
+
shu4
|
| 1047 |
+
shua1
|
| 1048 |
+
shua2
|
| 1049 |
+
shua3
|
| 1050 |
+
shua4
|
| 1051 |
+
shuai1
|
| 1052 |
+
shuai3
|
| 1053 |
+
shuai4
|
| 1054 |
+
shuan1
|
| 1055 |
+
shuan4
|
| 1056 |
+
shuang1
|
| 1057 |
+
shuang3
|
| 1058 |
+
shui2
|
| 1059 |
+
shui3
|
| 1060 |
+
shui4
|
| 1061 |
+
shun3
|
| 1062 |
+
shun4
|
| 1063 |
+
shuo1
|
| 1064 |
+
shuo4
|
| 1065 |
+
si
|
| 1066 |
+
si1
|
| 1067 |
+
si2
|
| 1068 |
+
si3
|
| 1069 |
+
si4
|
| 1070 |
+
song1
|
| 1071 |
+
song3
|
| 1072 |
+
song4
|
| 1073 |
+
sou1
|
| 1074 |
+
sou3
|
| 1075 |
+
sou4
|
| 1076 |
+
su1
|
| 1077 |
+
su2
|
| 1078 |
+
su4
|
| 1079 |
+
suan1
|
| 1080 |
+
suan4
|
| 1081 |
+
sui1
|
| 1082 |
+
sui2
|
| 1083 |
+
sui3
|
| 1084 |
+
sui4
|
| 1085 |
+
sun1
|
| 1086 |
+
sun3
|
| 1087 |
+
suo
|
| 1088 |
+
suo1
|
| 1089 |
+
suo2
|
| 1090 |
+
suo3
|
| 1091 |
+
t
|
| 1092 |
+
ta1
|
| 1093 |
+
ta2
|
| 1094 |
+
ta3
|
| 1095 |
+
ta4
|
| 1096 |
+
tai1
|
| 1097 |
+
tai2
|
| 1098 |
+
tai4
|
| 1099 |
+
tan1
|
| 1100 |
+
tan2
|
| 1101 |
+
tan3
|
| 1102 |
+
tan4
|
| 1103 |
+
tang1
|
| 1104 |
+
tang2
|
| 1105 |
+
tang3
|
| 1106 |
+
tang4
|
| 1107 |
+
tao1
|
| 1108 |
+
tao2
|
| 1109 |
+
tao3
|
| 1110 |
+
tao4
|
| 1111 |
+
te4
|
| 1112 |
+
teng
|
| 1113 |
+
teng2
|
| 1114 |
+
ti1
|
| 1115 |
+
ti2
|
| 1116 |
+
ti3
|
| 1117 |
+
ti4
|
| 1118 |
+
tian1
|
| 1119 |
+
tian2
|
| 1120 |
+
tian3
|
| 1121 |
+
tiao1
|
| 1122 |
+
tiao2
|
| 1123 |
+
tiao3
|
| 1124 |
+
tiao4
|
| 1125 |
+
tie1
|
| 1126 |
+
tie2
|
| 1127 |
+
tie3
|
| 1128 |
+
tie4
|
| 1129 |
+
ting1
|
| 1130 |
+
ting2
|
| 1131 |
+
ting3
|
| 1132 |
+
tong1
|
| 1133 |
+
tong2
|
| 1134 |
+
tong3
|
| 1135 |
+
tong4
|
| 1136 |
+
tou
|
| 1137 |
+
tou1
|
| 1138 |
+
tou2
|
| 1139 |
+
tou4
|
| 1140 |
+
tu1
|
| 1141 |
+
tu2
|
| 1142 |
+
tu3
|
| 1143 |
+
tu4
|
| 1144 |
+
tuan1
|
| 1145 |
+
tuan2
|
| 1146 |
+
tui1
|
| 1147 |
+
tui2
|
| 1148 |
+
tui3
|
| 1149 |
+
tui4
|
| 1150 |
+
tun1
|
| 1151 |
+
tun2
|
| 1152 |
+
tun4
|
| 1153 |
+
tuo1
|
| 1154 |
+
tuo2
|
| 1155 |
+
tuo3
|
| 1156 |
+
tuo4
|
| 1157 |
+
u
|
| 1158 |
+
v
|
| 1159 |
+
w
|
| 1160 |
+
wa
|
| 1161 |
+
wa1
|
| 1162 |
+
wa2
|
| 1163 |
+
wa3
|
| 1164 |
+
wa4
|
| 1165 |
+
wai1
|
| 1166 |
+
wai3
|
| 1167 |
+
wai4
|
| 1168 |
+
wan1
|
| 1169 |
+
wan2
|
| 1170 |
+
wan3
|
| 1171 |
+
wan4
|
| 1172 |
+
wang1
|
| 1173 |
+
wang2
|
| 1174 |
+
wang3
|
| 1175 |
+
wang4
|
| 1176 |
+
wei1
|
| 1177 |
+
wei2
|
| 1178 |
+
wei3
|
| 1179 |
+
wei4
|
| 1180 |
+
wen1
|
| 1181 |
+
wen2
|
| 1182 |
+
wen3
|
| 1183 |
+
wen4
|
| 1184 |
+
weng1
|
| 1185 |
+
weng4
|
| 1186 |
+
wo1
|
| 1187 |
+
wo2
|
| 1188 |
+
wo3
|
| 1189 |
+
wo4
|
| 1190 |
+
wu1
|
| 1191 |
+
wu2
|
| 1192 |
+
wu3
|
| 1193 |
+
wu4
|
| 1194 |
+
x
|
| 1195 |
+
xi
|
| 1196 |
+
xi1
|
| 1197 |
+
xi2
|
| 1198 |
+
xi3
|
| 1199 |
+
xi4
|
| 1200 |
+
xia1
|
| 1201 |
+
xia2
|
| 1202 |
+
xia4
|
| 1203 |
+
xian1
|
| 1204 |
+
xian2
|
| 1205 |
+
xian3
|
| 1206 |
+
xian4
|
| 1207 |
+
xiang1
|
| 1208 |
+
xiang2
|
| 1209 |
+
xiang3
|
| 1210 |
+
xiang4
|
| 1211 |
+
xiao1
|
| 1212 |
+
xiao2
|
| 1213 |
+
xiao3
|
| 1214 |
+
xiao4
|
| 1215 |
+
xie1
|
| 1216 |
+
xie2
|
| 1217 |
+
xie3
|
| 1218 |
+
xie4
|
| 1219 |
+
xin1
|
| 1220 |
+
xin2
|
| 1221 |
+
xin4
|
| 1222 |
+
xing1
|
| 1223 |
+
xing2
|
| 1224 |
+
xing3
|
| 1225 |
+
xing4
|
| 1226 |
+
xiong1
|
| 1227 |
+
xiong2
|
| 1228 |
+
xiu1
|
| 1229 |
+
xiu3
|
| 1230 |
+
xiu4
|
| 1231 |
+
xu
|
| 1232 |
+
xu1
|
| 1233 |
+
xu2
|
| 1234 |
+
xu3
|
| 1235 |
+
xu4
|
| 1236 |
+
xuan1
|
| 1237 |
+
xuan2
|
| 1238 |
+
xuan3
|
| 1239 |
+
xuan4
|
| 1240 |
+
xue1
|
| 1241 |
+
xue2
|
| 1242 |
+
xue3
|
| 1243 |
+
xue4
|
| 1244 |
+
xun1
|
| 1245 |
+
xun2
|
| 1246 |
+
xun4
|
| 1247 |
+
y
|
| 1248 |
+
ya
|
| 1249 |
+
ya1
|
| 1250 |
+
ya2
|
| 1251 |
+
ya3
|
| 1252 |
+
ya4
|
| 1253 |
+
yan1
|
| 1254 |
+
yan2
|
| 1255 |
+
yan3
|
| 1256 |
+
yan4
|
| 1257 |
+
yang1
|
| 1258 |
+
yang2
|
| 1259 |
+
yang3
|
| 1260 |
+
yang4
|
| 1261 |
+
yao1
|
| 1262 |
+
yao2
|
| 1263 |
+
yao3
|
| 1264 |
+
yao4
|
| 1265 |
+
ye1
|
| 1266 |
+
ye2
|
| 1267 |
+
ye3
|
| 1268 |
+
ye4
|
| 1269 |
+
yi
|
| 1270 |
+
yi1
|
| 1271 |
+
yi2
|
| 1272 |
+
yi3
|
| 1273 |
+
yi4
|
| 1274 |
+
yin1
|
| 1275 |
+
yin2
|
| 1276 |
+
yin3
|
| 1277 |
+
yin4
|
| 1278 |
+
ying1
|
| 1279 |
+
ying2
|
| 1280 |
+
ying3
|
| 1281 |
+
ying4
|
| 1282 |
+
yo1
|
| 1283 |
+
yong1
|
| 1284 |
+
yong2
|
| 1285 |
+
yong3
|
| 1286 |
+
yong4
|
| 1287 |
+
you1
|
| 1288 |
+
you2
|
| 1289 |
+
you3
|
| 1290 |
+
you4
|
| 1291 |
+
yu1
|
| 1292 |
+
yu2
|
| 1293 |
+
yu3
|
| 1294 |
+
yu4
|
| 1295 |
+
yuan1
|
| 1296 |
+
yuan2
|
| 1297 |
+
yuan3
|
| 1298 |
+
yuan4
|
| 1299 |
+
yue1
|
| 1300 |
+
yue4
|
| 1301 |
+
yun1
|
| 1302 |
+
yun2
|
| 1303 |
+
yun3
|
| 1304 |
+
yun4
|
| 1305 |
+
z
|
| 1306 |
+
za1
|
| 1307 |
+
za2
|
| 1308 |
+
za3
|
| 1309 |
+
zai1
|
| 1310 |
+
zai3
|
| 1311 |
+
zai4
|
| 1312 |
+
zan1
|
| 1313 |
+
zan2
|
| 1314 |
+
zan3
|
| 1315 |
+
zan4
|
| 1316 |
+
zang1
|
| 1317 |
+
zang4
|
| 1318 |
+
zao1
|
| 1319 |
+
zao2
|
| 1320 |
+
zao3
|
| 1321 |
+
zao4
|
| 1322 |
+
ze2
|
| 1323 |
+
ze4
|
| 1324 |
+
zei2
|
| 1325 |
+
zen3
|
| 1326 |
+
zeng1
|
| 1327 |
+
zeng4
|
| 1328 |
+
zha1
|
| 1329 |
+
zha2
|
| 1330 |
+
zha3
|
| 1331 |
+
zha4
|
| 1332 |
+
zhai1
|
| 1333 |
+
zhai2
|
| 1334 |
+
zhai3
|
| 1335 |
+
zhai4
|
| 1336 |
+
zhan1
|
| 1337 |
+
zhan2
|
| 1338 |
+
zhan3
|
| 1339 |
+
zhan4
|
| 1340 |
+
zhang1
|
| 1341 |
+
zhang2
|
| 1342 |
+
zhang3
|
| 1343 |
+
zhang4
|
| 1344 |
+
zhao1
|
| 1345 |
+
zhao2
|
| 1346 |
+
zhao3
|
| 1347 |
+
zhao4
|
| 1348 |
+
zhe
|
| 1349 |
+
zhe1
|
| 1350 |
+
zhe2
|
| 1351 |
+
zhe3
|
| 1352 |
+
zhe4
|
| 1353 |
+
zhen1
|
| 1354 |
+
zhen2
|
| 1355 |
+
zhen3
|
| 1356 |
+
zhen4
|
| 1357 |
+
zheng1
|
| 1358 |
+
zheng2
|
| 1359 |
+
zheng3
|
| 1360 |
+
zheng4
|
| 1361 |
+
zhi1
|
| 1362 |
+
zhi2
|
| 1363 |
+
zhi3
|
| 1364 |
+
zhi4
|
| 1365 |
+
zhong1
|
| 1366 |
+
zhong2
|
| 1367 |
+
zhong3
|
| 1368 |
+
zhong4
|
| 1369 |
+
zhou1
|
| 1370 |
+
zhou2
|
| 1371 |
+
zhou3
|
| 1372 |
+
zhou4
|
| 1373 |
+
zhu1
|
| 1374 |
+
zhu2
|
| 1375 |
+
zhu3
|
| 1376 |
+
zhu4
|
| 1377 |
+
zhua1
|
| 1378 |
+
zhua3
|
| 1379 |
+
zhuai1
|
| 1380 |
+
zhuai3
|
| 1381 |
+
zhuai4
|
| 1382 |
+
zhuan1
|
| 1383 |
+
zhuan2
|
| 1384 |
+
zhuan3
|
| 1385 |
+
zhuan4
|
| 1386 |
+
zhuang1
|
| 1387 |
+
zhuang4
|
| 1388 |
+
zhui1
|
| 1389 |
+
zhui4
|
| 1390 |
+
zhun1
|
| 1391 |
+
zhun2
|
| 1392 |
+
zhun3
|
| 1393 |
+
zhuo1
|
| 1394 |
+
zhuo2
|
| 1395 |
+
zi
|
| 1396 |
+
zi1
|
| 1397 |
+
zi2
|
| 1398 |
+
zi3
|
| 1399 |
+
zi4
|
| 1400 |
+
zong1
|
| 1401 |
+
zong2
|
| 1402 |
+
zong3
|
| 1403 |
+
zong4
|
| 1404 |
+
zou1
|
| 1405 |
+
zou2
|
| 1406 |
+
zou3
|
| 1407 |
+
zou4
|
| 1408 |
+
zu1
|
| 1409 |
+
zu2
|
| 1410 |
+
zu3
|
| 1411 |
+
zuan1
|
| 1412 |
+
zuan3
|
| 1413 |
+
zuan4
|
| 1414 |
+
zui2
|
| 1415 |
+
zui3
|
| 1416 |
+
zui4
|
| 1417 |
+
zun1
|
| 1418 |
+
zuo
|
| 1419 |
+
zuo1
|
| 1420 |
+
zuo2
|
| 1421 |
+
zuo3
|
| 1422 |
+
zuo4
|
| 1423 |
+
{
|
| 1424 |
+
~
|
| 1425 |
+
¡
|
| 1426 |
+
¢
|
| 1427 |
+
£
|
| 1428 |
+
¥
|
| 1429 |
+
§
|
| 1430 |
+
¨
|
| 1431 |
+
©
|
| 1432 |
+
«
|
| 1433 |
+
®
|
| 1434 |
+
¯
|
| 1435 |
+
°
|
| 1436 |
+
±
|
| 1437 |
+
²
|
| 1438 |
+
³
|
| 1439 |
+
´
|
| 1440 |
+
µ
|
| 1441 |
+
·
|
| 1442 |
+
¹
|
| 1443 |
+
º
|
| 1444 |
+
»
|
| 1445 |
+
¼
|
| 1446 |
+
½
|
| 1447 |
+
¾
|
| 1448 |
+
¿
|
| 1449 |
+
À
|
| 1450 |
+
Á
|
| 1451 |
+
Â
|
| 1452 |
+
Ã
|
| 1453 |
+
Ä
|
| 1454 |
+
Å
|
| 1455 |
+
Æ
|
| 1456 |
+
Ç
|
| 1457 |
+
È
|
| 1458 |
+
É
|
| 1459 |
+
Ê
|
| 1460 |
+
Í
|
| 1461 |
+
Î
|
| 1462 |
+
Ñ
|
| 1463 |
+
Ó
|
| 1464 |
+
Ö
|
| 1465 |
+
×
|
| 1466 |
+
Ø
|
| 1467 |
+
Ú
|
| 1468 |
+
Ü
|
| 1469 |
+
Ý
|
| 1470 |
+
Þ
|
| 1471 |
+
ß
|
| 1472 |
+
à
|
| 1473 |
+
á
|
| 1474 |
+
â
|
| 1475 |
+
ã
|
| 1476 |
+
ä
|
| 1477 |
+
å
|
| 1478 |
+
æ
|
| 1479 |
+
ç
|
| 1480 |
+
è
|
| 1481 |
+
é
|
| 1482 |
+
ê
|
| 1483 |
+
ë
|
| 1484 |
+
ì
|
| 1485 |
+
í
|
| 1486 |
+
î
|
| 1487 |
+
ï
|
| 1488 |
+
ð
|
| 1489 |
+
ñ
|
| 1490 |
+
ò
|
| 1491 |
+
ó
|
| 1492 |
+
ô
|
| 1493 |
+
õ
|
| 1494 |
+
ö
|
| 1495 |
+
ø
|
| 1496 |
+
ù
|
| 1497 |
+
ú
|
| 1498 |
+
û
|
| 1499 |
+
ü
|
| 1500 |
+
ý
|
| 1501 |
+
Ā
|
| 1502 |
+
ā
|
| 1503 |
+
ă
|
| 1504 |
+
ą
|
| 1505 |
+
ć
|
| 1506 |
+
Č
|
| 1507 |
+
č
|
| 1508 |
+
Đ
|
| 1509 |
+
đ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1578 |
+
ʿ
|
| 1579 |
+
ˈ
|
| 1580 |
+
ː
|
| 1581 |
+
˙
|
| 1582 |
+
˜
|
| 1583 |
+
ˢ
|
| 1584 |
+
́
|
| 1585 |
+
̅
|
| 1586 |
+
Α
|
| 1587 |
+
Β
|
| 1588 |
+
Δ
|
| 1589 |
+
Ε
|
| 1590 |
+
Θ
|
| 1591 |
+
Κ
|
| 1592 |
+
Λ
|
| 1593 |
+
Μ
|
| 1594 |
+
Ξ
|
| 1595 |
+
Π
|
| 1596 |
+
Σ
|
| 1597 |
+
Τ
|
| 1598 |
+
Φ
|
| 1599 |
+
Χ
|
| 1600 |
+
Ψ
|
| 1601 |
+
Ω
|
| 1602 |
+
ά
|
| 1603 |
+
έ
|
| 1604 |
+
ή
|
| 1605 |
+
ί
|
| 1606 |
+
α
|
| 1607 |
+
β
|
| 1608 |
+
γ
|
| 1609 |
+
δ
|
| 1610 |
+
ε
|
| 1611 |
+
ζ
|
| 1612 |
+
η
|
| 1613 |
+
θ
|
| 1614 |
+
ι
|
| 1615 |
+
κ
|
| 1616 |
+
λ
|
| 1617 |
+
μ
|
| 1618 |
+
ν
|
| 1619 |
+
ξ
|
| 1620 |
+
ο
|
| 1621 |
+
π
|
| 1622 |
+
ρ
|
| 1623 |
+
ς
|
| 1624 |
+
σ
|
| 1625 |
+
τ
|
| 1626 |
+
υ
|
| 1627 |
+
φ
|
| 1628 |
+
χ
|
| 1629 |
+
ψ
|
| 1630 |
+
ω
|
| 1631 |
+
ϊ
|
| 1632 |
+
ό
|
| 1633 |
+
ύ
|
| 1634 |
+
ώ
|
| 1635 |
+
ϕ
|
| 1636 |
+
ϵ
|
| 1637 |
+
Ё
|
| 1638 |
+
А
|
| 1639 |
+
Б
|
| 1640 |
+
В
|
| 1641 |
+
Г
|
| 1642 |
+
Д
|
| 1643 |
+
Е
|
| 1644 |
+
Ж
|
| 1645 |
+
З
|
| 1646 |
+
И
|
| 1647 |
+
Й
|
| 1648 |
+
К
|
| 1649 |
+
Л
|
| 1650 |
+
М
|
| 1651 |
+
Н
|
| 1652 |
+
О
|
| 1653 |
+
П
|
| 1654 |
+
Р
|
| 1655 |
+
С
|
| 1656 |
+
Т
|
| 1657 |
+
У
|
| 1658 |
+
Ф
|
| 1659 |
+
Х
|
| 1660 |
+
Ц
|
| 1661 |
+
Ч
|
| 1662 |
+
Ш
|
| 1663 |
+
Щ
|
| 1664 |
+
Ы
|
| 1665 |
+
Ь
|
| 1666 |
+
Э
|
| 1667 |
+
Ю
|
| 1668 |
+
Я
|
| 1669 |
+
а
|
| 1670 |
+
б
|
| 1671 |
+
в
|
| 1672 |
+
г
|
| 1673 |
+
д
|
| 1674 |
+
е
|
| 1675 |
+
ж
|
| 1676 |
+
з
|
| 1677 |
+
и
|
| 1678 |
+
й
|
| 1679 |
+
к
|
| 1680 |
+
л
|
| 1681 |
+
м
|
| 1682 |
+
н
|
| 1683 |
+
о
|
| 1684 |
+
п
|
| 1685 |
+
р
|
| 1686 |
+
с
|
| 1687 |
+
т
|
| 1688 |
+
у
|
| 1689 |
+
ф
|
| 1690 |
+
х
|
| 1691 |
+
ц
|
| 1692 |
+
ч
|
| 1693 |
+
ш
|
| 1694 |
+
щ
|
| 1695 |
+
ъ
|
| 1696 |
+
ы
|
| 1697 |
+
ь
|
| 1698 |
+
э
|
| 1699 |
+
ю
|
| 1700 |
+
я
|
| 1701 |
+
ё
|
| 1702 |
+
і
|
| 1703 |
+
ְ
|
| 1704 |
+
ִ
|
| 1705 |
+
ֵ
|
| 1706 |
+
ֶ
|
| 1707 |
+
ַ
|
| 1708 |
+
ָ
|
| 1709 |
+
ֹ
|
| 1710 |
+
ּ
|
| 1711 |
+
־
|
| 1712 |
+
ׁ
|
| 1713 |
+
א
|
| 1714 |
+
ב
|
| 1715 |
+
ג
|
| 1716 |
+
ד
|
| 1717 |
+
ה
|
| 1718 |
+
ו
|
| 1719 |
+
ז
|
| 1720 |
+
ח
|
| 1721 |
+
ט
|
| 1722 |
+
י
|
| 1723 |
+
כ
|
| 1724 |
+
ל
|
| 1725 |
+
ם
|
| 1726 |
+
מ
|
| 1727 |
+
ן
|
| 1728 |
+
נ
|
| 1729 |
+
ס
|
| 1730 |
+
ע
|
| 1731 |
+
פ
|
| 1732 |
+
ק
|
| 1733 |
+
ר
|
| 1734 |
+
ש
|
| 1735 |
+
ת
|
| 1736 |
+
أ
|
| 1737 |
+
ب
|
| 1738 |
+
ة
|
| 1739 |
+
ت
|
| 1740 |
+
ج
|
| 1741 |
+
ح
|
| 1742 |
+
د
|
| 1743 |
+
ر
|
| 1744 |
+
ز
|
| 1745 |
+
س
|
| 1746 |
+
ص
|
| 1747 |
+
ط
|
| 1748 |
+
ع
|
| 1749 |
+
ق
|
| 1750 |
+
ك
|
| 1751 |
+
ل
|
| 1752 |
+
م
|
| 1753 |
+
ن
|
| 1754 |
+
ه
|
| 1755 |
+
و
|
| 1756 |
+
ي
|
| 1757 |
+
َ
|
| 1758 |
+
ُ
|
| 1759 |
+
ِ
|
| 1760 |
+
ْ
|
| 1761 |
+
ก
|
| 1762 |
+
ข
|
| 1763 |
+
ง
|
| 1764 |
+
จ
|
| 1765 |
+
ต
|
| 1766 |
+
ท
|
| 1767 |
+
น
|
| 1768 |
+
ป
|
| 1769 |
+
ย
|
| 1770 |
+
ร
|
| 1771 |
+
ว
|
| 1772 |
+
ส
|
| 1773 |
+
ห
|
| 1774 |
+
อ
|
| 1775 |
+
ฮ
|
| 1776 |
+
ั
|
| 1777 |
+
า
|
| 1778 |
+
ี
|
| 1779 |
+
ึ
|
| 1780 |
+
โ
|
| 1781 |
+
ใ
|
| 1782 |
+
ไ
|
| 1783 |
+
่
|
| 1784 |
+
้
|
| 1785 |
+
์
|
| 1786 |
+
ḍ
|
| 1787 |
+
Ḥ
|
| 1788 |
+
ḥ
|
| 1789 |
+
ṁ
|
| 1790 |
+
ṃ
|
| 1791 |
+
ṅ
|
| 1792 |
+
ṇ
|
| 1793 |
+
Ṛ
|
| 1794 |
+
ṛ
|
| 1795 |
+
Ṣ
|
| 1796 |
+
ṣ
|
| 1797 |
+
Ṭ
|
| 1798 |
+
ṭ
|
| 1799 |
+
ạ
|
| 1800 |
+
ả
|
| 1801 |
+
Ấ
|
| 1802 |
+
ấ
|
| 1803 |
+
ầ
|
| 1804 |
+
ậ
|
| 1805 |
+
ắ
|
| 1806 |
+
ằ
|
| 1807 |
+
ẻ
|
| 1808 |
+
ẽ
|
| 1809 |
+
ế
|
| 1810 |
+
ề
|
| 1811 |
+
ể
|
| 1812 |
+
ễ
|
| 1813 |
+
ệ
|
| 1814 |
+
ị
|
| 1815 |
+
ọ
|
| 1816 |
+
ỏ
|
| 1817 |
+
ố
|
| 1818 |
+
ồ
|
| 1819 |
+
ộ
|
| 1820 |
+
ớ
|
| 1821 |
+
ờ
|
| 1822 |
+
ở
|
| 1823 |
+
ụ
|
| 1824 |
+
ủ
|
| 1825 |
+
ứ
|
| 1826 |
+
ữ
|
| 1827 |
+
ἀ
|
| 1828 |
+
ἁ
|
| 1829 |
+
Ἀ
|
| 1830 |
+
ἐ
|
| 1831 |
+
��
|
| 1832 |
+
ἰ
|
| 1833 |
+
ἱ
|
| 1834 |
+
ὀ
|
| 1835 |
+
ὁ
|
| 1836 |
+
ὐ
|
| 1837 |
+
ὲ
|
| 1838 |
+
ὸ
|
| 1839 |
+
ᾶ
|
| 1840 |
+
᾽
|
| 1841 |
+
ῆ
|
| 1842 |
+
ῇ
|
| 1843 |
+
ῶ
|
| 1844 |
+
|
| 1845 |
+
‑
|
| 1846 |
+
‒
|
| 1847 |
+
–
|
| 1848 |
+
—
|
| 1849 |
+
―
|
| 1850 |
+
‖
|
| 1851 |
+
†
|
| 1852 |
+
‡
|
| 1853 |
+
•
|
| 1854 |
+
…
|
| 1855 |
+
‧
|
| 1856 |
+
|
| 1857 |
+
′
|
| 1858 |
+
″
|
| 1859 |
+
⁄
|
| 1860 |
+
|
| 1861 |
+
⁰
|
| 1862 |
+
⁴
|
| 1863 |
+
⁵
|
| 1864 |
+
⁶
|
| 1865 |
+
⁷
|
| 1866 |
+
⁸
|
| 1867 |
+
⁹
|
| 1868 |
+
₁
|
| 1869 |
+
₂
|
| 1870 |
+
₃
|
| 1871 |
+
€
|
| 1872 |
+
₱
|
| 1873 |
+
₹
|
| 1874 |
+
₽
|
| 1875 |
+
℃
|
| 1876 |
+
ℏ
|
| 1877 |
+
ℓ
|
| 1878 |
+
№
|
| 1879 |
+
ℝ
|
| 1880 |
+
™
|
| 1881 |
+
⅓
|
| 1882 |
+
⅔
|
| 1883 |
+
⅛
|
| 1884 |
+
→
|
| 1885 |
+
∂
|
| 1886 |
+
∈
|
| 1887 |
+
∑
|
| 1888 |
+
−
|
| 1889 |
+
∗
|
| 1890 |
+
√
|
| 1891 |
+
∞
|
| 1892 |
+
∫
|
| 1893 |
+
≈
|
| 1894 |
+
≠
|
| 1895 |
+
≡
|
| 1896 |
+
≤
|
| 1897 |
+
≥
|
| 1898 |
+
⋅
|
| 1899 |
+
⋯
|
| 1900 |
+
█
|
| 1901 |
+
♪
|
| 1902 |
+
⟨
|
| 1903 |
+
⟩
|
| 1904 |
+
、
|
| 1905 |
+
。
|
| 1906 |
+
《
|
| 1907 |
+
》
|
| 1908 |
+
「
|
| 1909 |
+
」
|
| 1910 |
+
【
|
| 1911 |
+
】
|
| 1912 |
+
あ
|
| 1913 |
+
う
|
| 1914 |
+
え
|
| 1915 |
+
お
|
| 1916 |
+
か
|
| 1917 |
+
が
|
| 1918 |
+
き
|
| 1919 |
+
ぎ
|
| 1920 |
+
く
|
| 1921 |
+
ぐ
|
| 1922 |
+
け
|
| 1923 |
+
げ
|
| 1924 |
+
こ
|
| 1925 |
+
ご
|
| 1926 |
+
さ
|
| 1927 |
+
し
|
| 1928 |
+
じ
|
| 1929 |
+
す
|
| 1930 |
+
ず
|
| 1931 |
+
せ
|
| 1932 |
+
ぜ
|
| 1933 |
+
そ
|
| 1934 |
+
ぞ
|
| 1935 |
+
た
|
| 1936 |
+
だ
|
| 1937 |
+
ち
|
| 1938 |
+
っ
|
| 1939 |
+
つ
|
| 1940 |
+
で
|
| 1941 |
+
と
|
| 1942 |
+
ど
|
| 1943 |
+
な
|
| 1944 |
+
に
|
| 1945 |
+
ね
|
| 1946 |
+
の
|
| 1947 |
+
は
|
| 1948 |
+
ば
|
| 1949 |
+
ひ
|
| 1950 |
+
ぶ
|
| 1951 |
+
へ
|
| 1952 |
+
べ
|
| 1953 |
+
ま
|
| 1954 |
+
み
|
| 1955 |
+
む
|
| 1956 |
+
め
|
| 1957 |
+
も
|
| 1958 |
+
ゃ
|
| 1959 |
+
や
|
| 1960 |
+
ゆ
|
| 1961 |
+
ょ
|
| 1962 |
+
よ
|
| 1963 |
+
ら
|
| 1964 |
+
り
|
| 1965 |
+
る
|
| 1966 |
+
れ
|
| 1967 |
+
ろ
|
| 1968 |
+
わ
|
| 1969 |
+
を
|
| 1970 |
+
ん
|
| 1971 |
+
ァ
|
| 1972 |
+
ア
|
| 1973 |
+
ィ
|
| 1974 |
+
イ
|
| 1975 |
+
ウ
|
| 1976 |
+
ェ
|
| 1977 |
+
エ
|
| 1978 |
+
オ
|
| 1979 |
+
カ
|
| 1980 |
+
ガ
|
| 1981 |
+
キ
|
| 1982 |
+
ク
|
| 1983 |
+
ケ
|
| 1984 |
+
ゲ
|
| 1985 |
+
コ
|
| 1986 |
+
ゴ
|
| 1987 |
+
サ
|
| 1988 |
+
ザ
|
| 1989 |
+
シ
|
| 1990 |
+
ジ
|
| 1991 |
+
ス
|
| 1992 |
+
ズ
|
| 1993 |
+
セ
|
| 1994 |
+
ゾ
|
| 1995 |
+
タ
|
| 1996 |
+
ダ
|
| 1997 |
+
チ
|
| 1998 |
+
ッ
|
| 1999 |
+
ツ
|
| 2000 |
+
テ
|
| 2001 |
+
デ
|
| 2002 |
+
ト
|
| 2003 |
+
ド
|
| 2004 |
+
ナ
|
| 2005 |
+
ニ
|
| 2006 |
+
ネ
|
| 2007 |
+
ノ
|
| 2008 |
+
バ
|
| 2009 |
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
+
갓
|
| 2076 |
+
갔
|
| 2077 |
+
강
|
| 2078 |
+
같
|
| 2079 |
+
개
|
| 2080 |
+
거
|
| 2081 |
+
건
|
| 2082 |
+
걸
|
| 2083 |
+
겁
|
| 2084 |
+
것
|
| 2085 |
+
겉
|
| 2086 |
+
게
|
| 2087 |
+
겠
|
| 2088 |
+
겨
|
| 2089 |
+
결
|
| 2090 |
+
겼
|
| 2091 |
+
경
|
| 2092 |
+
계
|
| 2093 |
+
고
|
| 2094 |
+
곤
|
| 2095 |
+
골
|
| 2096 |
+
곱
|
| 2097 |
+
공
|
| 2098 |
+
과
|
| 2099 |
+
관
|
| 2100 |
+
광
|
| 2101 |
+
교
|
| 2102 |
+
구
|
| 2103 |
+
국
|
| 2104 |
+
굴
|
| 2105 |
+
귀
|
| 2106 |
+
귄
|
| 2107 |
+
그
|
| 2108 |
+
근
|
| 2109 |
+
글
|
| 2110 |
+
금
|
| 2111 |
+
기
|
| 2112 |
+
긴
|
| 2113 |
+
길
|
| 2114 |
+
까
|
| 2115 |
+
깍
|
| 2116 |
+
깔
|
| 2117 |
+
깜
|
| 2118 |
+
깨
|
| 2119 |
+
께
|
| 2120 |
+
꼬
|
| 2121 |
+
꼭
|
| 2122 |
+
꽃
|
| 2123 |
+
꾸
|
| 2124 |
+
꿔
|
| 2125 |
+
끔
|
| 2126 |
+
끗
|
| 2127 |
+
끝
|
| 2128 |
+
끼
|
| 2129 |
+
나
|
| 2130 |
+
난
|
| 2131 |
+
날
|
| 2132 |
+
남
|
| 2133 |
+
납
|
| 2134 |
+
내
|
| 2135 |
+
냐
|
| 2136 |
+
냥
|
| 2137 |
+
너
|
| 2138 |
+
넘
|
| 2139 |
+
넣
|
| 2140 |
+
네
|
| 2141 |
+
녁
|
| 2142 |
+
년
|
| 2143 |
+
녕
|
| 2144 |
+
노
|
| 2145 |
+
녹
|
| 2146 |
+
놀
|
| 2147 |
+
누
|
| 2148 |
+
눈
|
| 2149 |
+
느
|
| 2150 |
+
는
|
| 2151 |
+
늘
|
| 2152 |
+
니
|
| 2153 |
+
님
|
| 2154 |
+
닙
|
| 2155 |
+
다
|
| 2156 |
+
닥
|
| 2157 |
+
단
|
| 2158 |
+
달
|
| 2159 |
+
닭
|
| 2160 |
+
당
|
| 2161 |
+
대
|
| 2162 |
+
더
|
| 2163 |
+
덕
|
| 2164 |
+
던
|
| 2165 |
+
덥
|
| 2166 |
+
데
|
| 2167 |
+
도
|
| 2168 |
+
독
|
| 2169 |
+
동
|
| 2170 |
+
돼
|
| 2171 |
+
됐
|
| 2172 |
+
되
|
| 2173 |
+
된
|
| 2174 |
+
될
|
| 2175 |
+
두
|
| 2176 |
+
둑
|
| 2177 |
+
둥
|
| 2178 |
+
드
|
| 2179 |
+
들
|
| 2180 |
+
등
|
| 2181 |
+
디
|
| 2182 |
+
따
|
| 2183 |
+
딱
|
| 2184 |
+
딸
|
| 2185 |
+
땅
|
| 2186 |
+
때
|
| 2187 |
+
떤
|
| 2188 |
+
떨
|
| 2189 |
+
떻
|
| 2190 |
+
또
|
| 2191 |
+
똑
|
| 2192 |
+
뚱
|
| 2193 |
+
뛰
|
| 2194 |
+
뜻
|
| 2195 |
+
띠
|
| 2196 |
+
라
|
| 2197 |
+
락
|
| 2198 |
+
란
|
| 2199 |
+
람
|
| 2200 |
+
랍
|
| 2201 |
+
랑
|
| 2202 |
+
래
|
| 2203 |
+
랜
|
| 2204 |
+
러
|
| 2205 |
+
런
|
| 2206 |
+
럼
|
| 2207 |
+
렇
|
| 2208 |
+
레
|
| 2209 |
+
려
|
| 2210 |
+
력
|
| 2211 |
+
렵
|
| 2212 |
+
렸
|
| 2213 |
+
로
|
| 2214 |
+
록
|
| 2215 |
+
롬
|
| 2216 |
+
루
|
| 2217 |
+
르
|
| 2218 |
+
른
|
| 2219 |
+
를
|
| 2220 |
+
름
|
| 2221 |
+
릉
|
| 2222 |
+
리
|
| 2223 |
+
릴
|
| 2224 |
+
림
|
| 2225 |
+
마
|
| 2226 |
+
막
|
| 2227 |
+
만
|
| 2228 |
+
많
|
| 2229 |
+
말
|
| 2230 |
+
맑
|
| 2231 |
+
맙
|
| 2232 |
+
맛
|
| 2233 |
+
매
|
| 2234 |
+
머
|
| 2235 |
+
먹
|
| 2236 |
+
멍
|
| 2237 |
+
메
|
| 2238 |
+
면
|
| 2239 |
+
명
|
| 2240 |
+
몇
|
| 2241 |
+
모
|
| 2242 |
+
목
|
| 2243 |
+
몸
|
| 2244 |
+
못
|
| 2245 |
+
무
|
| 2246 |
+
문
|
| 2247 |
+
물
|
| 2248 |
+
뭐
|
| 2249 |
+
뭘
|
| 2250 |
+
미
|
| 2251 |
+
민
|
| 2252 |
+
밌
|
| 2253 |
+
밑
|
| 2254 |
+
바
|
| 2255 |
+
박
|
| 2256 |
+
밖
|
| 2257 |
+
반
|
| 2258 |
+
받
|
| 2259 |
+
발
|
| 2260 |
+
밤
|
| 2261 |
+
밥
|
| 2262 |
+
방
|
| 2263 |
+
배
|
| 2264 |
+
백
|
| 2265 |
+
밸
|
| 2266 |
+
뱀
|
| 2267 |
+
버
|
| 2268 |
+
번
|
| 2269 |
+
벌
|
| 2270 |
+
벚
|
| 2271 |
+
베
|
| 2272 |
+
벼
|
| 2273 |
+
벽
|
| 2274 |
+
별
|
| 2275 |
+
병
|
| 2276 |
+
보
|
| 2277 |
+
복
|
| 2278 |
+
본
|
| 2279 |
+
볼
|
| 2280 |
+
봐
|
| 2281 |
+
봤
|
| 2282 |
+
부
|
| 2283 |
+
분
|
| 2284 |
+
불
|
| 2285 |
+
비
|
| 2286 |
+
빔
|
| 2287 |
+
빛
|
| 2288 |
+
빠
|
| 2289 |
+
빨
|
| 2290 |
+
뼈
|
| 2291 |
+
뽀
|
| 2292 |
+
뿅
|
| 2293 |
+
쁘
|
| 2294 |
+
사
|
| 2295 |
+
산
|
| 2296 |
+
살
|
| 2297 |
+
삼
|
| 2298 |
+
샀
|
| 2299 |
+
상
|
| 2300 |
+
새
|
| 2301 |
+
색
|
| 2302 |
+
생
|
| 2303 |
+
서
|
| 2304 |
+
선
|
| 2305 |
+
설
|
| 2306 |
+
섭
|
| 2307 |
+
섰
|
| 2308 |
+
성
|
| 2309 |
+
세
|
| 2310 |
+
셔
|
| 2311 |
+
션
|
| 2312 |
+
셨
|
| 2313 |
+
소
|
| 2314 |
+
속
|
| 2315 |
+
손
|
| 2316 |
+
송
|
| 2317 |
+
수
|
| 2318 |
+
숙
|
| 2319 |
+
순
|
| 2320 |
+
술
|
| 2321 |
+
숫
|
| 2322 |
+
숭
|
| 2323 |
+
숲
|
| 2324 |
+
쉬
|
| 2325 |
+
쉽
|
| 2326 |
+
스
|
| 2327 |
+
슨
|
| 2328 |
+
습
|
| 2329 |
+
슷
|
| 2330 |
+
시
|
| 2331 |
+
식
|
| 2332 |
+
신
|
| 2333 |
+
실
|
| 2334 |
+
싫
|
| 2335 |
+
심
|
| 2336 |
+
십
|
| 2337 |
+
싶
|
| 2338 |
+
싸
|
| 2339 |
+
써
|
| 2340 |
+
쓰
|
| 2341 |
+
쓴
|
| 2342 |
+
씌
|
| 2343 |
+
씨
|
| 2344 |
+
씩
|
| 2345 |
+
씬
|
| 2346 |
+
아
|
| 2347 |
+
악
|
| 2348 |
+
안
|
| 2349 |
+
않
|
| 2350 |
+
알
|
| 2351 |
+
야
|
| 2352 |
+
약
|
| 2353 |
+
얀
|
| 2354 |
+
양
|
| 2355 |
+
얘
|
| 2356 |
+
어
|
| 2357 |
+
언
|
| 2358 |
+
얼
|
| 2359 |
+
엄
|
| 2360 |
+
업
|
| 2361 |
+
없
|
| 2362 |
+
었
|
| 2363 |
+
엉
|
| 2364 |
+
에
|
| 2365 |
+
여
|
| 2366 |
+
역
|
| 2367 |
+
연
|
| 2368 |
+
염
|
| 2369 |
+
엽
|
| 2370 |
+
영
|
| 2371 |
+
옆
|
| 2372 |
+
예
|
| 2373 |
+
옛
|
| 2374 |
+
오
|
| 2375 |
+
온
|
| 2376 |
+
올
|
| 2377 |
+
옷
|
| 2378 |
+
옹
|
| 2379 |
+
와
|
| 2380 |
+
왔
|
| 2381 |
+
왜
|
| 2382 |
+
요
|
| 2383 |
+
욕
|
| 2384 |
+
용
|
| 2385 |
+
우
|
| 2386 |
+
운
|
| 2387 |
+
울
|
| 2388 |
+
웃
|
| 2389 |
+
워
|
| 2390 |
+
원
|
| 2391 |
+
월
|
| 2392 |
+
웠
|
| 2393 |
+
위
|
| 2394 |
+
윙
|
| 2395 |
+
유
|
| 2396 |
+
육
|
| 2397 |
+
윤
|
| 2398 |
+
으
|
| 2399 |
+
은
|
| 2400 |
+
을
|
| 2401 |
+
음
|
| 2402 |
+
응
|
| 2403 |
+
의
|
| 2404 |
+
이
|
| 2405 |
+
익
|
| 2406 |
+
인
|
| 2407 |
+
일
|
| 2408 |
+
읽
|
| 2409 |
+
임
|
| 2410 |
+
입
|
| 2411 |
+
있
|
| 2412 |
+
자
|
| 2413 |
+
작
|
| 2414 |
+
잔
|
| 2415 |
+
잖
|
| 2416 |
+
잘
|
| 2417 |
+
잡
|
| 2418 |
+
잤
|
| 2419 |
+
장
|
| 2420 |
+
재
|
| 2421 |
+
저
|
| 2422 |
+
전
|
| 2423 |
+
점
|
| 2424 |
+
정
|
| 2425 |
+
제
|
| 2426 |
+
져
|
| 2427 |
+
졌
|
| 2428 |
+
조
|
| 2429 |
+
족
|
| 2430 |
+
좀
|
| 2431 |
+
종
|
| 2432 |
+
좋
|
| 2433 |
+
죠
|
| 2434 |
+
주
|
| 2435 |
+
준
|
| 2436 |
+
줄
|
| 2437 |
+
중
|
| 2438 |
+
줘
|
| 2439 |
+
즈
|
| 2440 |
+
즐
|
| 2441 |
+
즘
|
| 2442 |
+
지
|
| 2443 |
+
진
|
| 2444 |
+
집
|
| 2445 |
+
짜
|
| 2446 |
+
짝
|
| 2447 |
+
쩌
|
| 2448 |
+
쪼
|
| 2449 |
+
쪽
|
| 2450 |
+
쫌
|
| 2451 |
+
쭈
|
| 2452 |
+
쯔
|
| 2453 |
+
찌
|
| 2454 |
+
찍
|
| 2455 |
+
차
|
| 2456 |
+
착
|
| 2457 |
+
찾
|
| 2458 |
+
책
|
| 2459 |
+
처
|
| 2460 |
+
천
|
| 2461 |
+
철
|
| 2462 |
+
체
|
| 2463 |
+
쳐
|
| 2464 |
+
쳤
|
| 2465 |
+
초
|
| 2466 |
+
촌
|
| 2467 |
+
추
|
| 2468 |
+
출
|
| 2469 |
+
춤
|
| 2470 |
+
춥
|
| 2471 |
+
춰
|
| 2472 |
+
치
|
| 2473 |
+
친
|
| 2474 |
+
칠
|
| 2475 |
+
침
|
| 2476 |
+
칩
|
| 2477 |
+
칼
|
| 2478 |
+
커
|
| 2479 |
+
켓
|
| 2480 |
+
코
|
| 2481 |
+
콩
|
| 2482 |
+
쿠
|
| 2483 |
+
퀴
|
| 2484 |
+
크
|
| 2485 |
+
큰
|
| 2486 |
+
큽
|
| 2487 |
+
키
|
| 2488 |
+
킨
|
| 2489 |
+
타
|
| 2490 |
+
태
|
| 2491 |
+
터
|
| 2492 |
+
턴
|
| 2493 |
+
털
|
| 2494 |
+
테
|
| 2495 |
+
토
|
| 2496 |
+
통
|
| 2497 |
+
투
|
| 2498 |
+
트
|
| 2499 |
+
특
|
| 2500 |
+
튼
|
| 2501 |
+
틀
|
| 2502 |
+
티
|
| 2503 |
+
팀
|
| 2504 |
+
파
|
| 2505 |
+
팔
|
| 2506 |
+
패
|
| 2507 |
+
페
|
| 2508 |
+
펜
|
| 2509 |
+
펭
|
| 2510 |
+
평
|
| 2511 |
+
포
|
| 2512 |
+
폭
|
| 2513 |
+
표
|
| 2514 |
+
품
|
| 2515 |
+
풍
|
| 2516 |
+
프
|
| 2517 |
+
플
|
| 2518 |
+
피
|
| 2519 |
+
필
|
| 2520 |
+
하
|
| 2521 |
+
학
|
| 2522 |
+
한
|
| 2523 |
+
할
|
| 2524 |
+
함
|
| 2525 |
+
합
|
| 2526 |
+
항
|
| 2527 |
+
해
|
| 2528 |
+
햇
|
| 2529 |
+
했
|
| 2530 |
+
행
|
| 2531 |
+
허
|
| 2532 |
+
험
|
| 2533 |
+
형
|
| 2534 |
+
혜
|
| 2535 |
+
호
|
| 2536 |
+
혼
|
| 2537 |
+
홀
|
| 2538 |
+
화
|
| 2539 |
+
회
|
| 2540 |
+
획
|
| 2541 |
+
후
|
| 2542 |
+
휴
|
| 2543 |
+
흐
|
| 2544 |
+
흔
|
| 2545 |
+
희
|
| 2546 |
+
히
|
| 2547 |
+
힘
|
| 2548 |
+
ﷺ
|
| 2549 |
+
ﷻ
|
| 2550 |
+
!
|
| 2551 |
+
,
|
| 2552 |
+
?
|
| 2553 |
+
�
|
| 2554 |
+
𠮶
|
| 2555 |
+
𩠌
|
| 2556 |
+
𫚕
|
src/wavtts/infer/infer.sh
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
# Model Configuration
|
| 5 |
+
MODEL_NAME="WavTTS"
|
| 6 |
+
MODEL_CFG="src/wavtts/configs/WavTTS.yaml"
|
| 7 |
+
|
| 8 |
+
# Zero-shot TTS Configuration
|
| 9 |
+
VOCAB_FILE="infer/examples/vocab.txt"
|
| 10 |
+
REF_AUDIO="infer/examples/basic_ref_en.wav"
|
| 11 |
+
REF_TEXT="Some call me nature, others call me mother nature."
|
| 12 |
+
GEN_TEXT="I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall."
|
| 13 |
+
|
| 14 |
+
# Output Configuration
|
| 15 |
+
OUTPUT_DIR="output"
|
| 16 |
+
OUTPUT_FILE="infer_cli_basic.wav"
|
| 17 |
+
|
| 18 |
+
# Inference Configuration
|
| 19 |
+
NFE_STEP="50"
|
| 20 |
+
TIMESTEP_MAPPING="power"
|
| 21 |
+
TIMESTEP_POWER="2.0"
|
| 22 |
+
SHIFT="3.0"
|
| 23 |
+
DEVICE="cuda"
|
| 24 |
+
|
| 25 |
+
mkdir -p "${OUTPUT_DIR}"
|
| 26 |
+
|
| 27 |
+
export PYTHONPATH="$(pwd)/src${PYTHONPATH:+:${PYTHONPATH}}"
|
| 28 |
+
|
| 29 |
+
python src/wavtts/infer/infer_cli.py \
|
| 30 |
+
--model_cfg "${MODEL_CFG}" \
|
| 31 |
+
--ref_audio "${REF_AUDIO}" \
|
| 32 |
+
--ref_text "${REF_TEXT}" \
|
| 33 |
+
--gen_text "${GEN_TEXT}" \
|
| 34 |
+
--output_dir "${OUTPUT_DIR}" \
|
| 35 |
+
--output_file "${OUTPUT_FILE}" \
|
| 36 |
+
--vocab_file "${VOCAB_FILE}" \
|
| 37 |
+
--nfe_step "${NFE_STEP}" \
|
| 38 |
+
--timestep_mapping "${TIMESTEP_MAPPING}" \
|
| 39 |
+
--timestep_power "${TIMESTEP_POWER}" \
|
| 40 |
+
--shift "${SHIFT}" \
|
| 41 |
+
--device "${DEVICE}"
|
| 42 |
+
|
| 43 |
+
# bash src/wavtts/infer/infer.sh
|
src/wavtts/infer/infer_cli.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import codecs
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from importlib.resources import files
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import soundfile as sf
|
| 11 |
+
import tomli
|
| 12 |
+
from cached_path import cached_path
|
| 13 |
+
from hydra.utils import get_class
|
| 14 |
+
from omegaconf import OmegaConf
|
| 15 |
+
from unidecode import unidecode
|
| 16 |
+
|
| 17 |
+
from wavtts.infer.utils_infer import (
|
| 18 |
+
cfg_strength,
|
| 19 |
+
cross_fade_duration,
|
| 20 |
+
device,
|
| 21 |
+
fix_duration,
|
| 22 |
+
infer_process,
|
| 23 |
+
load_model,
|
| 24 |
+
nfe_step,
|
| 25 |
+
preprocess_ref_audio_text,
|
| 26 |
+
remove_silence_for_generated_wav,
|
| 27 |
+
speed,
|
| 28 |
+
sway_sampling_coef,
|
| 29 |
+
target_rms,
|
| 30 |
+
shift,
|
| 31 |
+
timestep_mapping,
|
| 32 |
+
timestep_power,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
DEFAULT_MODEL = "WavTTS"
|
| 37 |
+
DEFAULT_CKPT_FILES = {
|
| 38 |
+
DEFAULT_MODEL: "hf://worstchan/WavTTS/model_1200000.pt",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
parser = argparse.ArgumentParser(
|
| 43 |
+
prog="python3 infer-cli.py",
|
| 44 |
+
description="Commandline interface for WavTTS waveform inference.",
|
| 45 |
+
epilog="Specify options above to override one or more settings from config.",
|
| 46 |
+
)
|
| 47 |
+
parser.add_argument(
|
| 48 |
+
"-c",
|
| 49 |
+
"--config",
|
| 50 |
+
type=str,
|
| 51 |
+
default=os.path.join(files("wavtts").joinpath("infer/examples"), "basic.toml"),
|
| 52 |
+
help="The configuration file, default see infer/examples/basic.toml",
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Note. Not to provide default value here in order to read default from config file
|
| 57 |
+
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"-m",
|
| 60 |
+
"--model",
|
| 61 |
+
type=str,
|
| 62 |
+
help="The model config name under src/wavtts/configs, used only when --model_cfg is not provided.",
|
| 63 |
+
)
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"-mc",
|
| 66 |
+
"--model_cfg",
|
| 67 |
+
type=str,
|
| 68 |
+
help="The path to WavTTS model config file .yaml",
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"-p",
|
| 72 |
+
"--ckpt_file",
|
| 73 |
+
type=str,
|
| 74 |
+
help="The path or cached_path URI to model checkpoint. Leave blank to use the default WavTTS checkpoint.",
|
| 75 |
+
)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"-v",
|
| 78 |
+
"--vocab_file",
|
| 79 |
+
type=str,
|
| 80 |
+
help="The path to vocab file .txt, leave blank to use default",
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"-r",
|
| 84 |
+
"--ref_audio",
|
| 85 |
+
type=str,
|
| 86 |
+
help="The reference audio file.",
|
| 87 |
+
)
|
| 88 |
+
parser.add_argument(
|
| 89 |
+
"-s",
|
| 90 |
+
"--ref_text",
|
| 91 |
+
type=str,
|
| 92 |
+
help="The transcript/subtitle for the reference audio",
|
| 93 |
+
)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"-t",
|
| 96 |
+
"--gen_text",
|
| 97 |
+
type=str,
|
| 98 |
+
help="The text to make model synthesize a speech",
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"-f",
|
| 102 |
+
"--gen_file",
|
| 103 |
+
type=str,
|
| 104 |
+
help="The file with text to generate, will ignore --gen_text",
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"-o",
|
| 108 |
+
"--output_dir",
|
| 109 |
+
type=str,
|
| 110 |
+
help="The path to output folder",
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"-w",
|
| 114 |
+
"--output_file",
|
| 115 |
+
type=str,
|
| 116 |
+
help="The name of output file",
|
| 117 |
+
)
|
| 118 |
+
parser.add_argument(
|
| 119 |
+
"--save_chunk",
|
| 120 |
+
action="store_true",
|
| 121 |
+
help="To save each audio chunks during inference",
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--no_legacy_text",
|
| 125 |
+
action="store_false",
|
| 126 |
+
help="Not to use lossy ASCII transliterations of unicode text in saved file names.",
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--remove_silence",
|
| 130 |
+
action="store_true",
|
| 131 |
+
help="To remove long silence found in ouput",
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--target_rms",
|
| 135 |
+
type=float,
|
| 136 |
+
help=f"Target output speech loudness normalization value, default {target_rms}",
|
| 137 |
+
)
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--cross_fade_duration",
|
| 140 |
+
type=float,
|
| 141 |
+
help=f"Duration of cross-fade between audio segments in seconds, default {cross_fade_duration}",
|
| 142 |
+
)
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--nfe_step",
|
| 145 |
+
type=int,
|
| 146 |
+
help=f"The number of function evaluation (denoising steps), default {nfe_step}",
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--cfg_strength",
|
| 150 |
+
type=float,
|
| 151 |
+
help=f"Classifier-free guidance strength, default {cfg_strength}",
|
| 152 |
+
)
|
| 153 |
+
parser.add_argument(
|
| 154 |
+
"--sway_sampling_coef",
|
| 155 |
+
type=float,
|
| 156 |
+
help=f"Sway Sampling coefficient, default {sway_sampling_coef}",
|
| 157 |
+
)
|
| 158 |
+
parser.add_argument(
|
| 159 |
+
"--timestep_mapping",
|
| 160 |
+
type=str,
|
| 161 |
+
choices=["uniform", "sway_sampling", "power"],
|
| 162 |
+
help=f"Timestep mapping strategy, default {timestep_mapping}",
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--timestep_power",
|
| 166 |
+
type=float,
|
| 167 |
+
help=f"Power exponent when --timestep_mapping power is used, default {timestep_power}",
|
| 168 |
+
)
|
| 169 |
+
parser.add_argument(
|
| 170 |
+
"--shift",
|
| 171 |
+
type=float,
|
| 172 |
+
help=f"Timestep shift value, default {shift}",
|
| 173 |
+
)
|
| 174 |
+
parser.add_argument(
|
| 175 |
+
"--speed",
|
| 176 |
+
type=float,
|
| 177 |
+
help=f"The speed of the generated audio, default {speed}",
|
| 178 |
+
)
|
| 179 |
+
parser.add_argument(
|
| 180 |
+
"--fix_duration",
|
| 181 |
+
type=float,
|
| 182 |
+
help=f"Fix the total duration (ref and gen audios) in seconds, default {fix_duration}",
|
| 183 |
+
)
|
| 184 |
+
parser.add_argument(
|
| 185 |
+
"--device",
|
| 186 |
+
type=str,
|
| 187 |
+
help="Specify the device to run on",
|
| 188 |
+
)
|
| 189 |
+
args = parser.parse_args()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# config file
|
| 193 |
+
|
| 194 |
+
config = tomli.load(open(args.config, "rb"))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# command-line interface parameters
|
| 198 |
+
|
| 199 |
+
model = args.model or config.get("model", DEFAULT_MODEL)
|
| 200 |
+
ckpt_file = args.ckpt_file or config.get("ckpt_file", "")
|
| 201 |
+
vocab_file = args.vocab_file or config.get("vocab_file", "")
|
| 202 |
+
|
| 203 |
+
ref_audio = args.ref_audio or config.get("ref_audio", "infer/examples/basic_ref_en.wav")
|
| 204 |
+
ref_text = (
|
| 205 |
+
args.ref_text
|
| 206 |
+
if args.ref_text is not None
|
| 207 |
+
else config.get("ref_text", "Some call me nature, others call me mother nature.")
|
| 208 |
+
)
|
| 209 |
+
gen_text = args.gen_text or config.get("gen_text", "Here we generate something just for test.")
|
| 210 |
+
gen_file = args.gen_file or config.get("gen_file", "")
|
| 211 |
+
|
| 212 |
+
output_dir = args.output_dir or config.get("output_dir", "tests")
|
| 213 |
+
output_file = args.output_file or config.get(
|
| 214 |
+
"output_file", f"infer_cli_{datetime.now().strftime(r'%Y%m%d_%H%M%S')}.wav"
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
save_chunk = args.save_chunk or config.get("save_chunk", False)
|
| 218 |
+
use_legacy_text = args.no_legacy_text or config.get("no_legacy_text", False) # no_legacy_text is a store_false arg
|
| 219 |
+
if save_chunk and use_legacy_text:
|
| 220 |
+
print(
|
| 221 |
+
"\nWarning to --save_chunk: lossy ASCII transliterations of unicode text for legacy (.wav) file names, --no_legacy_text to disable.\n"
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
remove_silence = args.remove_silence or config.get("remove_silence", False)
|
| 225 |
+
target_rms = args.target_rms or config.get("target_rms", target_rms)
|
| 226 |
+
cross_fade_duration = args.cross_fade_duration or config.get("cross_fade_duration", cross_fade_duration)
|
| 227 |
+
nfe_step = args.nfe_step or config.get("nfe_step", nfe_step)
|
| 228 |
+
cfg_strength = args.cfg_strength or config.get("cfg_strength", cfg_strength)
|
| 229 |
+
sway_sampling_coef = args.sway_sampling_coef or config.get("sway_sampling_coef", sway_sampling_coef)
|
| 230 |
+
timestep_mapping = args.timestep_mapping or config.get("timestep_mapping", timestep_mapping)
|
| 231 |
+
timestep_power = args.timestep_power if args.timestep_power is not None else config.get("timestep_power", timestep_power)
|
| 232 |
+
shift = args.shift if args.shift is not None else config.get("shift", shift)
|
| 233 |
+
if timestep_mapping == "power" and timestep_power is None:
|
| 234 |
+
raise ValueError("--timestep_power must be provided when --timestep_mapping power is used")
|
| 235 |
+
speed = args.speed or config.get("speed", speed)
|
| 236 |
+
fix_duration = args.fix_duration or config.get("fix_duration", fix_duration)
|
| 237 |
+
device = args.device or config.get("device", device)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
# patches for pip pkg user
|
| 241 |
+
if "infer/examples/" in ref_audio:
|
| 242 |
+
ref_audio = str(files("wavtts").joinpath(f"{ref_audio}"))
|
| 243 |
+
if "infer/examples/" in vocab_file:
|
| 244 |
+
vocab_file = str(files("wavtts").joinpath(f"{vocab_file}"))
|
| 245 |
+
if "infer/examples/" in gen_file:
|
| 246 |
+
gen_file = str(files("wavtts").joinpath(f"{gen_file}"))
|
| 247 |
+
if "voices" in config:
|
| 248 |
+
for voice in config["voices"]:
|
| 249 |
+
voice_ref_audio = config["voices"][voice]["ref_audio"]
|
| 250 |
+
if "infer/examples/" in voice_ref_audio:
|
| 251 |
+
config["voices"][voice]["ref_audio"] = str(files("wavtts").joinpath(f"{voice_ref_audio}"))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
# ignore gen_text if gen_file provided
|
| 255 |
+
|
| 256 |
+
if gen_file:
|
| 257 |
+
gen_text = codecs.open(gen_file, "r", "utf-8").read()
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
# output path
|
| 261 |
+
|
| 262 |
+
wave_path = Path(output_dir) / output_file
|
| 263 |
+
# spectrogram_path = Path(output_dir) / "infer_cli_out.png"
|
| 264 |
+
if save_chunk:
|
| 265 |
+
output_chunk_dir = os.path.join(output_dir, f"{Path(output_file).stem}_chunks")
|
| 266 |
+
if not os.path.exists(output_chunk_dir):
|
| 267 |
+
os.makedirs(output_chunk_dir)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# load TTS model
|
| 272 |
+
|
| 273 |
+
model_cfg = OmegaConf.load(
|
| 274 |
+
args.model_cfg or config.get("model_cfg", str(files("wavtts").joinpath(f"configs/{model}.yaml")))
|
| 275 |
+
)
|
| 276 |
+
model_cls = get_class(f"wavtts.model.{model_cfg.model.backbone}")
|
| 277 |
+
model_arc = model_cfg.model.arch
|
| 278 |
+
cfm_kwargs = getattr(model_cfg.model, "cfm", {}) or {}
|
| 279 |
+
|
| 280 |
+
if not ckpt_file:
|
| 281 |
+
ckpt_file = DEFAULT_CKPT_FILES.get(model, DEFAULT_CKPT_FILES[DEFAULT_MODEL])
|
| 282 |
+
|
| 283 |
+
if ckpt_file.startswith(("hf://", "http://", "https://")):
|
| 284 |
+
ckpt_file = str(cached_path(ckpt_file))
|
| 285 |
+
|
| 286 |
+
print(f"Using config {model_cfg.model.name} with checkpoint {ckpt_file}...")
|
| 287 |
+
ema_model = load_model(
|
| 288 |
+
model_cls,
|
| 289 |
+
model_arc,
|
| 290 |
+
ckpt_file,
|
| 291 |
+
vocab_file=vocab_file,
|
| 292 |
+
device=device,
|
| 293 |
+
cfm_kwargs=cfm_kwargs,
|
| 294 |
+
waveform_kwargs=model_cfg.model.waveform,
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
# inference process
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def main():
|
| 302 |
+
main_voice = {"ref_audio": ref_audio, "ref_text": ref_text}
|
| 303 |
+
if "voices" not in config:
|
| 304 |
+
voices = {"main": main_voice}
|
| 305 |
+
else:
|
| 306 |
+
voices = config["voices"]
|
| 307 |
+
voices["main"] = main_voice
|
| 308 |
+
for voice in voices:
|
| 309 |
+
print("Voice:", voice)
|
| 310 |
+
print("ref_audio ", voices[voice]["ref_audio"])
|
| 311 |
+
voices[voice]["ref_audio"], voices[voice]["ref_text"] = preprocess_ref_audio_text(
|
| 312 |
+
voices[voice]["ref_audio"], voices[voice]["ref_text"]
|
| 313 |
+
)
|
| 314 |
+
print("ref_audio_", voices[voice]["ref_audio"], "\n\n")
|
| 315 |
+
|
| 316 |
+
generated_audio_segments = []
|
| 317 |
+
reg1 = r"(?=\[\w+\])"
|
| 318 |
+
chunks = re.split(reg1, gen_text)
|
| 319 |
+
reg2 = r"\[(\w+)\]"
|
| 320 |
+
for text in chunks:
|
| 321 |
+
if not text.strip():
|
| 322 |
+
continue
|
| 323 |
+
match = re.match(reg2, text)
|
| 324 |
+
if match:
|
| 325 |
+
voice = match[1]
|
| 326 |
+
else:
|
| 327 |
+
print("No voice tag found, using main.")
|
| 328 |
+
voice = "main"
|
| 329 |
+
if voice not in voices:
|
| 330 |
+
print(f"Voice {voice} not found, using main.")
|
| 331 |
+
voice = "main"
|
| 332 |
+
text = re.sub(reg2, "", text)
|
| 333 |
+
ref_audio_ = voices[voice]["ref_audio"]
|
| 334 |
+
ref_text_ = voices[voice]["ref_text"]
|
| 335 |
+
local_speed = voices[voice].get("speed", speed)
|
| 336 |
+
gen_text_ = text.strip()
|
| 337 |
+
print(f"Voice: {voice}")
|
| 338 |
+
audio_segment, final_sample_rate, spectrogram = infer_process(
|
| 339 |
+
ref_audio_,
|
| 340 |
+
ref_text_,
|
| 341 |
+
gen_text_,
|
| 342 |
+
ema_model,
|
| 343 |
+
target_rms=target_rms,
|
| 344 |
+
cross_fade_duration=cross_fade_duration,
|
| 345 |
+
nfe_step=nfe_step,
|
| 346 |
+
cfg_strength=cfg_strength,
|
| 347 |
+
sway_sampling_coef=sway_sampling_coef,
|
| 348 |
+
timestep_mapping=timestep_mapping,
|
| 349 |
+
timestep_power=timestep_power,
|
| 350 |
+
shift=shift,
|
| 351 |
+
speed=local_speed,
|
| 352 |
+
fix_duration=fix_duration,
|
| 353 |
+
device=device,
|
| 354 |
+
)
|
| 355 |
+
generated_audio_segments.append(audio_segment)
|
| 356 |
+
|
| 357 |
+
if save_chunk:
|
| 358 |
+
if len(gen_text_) > 200:
|
| 359 |
+
gen_text_ = gen_text_[:200] + " ... "
|
| 360 |
+
if use_legacy_text:
|
| 361 |
+
gen_text_ = unidecode(gen_text_)
|
| 362 |
+
sf.write(
|
| 363 |
+
os.path.join(output_chunk_dir, f"{len(generated_audio_segments) - 1}_{gen_text_}.wav"),
|
| 364 |
+
audio_segment,
|
| 365 |
+
final_sample_rate,
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
if generated_audio_segments:
|
| 369 |
+
final_wave = np.concatenate(generated_audio_segments)
|
| 370 |
+
|
| 371 |
+
if not os.path.exists(output_dir):
|
| 372 |
+
os.makedirs(output_dir)
|
| 373 |
+
|
| 374 |
+
with open(wave_path, "wb") as f:
|
| 375 |
+
sf.write(f.name, final_wave, final_sample_rate)
|
| 376 |
+
# Remove silence
|
| 377 |
+
if remove_silence:
|
| 378 |
+
remove_silence_for_generated_wav(f.name)
|
| 379 |
+
print(f.name)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
if __name__ == "__main__":
|
| 383 |
+
main()
|
src/wavtts/infer/utils_infer.py
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# A unified script for inference process
|
| 2 |
+
# Make adjustments inside functions, and consider both gradio and cli scripts if need to change func output format
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibility
|
| 10 |
+
import hashlib
|
| 11 |
+
import re
|
| 12 |
+
import tempfile
|
| 13 |
+
from importlib.resources import files
|
| 14 |
+
|
| 15 |
+
import matplotlib
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
matplotlib.use("Agg")
|
| 19 |
+
|
| 20 |
+
import matplotlib.pylab as plt
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torchaudio
|
| 24 |
+
import tqdm
|
| 25 |
+
from pydub import AudioSegment, silence
|
| 26 |
+
from transformers import pipeline
|
| 27 |
+
|
| 28 |
+
from wavtts.model import CFM
|
| 29 |
+
from wavtts.model.utils import convert_char_to_pinyin, get_tokenizer
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
_ref_audio_cache = {}
|
| 33 |
+
_ref_text_cache = {}
|
| 34 |
+
|
| 35 |
+
device = (
|
| 36 |
+
"cuda"
|
| 37 |
+
if torch.cuda.is_available()
|
| 38 |
+
else "xpu"
|
| 39 |
+
if torch.xpu.is_available()
|
| 40 |
+
else "mps"
|
| 41 |
+
if torch.backends.mps.is_available()
|
| 42 |
+
else "cpu"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
tempfile_kwargs = {"delete_on_close": False} if sys.version_info >= (3, 12) else {"delete": False}
|
| 46 |
+
|
| 47 |
+
# -----------------------------------------
|
| 48 |
+
|
| 49 |
+
target_sample_rate = 16000 # WavTTS waveform default
|
| 50 |
+
use_bfloat16 = True # True, False
|
| 51 |
+
wav_frame_len = 160
|
| 52 |
+
target_rms = 0.1
|
| 53 |
+
cross_fade_duration = 0.15
|
| 54 |
+
ode_method = "euler" # fixed WavTTS inference ODE method
|
| 55 |
+
nfe_step = 50
|
| 56 |
+
cfg_strength = 3.0
|
| 57 |
+
sway_sampling_coef = -1.0
|
| 58 |
+
timestep_mapping = "power"
|
| 59 |
+
timestep_power = 2.0
|
| 60 |
+
shift = 3.0
|
| 61 |
+
speed = 1.0
|
| 62 |
+
fix_duration = None
|
| 63 |
+
|
| 64 |
+
# -----------------------------------------
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# chunk text into smaller pieces
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def chunk_text(text, max_chars=135):
|
| 71 |
+
"""
|
| 72 |
+
Splits the input text into chunks, each with a maximum number of characters.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
text (str): The text to be split.
|
| 76 |
+
max_chars (int): The maximum number of characters per chunk.
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
List[str]: A list of text chunks.
|
| 80 |
+
"""
|
| 81 |
+
chunks = []
|
| 82 |
+
current_chunk = ""
|
| 83 |
+
# Split the text into sentences based on punctuation followed by whitespace
|
| 84 |
+
sentences = re.split(r"(?<=[;:,.!?])\s+|(?<=[;:,。!?])", text)
|
| 85 |
+
|
| 86 |
+
for sentence in sentences:
|
| 87 |
+
if len(current_chunk.encode("utf-8")) + len(sentence.encode("utf-8")) <= max_chars:
|
| 88 |
+
current_chunk += sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
|
| 89 |
+
else:
|
| 90 |
+
if current_chunk:
|
| 91 |
+
chunks.append(current_chunk.strip())
|
| 92 |
+
current_chunk = sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
|
| 93 |
+
|
| 94 |
+
if current_chunk:
|
| 95 |
+
chunks.append(current_chunk.strip())
|
| 96 |
+
|
| 97 |
+
return chunks
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# load asr pipeline
|
| 102 |
+
|
| 103 |
+
asr_pipe = None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def initialize_asr_pipeline(device: str = device, dtype=None):
|
| 107 |
+
if dtype is None:
|
| 108 |
+
dtype = (
|
| 109 |
+
torch.float16
|
| 110 |
+
if "cuda" in device
|
| 111 |
+
and torch.cuda.get_device_properties(device).major >= 7
|
| 112 |
+
and not torch.cuda.get_device_name().endswith("[ZLUDA]")
|
| 113 |
+
else torch.float32
|
| 114 |
+
)
|
| 115 |
+
global asr_pipe
|
| 116 |
+
asr_pipe = pipeline(
|
| 117 |
+
"automatic-speech-recognition",
|
| 118 |
+
model="openai/whisper-large-v3-turbo",
|
| 119 |
+
torch_dtype=dtype,
|
| 120 |
+
device=device,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# transcribe
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def transcribe(ref_audio, language=None):
|
| 128 |
+
global asr_pipe
|
| 129 |
+
if asr_pipe is None:
|
| 130 |
+
initialize_asr_pipeline(device=device)
|
| 131 |
+
return asr_pipe(
|
| 132 |
+
ref_audio,
|
| 133 |
+
chunk_length_s=30,
|
| 134 |
+
batch_size=128,
|
| 135 |
+
generate_kwargs={"task": "transcribe", "language": language} if language else {"task": "transcribe"},
|
| 136 |
+
return_timestamps=False,
|
| 137 |
+
)["text"].strip()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# load model checkpoint for inference
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def load_checkpoint(model, ckpt_path, device: str, dtype=None, use_ema=True):
|
| 144 |
+
if dtype is None:
|
| 145 |
+
dtype = (
|
| 146 |
+
torch.float16
|
| 147 |
+
if "cuda" in device
|
| 148 |
+
and torch.cuda.get_device_properties(device).major >= 7
|
| 149 |
+
and not torch.cuda.get_device_name().endswith("[ZLUDA]")
|
| 150 |
+
else torch.float32
|
| 151 |
+
)
|
| 152 |
+
model = model.to(dtype)
|
| 153 |
+
|
| 154 |
+
ckpt_type = ckpt_path.split(".")[-1]
|
| 155 |
+
if ckpt_type == "safetensors":
|
| 156 |
+
from safetensors.torch import load_file
|
| 157 |
+
|
| 158 |
+
checkpoint = load_file(ckpt_path, device=device)
|
| 159 |
+
else:
|
| 160 |
+
checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True)
|
| 161 |
+
|
| 162 |
+
if use_ema:
|
| 163 |
+
if ckpt_type == "safetensors":
|
| 164 |
+
checkpoint = {"ema_model_state_dict": checkpoint}
|
| 165 |
+
checkpoint["model_state_dict"] = {
|
| 166 |
+
k.replace("ema_model.", ""): v
|
| 167 |
+
for k, v in checkpoint["ema_model_state_dict"].items()
|
| 168 |
+
if k not in ["initted", "step"]
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 172 |
+
else:
|
| 173 |
+
if ckpt_type == "safetensors":
|
| 174 |
+
checkpoint = {"model_state_dict": checkpoint}
|
| 175 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 176 |
+
|
| 177 |
+
del checkpoint
|
| 178 |
+
if "cuda" in str(device) and torch.cuda.is_available():
|
| 179 |
+
torch.cuda.empty_cache()
|
| 180 |
+
|
| 181 |
+
return model.to(device)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# load model for inference
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def load_model(
|
| 188 |
+
model_cls,
|
| 189 |
+
model_cfg,
|
| 190 |
+
ckpt_path,
|
| 191 |
+
vocab_file="",
|
| 192 |
+
ode_method=ode_method,
|
| 193 |
+
use_ema=True,
|
| 194 |
+
device=device,
|
| 195 |
+
cfm_kwargs=None,
|
| 196 |
+
waveform_kwargs=None,
|
| 197 |
+
):
|
| 198 |
+
if vocab_file == "":
|
| 199 |
+
vocab_file = str(files("wavtts").joinpath("infer/examples/vocab.txt"))
|
| 200 |
+
tokenizer = "custom"
|
| 201 |
+
|
| 202 |
+
print("\nvocab : ", vocab_file)
|
| 203 |
+
print("token : ", tokenizer)
|
| 204 |
+
print("model : ", ckpt_path, "\n")
|
| 205 |
+
|
| 206 |
+
if waveform_kwargs is None:
|
| 207 |
+
waveform_kwargs = dict(
|
| 208 |
+
wav_frame_len=wav_frame_len,
|
| 209 |
+
target_sample_rate=target_sample_rate,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
vocab_char_map, vocab_size = get_tokenizer(vocab_file, tokenizer)
|
| 213 |
+
model = CFM(
|
| 214 |
+
transformer=model_cls(
|
| 215 |
+
**model_cfg,
|
| 216 |
+
text_num_embeds=vocab_size,
|
| 217 |
+
wav_frame_len=waveform_kwargs.get("wav_frame_len", wav_frame_len),
|
| 218 |
+
),
|
| 219 |
+
waveform_kwargs=waveform_kwargs,
|
| 220 |
+
odeint_kwargs=dict(
|
| 221 |
+
method=ode_method,
|
| 222 |
+
),
|
| 223 |
+
vocab_char_map=vocab_char_map,
|
| 224 |
+
**cfm_kwargs,
|
| 225 |
+
).to(device)
|
| 226 |
+
|
| 227 |
+
# Keep inference-time audio geometry available even when CFM is wav-only and has no MelSpec module.
|
| 228 |
+
model.target_sample_rate = int(waveform_kwargs.get("target_sample_rate", target_sample_rate))
|
| 229 |
+
|
| 230 |
+
model = load_checkpoint(model, ckpt_path, device, dtype=None, use_ema=use_ema)
|
| 231 |
+
|
| 232 |
+
return model
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def remove_silence_edges(audio, silence_threshold=-42):
|
| 236 |
+
# Remove silence from the start
|
| 237 |
+
non_silent_start_idx = silence.detect_leading_silence(audio, silence_threshold=silence_threshold)
|
| 238 |
+
audio = audio[non_silent_start_idx:]
|
| 239 |
+
|
| 240 |
+
# Remove silence from the end
|
| 241 |
+
non_silent_end_duration = audio.duration_seconds
|
| 242 |
+
for ms in reversed(audio):
|
| 243 |
+
if ms.dBFS > silence_threshold:
|
| 244 |
+
break
|
| 245 |
+
non_silent_end_duration -= 0.001
|
| 246 |
+
trimmed_audio = audio[: int(non_silent_end_duration * 1000)]
|
| 247 |
+
|
| 248 |
+
return trimmed_audio
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# preprocess reference audio and text
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=print):
|
| 255 |
+
show_info("Converting audio...")
|
| 256 |
+
|
| 257 |
+
# Compute a hash of the reference audio file
|
| 258 |
+
with open(ref_audio_orig, "rb") as audio_file:
|
| 259 |
+
audio_data = audio_file.read()
|
| 260 |
+
audio_hash = hashlib.md5(audio_data).hexdigest()
|
| 261 |
+
|
| 262 |
+
global _ref_audio_cache
|
| 263 |
+
|
| 264 |
+
if audio_hash in _ref_audio_cache:
|
| 265 |
+
show_info("Using cached preprocessed reference audio...")
|
| 266 |
+
ref_audio = _ref_audio_cache[audio_hash]
|
| 267 |
+
|
| 268 |
+
else: # first pass, do preprocess
|
| 269 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", **tempfile_kwargs) as f:
|
| 270 |
+
temp_path = f.name
|
| 271 |
+
|
| 272 |
+
aseg = AudioSegment.from_file(ref_audio_orig)
|
| 273 |
+
|
| 274 |
+
# 1. try to find long silence for clipping
|
| 275 |
+
non_silent_segs = silence.split_on_silence(
|
| 276 |
+
aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=1000, seek_step=10
|
| 277 |
+
)
|
| 278 |
+
non_silent_wave = AudioSegment.silent(duration=0)
|
| 279 |
+
for non_silent_seg in non_silent_segs:
|
| 280 |
+
if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 12000:
|
| 281 |
+
show_info("Audio is over 12s, clipping short. (1)")
|
| 282 |
+
break
|
| 283 |
+
non_silent_wave += non_silent_seg
|
| 284 |
+
|
| 285 |
+
# 2. try to find short silence for clipping if 1. failed
|
| 286 |
+
if len(non_silent_wave) > 12000:
|
| 287 |
+
non_silent_segs = silence.split_on_silence(
|
| 288 |
+
aseg, min_silence_len=100, silence_thresh=-40, keep_silence=1000, seek_step=10
|
| 289 |
+
)
|
| 290 |
+
non_silent_wave = AudioSegment.silent(duration=0)
|
| 291 |
+
for non_silent_seg in non_silent_segs:
|
| 292 |
+
if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 12000:
|
| 293 |
+
show_info("Audio is over 12s, clipping short. (2)")
|
| 294 |
+
break
|
| 295 |
+
non_silent_wave += non_silent_seg
|
| 296 |
+
|
| 297 |
+
aseg = non_silent_wave
|
| 298 |
+
|
| 299 |
+
# 3. if no proper silence found for clipping
|
| 300 |
+
if len(aseg) > 12000:
|
| 301 |
+
aseg = aseg[:12000]
|
| 302 |
+
show_info("Audio is over 12s, clipping short. (3)")
|
| 303 |
+
|
| 304 |
+
aseg = remove_silence_edges(aseg) + AudioSegment.silent(duration=50)
|
| 305 |
+
aseg.export(temp_path, format="wav")
|
| 306 |
+
ref_audio = temp_path
|
| 307 |
+
|
| 308 |
+
# Cache the processed reference audio
|
| 309 |
+
_ref_audio_cache[audio_hash] = ref_audio
|
| 310 |
+
|
| 311 |
+
if not ref_text.strip():
|
| 312 |
+
global _ref_text_cache
|
| 313 |
+
if audio_hash in _ref_text_cache:
|
| 314 |
+
# Use cached asr transcription
|
| 315 |
+
show_info("Using cached reference text...")
|
| 316 |
+
ref_text = _ref_text_cache[audio_hash]
|
| 317 |
+
else:
|
| 318 |
+
show_info("No reference text provided, transcribing reference audio...")
|
| 319 |
+
ref_text = transcribe(ref_audio)
|
| 320 |
+
# Cache the transcribed text (not caching custom ref_text, enabling users to do manual tweak)
|
| 321 |
+
_ref_text_cache[audio_hash] = ref_text
|
| 322 |
+
else:
|
| 323 |
+
show_info("Using custom reference text...")
|
| 324 |
+
|
| 325 |
+
# Ensure ref_text ends with a proper sentence-ending punctuation
|
| 326 |
+
if not ref_text.endswith(". ") and not ref_text.endswith("。"):
|
| 327 |
+
if ref_text.endswith("."):
|
| 328 |
+
ref_text += " "
|
| 329 |
+
else:
|
| 330 |
+
ref_text += ". "
|
| 331 |
+
|
| 332 |
+
print("\nref_text ", ref_text)
|
| 333 |
+
|
| 334 |
+
return ref_audio, ref_text
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# infer process: chunk text -> infer batches [i.e. infer_batch_process()]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def infer_process(
|
| 341 |
+
ref_audio,
|
| 342 |
+
ref_text,
|
| 343 |
+
gen_text,
|
| 344 |
+
model_obj,
|
| 345 |
+
show_info=print,
|
| 346 |
+
progress=tqdm,
|
| 347 |
+
target_rms=target_rms,
|
| 348 |
+
cross_fade_duration=cross_fade_duration,
|
| 349 |
+
nfe_step=nfe_step,
|
| 350 |
+
cfg_strength=cfg_strength,
|
| 351 |
+
sway_sampling_coef=sway_sampling_coef,
|
| 352 |
+
timestep_mapping=timestep_mapping,
|
| 353 |
+
timestep_power=timestep_power,
|
| 354 |
+
shift=shift,
|
| 355 |
+
speed=speed,
|
| 356 |
+
fix_duration=fix_duration,
|
| 357 |
+
device=device,
|
| 358 |
+
):
|
| 359 |
+
# Split the input text into batches
|
| 360 |
+
audio, sr = torchaudio.load(ref_audio)
|
| 361 |
+
max_chars = int(len(ref_text.encode("utf-8")) / (audio.shape[-1] / sr) * (22 - audio.shape[-1] / sr) * speed)
|
| 362 |
+
gen_text_batches = chunk_text(gen_text, max_chars=max_chars)
|
| 363 |
+
for i, gen_text in enumerate(gen_text_batches):
|
| 364 |
+
print(f"gen_text {i}", gen_text)
|
| 365 |
+
print("\n")
|
| 366 |
+
|
| 367 |
+
show_info(f"Generating audio in {len(gen_text_batches)} batches...")
|
| 368 |
+
return next(
|
| 369 |
+
infer_batch_process(
|
| 370 |
+
(audio, sr),
|
| 371 |
+
ref_text,
|
| 372 |
+
gen_text_batches,
|
| 373 |
+
model_obj,
|
| 374 |
+
progress=progress,
|
| 375 |
+
target_rms=target_rms,
|
| 376 |
+
cross_fade_duration=cross_fade_duration,
|
| 377 |
+
nfe_step=nfe_step,
|
| 378 |
+
cfg_strength=cfg_strength,
|
| 379 |
+
sway_sampling_coef=sway_sampling_coef,
|
| 380 |
+
timestep_mapping=timestep_mapping,
|
| 381 |
+
timestep_power=timestep_power,
|
| 382 |
+
shift=shift,
|
| 383 |
+
speed=speed,
|
| 384 |
+
fix_duration=fix_duration,
|
| 385 |
+
device=device,
|
| 386 |
+
)
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
# infer batches
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _model_audio_sample_rate(model_obj):
|
| 394 |
+
if hasattr(model_obj, "target_sample_rate"):
|
| 395 |
+
return int(model_obj.target_sample_rate)
|
| 396 |
+
return int(target_sample_rate)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _supports_cuda_autocast(device):
|
| 400 |
+
return use_bfloat16 and device is not None and "cuda" in str(device) and torch.cuda.is_available()
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def infer_batch_process(
|
| 404 |
+
ref_audio,
|
| 405 |
+
ref_text,
|
| 406 |
+
gen_text_batches,
|
| 407 |
+
model_obj,
|
| 408 |
+
progress=tqdm,
|
| 409 |
+
target_rms=0.1,
|
| 410 |
+
cross_fade_duration=0.15,
|
| 411 |
+
nfe_step=50,
|
| 412 |
+
cfg_strength=3.0,
|
| 413 |
+
sway_sampling_coef=-1,
|
| 414 |
+
timestep_mapping="power",
|
| 415 |
+
timestep_power=2.0,
|
| 416 |
+
shift=3.0,
|
| 417 |
+
speed=1,
|
| 418 |
+
fix_duration=None,
|
| 419 |
+
device=None,
|
| 420 |
+
streaming=False,
|
| 421 |
+
chunk_size=2048,
|
| 422 |
+
):
|
| 423 |
+
audio, sr = ref_audio
|
| 424 |
+
if audio.shape[0] > 1:
|
| 425 |
+
audio = torch.mean(audio, dim=0, keepdim=True)
|
| 426 |
+
|
| 427 |
+
model_sample_rate = _model_audio_sample_rate(model_obj)
|
| 428 |
+
|
| 429 |
+
rms = torch.sqrt(torch.mean(torch.square(audio))).clamp_min(1e-8)
|
| 430 |
+
if rms < target_rms:
|
| 431 |
+
audio = audio * target_rms / rms
|
| 432 |
+
|
| 433 |
+
if sr != model_sample_rate:
|
| 434 |
+
resampler = torchaudio.transforms.Resample(sr, model_sample_rate)
|
| 435 |
+
audio = resampler(audio)
|
| 436 |
+
|
| 437 |
+
audio = audio.to(device)
|
| 438 |
+
|
| 439 |
+
frame_len = int(getattr(model_obj, "wav_frame_len", getattr(model_obj, "num_channels", 160)))
|
| 440 |
+
ref_len_samples = audio.shape[-1]
|
| 441 |
+
ref_full_frames = ref_len_samples // frame_len
|
| 442 |
+
ref_len_aligned = max(ref_full_frames * frame_len, frame_len)
|
| 443 |
+
if ref_len_aligned > ref_len_samples:
|
| 444 |
+
audio = torch.nn.functional.pad(audio, (0, ref_len_aligned - ref_len_samples), value=0.0)
|
| 445 |
+
else:
|
| 446 |
+
audio = audio[..., :ref_len_aligned]
|
| 447 |
+
ref_audio_len = ref_len_aligned
|
| 448 |
+
|
| 449 |
+
generated_waves = []
|
| 450 |
+
|
| 451 |
+
if len(ref_text[-1].encode("utf-8")) == 1:
|
| 452 |
+
ref_text = ref_text + " "
|
| 453 |
+
|
| 454 |
+
def process_batch(gen_text):
|
| 455 |
+
local_speed = speed
|
| 456 |
+
if len(gen_text.encode("utf-8")) < 10:
|
| 457 |
+
local_speed = 0.3
|
| 458 |
+
|
| 459 |
+
# Prepare the text
|
| 460 |
+
text_list = [ref_text + gen_text]
|
| 461 |
+
final_text_list = convert_char_to_pinyin(text_list)
|
| 462 |
+
|
| 463 |
+
if fix_duration is not None:
|
| 464 |
+
duration = int(fix_duration * model_sample_rate) # samples
|
| 465 |
+
else:
|
| 466 |
+
# Calculate duration
|
| 467 |
+
ref_text_len = len(ref_text.encode("utf-8"))
|
| 468 |
+
gen_text_len = len(gen_text.encode("utf-8"))
|
| 469 |
+
duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / local_speed)
|
| 470 |
+
|
| 471 |
+
# inference
|
| 472 |
+
with torch.inference_mode():
|
| 473 |
+
if _supports_cuda_autocast(device):
|
| 474 |
+
audio_bf16 = audio.to(torch.bfloat16)
|
| 475 |
+
with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
|
| 476 |
+
generated, _ = model_obj.sample(
|
| 477 |
+
cond=audio_bf16,
|
| 478 |
+
text=final_text_list,
|
| 479 |
+
duration=duration,
|
| 480 |
+
steps=nfe_step,
|
| 481 |
+
cfg_strength=cfg_strength,
|
| 482 |
+
sway_sampling_coef=sway_sampling_coef,
|
| 483 |
+
timestep_mapping=timestep_mapping,
|
| 484 |
+
timestep_power=timestep_power,
|
| 485 |
+
shift=shift,
|
| 486 |
+
use_epss=timestep_mapping == "sway_sampling",
|
| 487 |
+
)
|
| 488 |
+
else:
|
| 489 |
+
generated, _ = model_obj.sample(
|
| 490 |
+
cond=audio,
|
| 491 |
+
text=final_text_list,
|
| 492 |
+
duration=duration,
|
| 493 |
+
steps=nfe_step,
|
| 494 |
+
cfg_strength=cfg_strength,
|
| 495 |
+
sway_sampling_coef=sway_sampling_coef,
|
| 496 |
+
timestep_mapping=timestep_mapping,
|
| 497 |
+
timestep_power=timestep_power,
|
| 498 |
+
shift=shift,
|
| 499 |
+
use_epss=timestep_mapping == "sway_sampling",
|
| 500 |
+
)
|
| 501 |
+
del _
|
| 502 |
+
|
| 503 |
+
generated = generated.to(torch.float32) # [1, N_total]
|
| 504 |
+
cut = ref_audio_len
|
| 505 |
+
generated_wave = generated[0, cut:].contiguous()
|
| 506 |
+
|
| 507 |
+
if rms < target_rms:
|
| 508 |
+
generated_wave = generated_wave * rms / target_rms
|
| 509 |
+
|
| 510 |
+
generated_wave = generated_wave.cpu().numpy()
|
| 511 |
+
|
| 512 |
+
if streaming:
|
| 513 |
+
for j in range(0, len(generated_wave), chunk_size):
|
| 514 |
+
yield generated_wave[j : j + chunk_size], model_sample_rate
|
| 515 |
+
else:
|
| 516 |
+
yield generated_wave, None
|
| 517 |
+
|
| 518 |
+
if streaming:
|
| 519 |
+
for gen_text in progress.tqdm(gen_text_batches) if progress is not None else gen_text_batches:
|
| 520 |
+
for chunk in process_batch(gen_text):
|
| 521 |
+
yield chunk
|
| 522 |
+
else:
|
| 523 |
+
with ThreadPoolExecutor() as executor:
|
| 524 |
+
futures = [executor.submit(process_batch, gen_text) for gen_text in gen_text_batches]
|
| 525 |
+
for future in progress.tqdm(futures) if progress is not None else futures:
|
| 526 |
+
result = future.result()
|
| 527 |
+
if result:
|
| 528 |
+
generated_wave, _ = next(result)
|
| 529 |
+
generated_waves.append(generated_wave)
|
| 530 |
+
|
| 531 |
+
if generated_waves:
|
| 532 |
+
if cross_fade_duration <= 0:
|
| 533 |
+
# Simply concatenate
|
| 534 |
+
final_wave = np.concatenate(generated_waves)
|
| 535 |
+
else:
|
| 536 |
+
# Combine all generated waves with cross-fading
|
| 537 |
+
final_wave = generated_waves[0]
|
| 538 |
+
for i in range(1, len(generated_waves)):
|
| 539 |
+
prev_wave = final_wave
|
| 540 |
+
next_wave = generated_waves[i]
|
| 541 |
+
|
| 542 |
+
# Calculate cross-fade samples, ensuring it does not exceed wave lengths
|
| 543 |
+
cross_fade_samples = int(cross_fade_duration * model_sample_rate)
|
| 544 |
+
cross_fade_samples = min(cross_fade_samples, len(prev_wave), len(next_wave))
|
| 545 |
+
|
| 546 |
+
if cross_fade_samples <= 0:
|
| 547 |
+
# No overlap possible, concatenate
|
| 548 |
+
final_wave = np.concatenate([prev_wave, next_wave])
|
| 549 |
+
continue
|
| 550 |
+
|
| 551 |
+
# Overlapping parts
|
| 552 |
+
prev_overlap = prev_wave[-cross_fade_samples:]
|
| 553 |
+
next_overlap = next_wave[:cross_fade_samples]
|
| 554 |
+
|
| 555 |
+
# Fade out and fade in
|
| 556 |
+
fade_out = np.linspace(1, 0, cross_fade_samples)
|
| 557 |
+
fade_in = np.linspace(0, 1, cross_fade_samples)
|
| 558 |
+
|
| 559 |
+
# Cross-faded overlap
|
| 560 |
+
cross_faded_overlap = prev_overlap * fade_out + next_overlap * fade_in
|
| 561 |
+
|
| 562 |
+
# Combine
|
| 563 |
+
new_wave = np.concatenate(
|
| 564 |
+
[prev_wave[:-cross_fade_samples], cross_faded_overlap, next_wave[cross_fade_samples:]]
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
final_wave = new_wave
|
| 568 |
+
|
| 569 |
+
yield final_wave, model_sample_rate, None
|
| 570 |
+
|
| 571 |
+
else:
|
| 572 |
+
yield None, model_sample_rate, None
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
# remove silence from generated wav
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def remove_silence_for_generated_wav(filename):
|
| 579 |
+
aseg = AudioSegment.from_file(filename)
|
| 580 |
+
non_silent_segs = silence.split_on_silence(
|
| 581 |
+
aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500, seek_step=10
|
| 582 |
+
)
|
| 583 |
+
non_silent_wave = AudioSegment.silent(duration=0)
|
| 584 |
+
for non_silent_seg in non_silent_segs:
|
| 585 |
+
non_silent_wave += non_silent_seg
|
| 586 |
+
aseg = non_silent_wave
|
| 587 |
+
aseg.export(filename, format="wav")
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
# save spectrogram
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def save_spectrogram(spectrogram, path):
|
| 594 |
+
plt.figure(figsize=(12, 4))
|
| 595 |
+
plt.imshow(spectrogram, origin="lower", aspect="auto")
|
| 596 |
+
plt.colorbar()
|
| 597 |
+
plt.savefig(path)
|
| 598 |
+
plt.close()
|
src/wavtts/model/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from wavtts.model.backbones.dit import DiT
|
| 2 |
+
from wavtts.model.backbones.mmdit import MMDiT
|
| 3 |
+
from wavtts.model.cfm import CFM
|
| 4 |
+
from wavtts.model.trainer import Trainer
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = ["CFM", "DiT", "MMDiT", "Trainer"]
|
src/wavtts/model/backbones/dit.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ein notation:
|
| 3 |
+
b - batch
|
| 4 |
+
n - sequence
|
| 5 |
+
nt - text sequence
|
| 6 |
+
nw - raw wave length
|
| 7 |
+
d - dimension
|
| 8 |
+
"""
|
| 9 |
+
# ruff: noqa: F722 F821
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch import nn
|
| 16 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 17 |
+
from x_transformers.x_transformers import RotaryEmbedding
|
| 18 |
+
|
| 19 |
+
from wavtts.model.modules import (
|
| 20 |
+
AdaLayerNorm_Final,
|
| 21 |
+
ConvNeXtV2Block,
|
| 22 |
+
ConvPositionEmbedding,
|
| 23 |
+
DiTBlock,
|
| 24 |
+
TimestepEmbedding,
|
| 25 |
+
precompute_freqs_cis,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Text embedding
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TextEmbedding(nn.Module):
|
| 33 |
+
def __init__(
|
| 34 |
+
self, text_num_embeds, text_dim, mask_padding=True, average_upsampling=False, conv_layers=0, conv_mult=2
|
| 35 |
+
):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.text_embed = nn.Embedding(text_num_embeds + 1, text_dim) # use 0 as filler token
|
| 38 |
+
|
| 39 |
+
self.mask_padding = mask_padding # mask filler and batch padding tokens or not
|
| 40 |
+
self.average_upsampling = average_upsampling # zipvoice-style text late average upsampling (after text encoder)
|
| 41 |
+
if average_upsampling:
|
| 42 |
+
assert mask_padding, "text_embedding_average_upsampling requires text_mask_padding to be True"
|
| 43 |
+
|
| 44 |
+
if conv_layers > 0:
|
| 45 |
+
self.extra_modeling = True
|
| 46 |
+
self.precompute_max_pos = 8192 # 8192 waveform tokens is ~81.92s at 16k / wav_frame_len=160
|
| 47 |
+
self.register_buffer("freqs_cis", precompute_freqs_cis(text_dim, self.precompute_max_pos), persistent=False)
|
| 48 |
+
self.text_blocks = nn.Sequential(
|
| 49 |
+
*[ConvNeXtV2Block(text_dim, text_dim * conv_mult) for _ in range(conv_layers)]
|
| 50 |
+
)
|
| 51 |
+
else:
|
| 52 |
+
self.extra_modeling = False
|
| 53 |
+
|
| 54 |
+
def average_upsample_text_by_mask(self, text, text_mask):
|
| 55 |
+
batch, seq_len, text_dim = text.shape
|
| 56 |
+
|
| 57 |
+
text_lens = text_mask.sum(dim=1) # [batch]
|
| 58 |
+
|
| 59 |
+
upsampled_text = torch.zeros_like(text)
|
| 60 |
+
|
| 61 |
+
for i in range(batch):
|
| 62 |
+
valid_text_len = text_lens[i].item()
|
| 63 |
+
|
| 64 |
+
if valid_text_len == 0:
|
| 65 |
+
continue
|
| 66 |
+
|
| 67 |
+
valid_ind = torch.where(text_mask[i])[0]
|
| 68 |
+
valid_data = text[i, valid_ind, :] # [valid_text_len, text_dim]
|
| 69 |
+
|
| 70 |
+
base_repeat = seq_len // valid_text_len
|
| 71 |
+
remainder = seq_len % valid_text_len
|
| 72 |
+
|
| 73 |
+
indices = []
|
| 74 |
+
for j in range(valid_text_len):
|
| 75 |
+
repeat_count = base_repeat + (1 if j >= valid_text_len - remainder else 0)
|
| 76 |
+
indices.extend([j] * repeat_count)
|
| 77 |
+
|
| 78 |
+
indices = torch.tensor(indices[:seq_len], device=text.device, dtype=torch.long)
|
| 79 |
+
upsampled = valid_data[indices] # [seq_len, text_dim]
|
| 80 |
+
|
| 81 |
+
upsampled_text[i, :seq_len, :] = upsampled
|
| 82 |
+
|
| 83 |
+
return upsampled_text
|
| 84 |
+
|
| 85 |
+
def forward(self, text: int["b nt"], seq_len, drop_text=False):
|
| 86 |
+
text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx()
|
| 87 |
+
text = text[:, :seq_len] # curtail if character tokens are more than waveform tokens
|
| 88 |
+
text = F.pad(text, (0, seq_len - text.shape[1]), value=0) # (opt.) if not self.average_upsampling:
|
| 89 |
+
if self.mask_padding:
|
| 90 |
+
text_mask = text == 0
|
| 91 |
+
|
| 92 |
+
if drop_text: # cfg for text
|
| 93 |
+
text = torch.zeros_like(text)
|
| 94 |
+
|
| 95 |
+
text = self.text_embed(text) # b n -> b n d
|
| 96 |
+
|
| 97 |
+
# possible extra modeling
|
| 98 |
+
if self.extra_modeling:
|
| 99 |
+
# sinus pos emb
|
| 100 |
+
text = text + self.freqs_cis[:seq_len, :]
|
| 101 |
+
|
| 102 |
+
# convnextv2 blocks
|
| 103 |
+
if self.mask_padding:
|
| 104 |
+
text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
|
| 105 |
+
for block in self.text_blocks:
|
| 106 |
+
text = block(text)
|
| 107 |
+
text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
|
| 108 |
+
else:
|
| 109 |
+
text = self.text_blocks(text)
|
| 110 |
+
|
| 111 |
+
if self.average_upsampling:
|
| 112 |
+
text = self.average_upsample_text_by_mask(text, ~text_mask)
|
| 113 |
+
|
| 114 |
+
return text
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# noised waveform and context mixing embedding
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class InputEmbedding(nn.Module):
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
wav_frame_len,
|
| 124 |
+
text_dim,
|
| 125 |
+
out_dim,
|
| 126 |
+
use_audio_proj: bool = False,
|
| 127 |
+
audio_proj_dim: int | None = None,
|
| 128 |
+
audio_proj_hidden: int | None = None,
|
| 129 |
+
):
|
| 130 |
+
super().__init__()
|
| 131 |
+
|
| 132 |
+
self.use_audio_proj = use_audio_proj
|
| 133 |
+
|
| 134 |
+
if not use_audio_proj:
|
| 135 |
+
self.proj = nn.Linear(wav_frame_len * 2 + text_dim, out_dim)
|
| 136 |
+
else:
|
| 137 |
+
audio_proj_dim = out_dim if audio_proj_dim is None else audio_proj_dim
|
| 138 |
+
audio_proj_hidden = audio_proj_dim if audio_proj_hidden is None else audio_proj_hidden
|
| 139 |
+
self.x_proj = nn.Sequential(
|
| 140 |
+
nn.Linear(wav_frame_len, audio_proj_hidden, bias=False),
|
| 141 |
+
nn.Linear(audio_proj_hidden, audio_proj_dim),
|
| 142 |
+
)
|
| 143 |
+
self.cond_proj = nn.Sequential(
|
| 144 |
+
nn.Linear(wav_frame_len, audio_proj_hidden, bias=False),
|
| 145 |
+
nn.Linear(audio_proj_hidden, audio_proj_dim),
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
self.fuse = nn.Linear(audio_proj_dim * 2 + text_dim, out_dim)
|
| 149 |
+
self.conv_pos_embed = ConvPositionEmbedding(dim=out_dim)
|
| 150 |
+
|
| 151 |
+
def forward(
|
| 152 |
+
self,
|
| 153 |
+
x: float["b n d"],
|
| 154 |
+
cond: float["b n d"],
|
| 155 |
+
text_embed: float["b n d"],
|
| 156 |
+
drop_audio_cond=False,
|
| 157 |
+
audio_mask: bool["b n"] | None = None,
|
| 158 |
+
):
|
| 159 |
+
if drop_audio_cond:
|
| 160 |
+
cond = torch.zeros_like(cond)
|
| 161 |
+
|
| 162 |
+
if not self.use_audio_proj:
|
| 163 |
+
h = self.proj(torch.cat((x, cond, text_embed), dim=-1))
|
| 164 |
+
else:
|
| 165 |
+
x_h = self.x_proj(x)
|
| 166 |
+
c_h = self.cond_proj(cond)
|
| 167 |
+
h = self.fuse(torch.cat((x_h, c_h, text_embed), dim=-1))
|
| 168 |
+
|
| 169 |
+
h = self.conv_pos_embed(h, mask=audio_mask) + h
|
| 170 |
+
return h
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# Transformer backbone using DiT blocks
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class DiT(nn.Module):
|
| 177 |
+
def __init__(
|
| 178 |
+
self,
|
| 179 |
+
*,
|
| 180 |
+
dim,
|
| 181 |
+
depth=8,
|
| 182 |
+
heads=8,
|
| 183 |
+
dim_head=64,
|
| 184 |
+
dropout=0.1,
|
| 185 |
+
ff_mult=4,
|
| 186 |
+
wav_frame_len=160,
|
| 187 |
+
text_num_embeds=256,
|
| 188 |
+
text_dim=None,
|
| 189 |
+
text_mask_padding=True,
|
| 190 |
+
text_embedding_average_upsampling=False,
|
| 191 |
+
qk_norm=None,
|
| 192 |
+
conv_layers=0,
|
| 193 |
+
pe_attn_head=None,
|
| 194 |
+
attn_backend="torch", # "torch" | "flash_attn"
|
| 195 |
+
attn_mask_enabled=False,
|
| 196 |
+
long_skip_connection=False,
|
| 197 |
+
checkpoint_activations=False,
|
| 198 |
+
use_audio_proj: bool = False,
|
| 199 |
+
audio_proj_dim: int | None = None,
|
| 200 |
+
audio_proj_hidden: int | None = None,
|
| 201 |
+
):
|
| 202 |
+
super().__init__()
|
| 203 |
+
|
| 204 |
+
self.time_embed = TimestepEmbedding(dim)
|
| 205 |
+
if text_dim is None:
|
| 206 |
+
text_dim = wav_frame_len
|
| 207 |
+
self.text_embed = TextEmbedding(
|
| 208 |
+
text_num_embeds,
|
| 209 |
+
text_dim,
|
| 210 |
+
mask_padding=text_mask_padding,
|
| 211 |
+
average_upsampling=text_embedding_average_upsampling,
|
| 212 |
+
conv_layers=conv_layers,
|
| 213 |
+
)
|
| 214 |
+
self.text_cond, self.text_uncond = None, None # text cache
|
| 215 |
+
self.input_embed = InputEmbedding(
|
| 216 |
+
wav_frame_len, text_dim, dim,
|
| 217 |
+
use_audio_proj=use_audio_proj,
|
| 218 |
+
audio_proj_dim=audio_proj_dim,
|
| 219 |
+
audio_proj_hidden=audio_proj_hidden,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
self.rotary_embed = RotaryEmbedding(dim_head)
|
| 223 |
+
|
| 224 |
+
self.dim = dim
|
| 225 |
+
self.depth = depth
|
| 226 |
+
|
| 227 |
+
self.transformer_blocks = nn.ModuleList(
|
| 228 |
+
[
|
| 229 |
+
DiTBlock(
|
| 230 |
+
dim=dim,
|
| 231 |
+
heads=heads,
|
| 232 |
+
dim_head=dim_head,
|
| 233 |
+
ff_mult=ff_mult,
|
| 234 |
+
dropout=dropout,
|
| 235 |
+
qk_norm=qk_norm,
|
| 236 |
+
pe_attn_head=pe_attn_head,
|
| 237 |
+
attn_backend=attn_backend,
|
| 238 |
+
attn_mask_enabled=attn_mask_enabled,
|
| 239 |
+
)
|
| 240 |
+
for _ in range(depth)
|
| 241 |
+
]
|
| 242 |
+
)
|
| 243 |
+
self.long_skip_connection = nn.Linear(dim * 2, dim, bias=False) if long_skip_connection else None
|
| 244 |
+
|
| 245 |
+
self.norm_out = AdaLayerNorm_Final(dim) # final modulation
|
| 246 |
+
self.proj_out_dim = wav_frame_len
|
| 247 |
+
self.proj_out = nn.Linear(dim, wav_frame_len)
|
| 248 |
+
self.proj_out_output_layer = self.proj_out
|
| 249 |
+
|
| 250 |
+
self.checkpoint_activations = checkpoint_activations
|
| 251 |
+
|
| 252 |
+
self.initialize_weights()
|
| 253 |
+
|
| 254 |
+
# raw waveform tokenization.
|
| 255 |
+
self.wav_frame_len = wav_frame_len
|
| 256 |
+
|
| 257 |
+
def initialize_weights(self):
|
| 258 |
+
# def _basic_init(module):
|
| 259 |
+
# if isinstance(module, nn.Linear):
|
| 260 |
+
# torch.nn.init.xavier_uniform_(module.weight)
|
| 261 |
+
# if module.bias is not None:
|
| 262 |
+
# nn.init.constant_(module.bias, 0)
|
| 263 |
+
|
| 264 |
+
# self.apply(_basic_init)
|
| 265 |
+
|
| 266 |
+
# # Initialize timestep embedding MLP:
|
| 267 |
+
# nn.init.normal_(self.t_embed.mlp[0].weight, std=0.02)
|
| 268 |
+
# nn.init.normal_(self.t_embed.mlp[2].weight, std=0.02)
|
| 269 |
+
|
| 270 |
+
# Zero-out AdaLN layers in DiT blocks:
|
| 271 |
+
for block in self.transformer_blocks:
|
| 272 |
+
nn.init.constant_(block.attn_norm.linear.weight, 0)
|
| 273 |
+
nn.init.constant_(block.attn_norm.linear.bias, 0)
|
| 274 |
+
|
| 275 |
+
# Zero-out output layers:
|
| 276 |
+
nn.init.constant_(self.norm_out.linear.weight, 0)
|
| 277 |
+
nn.init.constant_(self.norm_out.linear.bias, 0)
|
| 278 |
+
nn.init.constant_(self.proj_out_output_layer.weight, 0)
|
| 279 |
+
if self.proj_out_output_layer.bias is not None:
|
| 280 |
+
nn.init.constant_(self.proj_out_output_layer.bias, 0)
|
| 281 |
+
|
| 282 |
+
def set_wav_frame_len(self, wav_frame_len: int):
|
| 283 |
+
self.wav_frame_len = int(wav_frame_len)
|
| 284 |
+
|
| 285 |
+
if self.wav_frame_len != self.proj_out_dim:
|
| 286 |
+
raise ValueError(
|
| 287 |
+
f"wav_frame_len ({self.wav_frame_len}) must equal proj_out_dim ({self.proj_out_dim}) "
|
| 288 |
+
"for reshape wav front-end."
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
def _wav_to_tokens(
|
| 292 |
+
self,
|
| 293 |
+
wav: torch.Tensor,
|
| 294 |
+
mask: torch.Tensor | None = None,
|
| 295 |
+
lens: torch.Tensor | None = None,
|
| 296 |
+
):
|
| 297 |
+
assert wav.ndim == 2, f"Expected [B, N] wav input, got {tuple(wav.shape)}"
|
| 298 |
+
|
| 299 |
+
bsz, num_samples = wav.shape
|
| 300 |
+
frame_len = self.wav_frame_len
|
| 301 |
+
pad_len = (frame_len - (num_samples % frame_len)) % frame_len
|
| 302 |
+
|
| 303 |
+
if pad_len > 0:
|
| 304 |
+
wav = F.pad(wav, (0, pad_len), value=0.0)
|
| 305 |
+
if mask is not None:
|
| 306 |
+
mask = F.pad(mask, (0, pad_len), value=False)
|
| 307 |
+
|
| 308 |
+
tokens = wav.view(bsz, -1, frame_len)
|
| 309 |
+
|
| 310 |
+
token_mask = None
|
| 311 |
+
if mask is not None:
|
| 312 |
+
token_mask = mask.view(bsz, -1, frame_len).any(dim=-1)
|
| 313 |
+
|
| 314 |
+
token_lens = None
|
| 315 |
+
if lens is not None:
|
| 316 |
+
token_lens = (lens.to(dtype=torch.long, device=wav.device) + frame_len - 1) // frame_len
|
| 317 |
+
|
| 318 |
+
return tokens, token_mask, token_lens
|
| 319 |
+
|
| 320 |
+
def _tokens_to_wav(self, tokens: torch.Tensor, target_num_samples: int):
|
| 321 |
+
wav = tokens.reshape(tokens.shape[0], -1)
|
| 322 |
+
return wav[:, :target_num_samples]
|
| 323 |
+
|
| 324 |
+
def ckpt_wrapper(self, module):
|
| 325 |
+
# https://github.com/chuanyangjin/fast-DiT/blob/main/models.py
|
| 326 |
+
def ckpt_forward(*inputs):
|
| 327 |
+
outputs = module(*inputs)
|
| 328 |
+
return outputs
|
| 329 |
+
|
| 330 |
+
return ckpt_forward
|
| 331 |
+
|
| 332 |
+
def get_input_embed(
|
| 333 |
+
self,
|
| 334 |
+
x, # b n d
|
| 335 |
+
cond, # b n d
|
| 336 |
+
text, # b nt
|
| 337 |
+
drop_audio_cond: bool = False,
|
| 338 |
+
drop_text: bool = False,
|
| 339 |
+
cache: bool = True,
|
| 340 |
+
audio_mask: bool["b n"] | None = None,
|
| 341 |
+
):
|
| 342 |
+
if self.text_uncond is None or self.text_cond is None or not cache:
|
| 343 |
+
if audio_mask is None:
|
| 344 |
+
text_embed = self.text_embed(text, x.shape[1], drop_text=drop_text)
|
| 345 |
+
else:
|
| 346 |
+
batch = x.shape[0]
|
| 347 |
+
seq_lens = audio_mask.sum(dim=1) # Calculate the actual sequence length for each sample
|
| 348 |
+
text_embed_list = []
|
| 349 |
+
for i in range(batch):
|
| 350 |
+
text_embed_i = self.text_embed(
|
| 351 |
+
text[i].unsqueeze(0),
|
| 352 |
+
seq_len=seq_lens[i].item(),
|
| 353 |
+
drop_text=drop_text,
|
| 354 |
+
)
|
| 355 |
+
text_embed_list.append(text_embed_i[0])
|
| 356 |
+
text_embed = pad_sequence(text_embed_list, batch_first=True, padding_value=0)
|
| 357 |
+
if cache:
|
| 358 |
+
if drop_text:
|
| 359 |
+
self.text_uncond = text_embed
|
| 360 |
+
else:
|
| 361 |
+
self.text_cond = text_embed
|
| 362 |
+
|
| 363 |
+
if cache:
|
| 364 |
+
if drop_text:
|
| 365 |
+
text_embed = self.text_uncond
|
| 366 |
+
else:
|
| 367 |
+
text_embed = self.text_cond
|
| 368 |
+
|
| 369 |
+
x = self.input_embed(x, cond, text_embed, drop_audio_cond=drop_audio_cond, audio_mask=audio_mask)
|
| 370 |
+
|
| 371 |
+
return x
|
| 372 |
+
|
| 373 |
+
def clear_cache(self):
|
| 374 |
+
self.text_cond, self.text_uncond = None, None
|
| 375 |
+
|
| 376 |
+
def forward(
|
| 377 |
+
self,
|
| 378 |
+
x: float["b nw"], # noised waveform
|
| 379 |
+
cond: float["b nw"], # masked conditioning waveform
|
| 380 |
+
text: int["b nt"], # text
|
| 381 |
+
time: float["b"] | float[""], # time step
|
| 382 |
+
mask: bool["b n"] | bool["b nw"] | None = None,
|
| 383 |
+
drop_audio_cond: bool = False, # cfg for conditioning waveform
|
| 384 |
+
drop_text: bool = False, # cfg for text
|
| 385 |
+
cfg_infer: bool = False, # cfg inference, pack cond & uncond forward
|
| 386 |
+
cache: bool = False,
|
| 387 |
+
lens: int["b"] | None = None,
|
| 388 |
+
):
|
| 389 |
+
if x.ndim != 2 or cond.ndim != 2:
|
| 390 |
+
raise ValueError(f"WavTTS DiT expects raw waveform x/cond [B, N], got {x.ndim}D and {cond.ndim}D.")
|
| 391 |
+
|
| 392 |
+
target_num_samples = x.shape[1]
|
| 393 |
+
x, token_mask, token_lens = self._wav_to_tokens(x, mask=mask, lens=lens)
|
| 394 |
+
cond, _, _ = self._wav_to_tokens(cond, mask=None, lens=None)
|
| 395 |
+
mask = token_mask
|
| 396 |
+
lens = token_lens
|
| 397 |
+
|
| 398 |
+
batch, seq_len = x.shape[0], x.shape[1]
|
| 399 |
+
if time.ndim == 0:
|
| 400 |
+
time = time.repeat(batch)
|
| 401 |
+
|
| 402 |
+
# t: conditioning time, text: text, x: noised waveform + conditioning waveform + text
|
| 403 |
+
t = self.time_embed(time)
|
| 404 |
+
|
| 405 |
+
if cfg_infer: # pack cond & uncond forward: b n d -> 2b n d
|
| 406 |
+
x_cond = self.get_input_embed(
|
| 407 |
+
x, cond, text, drop_audio_cond=False, drop_text=False, cache=cache, audio_mask=mask
|
| 408 |
+
)
|
| 409 |
+
x_uncond = self.get_input_embed(
|
| 410 |
+
x, cond, text, drop_audio_cond=True, drop_text=True, cache=cache, audio_mask=mask
|
| 411 |
+
)
|
| 412 |
+
x = torch.cat((x_cond, x_uncond), dim=0)
|
| 413 |
+
t = torch.cat((t, t), dim=0)
|
| 414 |
+
mask = torch.cat((mask, mask), dim=0) if mask is not None else None
|
| 415 |
+
else:
|
| 416 |
+
x = self.get_input_embed(
|
| 417 |
+
x, cond, text, drop_audio_cond=drop_audio_cond, drop_text=drop_text, cache=cache, audio_mask=mask
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
rope = self.rotary_embed.forward_from_seq_len(seq_len)
|
| 421 |
+
|
| 422 |
+
if self.long_skip_connection is not None:
|
| 423 |
+
residual = x
|
| 424 |
+
|
| 425 |
+
for i, block in enumerate(self.transformer_blocks):
|
| 426 |
+
if self.checkpoint_activations:
|
| 427 |
+
# https://pytorch.org/docs/stable/checkpoint.html#torch.utils.checkpoint.checkpoint
|
| 428 |
+
x = torch.utils.checkpoint.checkpoint(self.ckpt_wrapper(block), x, t, mask, rope, use_reentrant=False)
|
| 429 |
+
else:
|
| 430 |
+
x = block(x, t, mask=mask, rope=rope)
|
| 431 |
+
|
| 432 |
+
if self.long_skip_connection is not None:
|
| 433 |
+
x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
|
| 434 |
+
|
| 435 |
+
x = self.norm_out(x, t)
|
| 436 |
+
output = self.proj_out(x)
|
| 437 |
+
|
| 438 |
+
output = self._tokens_to_wav(output, target_num_samples=target_num_samples)
|
| 439 |
+
|
| 440 |
+
return output, None, None
|
src/wavtts/model/backbones/mmdit.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ein notation:
|
| 3 |
+
b - batch
|
| 4 |
+
n - sequence
|
| 5 |
+
nt - text sequence
|
| 6 |
+
nw - raw wave length
|
| 7 |
+
d - dimension
|
| 8 |
+
"""
|
| 9 |
+
# ruff: noqa: F722 F821
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch import nn
|
| 15 |
+
from x_transformers.x_transformers import RotaryEmbedding
|
| 16 |
+
|
| 17 |
+
from wavtts.model.modules import (
|
| 18 |
+
AdaLayerNorm_Final,
|
| 19 |
+
ConvPositionEmbedding,
|
| 20 |
+
MMDiTBlock,
|
| 21 |
+
TimestepEmbedding,
|
| 22 |
+
get_pos_embed_indices,
|
| 23 |
+
precompute_freqs_cis,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# text embedding
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TextEmbedding(nn.Module):
|
| 31 |
+
def __init__(self, out_dim, text_num_embeds, mask_padding=True):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.text_embed = nn.Embedding(text_num_embeds + 1, out_dim) # will use 0 as filler token
|
| 34 |
+
|
| 35 |
+
self.mask_padding = mask_padding # mask filler and batch padding tokens or not
|
| 36 |
+
|
| 37 |
+
self.precompute_max_pos = 1024
|
| 38 |
+
self.register_buffer("freqs_cis", precompute_freqs_cis(out_dim, self.precompute_max_pos), persistent=False)
|
| 39 |
+
|
| 40 |
+
def forward(self, text: int["b nt"], drop_text=False) -> int["b nt d"]:
|
| 41 |
+
text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx()
|
| 42 |
+
if self.mask_padding:
|
| 43 |
+
text_mask = text == 0
|
| 44 |
+
|
| 45 |
+
if drop_text: # cfg for text
|
| 46 |
+
text = torch.zeros_like(text)
|
| 47 |
+
|
| 48 |
+
text = self.text_embed(text) # b nt -> b nt d
|
| 49 |
+
|
| 50 |
+
# sinus pos emb
|
| 51 |
+
batch_start = torch.zeros((text.shape[0],), dtype=torch.long)
|
| 52 |
+
batch_text_len = text.shape[1]
|
| 53 |
+
pos_idx = get_pos_embed_indices(batch_start, batch_text_len, max_pos=self.precompute_max_pos)
|
| 54 |
+
text_pos_embed = self.freqs_cis[pos_idx]
|
| 55 |
+
|
| 56 |
+
text = text + text_pos_embed
|
| 57 |
+
|
| 58 |
+
if self.mask_padding:
|
| 59 |
+
text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
|
| 60 |
+
|
| 61 |
+
return text
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# noised input & masked cond audio embedding
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class AudioEmbedding(nn.Module):
|
| 68 |
+
def __init__(self, in_dim, out_dim):
|
| 69 |
+
super().__init__()
|
| 70 |
+
self.linear = nn.Linear(2 * in_dim, out_dim)
|
| 71 |
+
self.conv_pos_embed = ConvPositionEmbedding(out_dim)
|
| 72 |
+
|
| 73 |
+
def forward(self, x: float["b n d"], cond: float["b n d"], drop_audio_cond=False):
|
| 74 |
+
if drop_audio_cond:
|
| 75 |
+
cond = torch.zeros_like(cond)
|
| 76 |
+
x = torch.cat((x, cond), dim=-1)
|
| 77 |
+
x = self.linear(x)
|
| 78 |
+
x = self.conv_pos_embed(x) + x
|
| 79 |
+
return x
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# Transformer backbone using MM-DiT blocks
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class MMDiT(nn.Module):
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
*,
|
| 89 |
+
dim,
|
| 90 |
+
depth=8,
|
| 91 |
+
heads=8,
|
| 92 |
+
dim_head=64,
|
| 93 |
+
dropout=0.1,
|
| 94 |
+
ff_mult=4,
|
| 95 |
+
wav_frame_len=100,
|
| 96 |
+
text_num_embeds=256,
|
| 97 |
+
text_mask_padding=True,
|
| 98 |
+
qk_norm=None,
|
| 99 |
+
):
|
| 100 |
+
super().__init__()
|
| 101 |
+
|
| 102 |
+
self.time_embed = TimestepEmbedding(dim)
|
| 103 |
+
self.text_embed = TextEmbedding(dim, text_num_embeds, mask_padding=text_mask_padding)
|
| 104 |
+
self.text_cond, self.text_uncond = None, None # text cache
|
| 105 |
+
self.audio_embed = AudioEmbedding(wav_frame_len, dim)
|
| 106 |
+
|
| 107 |
+
self.rotary_embed = RotaryEmbedding(dim_head)
|
| 108 |
+
|
| 109 |
+
self.dim = dim
|
| 110 |
+
self.depth = depth
|
| 111 |
+
|
| 112 |
+
self.transformer_blocks = nn.ModuleList(
|
| 113 |
+
[
|
| 114 |
+
MMDiTBlock(
|
| 115 |
+
dim=dim,
|
| 116 |
+
heads=heads,
|
| 117 |
+
dim_head=dim_head,
|
| 118 |
+
dropout=dropout,
|
| 119 |
+
ff_mult=ff_mult,
|
| 120 |
+
context_pre_only=i == depth - 1,
|
| 121 |
+
qk_norm=qk_norm,
|
| 122 |
+
)
|
| 123 |
+
for i in range(depth)
|
| 124 |
+
]
|
| 125 |
+
)
|
| 126 |
+
self.norm_out = AdaLayerNorm_Final(dim) # final modulation
|
| 127 |
+
self.proj_out = nn.Linear(dim, wav_frame_len)
|
| 128 |
+
|
| 129 |
+
self.initialize_weights()
|
| 130 |
+
|
| 131 |
+
def initialize_weights(self):
|
| 132 |
+
# Zero-out AdaLN layers in MMDiT blocks:
|
| 133 |
+
for block in self.transformer_blocks:
|
| 134 |
+
nn.init.constant_(block.attn_norm_x.linear.weight, 0)
|
| 135 |
+
nn.init.constant_(block.attn_norm_x.linear.bias, 0)
|
| 136 |
+
nn.init.constant_(block.attn_norm_c.linear.weight, 0)
|
| 137 |
+
nn.init.constant_(block.attn_norm_c.linear.bias, 0)
|
| 138 |
+
|
| 139 |
+
# Zero-out output layers:
|
| 140 |
+
nn.init.constant_(self.norm_out.linear.weight, 0)
|
| 141 |
+
nn.init.constant_(self.norm_out.linear.bias, 0)
|
| 142 |
+
nn.init.constant_(self.proj_out.weight, 0)
|
| 143 |
+
nn.init.constant_(self.proj_out.bias, 0)
|
| 144 |
+
|
| 145 |
+
def get_input_embed(
|
| 146 |
+
self,
|
| 147 |
+
x, # b n d
|
| 148 |
+
cond, # b n d
|
| 149 |
+
text, # b nt
|
| 150 |
+
drop_audio_cond: bool = False,
|
| 151 |
+
drop_text: bool = False,
|
| 152 |
+
cache: bool = True,
|
| 153 |
+
):
|
| 154 |
+
if cache:
|
| 155 |
+
if drop_text:
|
| 156 |
+
if self.text_uncond is None:
|
| 157 |
+
self.text_uncond = self.text_embed(text, drop_text=True)
|
| 158 |
+
c = self.text_uncond
|
| 159 |
+
else:
|
| 160 |
+
if self.text_cond is None:
|
| 161 |
+
self.text_cond = self.text_embed(text, drop_text=False)
|
| 162 |
+
c = self.text_cond
|
| 163 |
+
else:
|
| 164 |
+
c = self.text_embed(text, drop_text=drop_text)
|
| 165 |
+
x = self.audio_embed(x, cond, drop_audio_cond=drop_audio_cond)
|
| 166 |
+
|
| 167 |
+
return x, c
|
| 168 |
+
|
| 169 |
+
def clear_cache(self):
|
| 170 |
+
self.text_cond, self.text_uncond = None, None
|
| 171 |
+
|
| 172 |
+
def forward(
|
| 173 |
+
self,
|
| 174 |
+
x: float["b n d"], # nosied input audio
|
| 175 |
+
cond: float["b n d"], # masked cond audio
|
| 176 |
+
text: int["b nt"], # text
|
| 177 |
+
time: float["b"] | float[""], # time step
|
| 178 |
+
mask: bool["b n"] | None = None,
|
| 179 |
+
drop_audio_cond: bool = False, # cfg for cond audio
|
| 180 |
+
drop_text: bool = False, # cfg for text
|
| 181 |
+
cfg_infer: bool = False, # cfg inference, pack cond & uncond forward
|
| 182 |
+
cache: bool = False,
|
| 183 |
+
):
|
| 184 |
+
batch = x.shape[0]
|
| 185 |
+
if time.ndim == 0:
|
| 186 |
+
time = time.repeat(batch)
|
| 187 |
+
|
| 188 |
+
# t: conditioning (time), c: context (text + masked cond audio), x: noised input audio
|
| 189 |
+
t = self.time_embed(time)
|
| 190 |
+
if cfg_infer: # pack cond & uncond forward: b n d -> 2b n d
|
| 191 |
+
x_cond, c_cond = self.get_input_embed(x, cond, text, drop_audio_cond=False, drop_text=False, cache=cache)
|
| 192 |
+
x_uncond, c_uncond = self.get_input_embed(x, cond, text, drop_audio_cond=True, drop_text=True, cache=cache)
|
| 193 |
+
x = torch.cat((x_cond, x_uncond), dim=0)
|
| 194 |
+
c = torch.cat((c_cond, c_uncond), dim=0)
|
| 195 |
+
t = torch.cat((t, t), dim=0)
|
| 196 |
+
mask = torch.cat((mask, mask), dim=0) if mask is not None else None
|
| 197 |
+
else:
|
| 198 |
+
x, c = self.get_input_embed(
|
| 199 |
+
x, cond, text, drop_audio_cond=drop_audio_cond, drop_text=drop_text, cache=cache
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
seq_len = x.shape[1]
|
| 203 |
+
text_len = text.shape[1]
|
| 204 |
+
rope_audio = self.rotary_embed.forward_from_seq_len(seq_len)
|
| 205 |
+
rope_text = self.rotary_embed.forward_from_seq_len(text_len)
|
| 206 |
+
|
| 207 |
+
for block in self.transformer_blocks:
|
| 208 |
+
c, x = block(x, c, t, mask=mask, rope=rope_audio, c_rope=rope_text)
|
| 209 |
+
|
| 210 |
+
x = self.norm_out(x, t)
|
| 211 |
+
output = self.proj_out(x)
|
| 212 |
+
|
| 213 |
+
return output
|
src/wavtts/model/cfm.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ein notation:
|
| 3 |
+
b - batch
|
| 4 |
+
n - sequence
|
| 5 |
+
nt - text sequence
|
| 6 |
+
nw - raw wave length
|
| 7 |
+
d - dimension
|
| 8 |
+
"""
|
| 9 |
+
# ruff: noqa: F722 F821
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from random import random
|
| 14 |
+
import math
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from torch import nn
|
| 19 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 20 |
+
from torchdiffeq import odeint
|
| 21 |
+
|
| 22 |
+
from wavtts.model.modules import MelSpectrogramLoss
|
| 23 |
+
from wavtts.model.utils import (
|
| 24 |
+
exists,
|
| 25 |
+
get_epss_timesteps,
|
| 26 |
+
lens_to_mask,
|
| 27 |
+
list_str_to_idx,
|
| 28 |
+
list_str_to_tensor,
|
| 29 |
+
mask_from_frac_lengths,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class CFM(nn.Module):
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
transformer: nn.Module,
|
| 37 |
+
sigma=0.0,
|
| 38 |
+
odeint_kwargs: dict = dict(
|
| 39 |
+
# atol = 1e-5,
|
| 40 |
+
# rtol = 1e-5,
|
| 41 |
+
method="euler" # 'midpoint'
|
| 42 |
+
),
|
| 43 |
+
audio_drop_prob=0.3,
|
| 44 |
+
cond_drop_prob=0.2,
|
| 45 |
+
joint_cond_drop_prob=0.0,
|
| 46 |
+
waveform_kwargs: dict = dict(),
|
| 47 |
+
frac_lengths_mask: tuple[float, float] = (0.7, 1.0),
|
| 48 |
+
vocab_char_map: dict[str:int] | None = None,
|
| 49 |
+
prediction: str = "flow", # "flow" | "x_pred"
|
| 50 |
+
loss_space: str = "flow", # "flow" | "v" | "x"
|
| 51 |
+
t_sampling: str = "uniform", # "uniform" | "logistic_normal"
|
| 52 |
+
P_mean: float = 0.0,
|
| 53 |
+
P_std: float = 1.0,
|
| 54 |
+
time_shift: float = 1.0,
|
| 55 |
+
t_eps: float = 1e-4,
|
| 56 |
+
use_aux_mel_loss: bool = False,
|
| 57 |
+
aux_mel_loss_weight: float = 0.0,
|
| 58 |
+
aux_mel_loss_masked: bool = True,
|
| 59 |
+
sample_rate: int = 16000,
|
| 60 |
+
latents_scale: float = 1.0,
|
| 61 |
+
):
|
| 62 |
+
super().__init__()
|
| 63 |
+
|
| 64 |
+
self.frac_lengths_mask = frac_lengths_mask
|
| 65 |
+
|
| 66 |
+
# waveform geometry
|
| 67 |
+
waveform_kwargs = dict(waveform_kwargs)
|
| 68 |
+
self.wav_frame_len = int(waveform_kwargs.pop("wav_frame_len", 160))
|
| 69 |
+
self.num_channels = self.wav_frame_len
|
| 70 |
+
|
| 71 |
+
# classifier-free guidance
|
| 72 |
+
self.audio_drop_prob = audio_drop_prob
|
| 73 |
+
self.cond_drop_prob = cond_drop_prob
|
| 74 |
+
self.joint_cond_drop_prob = joint_cond_drop_prob
|
| 75 |
+
|
| 76 |
+
# transformer
|
| 77 |
+
self.transformer = transformer
|
| 78 |
+
self.dim = transformer.dim
|
| 79 |
+
|
| 80 |
+
if hasattr(self.transformer, "set_wav_frame_len"):
|
| 81 |
+
self.transformer.set_wav_frame_len(self.wav_frame_len)
|
| 82 |
+
|
| 83 |
+
# conditional flow related
|
| 84 |
+
self.sigma = sigma
|
| 85 |
+
|
| 86 |
+
# sampling related
|
| 87 |
+
self.odeint_kwargs = odeint_kwargs
|
| 88 |
+
|
| 89 |
+
# vocab map for tokenization
|
| 90 |
+
self.vocab_char_map = vocab_char_map
|
| 91 |
+
|
| 92 |
+
# enhanced flow model settings
|
| 93 |
+
self.prediction = prediction
|
| 94 |
+
self.loss_space = loss_space
|
| 95 |
+
self.t_sampling = t_sampling
|
| 96 |
+
self.P_mean = P_mean
|
| 97 |
+
self.P_std = P_std
|
| 98 |
+
self.time_shift = time_shift
|
| 99 |
+
self.t_eps = t_eps
|
| 100 |
+
self.latents_scale = latents_scale
|
| 101 |
+
self.target_sample_rate = sample_rate
|
| 102 |
+
# aux mel loss
|
| 103 |
+
self.use_aux_mel_loss = use_aux_mel_loss
|
| 104 |
+
self.aux_mel_loss_masked = aux_mel_loss_masked
|
| 105 |
+
if self.use_aux_mel_loss:
|
| 106 |
+
self.aux_mel_loss = MelSpectrogramLoss(
|
| 107 |
+
sample_rate=sample_rate,
|
| 108 |
+
n_mels=[5, 10, 20, 40, 80, 160, 320],
|
| 109 |
+
window_lengths=[32, 64, 128, 256, 512, 1024, 2048],
|
| 110 |
+
mel_fmin=[0, 0, 0, 0, 0, 0, 0],
|
| 111 |
+
mel_fmax=[None] * 7,
|
| 112 |
+
pow=1.0,
|
| 113 |
+
clamp_eps=1e-5,
|
| 114 |
+
weight=aux_mel_loss_weight,
|
| 115 |
+
)
|
| 116 |
+
else:
|
| 117 |
+
self.aux_mel_loss = None
|
| 118 |
+
|
| 119 |
+
self.mask_align_to = 1
|
| 120 |
+
alignments = []
|
| 121 |
+
if self.aux_mel_loss is not None and hasattr(self.aux_mel_loss, "mel_transforms"):
|
| 122 |
+
hop_lengths = [int(m.hop_length) for m in self.aux_mel_loss.mel_transforms]
|
| 123 |
+
if len(hop_lengths) > 0:
|
| 124 |
+
lcm_hop = hop_lengths[0]
|
| 125 |
+
for h in hop_lengths[1:]:
|
| 126 |
+
lcm_hop = math.lcm(lcm_hop, h)
|
| 127 |
+
alignments.append(lcm_hop)
|
| 128 |
+
if len(alignments) > 0:
|
| 129 |
+
lcm_align = alignments[0]
|
| 130 |
+
for a in alignments[1:]:
|
| 131 |
+
lcm_align = math.lcm(lcm_align, a)
|
| 132 |
+
self.mask_align_to = max(1, lcm_align)
|
| 133 |
+
|
| 134 |
+
@property
|
| 135 |
+
def device(self):
|
| 136 |
+
return next(self.parameters()).device
|
| 137 |
+
|
| 138 |
+
def _sample_time(self, batch: int, dtype, device):
|
| 139 |
+
if self.t_sampling == "uniform":
|
| 140 |
+
t = torch.rand((batch,), dtype=dtype, device=device)
|
| 141 |
+
elif self.t_sampling == "logistic_normal":
|
| 142 |
+
# JiT: t = sigmoid(N(P_mean, P_std))
|
| 143 |
+
z = torch.randn((batch,), device=device, dtype=dtype) * self.P_std + self.P_mean
|
| 144 |
+
t = torch.sigmoid(z)
|
| 145 |
+
else:
|
| 146 |
+
raise ValueError(f"Unknown t_sampling: {self.t_sampling}")
|
| 147 |
+
|
| 148 |
+
if self.time_shift != 1.0:
|
| 149 |
+
t = t / (t + self.time_shift * (1 - t))
|
| 150 |
+
|
| 151 |
+
return t
|
| 152 |
+
|
| 153 |
+
def _x_to_v(self, x_pred, z, t):
|
| 154 |
+
# v_pred = (x_pred - z) / (1 - t)
|
| 155 |
+
denom = (1.0 - t).clamp_min(self.t_eps)
|
| 156 |
+
while denom.ndim < z.ndim:
|
| 157 |
+
denom = denom.unsqueeze(-1)
|
| 158 |
+
return (x_pred - z) / denom
|
| 159 |
+
|
| 160 |
+
@torch.no_grad()
|
| 161 |
+
def sample(
|
| 162 |
+
self,
|
| 163 |
+
cond: float["b n d"] | float["b nw"],
|
| 164 |
+
text: int["b nt"] | list[str],
|
| 165 |
+
duration: int | int["b"],
|
| 166 |
+
*,
|
| 167 |
+
lens: int["b"] | None = None,
|
| 168 |
+
steps=32,
|
| 169 |
+
cfg_strength=1.0,
|
| 170 |
+
sway_sampling_coef=None,
|
| 171 |
+
timestep_mapping="sway_sampling",
|
| 172 |
+
timestep_power=None,
|
| 173 |
+
shift=1.0,
|
| 174 |
+
seed: int | None = None,
|
| 175 |
+
max_duration=4096,
|
| 176 |
+
use_epss=True,
|
| 177 |
+
no_ref_audio=False,
|
| 178 |
+
duplicate_test=False,
|
| 179 |
+
t_inter=0.1,
|
| 180 |
+
edit_mask=None,
|
| 181 |
+
):
|
| 182 |
+
self.eval()
|
| 183 |
+
# raw wave
|
| 184 |
+
if cond.ndim != 2:
|
| 185 |
+
raise ValueError(f"WavTTS expects raw waveform conditioning [B, N], got {tuple(cond.shape)}")
|
| 186 |
+
|
| 187 |
+
cond = cond.to(next(self.parameters()).dtype)
|
| 188 |
+
cond = cond * self.latents_scale
|
| 189 |
+
|
| 190 |
+
batch, cond_seq_len, device = *cond.shape[:2], cond.device
|
| 191 |
+
if not exists(lens):
|
| 192 |
+
lens = torch.full((batch,), cond_seq_len, device=device, dtype=torch.long)
|
| 193 |
+
|
| 194 |
+
# text
|
| 195 |
+
if isinstance(text, list):
|
| 196 |
+
if exists(self.vocab_char_map):
|
| 197 |
+
text = list_str_to_idx(text, self.vocab_char_map).to(device)
|
| 198 |
+
else:
|
| 199 |
+
text = list_str_to_tensor(text).to(device)
|
| 200 |
+
assert text.shape[0] == batch
|
| 201 |
+
|
| 202 |
+
# duration
|
| 203 |
+
cond_mask = lens_to_mask(lens)
|
| 204 |
+
if edit_mask is not None:
|
| 205 |
+
cond_mask = cond_mask & edit_mask
|
| 206 |
+
|
| 207 |
+
if isinstance(duration, int):
|
| 208 |
+
duration = torch.full((batch,), duration, device=device, dtype=torch.long)
|
| 209 |
+
|
| 210 |
+
# keep legacy max_duration semantics for wav path: 4096 means 4096 frame-tokens.
|
| 211 |
+
max_duration_limit = max_duration * self.wav_frame_len
|
| 212 |
+
duration = torch.maximum(
|
| 213 |
+
torch.maximum((text != -1).sum(dim=-1), lens) + 1, duration
|
| 214 |
+
) # duration at least text/audio prompt length plus one token, so something is generated
|
| 215 |
+
duration = duration.clamp(max=max_duration_limit)
|
| 216 |
+
max_duration = duration.amax()
|
| 217 |
+
|
| 218 |
+
# duplicate test corner for inner time step oberservation
|
| 219 |
+
if duplicate_test:
|
| 220 |
+
test_cond = F.pad(cond, (cond_seq_len, max_duration - 2 * cond_seq_len), value=0.0)
|
| 221 |
+
|
| 222 |
+
cond = F.pad(cond, (0, max_duration - cond_seq_len), value=0.0)
|
| 223 |
+
if no_ref_audio:
|
| 224 |
+
cond = torch.zeros_like(cond)
|
| 225 |
+
|
| 226 |
+
cond_mask = F.pad(cond_mask, (0, max_duration - cond_mask.shape[-1]), value=False)
|
| 227 |
+
step_cond = torch.where(cond_mask, cond, torch.zeros_like(cond))
|
| 228 |
+
|
| 229 |
+
if batch > 1:
|
| 230 |
+
mask = lens_to_mask(duration, length=max_duration)
|
| 231 |
+
else: # save memory and speed up, as single inference need no mask currently
|
| 232 |
+
mask = None
|
| 233 |
+
|
| 234 |
+
# neural ode
|
| 235 |
+
|
| 236 |
+
def fn(t, x):
|
| 237 |
+
# at each step, conditioning is fixed
|
| 238 |
+
# step_cond = torch.where(cond_mask, cond, torch.zeros_like(cond))
|
| 239 |
+
def to_v(pred_x_or_v):
|
| 240 |
+
if self.prediction == "flow":
|
| 241 |
+
return pred_x_or_v
|
| 242 |
+
else: # x_pred
|
| 243 |
+
return self._x_to_v(pred_x_or_v, x, t)
|
| 244 |
+
|
| 245 |
+
# predict flow (cond)
|
| 246 |
+
if cfg_strength < 1e-5:
|
| 247 |
+
pred, *_ = self.transformer(
|
| 248 |
+
x=x, cond=step_cond, text=text, time=t, mask=mask,
|
| 249 |
+
drop_audio_cond=False, drop_text=False, cache=True,
|
| 250 |
+
)
|
| 251 |
+
return to_v(pred)
|
| 252 |
+
|
| 253 |
+
# predict flow (cond and uncond), for classifier-free guidance
|
| 254 |
+
pred_cfg, *_ = self.transformer(
|
| 255 |
+
x=x, cond=step_cond, text=text, time=t, mask=mask,
|
| 256 |
+
cfg_infer=True, cache=True,
|
| 257 |
+
)
|
| 258 |
+
pred, null_pred = torch.chunk(pred_cfg, 2, dim=0)
|
| 259 |
+
v_cond = to_v(pred)
|
| 260 |
+
v_uncond = to_v(null_pred)
|
| 261 |
+
|
| 262 |
+
return v_cond + (v_cond - v_uncond) * cfg_strength
|
| 263 |
+
|
| 264 |
+
# noise input
|
| 265 |
+
# to make sure batch inference result is same with different batch size, and for sure single inference
|
| 266 |
+
# still some difference maybe due to convolutional layers
|
| 267 |
+
y0 = []
|
| 268 |
+
for dur in duration:
|
| 269 |
+
if exists(seed):
|
| 270 |
+
torch.manual_seed(seed)
|
| 271 |
+
y0.append(torch.randn(dur, device=self.device, dtype=step_cond.dtype))
|
| 272 |
+
y0 = pad_sequence(y0, padding_value=0, batch_first=True)
|
| 273 |
+
|
| 274 |
+
t_start = 0
|
| 275 |
+
|
| 276 |
+
# duplicate test corner for inner time step oberservation
|
| 277 |
+
if duplicate_test:
|
| 278 |
+
t_start = t_inter
|
| 279 |
+
y0 = (1 - t_start) * y0 + t_start * test_cond
|
| 280 |
+
steps = int(steps * (1 - t_start))
|
| 281 |
+
|
| 282 |
+
use_epss = use_epss and timestep_mapping == "sway_sampling"
|
| 283 |
+
|
| 284 |
+
if t_start == 0 and use_epss: # use Empirically Pruned Step Sampling for low NFE
|
| 285 |
+
t = get_epss_timesteps(steps, device=self.device, dtype=torch.float32)
|
| 286 |
+
else:
|
| 287 |
+
t = torch.linspace(t_start, 1, steps + 1, device=self.device, dtype=torch.float32)
|
| 288 |
+
|
| 289 |
+
if timestep_mapping == "uniform":
|
| 290 |
+
pass
|
| 291 |
+
elif timestep_mapping == "sway_sampling":
|
| 292 |
+
if sway_sampling_coef is not None:
|
| 293 |
+
t = t + sway_sampling_coef * (torch.cos(torch.pi / 2 * t) - 1 + t)
|
| 294 |
+
elif timestep_mapping == "power":
|
| 295 |
+
if timestep_power is None:
|
| 296 |
+
raise ValueError("timestep_power must be provided when timestep_mapping='power'")
|
| 297 |
+
t = t.pow(timestep_power)
|
| 298 |
+
else:
|
| 299 |
+
raise ValueError(f"Unknown timestep_mapping: {timestep_mapping}")
|
| 300 |
+
|
| 301 |
+
effective_shift = shift
|
| 302 |
+
if effective_shift != 1.0:
|
| 303 |
+
t = t / (t + effective_shift * (1 - t))
|
| 304 |
+
|
| 305 |
+
# WavTTS inference uses Euler ODE sampling.
|
| 306 |
+
odeint_kwargs = dict(self.odeint_kwargs)
|
| 307 |
+
odeint_kwargs["method"] = "euler"
|
| 308 |
+
trajectory = odeint(fn, y0, t, **odeint_kwargs)
|
| 309 |
+
self.transformer.clear_cache()
|
| 310 |
+
|
| 311 |
+
sampled = trajectory[-1]
|
| 312 |
+
out = sampled
|
| 313 |
+
|
| 314 |
+
out = out / self.latents_scale
|
| 315 |
+
cond_unscaled = cond / self.latents_scale
|
| 316 |
+
out = torch.where(cond_mask, cond_unscaled, out)
|
| 317 |
+
|
| 318 |
+
# ---- wav-only: trim to generated waveform duration ----
|
| 319 |
+
wav_list = []
|
| 320 |
+
for b in range(batch):
|
| 321 |
+
wav_list.append(out[b, : duration[b].item()])
|
| 322 |
+
out = pad_sequence(wav_list, batch_first=True, padding_value=0.0) # [B, N]
|
| 323 |
+
|
| 324 |
+
return out, trajectory
|
| 325 |
+
|
| 326 |
+
def forward(
|
| 327 |
+
self,
|
| 328 |
+
inp: float["b nw"], # raw waveform
|
| 329 |
+
text: int["b nt"] | list[str],
|
| 330 |
+
*,
|
| 331 |
+
lens: int["b"] | None = None,
|
| 332 |
+
noise_scheduler: str | None = None,
|
| 333 |
+
):
|
| 334 |
+
# handle raw waveform
|
| 335 |
+
if inp.ndim != 2:
|
| 336 |
+
raise ValueError(f"WavTTS expects raw waveform input [B, N], got {tuple(inp.shape)}")
|
| 337 |
+
|
| 338 |
+
batch, seq_len, dtype, device, _σ1 = *inp.shape[:2], inp.dtype, self.device, self.sigma
|
| 339 |
+
|
| 340 |
+
# handle text as string
|
| 341 |
+
if isinstance(text, list):
|
| 342 |
+
if exists(self.vocab_char_map):
|
| 343 |
+
text = list_str_to_idx(text, self.vocab_char_map).to(device)
|
| 344 |
+
else:
|
| 345 |
+
text = list_str_to_tensor(text).to(device)
|
| 346 |
+
assert text.shape[0] == batch
|
| 347 |
+
|
| 348 |
+
# lens and mask
|
| 349 |
+
if not exists(lens): # if lens not acquired by trainer from collate_fn
|
| 350 |
+
lens = torch.full((batch,), seq_len, device=device)
|
| 351 |
+
mask = lens_to_mask(lens, length=seq_len)
|
| 352 |
+
|
| 353 |
+
# get a random span to mask out for training conditionally
|
| 354 |
+
frac_lengths = torch.zeros((batch,), device=self.device).float().uniform_(*self.frac_lengths_mask)
|
| 355 |
+
if self.mask_align_to > 1:
|
| 356 |
+
rand_span_mask = MelSpectrogramLoss._aligned_random_span_mask(
|
| 357 |
+
lengths=lens,
|
| 358 |
+
frac_lengths=frac_lengths,
|
| 359 |
+
align_to=self.mask_align_to,
|
| 360 |
+
max_length=seq_len,
|
| 361 |
+
)
|
| 362 |
+
else:
|
| 363 |
+
rand_span_mask = mask_from_frac_lengths(lens, frac_lengths)
|
| 364 |
+
|
| 365 |
+
if exists(mask):
|
| 366 |
+
rand_span_mask &= mask
|
| 367 |
+
|
| 368 |
+
# x1 is raw waveform
|
| 369 |
+
x1 = inp
|
| 370 |
+
|
| 371 |
+
x1 = x1 * self.latents_scale
|
| 372 |
+
|
| 373 |
+
# x0 is gaussian noise
|
| 374 |
+
x0 = torch.randn_like(x1)
|
| 375 |
+
|
| 376 |
+
# time step
|
| 377 |
+
time = self._sample_time(batch, dtype=dtype, device=self.device)
|
| 378 |
+
|
| 379 |
+
# sample xt (φ_t(x) in the paper)
|
| 380 |
+
t = time.unsqueeze(-1)
|
| 381 |
+
φ = (1 - t) * x0 + t * x1
|
| 382 |
+
flow = x1 - x0
|
| 383 |
+
|
| 384 |
+
# only predict what is within the random mask span for infilling
|
| 385 |
+
cond = torch.where(rand_span_mask, torch.zeros_like(x1), x1)
|
| 386 |
+
|
| 387 |
+
# transformer and cfg training with a drop rate
|
| 388 |
+
if self.joint_cond_drop_prob > 0.0:
|
| 389 |
+
joint_drop = random() < self.joint_cond_drop_prob
|
| 390 |
+
drop_audio_cond = joint_drop
|
| 391 |
+
drop_text = joint_drop
|
| 392 |
+
else:
|
| 393 |
+
drop_audio_cond = random() < self.audio_drop_prob # p_drop in voicebox paper
|
| 394 |
+
if random() < self.cond_drop_prob: # p_uncond in voicebox paper
|
| 395 |
+
drop_audio_cond = True
|
| 396 |
+
drop_text = True
|
| 397 |
+
else:
|
| 398 |
+
drop_text = False
|
| 399 |
+
|
| 400 |
+
# apply mask will use more memory; might adjust batchsize or batchsampler long sequence threshold
|
| 401 |
+
raw_pred, *_ = self.transformer(
|
| 402 |
+
x=φ, cond=cond, text=text, time=time,
|
| 403 |
+
drop_audio_cond=drop_audio_cond, drop_text=drop_text, mask=mask,
|
| 404 |
+
lens=lens,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
# interpret prediction
|
| 408 |
+
if self.prediction == "flow":
|
| 409 |
+
v_pred = raw_pred
|
| 410 |
+
x_pred = φ + (1.0 - t) * v_pred
|
| 411 |
+
elif self.prediction == "x_pred":
|
| 412 |
+
x_pred = raw_pred
|
| 413 |
+
v_pred = self._x_to_v(x_pred, φ, time)
|
| 414 |
+
else:
|
| 415 |
+
raise ValueError(f"Unknown prediction: {self.prediction}")
|
| 416 |
+
|
| 417 |
+
# loss space
|
| 418 |
+
if self.loss_space == "flow":
|
| 419 |
+
loss = F.mse_loss(v_pred, flow, reduction="none")
|
| 420 |
+
elif self.loss_space == "v":
|
| 421 |
+
# v-loss (same target flow, but v_pred computed from x_pred) & use clamp_min
|
| 422 |
+
denom = (1.0 - time).clamp_min(self.t_eps)
|
| 423 |
+
while denom.ndim < φ.ndim:
|
| 424 |
+
denom = denom.unsqueeze(-1)
|
| 425 |
+
target = (x1 - φ) / denom
|
| 426 |
+
loss = F.mse_loss(v_pred, target, reduction="none")
|
| 427 |
+
elif self.loss_space == "x":
|
| 428 |
+
loss = F.mse_loss(x_pred, x1, reduction="none")
|
| 429 |
+
else:
|
| 430 |
+
raise ValueError(f"Unknown loss_space: {self.loss_space}")
|
| 431 |
+
|
| 432 |
+
loss = loss[rand_span_mask]
|
| 433 |
+
flow_loss = loss.mean()
|
| 434 |
+
total_loss = flow_loss
|
| 435 |
+
|
| 436 |
+
aux_mel_loss = torch.tensor(0.0, device=device)
|
| 437 |
+
if self.use_aux_mel_loss and self.aux_mel_loss is not None:
|
| 438 |
+
x1_flat_unscaled = x1 / self.latents_scale
|
| 439 |
+
x1_pred_flat_unscaled = x_pred / self.latents_scale
|
| 440 |
+
|
| 441 |
+
aux_mel_kwargs = {}
|
| 442 |
+
if self.aux_mel_loss_masked:
|
| 443 |
+
aux_mel_kwargs.update(
|
| 444 |
+
frame_mask=rand_span_mask,
|
| 445 |
+
frame_lengths=lens,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
aux_mel_loss = self.aux_mel_loss(
|
| 449 |
+
x1_pred_flat_unscaled,
|
| 450 |
+
x1_flat_unscaled,
|
| 451 |
+
**aux_mel_kwargs,
|
| 452 |
+
)
|
| 453 |
+
total_loss = total_loss + aux_mel_loss
|
| 454 |
+
|
| 455 |
+
loss_dict = {
|
| 456 |
+
"total_loss": total_loss,
|
| 457 |
+
"flow_loss": flow_loss,
|
| 458 |
+
"aux_mel_loss": aux_mel_loss,
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
return total_loss, cond, v_pred, loss_dict
|
src/wavtts/model/dataset.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
import torchaudio
|
| 7 |
+
from datasets import Dataset as Dataset_
|
| 8 |
+
from datasets import load_from_disk
|
| 9 |
+
from torch.utils.data import Dataset, Sampler
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class CustomDataset(Dataset):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
custom_dataset: Dataset,
|
| 18 |
+
durations=None,
|
| 19 |
+
target_sample_rate=16_000,
|
| 20 |
+
wav_frame_len: int = 160,
|
| 21 |
+
**_,
|
| 22 |
+
):
|
| 23 |
+
self.data = custom_dataset
|
| 24 |
+
self.durations = durations
|
| 25 |
+
self.target_sample_rate = target_sample_rate
|
| 26 |
+
self.wav_frame_len = wav_frame_len
|
| 27 |
+
|
| 28 |
+
self._resamplers = {}
|
| 29 |
+
|
| 30 |
+
def get_frame_len(self, index):
|
| 31 |
+
if (
|
| 32 |
+
self.durations is not None
|
| 33 |
+
): # Please make sure the separately provided durations are correct, otherwise 99.99% OOM
|
| 34 |
+
return self.durations[index] * self.target_sample_rate / self.wav_frame_len
|
| 35 |
+
return self.data[index]["duration"] * self.target_sample_rate / self.wav_frame_len
|
| 36 |
+
|
| 37 |
+
def __len__(self):
|
| 38 |
+
return len(self.data)
|
| 39 |
+
|
| 40 |
+
def __getitem__(self, index):
|
| 41 |
+
while True:
|
| 42 |
+
row = self.data[index]
|
| 43 |
+
audio_path = row["audio_path"]
|
| 44 |
+
text = row["text"]
|
| 45 |
+
duration = row["duration"]
|
| 46 |
+
|
| 47 |
+
# filter by given length
|
| 48 |
+
if 0.3 <= duration <= 30:
|
| 49 |
+
break # valid
|
| 50 |
+
|
| 51 |
+
index = (index + 1) % len(self.data)
|
| 52 |
+
|
| 53 |
+
audio, source_sample_rate = torchaudio.load(audio_path)
|
| 54 |
+
|
| 55 |
+
# make sure mono input
|
| 56 |
+
if audio.shape[0] > 1:
|
| 57 |
+
audio = torch.mean(audio, dim=0, keepdim=True)
|
| 58 |
+
|
| 59 |
+
# resample if necessary
|
| 60 |
+
if source_sample_rate != self.target_sample_rate:
|
| 61 |
+
if source_sample_rate not in self._resamplers:
|
| 62 |
+
self._resamplers[source_sample_rate] = torchaudio.transforms.Resample(
|
| 63 |
+
source_sample_rate, self.target_sample_rate
|
| 64 |
+
)
|
| 65 |
+
audio = self._resamplers[source_sample_rate](audio)
|
| 66 |
+
|
| 67 |
+
return {
|
| 68 |
+
"wav": audio.squeeze(0),
|
| 69 |
+
"text": text,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# Dynamic Batch Sampler
|
| 74 |
+
class DynamicBatchSampler(Sampler[list[int]]):
|
| 75 |
+
"""Extension of Sampler that will do the following:
|
| 76 |
+
1. Change the batch size (essentially number of sequences)
|
| 77 |
+
in a batch to ensure that the total number of frames are less
|
| 78 |
+
than a certain threshold.
|
| 79 |
+
2. Make sure the padding efficiency in the batch is high.
|
| 80 |
+
3. Shuffle batches each epoch while maintaining reproducibility.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(
|
| 84 |
+
self, sampler: Sampler[int], frames_threshold: int, max_samples=0, random_seed=None, drop_residual: bool = False
|
| 85 |
+
):
|
| 86 |
+
self.sampler = sampler
|
| 87 |
+
self.frames_threshold = frames_threshold
|
| 88 |
+
self.max_samples = max_samples
|
| 89 |
+
self.random_seed = random_seed
|
| 90 |
+
self.epoch = 0
|
| 91 |
+
|
| 92 |
+
indices, batches = [], []
|
| 93 |
+
data_source = self.sampler.data_source
|
| 94 |
+
|
| 95 |
+
for idx in tqdm(
|
| 96 |
+
self.sampler, desc="Sorting with sampler... if slow, check whether dataset is provided with duration"
|
| 97 |
+
):
|
| 98 |
+
indices.append((idx, data_source.get_frame_len(idx)))
|
| 99 |
+
indices.sort(key=lambda elem: elem[1])
|
| 100 |
+
|
| 101 |
+
batch = []
|
| 102 |
+
batch_frames = 0
|
| 103 |
+
for idx, frame_len in tqdm(
|
| 104 |
+
indices, desc=f"Creating dynamic batches with {frames_threshold} audio frames per gpu"
|
| 105 |
+
):
|
| 106 |
+
if batch_frames + frame_len <= self.frames_threshold and (max_samples == 0 or len(batch) < max_samples):
|
| 107 |
+
batch.append(idx)
|
| 108 |
+
batch_frames += frame_len
|
| 109 |
+
else:
|
| 110 |
+
if len(batch) > 0:
|
| 111 |
+
batches.append(batch)
|
| 112 |
+
if frame_len <= self.frames_threshold:
|
| 113 |
+
batch = [idx]
|
| 114 |
+
batch_frames = frame_len
|
| 115 |
+
else:
|
| 116 |
+
batch = []
|
| 117 |
+
batch_frames = 0
|
| 118 |
+
|
| 119 |
+
if not drop_residual and len(batch) > 0:
|
| 120 |
+
batches.append(batch)
|
| 121 |
+
|
| 122 |
+
del indices
|
| 123 |
+
self.batches = batches
|
| 124 |
+
|
| 125 |
+
# Ensure even batches with accelerate BatchSamplerShard cls under frame_per_batch setting
|
| 126 |
+
self.drop_last = True
|
| 127 |
+
|
| 128 |
+
def set_epoch(self, epoch: int) -> None:
|
| 129 |
+
"""Sets the epoch for this sampler."""
|
| 130 |
+
self.epoch = epoch
|
| 131 |
+
|
| 132 |
+
def __iter__(self):
|
| 133 |
+
# Use both random_seed and epoch for deterministic but different shuffling per epoch
|
| 134 |
+
if self.random_seed is not None:
|
| 135 |
+
g = torch.Generator()
|
| 136 |
+
g.manual_seed(self.random_seed + self.epoch)
|
| 137 |
+
# Use PyTorch's random permutation for better reproducibility across PyTorch versions
|
| 138 |
+
indices = torch.randperm(len(self.batches), generator=g).tolist()
|
| 139 |
+
batches = [self.batches[i] for i in indices]
|
| 140 |
+
else:
|
| 141 |
+
batches = self.batches
|
| 142 |
+
return iter(batches)
|
| 143 |
+
|
| 144 |
+
def __len__(self):
|
| 145 |
+
return len(self.batches)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# Load dataset
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def load_dataset(
|
| 152 |
+
dataset_name: str,
|
| 153 |
+
tokenizer: str = "pinyin",
|
| 154 |
+
dataset_type: str = "CustomDataset",
|
| 155 |
+
audio_type: str = "raw",
|
| 156 |
+
waveform_kwargs: dict = dict(),
|
| 157 |
+
) -> CustomDataset:
|
| 158 |
+
"""
|
| 159 |
+
WavTTS only supports raw waveform datasets.
|
| 160 |
+
dataset_type:
|
| 161 |
+
- "CustomDataset": use tokenizer name and default data path
|
| 162 |
+
- "CustomDatasetPath": pass the full path to a prepared dataset
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
print("Loading dataset ...")
|
| 166 |
+
|
| 167 |
+
if audio_type != "raw":
|
| 168 |
+
raise ValueError("WavTTS only supports raw waveform datasets; audio_type must be 'raw'.")
|
| 169 |
+
|
| 170 |
+
if dataset_type == "CustomDataset":
|
| 171 |
+
rel_data_path = str(files("wavtts").joinpath(f"../../data/{dataset_name}_{tokenizer}"))
|
| 172 |
+
try:
|
| 173 |
+
train_dataset = load_from_disk(f"{rel_data_path}/raw")
|
| 174 |
+
except: # noqa: E722
|
| 175 |
+
train_dataset = Dataset_.from_file(f"{rel_data_path}/raw.arrow")
|
| 176 |
+
with open(f"{rel_data_path}/duration.json", "r", encoding="utf-8") as f:
|
| 177 |
+
data_dict = json.load(f)
|
| 178 |
+
durations = data_dict["duration"]
|
| 179 |
+
train_dataset = CustomDataset(train_dataset, durations=durations, **waveform_kwargs)
|
| 180 |
+
|
| 181 |
+
elif dataset_type == "CustomDatasetPath":
|
| 182 |
+
try:
|
| 183 |
+
train_dataset = load_from_disk(f"{dataset_name}/raw")
|
| 184 |
+
except: # noqa: E722
|
| 185 |
+
train_dataset = Dataset_.from_file(f"{dataset_name}/raw.arrow")
|
| 186 |
+
|
| 187 |
+
with open(f"{dataset_name}/duration.json", "r", encoding="utf-8") as f:
|
| 188 |
+
data_dict = json.load(f)
|
| 189 |
+
durations = data_dict["duration"]
|
| 190 |
+
train_dataset = CustomDataset(train_dataset, durations=durations, **waveform_kwargs)
|
| 191 |
+
|
| 192 |
+
else:
|
| 193 |
+
raise ValueError(f"Unsupported dataset_type for WavTTS wav-only training: {dataset_type}")
|
| 194 |
+
|
| 195 |
+
return train_dataset
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
# collation
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def collate_fn(batch):
|
| 202 |
+
text = [item["text"] for item in batch]
|
| 203 |
+
text_lengths = torch.LongTensor([len(item) for item in text])
|
| 204 |
+
|
| 205 |
+
wavs = [item["wav"] for item in batch]
|
| 206 |
+
has_wav = wavs[0] is not None
|
| 207 |
+
if has_wav:
|
| 208 |
+
wav_lengths = torch.LongTensor([w.shape[0] for w in wavs])
|
| 209 |
+
max_wav_len = wav_lengths.max().item()
|
| 210 |
+
|
| 211 |
+
padded_wavs = []
|
| 212 |
+
for w in wavs:
|
| 213 |
+
pad_len = max_wav_len - w.shape[0]
|
| 214 |
+
padded_wavs.append(
|
| 215 |
+
F.pad(w, (0, pad_len), value=0.0)
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
wavs = torch.stack(padded_wavs) # [B, T_wav]
|
| 219 |
+
else:
|
| 220 |
+
wavs = None
|
| 221 |
+
wav_lengths = None
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
return dict(
|
| 225 |
+
text=text,
|
| 226 |
+
text_lengths=text_lengths,
|
| 227 |
+
wav=wavs,
|
| 228 |
+
wav_lengths=wav_lengths,
|
| 229 |
+
)
|
src/wavtts/model/modules.py
ADDED
|
@@ -0,0 +1,876 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 9 |
+
# ruff: noqa: F722 F821
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import math
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
import torchaudio
|
| 19 |
+
from torch import nn
|
| 20 |
+
from x_transformers.x_transformers import apply_rotary_pos_emb
|
| 21 |
+
from transformers import AutoModel, AutoFeatureExtractor
|
| 22 |
+
|
| 23 |
+
from wavtts.model.utils import is_package_available, lens_to_mask
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# sinusoidal position embedding
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class SinusPositionEmbedding(nn.Module):
|
| 30 |
+
def __init__(self, dim):
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.dim = dim
|
| 33 |
+
|
| 34 |
+
def forward(self, x, scale=1000):
|
| 35 |
+
device = x.device
|
| 36 |
+
half_dim = self.dim // 2
|
| 37 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 38 |
+
emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
|
| 39 |
+
emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
|
| 40 |
+
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
|
| 41 |
+
return emb
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# convolutional position embedding
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ConvPositionEmbedding(nn.Module):
|
| 48 |
+
def __init__(self, dim, kernel_size=31, groups=16):
|
| 49 |
+
super().__init__()
|
| 50 |
+
assert kernel_size % 2 != 0
|
| 51 |
+
self.conv1d = nn.Sequential(
|
| 52 |
+
nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2),
|
| 53 |
+
nn.Mish(),
|
| 54 |
+
nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2),
|
| 55 |
+
nn.Mish(),
|
| 56 |
+
)
|
| 57 |
+
self.layer_need_mask_idx = [i for i, layer in enumerate(self.conv1d) if isinstance(layer, nn.Conv1d)]
|
| 58 |
+
|
| 59 |
+
def forward(self, x: float["b n d"], mask: bool["b n"] | None = None):
|
| 60 |
+
if mask is not None:
|
| 61 |
+
mask = mask.unsqueeze(1) # [B 1 N]
|
| 62 |
+
x = x.permute(0, 2, 1) # [B D N]
|
| 63 |
+
|
| 64 |
+
if mask is not None:
|
| 65 |
+
x = x.masked_fill(~mask, 0.0)
|
| 66 |
+
for i, block in enumerate(self.conv1d):
|
| 67 |
+
x = block(x)
|
| 68 |
+
if mask is not None and i in self.layer_need_mask_idx:
|
| 69 |
+
x = x.masked_fill(~mask, 0.0)
|
| 70 |
+
|
| 71 |
+
x = x.permute(0, 2, 1) # [B N D]
|
| 72 |
+
|
| 73 |
+
return x
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# rotary positional embedding related
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0, theta_rescale_factor=1.0):
|
| 80 |
+
# proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
|
| 81 |
+
# has some connection to NTK literature
|
| 82 |
+
# https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/
|
| 83 |
+
# https://github.com/lucidrains/rotary-embedding-torch/blob/main/rotary_embedding_torch/rotary_embedding_torch.py
|
| 84 |
+
theta *= theta_rescale_factor ** (dim / (dim - 2))
|
| 85 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
| 86 |
+
t = torch.arange(end, device=freqs.device) # type: ignore
|
| 87 |
+
freqs = torch.outer(t, freqs).float() # type: ignore
|
| 88 |
+
freqs_cos = torch.cos(freqs) # real part
|
| 89 |
+
freqs_sin = torch.sin(freqs) # imaginary part
|
| 90 |
+
return torch.cat([freqs_cos, freqs_sin], dim=-1)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def get_pos_embed_indices(start, length, max_pos, scale=1.0):
|
| 94 |
+
# length = length if isinstance(length, int) else length.max()
|
| 95 |
+
scale = scale * torch.ones_like(start, dtype=torch.float32) # in case scale is a scalar
|
| 96 |
+
pos = (
|
| 97 |
+
start.unsqueeze(1)
|
| 98 |
+
+ (torch.arange(length, device=start.device, dtype=torch.float32).unsqueeze(0) * scale.unsqueeze(1)).long()
|
| 99 |
+
)
|
| 100 |
+
# avoid extra long error.
|
| 101 |
+
pos = torch.where(pos < max_pos, pos, max_pos - 1)
|
| 102 |
+
return pos
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# Global Response Normalization layer (Instance Normalization ?)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class GRN(nn.Module):
|
| 109 |
+
def __init__(self, dim):
|
| 110 |
+
super().__init__()
|
| 111 |
+
self.gamma = nn.Parameter(torch.zeros(1, 1, dim))
|
| 112 |
+
self.beta = nn.Parameter(torch.zeros(1, 1, dim))
|
| 113 |
+
|
| 114 |
+
def forward(self, x):
|
| 115 |
+
Gx = torch.norm(x, p=2, dim=1, keepdim=True)
|
| 116 |
+
Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
|
| 117 |
+
return self.gamma * (x * Nx) + self.beta + x
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# ConvNeXt-V2 Block https://github.com/facebookresearch/ConvNeXt-V2/blob/main/models/convnextv2.py
|
| 121 |
+
# ref: https://github.com/bfs18/e2_tts/blob/main/rfwave/modules.py#L108
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class ConvNeXtV2Block(nn.Module):
|
| 125 |
+
def __init__(
|
| 126 |
+
self,
|
| 127 |
+
dim: int,
|
| 128 |
+
intermediate_dim: int,
|
| 129 |
+
dilation: int = 1,
|
| 130 |
+
):
|
| 131 |
+
super().__init__()
|
| 132 |
+
padding = (dilation * (7 - 1)) // 2
|
| 133 |
+
self.dwconv = nn.Conv1d(
|
| 134 |
+
dim, dim, kernel_size=7, padding=padding, groups=dim, dilation=dilation
|
| 135 |
+
) # depthwise conv
|
| 136 |
+
self.norm = nn.LayerNorm(dim, eps=1e-6)
|
| 137 |
+
self.pwconv1 = nn.Linear(dim, intermediate_dim) # pointwise/1x1 convs, implemented with linear layers
|
| 138 |
+
self.act = nn.GELU()
|
| 139 |
+
self.grn = GRN(intermediate_dim)
|
| 140 |
+
self.pwconv2 = nn.Linear(intermediate_dim, dim)
|
| 141 |
+
|
| 142 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 143 |
+
residual = x
|
| 144 |
+
x = x.transpose(1, 2) # b n d -> b d n
|
| 145 |
+
x = self.dwconv(x)
|
| 146 |
+
x = x.transpose(1, 2) # b d n -> b n d
|
| 147 |
+
x = self.norm(x)
|
| 148 |
+
x = self.pwconv1(x)
|
| 149 |
+
x = self.act(x)
|
| 150 |
+
x = self.grn(x)
|
| 151 |
+
x = self.pwconv2(x)
|
| 152 |
+
return residual + x
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# RMSNorm
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class RMSNorm(nn.Module):
|
| 159 |
+
def __init__(self, dim: int, eps: float):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.eps = eps
|
| 162 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 163 |
+
self.native_rms_norm = float(torch.__version__[:3]) >= 2.4
|
| 164 |
+
|
| 165 |
+
def forward(self, x):
|
| 166 |
+
if self.native_rms_norm:
|
| 167 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
| 168 |
+
x = x.to(self.weight.dtype)
|
| 169 |
+
x = F.rms_norm(x, normalized_shape=(x.shape[-1],), weight=self.weight, eps=self.eps)
|
| 170 |
+
else:
|
| 171 |
+
variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
| 172 |
+
x = x * torch.rsqrt(variance + self.eps)
|
| 173 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
| 174 |
+
x = x.to(self.weight.dtype)
|
| 175 |
+
x = x * self.weight
|
| 176 |
+
|
| 177 |
+
return x
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# AdaLayerNorm
|
| 181 |
+
# return with modulated x for attn input, and params for later mlp modulation
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class AdaLayerNorm(nn.Module):
|
| 185 |
+
def __init__(self, dim):
|
| 186 |
+
super().__init__()
|
| 187 |
+
|
| 188 |
+
self.silu = nn.SiLU()
|
| 189 |
+
self.linear = nn.Linear(dim, dim * 6)
|
| 190 |
+
|
| 191 |
+
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 192 |
+
|
| 193 |
+
def forward(self, x, emb=None):
|
| 194 |
+
emb = self.linear(self.silu(emb))
|
| 195 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = torch.chunk(emb, 6, dim=1)
|
| 196 |
+
|
| 197 |
+
x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
|
| 198 |
+
return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# AdaLayerNorm for final layer
|
| 202 |
+
# return only with modulated x for attn input, cuz no more mlp modulation
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class AdaLayerNorm_Final(nn.Module):
|
| 206 |
+
def __init__(self, dim):
|
| 207 |
+
super().__init__()
|
| 208 |
+
|
| 209 |
+
self.silu = nn.SiLU()
|
| 210 |
+
self.linear = nn.Linear(dim, dim * 2)
|
| 211 |
+
|
| 212 |
+
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 213 |
+
|
| 214 |
+
def forward(self, x, emb):
|
| 215 |
+
emb = self.linear(self.silu(emb))
|
| 216 |
+
scale, shift = torch.chunk(emb, 2, dim=1)
|
| 217 |
+
|
| 218 |
+
x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
|
| 219 |
+
return x
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# FeedForward
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class FeedForward(nn.Module):
|
| 226 |
+
def __init__(self, dim, dim_out=None, mult=4, dropout=0.0, approximate: str = "none"):
|
| 227 |
+
super().__init__()
|
| 228 |
+
inner_dim = int(dim * mult)
|
| 229 |
+
dim_out = dim_out if dim_out is not None else dim
|
| 230 |
+
|
| 231 |
+
activation = nn.GELU(approximate=approximate)
|
| 232 |
+
project_in = nn.Sequential(nn.Linear(dim, inner_dim), activation)
|
| 233 |
+
self.ff = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out))
|
| 234 |
+
|
| 235 |
+
def forward(self, x):
|
| 236 |
+
return self.ff(x)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# Attention with possible joint part
|
| 240 |
+
# modified from diffusers/src/diffusers/models/attention_processor.py
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class Attention(nn.Module):
|
| 244 |
+
def __init__(
|
| 245 |
+
self,
|
| 246 |
+
processor: JointAttnProcessor | AttnProcessor,
|
| 247 |
+
dim: int,
|
| 248 |
+
heads: int = 8,
|
| 249 |
+
dim_head: int = 64,
|
| 250 |
+
dropout: float = 0.0,
|
| 251 |
+
context_dim: Optional[int] = None, # if not None -> joint attention
|
| 252 |
+
context_pre_only: bool = False,
|
| 253 |
+
qk_norm: Optional[str] = None,
|
| 254 |
+
):
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 258 |
+
raise ImportError("Attention equires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
| 259 |
+
|
| 260 |
+
self.processor = processor
|
| 261 |
+
|
| 262 |
+
self.dim = dim
|
| 263 |
+
self.heads = heads
|
| 264 |
+
self.inner_dim = dim_head * heads
|
| 265 |
+
self.dropout = dropout
|
| 266 |
+
|
| 267 |
+
self.context_dim = context_dim
|
| 268 |
+
self.context_pre_only = context_pre_only
|
| 269 |
+
|
| 270 |
+
self.to_q = nn.Linear(dim, self.inner_dim)
|
| 271 |
+
self.to_k = nn.Linear(dim, self.inner_dim)
|
| 272 |
+
self.to_v = nn.Linear(dim, self.inner_dim)
|
| 273 |
+
|
| 274 |
+
if qk_norm is None:
|
| 275 |
+
self.q_norm = None
|
| 276 |
+
self.k_norm = None
|
| 277 |
+
elif qk_norm == "rms_norm":
|
| 278 |
+
self.q_norm = RMSNorm(dim_head, eps=1e-6)
|
| 279 |
+
self.k_norm = RMSNorm(dim_head, eps=1e-6)
|
| 280 |
+
else:
|
| 281 |
+
raise ValueError(f"Unimplemented qk_norm: {qk_norm}")
|
| 282 |
+
|
| 283 |
+
if self.context_dim is not None:
|
| 284 |
+
self.to_q_c = nn.Linear(context_dim, self.inner_dim)
|
| 285 |
+
self.to_k_c = nn.Linear(context_dim, self.inner_dim)
|
| 286 |
+
self.to_v_c = nn.Linear(context_dim, self.inner_dim)
|
| 287 |
+
if qk_norm is None:
|
| 288 |
+
self.c_q_norm = None
|
| 289 |
+
self.c_k_norm = None
|
| 290 |
+
elif qk_norm == "rms_norm":
|
| 291 |
+
self.c_q_norm = RMSNorm(dim_head, eps=1e-6)
|
| 292 |
+
self.c_k_norm = RMSNorm(dim_head, eps=1e-6)
|
| 293 |
+
|
| 294 |
+
self.to_out = nn.ModuleList([])
|
| 295 |
+
self.to_out.append(nn.Linear(self.inner_dim, dim))
|
| 296 |
+
self.to_out.append(nn.Dropout(dropout))
|
| 297 |
+
|
| 298 |
+
if self.context_dim is not None and not self.context_pre_only:
|
| 299 |
+
self.to_out_c = nn.Linear(self.inner_dim, context_dim)
|
| 300 |
+
|
| 301 |
+
def forward(
|
| 302 |
+
self,
|
| 303 |
+
x: float["b n d"], # noised input x
|
| 304 |
+
c: float["b n d"] = None, # context c
|
| 305 |
+
mask: bool["b n"] | None = None,
|
| 306 |
+
rope=None, # rotary position embedding for x
|
| 307 |
+
c_rope=None, # rotary position embedding for c
|
| 308 |
+
) -> torch.Tensor:
|
| 309 |
+
if c is not None:
|
| 310 |
+
return self.processor(self, x, c=c, mask=mask, rope=rope, c_rope=c_rope)
|
| 311 |
+
else:
|
| 312 |
+
return self.processor(self, x, mask=mask, rope=rope)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
# Attention processor
|
| 316 |
+
|
| 317 |
+
if is_package_available("flash_attn"):
|
| 318 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 319 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class AttnProcessor:
|
| 323 |
+
def __init__(
|
| 324 |
+
self,
|
| 325 |
+
pe_attn_head: int | None = None, # number of attention head to apply rope, None for all
|
| 326 |
+
attn_backend: str = "torch", # "torch" or "flash_attn"
|
| 327 |
+
attn_mask_enabled: bool = True,
|
| 328 |
+
):
|
| 329 |
+
if attn_backend == "flash_attn":
|
| 330 |
+
assert is_package_available("flash_attn"), "Please install flash-attn first."
|
| 331 |
+
|
| 332 |
+
self.pe_attn_head = pe_attn_head
|
| 333 |
+
self.attn_backend = attn_backend
|
| 334 |
+
self.attn_mask_enabled = attn_mask_enabled
|
| 335 |
+
|
| 336 |
+
def __call__(
|
| 337 |
+
self,
|
| 338 |
+
attn: Attention,
|
| 339 |
+
x: float["b n d"], # noised input x
|
| 340 |
+
mask: bool["b n"] | None = None,
|
| 341 |
+
rope=None, # rotary position embedding
|
| 342 |
+
) -> torch.FloatTensor:
|
| 343 |
+
batch_size = x.shape[0]
|
| 344 |
+
|
| 345 |
+
# `sample` projections
|
| 346 |
+
query = attn.to_q(x)
|
| 347 |
+
key = attn.to_k(x)
|
| 348 |
+
value = attn.to_v(x)
|
| 349 |
+
|
| 350 |
+
# attention
|
| 351 |
+
inner_dim = key.shape[-1]
|
| 352 |
+
head_dim = inner_dim // attn.heads
|
| 353 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 354 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 355 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 356 |
+
|
| 357 |
+
# qk norm
|
| 358 |
+
if attn.q_norm is not None:
|
| 359 |
+
query = attn.q_norm(query)
|
| 360 |
+
if attn.k_norm is not None:
|
| 361 |
+
key = attn.k_norm(key)
|
| 362 |
+
|
| 363 |
+
# apply rotary position embedding
|
| 364 |
+
if rope is not None:
|
| 365 |
+
freqs, xpos_scale = rope
|
| 366 |
+
q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
|
| 367 |
+
|
| 368 |
+
if self.pe_attn_head is not None:
|
| 369 |
+
pn = self.pe_attn_head
|
| 370 |
+
query[:, :pn, :, :] = apply_rotary_pos_emb(query[:, :pn, :, :], freqs, q_xpos_scale)
|
| 371 |
+
key[:, :pn, :, :] = apply_rotary_pos_emb(key[:, :pn, :, :], freqs, k_xpos_scale)
|
| 372 |
+
else:
|
| 373 |
+
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
|
| 374 |
+
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
|
| 375 |
+
|
| 376 |
+
if self.attn_backend == "torch":
|
| 377 |
+
# mask. e.g. inference got a batch with different target durations, mask out the padding
|
| 378 |
+
if self.attn_mask_enabled and mask is not None:
|
| 379 |
+
attn_mask = mask
|
| 380 |
+
attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) # 'b n -> b 1 1 n'
|
| 381 |
+
attn_mask = attn_mask.expand(batch_size, attn.heads, query.shape[-2], key.shape[-2])
|
| 382 |
+
else:
|
| 383 |
+
attn_mask = None
|
| 384 |
+
x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
|
| 385 |
+
x = x.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 386 |
+
|
| 387 |
+
elif self.attn_backend == "flash_attn":
|
| 388 |
+
query = query.transpose(1, 2) # [b, h, n, d] -> [b, n, h, d]
|
| 389 |
+
key = key.transpose(1, 2)
|
| 390 |
+
value = value.transpose(1, 2)
|
| 391 |
+
if self.attn_mask_enabled and mask is not None:
|
| 392 |
+
query, indices, q_cu_seqlens, q_max_seqlen_in_batch, _ = unpad_input(query, mask)
|
| 393 |
+
key, _, k_cu_seqlens, k_max_seqlen_in_batch, _ = unpad_input(key, mask)
|
| 394 |
+
value, _, _, _, _ = unpad_input(value, mask)
|
| 395 |
+
x = flash_attn_varlen_func(
|
| 396 |
+
query,
|
| 397 |
+
key,
|
| 398 |
+
value,
|
| 399 |
+
q_cu_seqlens,
|
| 400 |
+
k_cu_seqlens,
|
| 401 |
+
q_max_seqlen_in_batch,
|
| 402 |
+
k_max_seqlen_in_batch,
|
| 403 |
+
)
|
| 404 |
+
x = pad_input(x, indices, batch_size, q_max_seqlen_in_batch)
|
| 405 |
+
x = x.reshape(batch_size, -1, attn.heads * head_dim)
|
| 406 |
+
else:
|
| 407 |
+
x = flash_attn_func(query, key, value, dropout_p=0.0, causal=False)
|
| 408 |
+
x = x.reshape(batch_size, -1, attn.heads * head_dim)
|
| 409 |
+
|
| 410 |
+
x = x.to(query.dtype)
|
| 411 |
+
|
| 412 |
+
# linear proj
|
| 413 |
+
x = attn.to_out[0](x)
|
| 414 |
+
# dropout
|
| 415 |
+
x = attn.to_out[1](x)
|
| 416 |
+
|
| 417 |
+
if mask is not None:
|
| 418 |
+
mask = mask.unsqueeze(-1)
|
| 419 |
+
x = x.masked_fill(~mask, 0.0)
|
| 420 |
+
|
| 421 |
+
return x
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
# Joint Attention processor for MM-DiT
|
| 425 |
+
# modified from diffusers/src/diffusers/models/attention_processor.py
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class JointAttnProcessor:
|
| 429 |
+
def __init__(self):
|
| 430 |
+
pass
|
| 431 |
+
|
| 432 |
+
def __call__(
|
| 433 |
+
self,
|
| 434 |
+
attn: Attention,
|
| 435 |
+
x: float["b n d"], # noised input x
|
| 436 |
+
c: float["b nt d"] = None, # context c, here text
|
| 437 |
+
mask: bool["b n"] | None = None,
|
| 438 |
+
rope=None, # rotary position embedding for x
|
| 439 |
+
c_rope=None, # rotary position embedding for c
|
| 440 |
+
) -> torch.FloatTensor:
|
| 441 |
+
residual = x
|
| 442 |
+
|
| 443 |
+
batch_size = c.shape[0]
|
| 444 |
+
|
| 445 |
+
# `sample` projections
|
| 446 |
+
query = attn.to_q(x)
|
| 447 |
+
key = attn.to_k(x)
|
| 448 |
+
value = attn.to_v(x)
|
| 449 |
+
|
| 450 |
+
# `context` projections
|
| 451 |
+
c_query = attn.to_q_c(c)
|
| 452 |
+
c_key = attn.to_k_c(c)
|
| 453 |
+
c_value = attn.to_v_c(c)
|
| 454 |
+
|
| 455 |
+
# attention
|
| 456 |
+
inner_dim = key.shape[-1]
|
| 457 |
+
head_dim = inner_dim // attn.heads
|
| 458 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 459 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 460 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 461 |
+
c_query = c_query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 462 |
+
c_key = c_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 463 |
+
c_value = c_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 464 |
+
|
| 465 |
+
# qk norm
|
| 466 |
+
if attn.q_norm is not None:
|
| 467 |
+
query = attn.q_norm(query)
|
| 468 |
+
if attn.k_norm is not None:
|
| 469 |
+
key = attn.k_norm(key)
|
| 470 |
+
if attn.c_q_norm is not None:
|
| 471 |
+
c_query = attn.c_q_norm(c_query)
|
| 472 |
+
if attn.c_k_norm is not None:
|
| 473 |
+
c_key = attn.c_k_norm(c_key)
|
| 474 |
+
|
| 475 |
+
# apply rope for context and noised input independently
|
| 476 |
+
if rope is not None:
|
| 477 |
+
freqs, xpos_scale = rope
|
| 478 |
+
q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
|
| 479 |
+
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
|
| 480 |
+
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
|
| 481 |
+
if c_rope is not None:
|
| 482 |
+
freqs, xpos_scale = c_rope
|
| 483 |
+
q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
|
| 484 |
+
c_query = apply_rotary_pos_emb(c_query, freqs, q_xpos_scale)
|
| 485 |
+
c_key = apply_rotary_pos_emb(c_key, freqs, k_xpos_scale)
|
| 486 |
+
|
| 487 |
+
# joint attention
|
| 488 |
+
query = torch.cat([query, c_query], dim=2)
|
| 489 |
+
key = torch.cat([key, c_key], dim=2)
|
| 490 |
+
value = torch.cat([value, c_value], dim=2)
|
| 491 |
+
|
| 492 |
+
# mask. e.g. inference got a batch with different target durations, mask out the padding
|
| 493 |
+
if mask is not None:
|
| 494 |
+
attn_mask = F.pad(mask, (0, c.shape[1]), value=True) # no mask for c (text)
|
| 495 |
+
attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) # 'b n -> b 1 1 n'
|
| 496 |
+
attn_mask = attn_mask.expand(batch_size, attn.heads, query.shape[-2], key.shape[-2])
|
| 497 |
+
else:
|
| 498 |
+
attn_mask = None
|
| 499 |
+
|
| 500 |
+
x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
|
| 501 |
+
x = x.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 502 |
+
x = x.to(query.dtype)
|
| 503 |
+
|
| 504 |
+
# Split the attention outputs.
|
| 505 |
+
x, c = (
|
| 506 |
+
x[:, : residual.shape[1]],
|
| 507 |
+
x[:, residual.shape[1] :],
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
# linear proj
|
| 511 |
+
x = attn.to_out[0](x)
|
| 512 |
+
# dropout
|
| 513 |
+
x = attn.to_out[1](x)
|
| 514 |
+
if not attn.context_pre_only:
|
| 515 |
+
c = attn.to_out_c(c)
|
| 516 |
+
|
| 517 |
+
if mask is not None:
|
| 518 |
+
mask = mask.unsqueeze(-1)
|
| 519 |
+
x = x.masked_fill(~mask, 0.0)
|
| 520 |
+
# c = c.masked_fill(~mask, 0.) # no mask for c (text)
|
| 521 |
+
|
| 522 |
+
return x, c
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
# DiT Block
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
class DiTBlock(nn.Module):
|
| 529 |
+
def __init__(
|
| 530 |
+
self,
|
| 531 |
+
dim,
|
| 532 |
+
heads,
|
| 533 |
+
dim_head,
|
| 534 |
+
ff_mult=4,
|
| 535 |
+
dropout=0.1,
|
| 536 |
+
qk_norm=None,
|
| 537 |
+
pe_attn_head=None,
|
| 538 |
+
attn_backend="torch", # "torch" or "flash_attn"
|
| 539 |
+
attn_mask_enabled=True,
|
| 540 |
+
):
|
| 541 |
+
super().__init__()
|
| 542 |
+
|
| 543 |
+
self.attn_norm = AdaLayerNorm(dim)
|
| 544 |
+
self.attn = Attention(
|
| 545 |
+
processor=AttnProcessor(
|
| 546 |
+
pe_attn_head=pe_attn_head,
|
| 547 |
+
attn_backend=attn_backend,
|
| 548 |
+
attn_mask_enabled=attn_mask_enabled,
|
| 549 |
+
),
|
| 550 |
+
dim=dim,
|
| 551 |
+
heads=heads,
|
| 552 |
+
dim_head=dim_head,
|
| 553 |
+
dropout=dropout,
|
| 554 |
+
qk_norm=qk_norm,
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
self.ff_norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 558 |
+
self.ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
|
| 559 |
+
|
| 560 |
+
def forward(self, x, t, mask=None, rope=None): # x: noised input, t: time embedding
|
| 561 |
+
# pre-norm & modulation for attention input
|
| 562 |
+
norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t)
|
| 563 |
+
|
| 564 |
+
# attention
|
| 565 |
+
attn_output = self.attn(x=norm, mask=mask, rope=rope)
|
| 566 |
+
|
| 567 |
+
# process attention output for input x
|
| 568 |
+
x = x + gate_msa.unsqueeze(1) * attn_output
|
| 569 |
+
|
| 570 |
+
norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
| 571 |
+
ff_output = self.ff(norm)
|
| 572 |
+
x = x + gate_mlp.unsqueeze(1) * ff_output
|
| 573 |
+
|
| 574 |
+
return x
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
# MMDiT Block https://arxiv.org/abs/2403.03206
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
class MMDiTBlock(nn.Module):
|
| 581 |
+
r"""
|
| 582 |
+
modified from diffusers/src/diffusers/models/attention.py
|
| 583 |
+
|
| 584 |
+
notes.
|
| 585 |
+
_c: context related. text, cond, etc. (left part in sd3 fig2.b)
|
| 586 |
+
_x: noised input related. (right part)
|
| 587 |
+
context_pre_only: last layer only do prenorm + modulation cuz no more ffn
|
| 588 |
+
"""
|
| 589 |
+
|
| 590 |
+
def __init__(
|
| 591 |
+
self, dim, heads, dim_head, ff_mult=4, dropout=0.1, context_dim=None, context_pre_only=False, qk_norm=None
|
| 592 |
+
):
|
| 593 |
+
super().__init__()
|
| 594 |
+
if context_dim is None:
|
| 595 |
+
context_dim = dim
|
| 596 |
+
self.context_pre_only = context_pre_only
|
| 597 |
+
|
| 598 |
+
self.attn_norm_c = AdaLayerNorm_Final(context_dim) if context_pre_only else AdaLayerNorm(context_dim)
|
| 599 |
+
self.attn_norm_x = AdaLayerNorm(dim)
|
| 600 |
+
self.attn = Attention(
|
| 601 |
+
processor=JointAttnProcessor(),
|
| 602 |
+
dim=dim,
|
| 603 |
+
heads=heads,
|
| 604 |
+
dim_head=dim_head,
|
| 605 |
+
dropout=dropout,
|
| 606 |
+
context_dim=context_dim,
|
| 607 |
+
context_pre_only=context_pre_only,
|
| 608 |
+
qk_norm=qk_norm,
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
if not context_pre_only:
|
| 612 |
+
self.ff_norm_c = nn.LayerNorm(context_dim, elementwise_affine=False, eps=1e-6)
|
| 613 |
+
self.ff_c = FeedForward(dim=context_dim, mult=ff_mult, dropout=dropout, approximate="tanh")
|
| 614 |
+
else:
|
| 615 |
+
self.ff_norm_c = None
|
| 616 |
+
self.ff_c = None
|
| 617 |
+
self.ff_norm_x = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 618 |
+
self.ff_x = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
|
| 619 |
+
|
| 620 |
+
def forward(self, x, c, t, mask=None, rope=None, c_rope=None): # x: noised input, c: context, t: time embedding
|
| 621 |
+
# pre-norm & modulation for attention input
|
| 622 |
+
if self.context_pre_only:
|
| 623 |
+
norm_c = self.attn_norm_c(c, t)
|
| 624 |
+
else:
|
| 625 |
+
norm_c, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.attn_norm_c(c, emb=t)
|
| 626 |
+
norm_x, x_gate_msa, x_shift_mlp, x_scale_mlp, x_gate_mlp = self.attn_norm_x(x, emb=t)
|
| 627 |
+
|
| 628 |
+
# attention
|
| 629 |
+
x_attn_output, c_attn_output = self.attn(x=norm_x, c=norm_c, mask=mask, rope=rope, c_rope=c_rope)
|
| 630 |
+
|
| 631 |
+
# process attention output for context c
|
| 632 |
+
if self.context_pre_only:
|
| 633 |
+
c = None
|
| 634 |
+
else: # if not last layer
|
| 635 |
+
c = c + c_gate_msa.unsqueeze(1) * c_attn_output
|
| 636 |
+
|
| 637 |
+
norm_c = self.ff_norm_c(c) * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
|
| 638 |
+
c_ff_output = self.ff_c(norm_c)
|
| 639 |
+
c = c + c_gate_mlp.unsqueeze(1) * c_ff_output
|
| 640 |
+
|
| 641 |
+
# process attention output for input x
|
| 642 |
+
x = x + x_gate_msa.unsqueeze(1) * x_attn_output
|
| 643 |
+
|
| 644 |
+
norm_x = self.ff_norm_x(x) * (1 + x_scale_mlp[:, None]) + x_shift_mlp[:, None]
|
| 645 |
+
x_ff_output = self.ff_x(norm_x)
|
| 646 |
+
x = x + x_gate_mlp.unsqueeze(1) * x_ff_output
|
| 647 |
+
|
| 648 |
+
return c, x
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
# time step conditioning embedding
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
class TimestepEmbedding(nn.Module):
|
| 655 |
+
def __init__(self, dim, freq_embed_dim=256):
|
| 656 |
+
super().__init__()
|
| 657 |
+
self.time_embed = SinusPositionEmbedding(freq_embed_dim)
|
| 658 |
+
self.time_mlp = nn.Sequential(nn.Linear(freq_embed_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
|
| 659 |
+
|
| 660 |
+
def forward(self, timestep: float["b"]):
|
| 661 |
+
time_hidden = self.time_embed(timestep)
|
| 662 |
+
time_hidden = time_hidden.to(timestep.dtype)
|
| 663 |
+
time = self.time_mlp(time_hidden) # b d
|
| 664 |
+
return time
|
| 665 |
+
|
| 666 |
+
# auxiliary loss for mel spectrogram
|
| 667 |
+
class MelSpectrogramLoss(nn.Module):
|
| 668 |
+
"""
|
| 669 |
+
General PyTorch implementation of the Multi-Scale Mel Spectrogram Loss from DAC.
|
| 670 |
+
Reference: https://github.com/descriptinc/lyrebird-audiotools
|
| 671 |
+
"""
|
| 672 |
+
def __init__(
|
| 673 |
+
self,
|
| 674 |
+
sample_rate: int = 24000,
|
| 675 |
+
n_mels: List[int] = [5, 10, 20, 40, 80, 160, 320],
|
| 676 |
+
window_lengths: List[int] = [32, 64, 128, 256, 512, 1024, 2048],
|
| 677 |
+
mel_fmin: List[float] = [0, 0, 0, 0, 0, 0, 0],
|
| 678 |
+
mel_fmax: List[Optional[float]] = [None, None, None, None, None, None, None],
|
| 679 |
+
pow: float = 1.0,
|
| 680 |
+
clamp_eps: float = 1e-5,
|
| 681 |
+
weight: float = 1.0,
|
| 682 |
+
):
|
| 683 |
+
super().__init__()
|
| 684 |
+
self.sample_rate = sample_rate
|
| 685 |
+
self.weight = weight
|
| 686 |
+
self.pow = pow
|
| 687 |
+
self.clamp_eps = clamp_eps
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
assert len(n_mels) == len(window_lengths), "n_mels and window_lengths must have the same length"
|
| 691 |
+
|
| 692 |
+
self.mel_transforms = nn.ModuleList()
|
| 693 |
+
|
| 694 |
+
for i, (nm, wl) in enumerate(zip(n_mels, window_lengths)):
|
| 695 |
+
fmin = mel_fmin[i] if i < len(mel_fmin) else 0.0
|
| 696 |
+
fmax = mel_fmax[i] if i < len(mel_fmax) else None
|
| 697 |
+
|
| 698 |
+
# DAC default logic: hop_length = window_length // 4
|
| 699 |
+
hop_length = wl // 4
|
| 700 |
+
|
| 701 |
+
transform = torchaudio.transforms.MelSpectrogram(
|
| 702 |
+
sample_rate=sample_rate,
|
| 703 |
+
n_fft=wl, # using window_length as n_fft usually
|
| 704 |
+
win_length=wl,
|
| 705 |
+
hop_length=hop_length,
|
| 706 |
+
n_mels=nm,
|
| 707 |
+
f_min=fmin,
|
| 708 |
+
f_max=fmax,
|
| 709 |
+
power=1.0, # computing Magnitude Mel (power=1.0) initially
|
| 710 |
+
normalized=False,
|
| 711 |
+
center=True,
|
| 712 |
+
pad_mode="reflect"
|
| 713 |
+
)
|
| 714 |
+
self.mel_transforms.append(transform)
|
| 715 |
+
|
| 716 |
+
def forward(
|
| 717 |
+
self,
|
| 718 |
+
x_pred: torch.Tensor,
|
| 719 |
+
x_true: torch.Tensor,
|
| 720 |
+
frame_mask: torch.Tensor | None = None,
|
| 721 |
+
frame_lengths: torch.Tensor | None = None,
|
| 722 |
+
):
|
| 723 |
+
"""
|
| 724 |
+
Args:
|
| 725 |
+
x_pred: [B, T] or [B, 1, T] Estimated Waveform
|
| 726 |
+
x_true: [B, T] or [B, 1, T] Ground Truth Waveform
|
| 727 |
+
Returns:
|
| 728 |
+
Weighted scalar loss
|
| 729 |
+
"""
|
| 730 |
+
# Ensure correct shape [B, T] for torchaudio, or [B, 1, T] is also fine but usually squeeze
|
| 731 |
+
if x_pred.ndim == 3 and x_pred.shape[1] == 1:
|
| 732 |
+
x_pred = x_pred.squeeze(1)
|
| 733 |
+
if x_true.ndim == 3 and x_true.shape[1] == 1:
|
| 734 |
+
x_true = x_true.squeeze(1)
|
| 735 |
+
|
| 736 |
+
total_loss = x_pred.new_tensor(0.0)
|
| 737 |
+
|
| 738 |
+
use_mask = frame_mask is not None
|
| 739 |
+
if use_mask:
|
| 740 |
+
span_starts, span_ends = self._get_span_bounds_from_mask(frame_mask, frame_lengths)
|
| 741 |
+
span_starts = span_starts.to(device=x_pred.device)
|
| 742 |
+
span_ends = span_ends.to(device=x_pred.device)
|
| 743 |
+
|
| 744 |
+
for mel_transform in self.mel_transforms:
|
| 745 |
+
x_mels = mel_transform(x_pred)
|
| 746 |
+
y_mels = mel_transform(x_true)
|
| 747 |
+
|
| 748 |
+
mel_mask = None
|
| 749 |
+
if use_mask:
|
| 750 |
+
hop = int(mel_transform.hop_length)
|
| 751 |
+
mel_t = x_mels.shape[-1]
|
| 752 |
+
mel_mask = torch.zeros(
|
| 753 |
+
(x_mels.shape[0], mel_t),
|
| 754 |
+
device=x_mels.device,
|
| 755 |
+
dtype=torch.bool,
|
| 756 |
+
)
|
| 757 |
+
for i in range(x_mels.shape[0]):
|
| 758 |
+
s = int(span_starts[i].item())
|
| 759 |
+
e = int(span_ends[i].item())
|
| 760 |
+
if e <= s:
|
| 761 |
+
continue
|
| 762 |
+
ms = s // hop
|
| 763 |
+
me = (e + hop - 1) // hop
|
| 764 |
+
ms = max(0, min(ms, mel_t))
|
| 765 |
+
me = max(0, min(me, mel_t))
|
| 766 |
+
if me > ms:
|
| 767 |
+
mel_mask[i, ms:me] = True
|
| 768 |
+
|
| 769 |
+
if not mel_mask.any():
|
| 770 |
+
continue
|
| 771 |
+
|
| 772 |
+
mel_mask = mel_mask.unsqueeze(1)
|
| 773 |
+
|
| 774 |
+
# Log Magnitude Loss
|
| 775 |
+
# Formula: L1( log10(x^pow + eps), log10(y^pow + eps) )
|
| 776 |
+
x_log = x_mels.clamp(min=self.clamp_eps).pow(self.pow).log10()
|
| 777 |
+
y_log = y_mels.clamp(min=self.clamp_eps).pow(self.pow).log10()
|
| 778 |
+
|
| 779 |
+
diff_full = (x_log - y_log).abs()
|
| 780 |
+
|
| 781 |
+
if mel_mask is None:
|
| 782 |
+
diff = diff_full.mean(dim=(1, 2))
|
| 783 |
+
else:
|
| 784 |
+
diff = []
|
| 785 |
+
for i in range(diff_full.shape[0]):
|
| 786 |
+
m = mel_mask[i]
|
| 787 |
+
if m.any():
|
| 788 |
+
diff.append(diff_full[i].masked_select(m).mean())
|
| 789 |
+
else:
|
| 790 |
+
diff.append(diff_full.new_tensor(0.0))
|
| 791 |
+
diff = torch.stack(diff, dim=0)
|
| 792 |
+
|
| 793 |
+
total_loss += diff.mean()
|
| 794 |
+
|
| 795 |
+
return total_loss * self.weight
|
| 796 |
+
|
| 797 |
+
@staticmethod
|
| 798 |
+
def _get_span_bounds_from_mask(mask: torch.Tensor, lengths: torch.Tensor | None = None) -> tuple[torch.Tensor, torch.Tensor]:
|
| 799 |
+
"""Convert boolean frame mask [B, T] into per-sample [start, end) bounds.
|
| 800 |
+
|
| 801 |
+
This helper assumes one contiguous masked span per sample (matching current
|
| 802 |
+
random-span masking strategy). If a sample has no masked frame, start=end=0.
|
| 803 |
+
"""
|
| 804 |
+
if mask.dtype != torch.bool:
|
| 805 |
+
mask = mask.bool()
|
| 806 |
+
|
| 807 |
+
bsz, t = mask.shape
|
| 808 |
+
device = mask.device
|
| 809 |
+
|
| 810 |
+
if lengths is None:
|
| 811 |
+
lengths = torch.full((bsz,), t, device=device, dtype=torch.long)
|
| 812 |
+
else:
|
| 813 |
+
lengths = lengths.to(device=device, dtype=torch.long)
|
| 814 |
+
|
| 815 |
+
starts = torch.zeros((bsz,), device=device, dtype=torch.long)
|
| 816 |
+
ends = torch.zeros((bsz,), device=device, dtype=torch.long)
|
| 817 |
+
|
| 818 |
+
for i in range(bsz):
|
| 819 |
+
li = int(lengths[i].item())
|
| 820 |
+
row = mask[i, :li]
|
| 821 |
+
idx = row.nonzero(as_tuple=False).squeeze(-1)
|
| 822 |
+
if idx.numel() == 0:
|
| 823 |
+
continue
|
| 824 |
+
starts[i] = idx[0]
|
| 825 |
+
ends[i] = idx[-1] + 1
|
| 826 |
+
|
| 827 |
+
return starts, ends
|
| 828 |
+
|
| 829 |
+
@staticmethod
|
| 830 |
+
def _aligned_random_span_mask(
|
| 831 |
+
lengths: torch.Tensor,
|
| 832 |
+
frac_lengths: torch.Tensor,
|
| 833 |
+
align_to: int,
|
| 834 |
+
max_length: int | None = None,
|
| 835 |
+
) -> torch.Tensor:
|
| 836 |
+
"""Sample one contiguous mask span per sample with boundary alignment.
|
| 837 |
+
|
| 838 |
+
Args:
|
| 839 |
+
lengths: [B] valid sequence lengths in model frames.
|
| 840 |
+
frac_lengths: [B] desired masked length fraction.
|
| 841 |
+
align_to: span start/end alignment in model frames.
|
| 842 |
+
max_length: optional mask width. If None, use lengths.max().
|
| 843 |
+
Returns:
|
| 844 |
+
bool mask with shape [B, max_length].
|
| 845 |
+
"""
|
| 846 |
+
assert align_to >= 1
|
| 847 |
+
device = lengths.device
|
| 848 |
+
lengths = lengths.to(dtype=torch.long)
|
| 849 |
+
frac_lengths = frac_lengths.to(device=device, dtype=torch.float32)
|
| 850 |
+
|
| 851 |
+
max_len = int(lengths.max().item()) if max_length is None else int(max_length)
|
| 852 |
+
mask = torch.zeros((lengths.shape[0], max_len), device=device, dtype=torch.bool)
|
| 853 |
+
|
| 854 |
+
for i in range(lengths.shape[0]):
|
| 855 |
+
li = int(lengths[i].item())
|
| 856 |
+
if li <= 0:
|
| 857 |
+
continue
|
| 858 |
+
|
| 859 |
+
target = int((frac_lengths[i].item() * li))
|
| 860 |
+
target = max(1, min(target, li))
|
| 861 |
+
|
| 862 |
+
span_len = ((target + align_to - 1) // align_to) * align_to
|
| 863 |
+
span_len = min(span_len, li)
|
| 864 |
+
|
| 865 |
+
max_start = li - span_len
|
| 866 |
+
if max_start <= 0:
|
| 867 |
+
start = 0
|
| 868 |
+
else:
|
| 869 |
+
candidate = torch.randint(0, max_start + 1, (1,), device=device).item()
|
| 870 |
+
start = (candidate // align_to) * align_to
|
| 871 |
+
start = min(start, max_start)
|
| 872 |
+
|
| 873 |
+
end = start + span_len
|
| 874 |
+
mask[i, start:end] = True
|
| 875 |
+
|
| 876 |
+
return mask
|
src/wavtts/model/trainer.py
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import gc
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torchaudio
|
| 9 |
+
import wandb
|
| 10 |
+
from accelerate import Accelerator
|
| 11 |
+
from accelerate.utils import DistributedDataParallelKwargs
|
| 12 |
+
from ema_pytorch import EMA
|
| 13 |
+
from torch.optim import AdamW
|
| 14 |
+
from torch.optim.lr_scheduler import LinearLR, SequentialLR
|
| 15 |
+
from torch.utils.data import DataLoader, Dataset, SequentialSampler
|
| 16 |
+
from tqdm import tqdm
|
| 17 |
+
|
| 18 |
+
from wavtts.model import CFM
|
| 19 |
+
from wavtts.model.dataset import DynamicBatchSampler, collate_fn
|
| 20 |
+
from wavtts.model.utils import default, exists
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# trainer
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Trainer:
|
| 27 |
+
@staticmethod
|
| 28 |
+
def _format_params_in_mb(count: int) -> str:
|
| 29 |
+
return f"{count / 1e6:,.3f}M / {count / 1e9:,.6f}B"
|
| 30 |
+
|
| 31 |
+
@staticmethod
|
| 32 |
+
def _count_model_params(model: torch.nn.Module) -> tuple[int, int, int]:
|
| 33 |
+
total = 0
|
| 34 |
+
trainable = 0
|
| 35 |
+
frozen = 0
|
| 36 |
+
for param in model.parameters():
|
| 37 |
+
numel = param.numel()
|
| 38 |
+
total += numel
|
| 39 |
+
if param.requires_grad:
|
| 40 |
+
trainable += numel
|
| 41 |
+
else:
|
| 42 |
+
frozen += numel
|
| 43 |
+
return total, trainable, frozen
|
| 44 |
+
|
| 45 |
+
def _print_model_param_summary(self, model: torch.nn.Module):
|
| 46 |
+
total, trainable, frozen = self._count_model_params(model)
|
| 47 |
+
trainable_ratio = (trainable / total * 100.0) if total > 0 else 0.0
|
| 48 |
+
frozen_ratio = (frozen / total * 100.0) if total > 0 else 0.0
|
| 49 |
+
|
| 50 |
+
table_width = 76
|
| 51 |
+
print("\n" + "=" * table_width)
|
| 52 |
+
print("Model Parameter Summary".center(table_width))
|
| 53 |
+
print("-" * table_width)
|
| 54 |
+
print(f"{'Type':<12}{'Count':>18}{'Scale (M / B)':>30}{'Ratio':>16}")
|
| 55 |
+
print("-" * table_width)
|
| 56 |
+
print(
|
| 57 |
+
f"{'Total':<12}{total:>18,}{self._format_params_in_mb(total):>30}{'100.00%':>16}"
|
| 58 |
+
)
|
| 59 |
+
print(
|
| 60 |
+
f"{'Trainable':<12}{trainable:>18,}{self._format_params_in_mb(trainable):>30}{f'{trainable_ratio:.2f}%':>16}"
|
| 61 |
+
)
|
| 62 |
+
print(
|
| 63 |
+
f"{'Frozen':<12}{frozen:>18,}{self._format_params_in_mb(frozen):>30}{f'{frozen_ratio:.2f}%':>16}"
|
| 64 |
+
)
|
| 65 |
+
print("=" * table_width)
|
| 66 |
+
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
model: CFM,
|
| 70 |
+
epochs,
|
| 71 |
+
learning_rate,
|
| 72 |
+
num_warmup_updates=20000,
|
| 73 |
+
save_per_updates=1000,
|
| 74 |
+
keep_last_n_checkpoints: int = -1, # -1 to keep all, 0 to not save intermediate, > 0 to keep last N checkpoints
|
| 75 |
+
checkpoint_path=None,
|
| 76 |
+
batch_size_per_gpu=32,
|
| 77 |
+
batch_size_type: str = "sample",
|
| 78 |
+
max_samples=32,
|
| 79 |
+
grad_accumulation_steps=1,
|
| 80 |
+
max_grad_norm=1.0,
|
| 81 |
+
noise_scheduler: str | None = None,
|
| 82 |
+
duration_predictor: torch.nn.Module | None = None,
|
| 83 |
+
logger: str | None = "wandb", # "wandb" | "tensorboard" | None
|
| 84 |
+
wandb_project="test_wavtts",
|
| 85 |
+
wandb_run_name="test_run",
|
| 86 |
+
wandb_resume_id: str = None,
|
| 87 |
+
log_samples: bool = False,
|
| 88 |
+
last_per_updates=None,
|
| 89 |
+
accelerate_kwargs: dict = dict(),
|
| 90 |
+
ema_kwargs: dict = dict(),
|
| 91 |
+
bnb_optimizer: bool = False,
|
| 92 |
+
model_cfg_dict: dict = dict(), # training config
|
| 93 |
+
):
|
| 94 |
+
ddp_kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
|
| 95 |
+
|
| 96 |
+
if logger == "wandb" and not wandb.api.api_key:
|
| 97 |
+
logger = None
|
| 98 |
+
self.log_samples = log_samples
|
| 99 |
+
|
| 100 |
+
self.accelerator = Accelerator(
|
| 101 |
+
log_with=logger if logger == "wandb" else None,
|
| 102 |
+
kwargs_handlers=[ddp_kwargs],
|
| 103 |
+
gradient_accumulation_steps=grad_accumulation_steps,
|
| 104 |
+
**accelerate_kwargs,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
self.logger = logger
|
| 108 |
+
if self.logger == "wandb":
|
| 109 |
+
if exists(wandb_resume_id):
|
| 110 |
+
init_kwargs = {"wandb": {"resume": "allow", "name": wandb_run_name, "id": wandb_resume_id}}
|
| 111 |
+
else:
|
| 112 |
+
init_kwargs = {"wandb": {"resume": "allow", "name": wandb_run_name}}
|
| 113 |
+
|
| 114 |
+
if not model_cfg_dict:
|
| 115 |
+
model_cfg_dict = {
|
| 116 |
+
"epochs": epochs,
|
| 117 |
+
"learning_rate": learning_rate,
|
| 118 |
+
"num_warmup_updates": num_warmup_updates,
|
| 119 |
+
"batch_size_per_gpu": batch_size_per_gpu,
|
| 120 |
+
"batch_size_type": batch_size_type,
|
| 121 |
+
"max_samples": max_samples,
|
| 122 |
+
"grad_accumulation_steps": grad_accumulation_steps,
|
| 123 |
+
"max_grad_norm": max_grad_norm,
|
| 124 |
+
"noise_scheduler": noise_scheduler,
|
| 125 |
+
}
|
| 126 |
+
model_cfg_dict["gpus"] = self.accelerator.num_processes
|
| 127 |
+
self.accelerator.init_trackers(
|
| 128 |
+
project_name=wandb_project,
|
| 129 |
+
init_kwargs=init_kwargs,
|
| 130 |
+
config=model_cfg_dict,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
elif self.logger == "tensorboard":
|
| 134 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 135 |
+
|
| 136 |
+
self.writer = SummaryWriter(log_dir=f"runs/{wandb_run_name}")
|
| 137 |
+
|
| 138 |
+
self.model = model
|
| 139 |
+
|
| 140 |
+
if self.is_main:
|
| 141 |
+
self.ema_model = EMA(model, include_online_model=False, **ema_kwargs)
|
| 142 |
+
self.ema_model.to(self.accelerator.device)
|
| 143 |
+
self._print_model_param_summary(self.model)
|
| 144 |
+
|
| 145 |
+
print(f"Using logger: {logger}")
|
| 146 |
+
if grad_accumulation_steps > 1:
|
| 147 |
+
print(
|
| 148 |
+
"Gradient accumulation checkpointing with per_updates now, old logic per_steps used with before f992c4e"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
self.epochs = epochs
|
| 152 |
+
self.num_warmup_updates = num_warmup_updates
|
| 153 |
+
self.save_per_updates = save_per_updates
|
| 154 |
+
self.keep_last_n_checkpoints = keep_last_n_checkpoints
|
| 155 |
+
self.last_per_updates = default(last_per_updates, save_per_updates)
|
| 156 |
+
self.checkpoint_path = default(checkpoint_path, "ckpts/test_wavtts")
|
| 157 |
+
|
| 158 |
+
self.batch_size_per_gpu = batch_size_per_gpu
|
| 159 |
+
self.batch_size_type = batch_size_type
|
| 160 |
+
self.max_samples = max_samples
|
| 161 |
+
self.grad_accumulation_steps = grad_accumulation_steps
|
| 162 |
+
self.max_grad_norm = max_grad_norm
|
| 163 |
+
|
| 164 |
+
self.noise_scheduler = noise_scheduler
|
| 165 |
+
|
| 166 |
+
self.duration_predictor = duration_predictor
|
| 167 |
+
|
| 168 |
+
if bnb_optimizer:
|
| 169 |
+
import bitsandbytes as bnb
|
| 170 |
+
|
| 171 |
+
self.optimizer = bnb.optim.AdamW8bit(model.parameters(), lr=learning_rate)
|
| 172 |
+
else:
|
| 173 |
+
self.optimizer = AdamW(model.parameters(), lr=learning_rate)
|
| 174 |
+
self.model, self.optimizer = self.accelerator.prepare(self.model, self.optimizer)
|
| 175 |
+
|
| 176 |
+
@property
|
| 177 |
+
def is_main(self):
|
| 178 |
+
return self.accelerator.is_main_process
|
| 179 |
+
|
| 180 |
+
def save_checkpoint(self, update, last=False):
|
| 181 |
+
self.accelerator.wait_for_everyone()
|
| 182 |
+
if self.is_main:
|
| 183 |
+
checkpoint = dict(
|
| 184 |
+
model_state_dict=self.accelerator.unwrap_model(self.model).state_dict(),
|
| 185 |
+
optimizer_state_dict=self.optimizer.state_dict(),
|
| 186 |
+
ema_model_state_dict=self.ema_model.state_dict(),
|
| 187 |
+
scheduler_state_dict=self.scheduler.state_dict(),
|
| 188 |
+
update=update,
|
| 189 |
+
)
|
| 190 |
+
if not os.path.exists(self.checkpoint_path):
|
| 191 |
+
os.makedirs(self.checkpoint_path)
|
| 192 |
+
if last:
|
| 193 |
+
self.accelerator.save(checkpoint, f"{self.checkpoint_path}/model_last.pt")
|
| 194 |
+
print(f"Saved last checkpoint at update {update}")
|
| 195 |
+
else:
|
| 196 |
+
if self.keep_last_n_checkpoints == 0:
|
| 197 |
+
return
|
| 198 |
+
self.accelerator.save(checkpoint, f"{self.checkpoint_path}/model_{update}.pt")
|
| 199 |
+
if self.keep_last_n_checkpoints > 0:
|
| 200 |
+
# Updated logic to exclude pretrained model from rotation
|
| 201 |
+
checkpoints = [
|
| 202 |
+
f
|
| 203 |
+
for f in os.listdir(self.checkpoint_path)
|
| 204 |
+
if f.startswith("model_")
|
| 205 |
+
and not f.startswith("pretrained_") # Exclude pretrained models
|
| 206 |
+
and f.endswith(".pt")
|
| 207 |
+
and f != "model_last.pt"
|
| 208 |
+
]
|
| 209 |
+
checkpoints.sort(key=lambda x: int(x.split("_")[1].split(".")[0]))
|
| 210 |
+
while len(checkpoints) > self.keep_last_n_checkpoints:
|
| 211 |
+
oldest_checkpoint = checkpoints.pop(0)
|
| 212 |
+
os.remove(os.path.join(self.checkpoint_path, oldest_checkpoint))
|
| 213 |
+
print(f"Removed old checkpoint: {oldest_checkpoint}")
|
| 214 |
+
|
| 215 |
+
def load_checkpoint(self):
|
| 216 |
+
if (
|
| 217 |
+
not exists(self.checkpoint_path)
|
| 218 |
+
or not os.path.exists(self.checkpoint_path)
|
| 219 |
+
or not any(filename.endswith((".pt", ".safetensors")) for filename in os.listdir(self.checkpoint_path))
|
| 220 |
+
):
|
| 221 |
+
return 0
|
| 222 |
+
|
| 223 |
+
self.accelerator.wait_for_everyone()
|
| 224 |
+
if "model_last.pt" in os.listdir(self.checkpoint_path):
|
| 225 |
+
latest_checkpoint = "model_last.pt"
|
| 226 |
+
else:
|
| 227 |
+
# Updated to consider pretrained models for loading but prioritize training checkpoints
|
| 228 |
+
all_checkpoints = [
|
| 229 |
+
f
|
| 230 |
+
for f in os.listdir(self.checkpoint_path)
|
| 231 |
+
if (f.startswith("model_") or f.startswith("pretrained_")) and f.endswith((".pt", ".safetensors"))
|
| 232 |
+
]
|
| 233 |
+
|
| 234 |
+
# First try to find regular training checkpoints
|
| 235 |
+
training_checkpoints = [f for f in all_checkpoints if f.startswith("model_") and f != "model_last.pt"]
|
| 236 |
+
if training_checkpoints:
|
| 237 |
+
latest_checkpoint = sorted(
|
| 238 |
+
training_checkpoints,
|
| 239 |
+
key=lambda x: int("".join(filter(str.isdigit, x))),
|
| 240 |
+
)[-1]
|
| 241 |
+
else:
|
| 242 |
+
# If no training checkpoints, use pretrained model
|
| 243 |
+
latest_checkpoint = next(f for f in all_checkpoints if f.startswith("pretrained_"))
|
| 244 |
+
|
| 245 |
+
if latest_checkpoint.endswith(".safetensors"): # always a pretrained checkpoint
|
| 246 |
+
from safetensors.torch import load_file
|
| 247 |
+
|
| 248 |
+
checkpoint = load_file(f"{self.checkpoint_path}/{latest_checkpoint}", device="cpu")
|
| 249 |
+
checkpoint = {"ema_model_state_dict": checkpoint}
|
| 250 |
+
elif latest_checkpoint.endswith(".pt"):
|
| 251 |
+
# checkpoint = torch.load(f"{self.checkpoint_path}/{latest_checkpoint}", map_location=self.accelerator.device) # rather use accelerator.load_state ಥ_ಥ
|
| 252 |
+
checkpoint = torch.load(
|
| 253 |
+
f"{self.checkpoint_path}/{latest_checkpoint}", weights_only=True, map_location="cpu"
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
if self.is_main:
|
| 257 |
+
print("=" * 80)
|
| 258 |
+
print("Resume training: found checkpoint and loading state")
|
| 259 |
+
print(f"Checkpoint directory: {self.checkpoint_path}")
|
| 260 |
+
print(f"Checkpoint file: {latest_checkpoint}")
|
| 261 |
+
print("=" * 80)
|
| 262 |
+
|
| 263 |
+
if self.is_main:
|
| 264 |
+
self.ema_model.load_state_dict(checkpoint["ema_model_state_dict"])
|
| 265 |
+
|
| 266 |
+
if "update" in checkpoint or "step" in checkpoint:
|
| 267 |
+
# patch for backward compatibility, with before f992c4e
|
| 268 |
+
if "step" in checkpoint:
|
| 269 |
+
checkpoint["update"] = checkpoint["step"] // self.grad_accumulation_steps
|
| 270 |
+
if self.grad_accumulation_steps > 1 and self.is_main:
|
| 271 |
+
print(
|
| 272 |
+
"WavTTS WARNING: Loading checkpoint saved with per_steps logic (before f992c4e), will convert to per_updates according to grad_accumulation_steps setting, may have unexpected behaviour."
|
| 273 |
+
)
|
| 274 |
+
self.accelerator.unwrap_model(self.model).load_state_dict(checkpoint["model_state_dict"])
|
| 275 |
+
self.optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
|
| 276 |
+
if self.scheduler:
|
| 277 |
+
self.scheduler.load_state_dict(checkpoint["scheduler_state_dict"])
|
| 278 |
+
update = checkpoint["update"]
|
| 279 |
+
if self.is_main:
|
| 280 |
+
print(f"Resume mode: full-state resume (model + optimizer + scheduler), update={update}")
|
| 281 |
+
else:
|
| 282 |
+
checkpoint["model_state_dict"] = {
|
| 283 |
+
k.replace("ema_model.", ""): v
|
| 284 |
+
for k, v in checkpoint["ema_model_state_dict"].items()
|
| 285 |
+
if k not in ["initted", "update", "step"]
|
| 286 |
+
}
|
| 287 |
+
self.accelerator.unwrap_model(self.model).load_state_dict(checkpoint["model_state_dict"])
|
| 288 |
+
update = 0
|
| 289 |
+
if self.is_main:
|
| 290 |
+
print("Resume mode: pretrained-weight init only, update=0")
|
| 291 |
+
|
| 292 |
+
del checkpoint
|
| 293 |
+
gc.collect()
|
| 294 |
+
return update
|
| 295 |
+
|
| 296 |
+
def train(self, train_dataset: Dataset, num_workers=16, resumable_with_seed: int = None):
|
| 297 |
+
if self.log_samples:
|
| 298 |
+
from wavtts.infer.utils_infer import cfg_strength, nfe_step, sway_sampling_coef
|
| 299 |
+
|
| 300 |
+
target_sample_rate = train_dataset.target_sample_rate
|
| 301 |
+
log_samples_path = f"{self.checkpoint_path}/samples"
|
| 302 |
+
os.makedirs(log_samples_path, exist_ok=True)
|
| 303 |
+
|
| 304 |
+
if exists(resumable_with_seed):
|
| 305 |
+
generator = torch.Generator()
|
| 306 |
+
generator.manual_seed(resumable_with_seed)
|
| 307 |
+
else:
|
| 308 |
+
generator = None
|
| 309 |
+
|
| 310 |
+
if self.batch_size_type == "sample":
|
| 311 |
+
train_dataloader = DataLoader(
|
| 312 |
+
train_dataset,
|
| 313 |
+
collate_fn=collate_fn,
|
| 314 |
+
num_workers=num_workers,
|
| 315 |
+
pin_memory=True,
|
| 316 |
+
persistent_workers=True,
|
| 317 |
+
batch_size=self.batch_size_per_gpu,
|
| 318 |
+
shuffle=True,
|
| 319 |
+
generator=generator,
|
| 320 |
+
)
|
| 321 |
+
elif self.batch_size_type == "frame":
|
| 322 |
+
self.accelerator.even_batches = False
|
| 323 |
+
sampler = SequentialSampler(train_dataset)
|
| 324 |
+
batch_sampler = DynamicBatchSampler(
|
| 325 |
+
sampler,
|
| 326 |
+
self.batch_size_per_gpu,
|
| 327 |
+
max_samples=self.max_samples,
|
| 328 |
+
random_seed=resumable_with_seed, # This enables reproducible shuffling
|
| 329 |
+
drop_residual=False,
|
| 330 |
+
)
|
| 331 |
+
train_dataloader = DataLoader(
|
| 332 |
+
train_dataset,
|
| 333 |
+
collate_fn=collate_fn,
|
| 334 |
+
num_workers=num_workers,
|
| 335 |
+
pin_memory=True,
|
| 336 |
+
persistent_workers=True,
|
| 337 |
+
batch_sampler=batch_sampler,
|
| 338 |
+
)
|
| 339 |
+
else:
|
| 340 |
+
raise ValueError(f"batch_size_type must be either 'sample' or 'frame', but received {self.batch_size_type}")
|
| 341 |
+
|
| 342 |
+
# accelerator.prepare() dispatches batches to devices;
|
| 343 |
+
# which means the length of dataloader calculated before, should consider the number of devices
|
| 344 |
+
warmup_updates = (
|
| 345 |
+
self.num_warmup_updates * self.accelerator.num_processes
|
| 346 |
+
) # consider a fixed warmup steps while using accelerate multi-gpu ddp
|
| 347 |
+
# otherwise by default with split_batches=False, warmup steps change with num_processes
|
| 348 |
+
total_updates = math.ceil(len(train_dataloader) / self.grad_accumulation_steps) * self.epochs
|
| 349 |
+
decay_updates = total_updates - warmup_updates
|
| 350 |
+
warmup_scheduler = LinearLR(self.optimizer, start_factor=1e-8, end_factor=1.0, total_iters=warmup_updates)
|
| 351 |
+
decay_scheduler = LinearLR(self.optimizer, start_factor=1.0, end_factor=1e-8, total_iters=decay_updates)
|
| 352 |
+
self.scheduler = SequentialLR(
|
| 353 |
+
self.optimizer, schedulers=[warmup_scheduler, decay_scheduler], milestones=[warmup_updates]
|
| 354 |
+
)
|
| 355 |
+
train_dataloader, self.scheduler = self.accelerator.prepare(
|
| 356 |
+
train_dataloader, self.scheduler
|
| 357 |
+
) # actual multi_gpu updates = single_gpu updates / gpu nums
|
| 358 |
+
start_update = self.load_checkpoint()
|
| 359 |
+
global_update = start_update
|
| 360 |
+
|
| 361 |
+
if exists(resumable_with_seed):
|
| 362 |
+
orig_epoch_step = len(train_dataloader)
|
| 363 |
+
start_step = start_update * self.grad_accumulation_steps
|
| 364 |
+
skipped_epoch = int(start_step // orig_epoch_step)
|
| 365 |
+
skipped_batch = start_step % orig_epoch_step
|
| 366 |
+
skipped_dataloader = self.accelerator.skip_first_batches(train_dataloader, num_batches=skipped_batch)
|
| 367 |
+
else:
|
| 368 |
+
skipped_epoch = 0
|
| 369 |
+
|
| 370 |
+
for epoch in range(skipped_epoch, self.epochs):
|
| 371 |
+
self.model.train()
|
| 372 |
+
if exists(resumable_with_seed) and epoch == skipped_epoch:
|
| 373 |
+
progress_bar_initial = math.ceil(skipped_batch / self.grad_accumulation_steps)
|
| 374 |
+
current_dataloader = skipped_dataloader
|
| 375 |
+
else:
|
| 376 |
+
progress_bar_initial = 0
|
| 377 |
+
current_dataloader = train_dataloader
|
| 378 |
+
|
| 379 |
+
# Set epoch for the batch sampler if it exists
|
| 380 |
+
if hasattr(train_dataloader, "batch_sampler") and hasattr(train_dataloader.batch_sampler, "set_epoch"):
|
| 381 |
+
train_dataloader.batch_sampler.set_epoch(epoch)
|
| 382 |
+
|
| 383 |
+
progress_bar = tqdm(
|
| 384 |
+
range(math.ceil(len(train_dataloader) / self.grad_accumulation_steps)),
|
| 385 |
+
desc=f"Epoch {epoch + 1}/{self.epochs}",
|
| 386 |
+
unit="update",
|
| 387 |
+
disable=not self.accelerator.is_local_main_process,
|
| 388 |
+
initial=progress_bar_initial,
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
for batch in current_dataloader:
|
| 392 |
+
with self.accelerator.accumulate(self.model):
|
| 393 |
+
text_inputs = batch["text"]
|
| 394 |
+
wav = batch["wav"]
|
| 395 |
+
wav_lengths = batch["wav_lengths"]
|
| 396 |
+
text_lengths = batch["text_lengths"]
|
| 397 |
+
|
| 398 |
+
# TODO. add duration predictor training
|
| 399 |
+
if self.duration_predictor is not None and self.accelerator.is_local_main_process:
|
| 400 |
+
dur_loss = self.duration_predictor(wav, lens=batch.get("durations"))
|
| 401 |
+
self.accelerator.log({"duration loss": dur_loss.item()}, step=global_update)
|
| 402 |
+
|
| 403 |
+
loss, cond, pred, loss_dict = self.model(
|
| 404 |
+
wav, text=text_inputs, lens=wav_lengths, noise_scheduler=self.noise_scheduler,
|
| 405 |
+
)
|
| 406 |
+
self.accelerator.backward(loss)
|
| 407 |
+
|
| 408 |
+
if self.max_grad_norm > 0 and self.accelerator.sync_gradients:
|
| 409 |
+
self.accelerator.clip_grad_norm_(self.model.parameters(), self.max_grad_norm)
|
| 410 |
+
|
| 411 |
+
self.optimizer.step()
|
| 412 |
+
self.scheduler.step()
|
| 413 |
+
self.optimizer.zero_grad()
|
| 414 |
+
|
| 415 |
+
if self.accelerator.sync_gradients:
|
| 416 |
+
if self.is_main:
|
| 417 |
+
self.ema_model.update()
|
| 418 |
+
|
| 419 |
+
global_update += 1
|
| 420 |
+
progress_bar.update(1)
|
| 421 |
+
progress_bar.set_postfix(
|
| 422 |
+
update=str(global_update),
|
| 423 |
+
aux_mel_loss=loss_dict["aux_mel_loss"].item(),
|
| 424 |
+
flow_loss=loss_dict["flow_loss"].item(),
|
| 425 |
+
loss=loss.item()
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
if self.accelerator.is_local_main_process:
|
| 429 |
+
self.accelerator.log(
|
| 430 |
+
{"loss": loss.item(), "lr": self.scheduler.get_last_lr()[0]}, step=global_update
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
if loss_dict["flow_loss"] is not None:
|
| 434 |
+
self.accelerator.log({"flow_loss": loss_dict["flow_loss"].item()}, step=global_update)
|
| 435 |
+
if loss_dict["aux_mel_loss"] is not None:
|
| 436 |
+
self.accelerator.log({"aux_mel_loss": loss_dict["aux_mel_loss"].item()}, step=global_update)
|
| 437 |
+
|
| 438 |
+
if self.logger == "tensorboard":
|
| 439 |
+
self.writer.add_scalar("loss", loss.item(), global_update)
|
| 440 |
+
self.writer.add_scalar("lr", self.scheduler.get_last_lr()[0], global_update)
|
| 441 |
+
if loss_dict["flow_loss"] is not None:
|
| 442 |
+
self.writer.add_scalar("flow_loss", loss_dict["flow_loss"].item(), global_update)
|
| 443 |
+
if loss_dict["aux_mel_loss"] is not None:
|
| 444 |
+
self.writer.add_scalar("aux_mel_loss", loss_dict["aux_mel_loss"].item(), global_update)
|
| 445 |
+
|
| 446 |
+
if global_update % self.last_per_updates == 0 and self.accelerator.sync_gradients:
|
| 447 |
+
self.save_checkpoint(global_update, last=True)
|
| 448 |
+
|
| 449 |
+
if global_update % self.save_per_updates == 0 and self.accelerator.sync_gradients:
|
| 450 |
+
self.save_checkpoint(global_update)
|
| 451 |
+
|
| 452 |
+
if self.log_samples and self.accelerator.is_local_main_process:
|
| 453 |
+
unwrap = self.accelerator.unwrap_model(self.model)
|
| 454 |
+
|
| 455 |
+
infer_text = [
|
| 456 |
+
text_inputs[0] + ([" "] if isinstance(text_inputs[0], list) else " ") + text_inputs[0]
|
| 457 |
+
]
|
| 458 |
+
|
| 459 |
+
with torch.inference_mode():
|
| 460 |
+
ref_wav_len = wav_lengths[0].item()
|
| 461 |
+
ref_wav = wav[0][:ref_wav_len].unsqueeze(0).to(self.accelerator.device) # [1, N]
|
| 462 |
+
|
| 463 |
+
generated, _ = unwrap.sample(
|
| 464 |
+
cond=ref_wav, # [1, N]
|
| 465 |
+
text=infer_text,
|
| 466 |
+
duration=ref_wav_len * 2,
|
| 467 |
+
steps=nfe_step,
|
| 468 |
+
cfg_strength=cfg_strength,
|
| 469 |
+
sway_sampling_coef=sway_sampling_coef,
|
| 470 |
+
)
|
| 471 |
+
generated = generated.to(torch.float32).cpu() # [1, N_total]
|
| 472 |
+
|
| 473 |
+
cut = ref_wav_len
|
| 474 |
+
gen_audio = generated[:, cut:] # [1, N_gen]
|
| 475 |
+
ref_audio = ref_wav.cpu() # [1, N_ref]
|
| 476 |
+
|
| 477 |
+
torchaudio.save(
|
| 478 |
+
f"{log_samples_path}/update_{global_update}_gen.wav", gen_audio, target_sample_rate
|
| 479 |
+
)
|
| 480 |
+
torchaudio.save(
|
| 481 |
+
f"{log_samples_path}/update_{global_update}_ref.wav", ref_audio, target_sample_rate
|
| 482 |
+
)
|
| 483 |
+
self.model.train()
|
| 484 |
+
|
| 485 |
+
self.save_checkpoint(global_update, last=True)
|
| 486 |
+
|
| 487 |
+
self.accelerator.end_training()
|
src/wavtts/model/utils.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ruff: noqa: F722 F821
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from importlib.resources import files
|
| 9 |
+
|
| 10 |
+
import rjieba
|
| 11 |
+
import torch
|
| 12 |
+
from pypinyin import Style, lazy_pinyin
|
| 13 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# seed everything
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def seed_everything(seed=0):
|
| 20 |
+
random.seed(seed)
|
| 21 |
+
os.environ["PYTHONHASHSEED"] = str(seed)
|
| 22 |
+
torch.manual_seed(seed)
|
| 23 |
+
torch.cuda.manual_seed(seed)
|
| 24 |
+
torch.cuda.manual_seed_all(seed)
|
| 25 |
+
torch.backends.cudnn.deterministic = True
|
| 26 |
+
torch.backends.cudnn.benchmark = False
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# helpers
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def exists(v):
|
| 33 |
+
return v is not None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def default(v, d):
|
| 37 |
+
return v if exists(v) else d
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def is_package_available(package_name: str) -> bool:
|
| 41 |
+
try:
|
| 42 |
+
import importlib
|
| 43 |
+
|
| 44 |
+
package_exists = importlib.util.find_spec(package_name) is not None
|
| 45 |
+
return package_exists
|
| 46 |
+
except Exception:
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# tensor helpers
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def lens_to_mask(t: int["b"], length: int | None = None) -> bool["b n"]:
|
| 54 |
+
if not exists(length):
|
| 55 |
+
length = t.amax()
|
| 56 |
+
|
| 57 |
+
seq = torch.arange(length, device=t.device)
|
| 58 |
+
return seq[None, :] < t[:, None]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def mask_from_start_end_indices(seq_len: int["b"], start: int["b"], end: int["b"]):
|
| 62 |
+
max_seq_len = seq_len.max().item()
|
| 63 |
+
seq = torch.arange(max_seq_len, device=start.device).long()
|
| 64 |
+
start_mask = seq[None, :] >= start[:, None]
|
| 65 |
+
end_mask = seq[None, :] < end[:, None]
|
| 66 |
+
return start_mask & end_mask
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def mask_from_frac_lengths(seq_len: int["b"], frac_lengths: float["b"]):
|
| 70 |
+
lengths = (frac_lengths * seq_len).long()
|
| 71 |
+
max_start = seq_len - lengths
|
| 72 |
+
|
| 73 |
+
rand = torch.rand_like(frac_lengths)
|
| 74 |
+
start = (max_start * rand).long().clamp(min=0)
|
| 75 |
+
end = start + lengths
|
| 76 |
+
|
| 77 |
+
return mask_from_start_end_indices(seq_len, start, end)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def maybe_masked_mean(t: float["b n d"], mask: bool["b n"] = None) -> float["b d"]:
|
| 81 |
+
if not exists(mask):
|
| 82 |
+
return t.mean(dim=1)
|
| 83 |
+
|
| 84 |
+
t = torch.where(mask[:, :, None], t, torch.tensor(0.0, device=t.device))
|
| 85 |
+
num = t.sum(dim=1)
|
| 86 |
+
den = mask.float().sum(dim=1)
|
| 87 |
+
|
| 88 |
+
return num / den.clamp(min=1.0)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# simple utf-8 tokenizer, since paper went character based
|
| 92 |
+
def list_str_to_tensor(text: list[str], padding_value=-1) -> int["b nt"]:
|
| 93 |
+
list_tensors = [torch.tensor([*bytes(t, "UTF-8")]) for t in text] # ByT5 style
|
| 94 |
+
text = pad_sequence(list_tensors, padding_value=padding_value, batch_first=True)
|
| 95 |
+
return text
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# char tokenizer, based on custom dataset's extracted .txt file
|
| 99 |
+
def list_str_to_idx(
|
| 100 |
+
text: list[str] | list[list[str]],
|
| 101 |
+
vocab_char_map: dict[str, int], # {char: idx}
|
| 102 |
+
padding_value=-1,
|
| 103 |
+
) -> int["b nt"]:
|
| 104 |
+
list_idx_tensors = [torch.tensor([vocab_char_map.get(c, 0) for c in t]) for t in text] # pinyin or char style
|
| 105 |
+
text = pad_sequence(list_idx_tensors, padding_value=padding_value, batch_first=True)
|
| 106 |
+
return text
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# Get tokenizer
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def get_tokenizer(dataset_name, tokenizer: str = "pinyin"):
|
| 113 |
+
"""
|
| 114 |
+
tokenizer - "pinyin" do g2p for only chinese characters, need .txt vocab_file
|
| 115 |
+
- "char" for char-wise tokenizer, need .txt vocab_file
|
| 116 |
+
- "byte" for utf-8 tokenizer
|
| 117 |
+
- "custom" if you're directly passing in a path to the vocab.txt you want to use
|
| 118 |
+
vocab_size - if use "pinyin", all available pinyin types, common alphabets (also those with accent) and symbols
|
| 119 |
+
- if use "char", derived from unfiltered character & symbol counts of custom dataset
|
| 120 |
+
- if use "byte", set to 256 (unicode byte range)
|
| 121 |
+
"""
|
| 122 |
+
if tokenizer in ["pinyin", "char"]:
|
| 123 |
+
tokenizer_path = os.path.join(files("wavtts").joinpath("../../data"), f"{dataset_name}_{tokenizer}/vocab.txt")
|
| 124 |
+
with open(tokenizer_path, "r", encoding="utf-8") as f:
|
| 125 |
+
vocab_char_map = {}
|
| 126 |
+
for i, char in enumerate(f):
|
| 127 |
+
vocab_char_map[char[:-1]] = i
|
| 128 |
+
vocab_size = len(vocab_char_map)
|
| 129 |
+
assert vocab_char_map[" "] == 0, "make sure space is of idx 0 in vocab.txt, cuz 0 is used for unknown char"
|
| 130 |
+
|
| 131 |
+
elif tokenizer == "byte":
|
| 132 |
+
vocab_char_map = None
|
| 133 |
+
vocab_size = 256
|
| 134 |
+
|
| 135 |
+
elif tokenizer == "custom":
|
| 136 |
+
with open(dataset_name, "r", encoding="utf-8") as f:
|
| 137 |
+
vocab_char_map = {}
|
| 138 |
+
for i, char in enumerate(f):
|
| 139 |
+
vocab_char_map[char[:-1]] = i
|
| 140 |
+
vocab_size = len(vocab_char_map)
|
| 141 |
+
|
| 142 |
+
return vocab_char_map, vocab_size
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# convert char to pinyin
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def convert_char_to_pinyin(text_list, polyphone=True):
|
| 149 |
+
final_text_list = []
|
| 150 |
+
custom_trans = str.maketrans(
|
| 151 |
+
{";": ",", "“": '"', "”": '"', "‘": "'", "’": "'"}
|
| 152 |
+
) # add custom trans here, to address oov
|
| 153 |
+
|
| 154 |
+
def is_chinese(c):
|
| 155 |
+
return (
|
| 156 |
+
"\u3100" <= c <= "\u9fff" # common chinese characters
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
for text in text_list:
|
| 160 |
+
char_list = []
|
| 161 |
+
text = text.translate(custom_trans)
|
| 162 |
+
for seg in rjieba.cut(text):
|
| 163 |
+
seg_byte_len = len(bytes(seg, "UTF-8"))
|
| 164 |
+
if seg_byte_len == len(seg): # if pure alphabets and symbols
|
| 165 |
+
if char_list and seg_byte_len > 1 and char_list[-1] not in " :'\"":
|
| 166 |
+
char_list.append(" ")
|
| 167 |
+
char_list.extend(seg)
|
| 168 |
+
elif polyphone and seg_byte_len == 3 * len(seg): # if pure east asian characters
|
| 169 |
+
seg_ = lazy_pinyin(seg, style=Style.TONE3, tone_sandhi=True)
|
| 170 |
+
for i, c in enumerate(seg):
|
| 171 |
+
if is_chinese(c):
|
| 172 |
+
char_list.append(" ")
|
| 173 |
+
char_list.append(seg_[i])
|
| 174 |
+
else: # if mixed characters, alphabets and symbols
|
| 175 |
+
for c in seg:
|
| 176 |
+
if ord(c) < 256:
|
| 177 |
+
char_list.extend(c)
|
| 178 |
+
elif is_chinese(c):
|
| 179 |
+
char_list.append(" ")
|
| 180 |
+
char_list.extend(lazy_pinyin(c, style=Style.TONE3, tone_sandhi=True))
|
| 181 |
+
else:
|
| 182 |
+
char_list.append(c)
|
| 183 |
+
final_text_list.append(char_list)
|
| 184 |
+
|
| 185 |
+
return final_text_list
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# filter func for dirty data with many repetitions
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def repetition_found(text, length=2, tolerance=10):
|
| 192 |
+
pattern_count = defaultdict(int)
|
| 193 |
+
for i in range(len(text) - length + 1):
|
| 194 |
+
pattern = text[i : i + length]
|
| 195 |
+
pattern_count[pattern] += 1
|
| 196 |
+
for pattern, count in pattern_count.items():
|
| 197 |
+
if count > tolerance:
|
| 198 |
+
return True
|
| 199 |
+
return False
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# get the empirically pruned step for sampling
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def get_epss_timesteps(n, device, dtype):
|
| 206 |
+
dt = 1 / 32
|
| 207 |
+
predefined_timesteps = {
|
| 208 |
+
5: [0, 2, 4, 8, 16, 32],
|
| 209 |
+
6: [0, 2, 4, 6, 8, 16, 32],
|
| 210 |
+
7: [0, 2, 4, 6, 8, 16, 24, 32],
|
| 211 |
+
10: [0, 2, 4, 6, 8, 12, 16, 20, 24, 28, 32],
|
| 212 |
+
12: [0, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32],
|
| 213 |
+
16: [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32],
|
| 214 |
+
}
|
| 215 |
+
t = predefined_timesteps.get(n, [])
|
| 216 |
+
if not t:
|
| 217 |
+
return torch.linspace(0, 1, n + 1, device=device, dtype=dtype)
|
| 218 |
+
return dt * torch.tensor(t, device=device, dtype=dtype)
|
| 219 |
+
|
| 220 |
+
def masked_mean(x, mask):
|
| 221 |
+
return (x * mask).sum() / mask.sum()
|
src/wavtts/scripts/count_max_epoch.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ADAPTIVE BATCH SIZE"""
|
| 2 |
+
|
| 3 |
+
print("Adaptive batch size: using grouping batch sampler, frames_per_gpu fixed fed in")
|
| 4 |
+
print(" -> least padding, gather wavs with accumulated frames in a batch\n")
|
| 5 |
+
|
| 6 |
+
# data
|
| 7 |
+
total_hours = 95282
|
| 8 |
+
wav_frame_len = 160
|
| 9 |
+
target_sample_rate = 16000
|
| 10 |
+
|
| 11 |
+
# target
|
| 12 |
+
wanted_max_updates = 1200000
|
| 13 |
+
|
| 14 |
+
# train params
|
| 15 |
+
gpus = 8
|
| 16 |
+
frames_per_gpu = 38400 # 8 * 38400 = 307200
|
| 17 |
+
grad_accum = 1
|
| 18 |
+
|
| 19 |
+
# intermediate
|
| 20 |
+
mini_batch_frames = frames_per_gpu * grad_accum * gpus
|
| 21 |
+
mini_batch_hours = mini_batch_frames * wav_frame_len / target_sample_rate / 3600
|
| 22 |
+
updates_per_epoch = total_hours / mini_batch_hours
|
| 23 |
+
# steps_per_epoch = updates_per_epoch * grad_accum
|
| 24 |
+
|
| 25 |
+
# result
|
| 26 |
+
epochs = wanted_max_updates / updates_per_epoch
|
| 27 |
+
print(f"epochs should be set to: {epochs:.0f} ({epochs / grad_accum:.1f} x gd_acum {grad_accum})")
|
| 28 |
+
print(f"progress_bar should show approx. 0/{updates_per_epoch:.0f} updates")
|
| 29 |
+
# print(f" or approx. 0/{steps_per_epoch:.0f} steps")
|
| 30 |
+
|
| 31 |
+
# others
|
| 32 |
+
print(f"total {total_hours:.0f} hours")
|
| 33 |
+
print(f"mini-batch of {mini_batch_frames:.0f} frames, {mini_batch_hours:.2f} hours per mini-batch")
|
src/wavtts/scripts/count_max_epoch_precise.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
from torch.utils.data import SequentialSampler
|
| 4 |
+
|
| 5 |
+
from wavtts.model.dataset import DynamicBatchSampler, load_dataset
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
train_dataset = load_dataset("Emilia_ZH_EN", "pinyin")
|
| 9 |
+
sampler = SequentialSampler(train_dataset)
|
| 10 |
+
|
| 11 |
+
gpus = 8
|
| 12 |
+
batch_size_per_gpu = 38400
|
| 13 |
+
max_samples_per_gpu = 64
|
| 14 |
+
max_updates = 1250000
|
| 15 |
+
|
| 16 |
+
batch_sampler = DynamicBatchSampler(
|
| 17 |
+
sampler,
|
| 18 |
+
batch_size_per_gpu,
|
| 19 |
+
max_samples=max_samples_per_gpu,
|
| 20 |
+
random_seed=666,
|
| 21 |
+
drop_residual=False,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
print(
|
| 25 |
+
f"One epoch has {len(batch_sampler) / gpus} updates if gpus={gpus}, with "
|
| 26 |
+
f"batch_size_per_gpu={batch_size_per_gpu} (frames) & "
|
| 27 |
+
f"max_samples_per_gpu={max_samples_per_gpu}."
|
| 28 |
+
)
|
| 29 |
+
print(
|
| 30 |
+
f"If gpus={gpus}, for max_updates={max_updates} "
|
| 31 |
+
f"should set epoch={math.ceil(max_updates / len(batch_sampler) * gpus)}."
|
| 32 |
+
)
|
src/wavtts/scripts/count_params_gflops.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
sys.path.append(os.getcwd())
|
| 6 |
+
|
| 7 |
+
import thop
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from wavtts.model import CFM, DiT
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
""" ~155M """
|
| 14 |
+
# transformer = DiT(dim = 768, depth = 18, heads = 12, ff_mult = 2)
|
| 15 |
+
# transformer = DiT(dim = 768, depth = 18, heads = 12, ff_mult = 2, text_dim = 512, conv_layers = 4)
|
| 16 |
+
# transformer = DiT(dim = 768, depth = 18, heads = 12, ff_mult = 2, text_dim = 512, conv_layers = 4, long_skip_connection = True)
|
| 17 |
+
# transformer = MMDiT(dim = 512, depth = 16, heads = 16, ff_mult = 2)
|
| 18 |
+
|
| 19 |
+
""" ~335M """
|
| 20 |
+
# FLOPs: 622.1 G, Params: 333.2 M
|
| 21 |
+
# FLOPs: 363.4 G, Params: 335.8 M
|
| 22 |
+
transformer = DiT(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
model = CFM(transformer=transformer)
|
| 26 |
+
target_sample_rate = 16000
|
| 27 |
+
wav_frame_len = 160
|
| 28 |
+
duration = 20
|
| 29 |
+
frame_length = int(duration * target_sample_rate / wav_frame_len)
|
| 30 |
+
text_length = 150
|
| 31 |
+
|
| 32 |
+
flops, params = thop.profile(
|
| 33 |
+
model, inputs=(torch.randn(1, frame_length, wav_frame_len), torch.zeros(1, text_length, dtype=torch.long))
|
| 34 |
+
)
|
| 35 |
+
print(f"FLOPs: {flops / 1e9} G")
|
| 36 |
+
print(f"Params: {params / 1e6} M")
|
src/wavtts/train/README.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Training
|
| 2 |
+
|
| 3 |
+
> **💡 Note:** The training pipeline is consistent with [F5-TTS](https://github.com/SWivid/F5-TTS). If you encounter any issues during data preparation or training, we highly recommend checking the original F5-TTS repository's documentation and issue tracker first.
|
| 4 |
+
|
| 5 |
+
## 0. Prerequisites
|
| 6 |
+
|
| 7 |
+
Ensure FFmpeg is installed on your system. You can verify your installation by running:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
ffmpeg -version
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
*(If FFmpeg is not found, please install it using your system's package manager, or ensure you have an alternative audio backend available.)*
|
| 14 |
+
|
| 15 |
+
## 1. Prepare Dataset
|
| 16 |
+
|
| 17 |
+
We provide example data processing scripts for several open-source datasets. You can adapt these scripts for your own data or customize the `Dataset` class in `src/wavtts/model/dataset.py`.
|
| 18 |
+
|
| 19 |
+
### A. Pre-built Dataset Scripts
|
| 20 |
+
Before running these scripts, please download the corresponding dataset and update the data paths within the script.
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
# Prepare the Emilia dataset (Primary dataset for WavTTS)
|
| 24 |
+
python src/wavtts/train/datasets/prepare_emilia.py
|
| 25 |
+
|
| 26 |
+
# Prepare the Wenetspeech4TTS dataset
|
| 27 |
+
python src/wavtts/train/datasets/prepare_wenetspeech4tts.py
|
| 28 |
+
|
| 29 |
+
# Prepare the LibriTTS dataset
|
| 30 |
+
python src/wavtts/train/datasets/prepare_libritts.py
|
| 31 |
+
|
| 32 |
+
# Prepare the LJSpeech dataset
|
| 33 |
+
python src/wavtts/train/datasets/prepare_ljspeech.py
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
### B. Custom Dataset via Metadata (CSV)
|
| 37 |
+
|
| 38 |
+
If you are using a custom dataset, you can format it with a `metadata.csv` file. For detailed guidance, see [this discussion thread (#57)](https://github.com/SWivid/F5-TTS/discussions/57#discussioncomment-10959029).
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
python src/wavtts/train/datasets/prepare_csv_wavs.py
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
## 2. Training & Fine-Tuning
|
| 45 |
+
|
| 46 |
+
Once your dataset is ready, you can launch the training process using Hugging Face Accelerate.
|
| 47 |
+
|
| 48 |
+
### A. Training from Scratch / Pre-training
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
# 1. Setup accelerate config (e.g., multi-GPU DDP, mixed precision)
|
| 52 |
+
# This generates a config file at ~/.cache/huggingface/accelerate/default_config.yaml
|
| 53 |
+
accelerate config
|
| 54 |
+
|
| 55 |
+
# 2. Launch training
|
| 56 |
+
# YAML configuration files are located under the src/wavtts/configs/ directory.
|
| 57 |
+
accelerate launch src/wavtts/train/train.py --config-name WavTTS.yaml
|
| 58 |
+
|
| 59 |
+
# Example with inline overrides:
|
| 60 |
+
accelerate launch --mixed_precision=bf16 src/wavtts/train/train.py \
|
| 61 |
+
--config-name WavTTS.yaml \
|
| 62 |
+
++datasets.batch_size_per_gpu=19200
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
### B. Fine-Tuning
|
| 66 |
+
For community best practices on fine-tuning, please refer to the [Finetuning Discussion Board (#57)](https://github.com/SWivid/F5-TTS/discussions/57).
|
| 67 |
+
|
| 68 |
+
The `use_ema = True` might be harmful for early-stage fine-tuned checkpoints. Because the model undergoes very few updates initially, the EMA weights remain heavily dominated by the pre-trained weights, masking your fine-tuning progress. Try turning it off by setting `load_model(..., use_ema=False)` during inference to see if it yields better results.
|
| 69 |
+
|
| 70 |
+
*(Optional: If you use TensorBoard for logging, ensure it is installed via `pip install tensorboard`.)*
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
## 3. Logging with Weights & Biases (W&B)
|
| 74 |
+
|
| 75 |
+
By default, the training script does **not** log metrics to W&B unless you are authenticated. A local `wandb/` directory will be created in the path where you run the training script.
|
| 76 |
+
|
| 77 |
+
To enable W&B logging, choose one of the following methods:
|
| 78 |
+
|
| 79 |
+
**Method 1: Interactive Login**
|
| 80 |
+
Log in via the CLI (Learn more [here](https://docs.wandb.ai/ref/cli/wandb-login)):
|
| 81 |
+
```bash
|
| 82 |
+
wandb login
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
**Method 2: Environment Variable**
|
| 86 |
+
Get your API key from [https://wandb.ai/authorize](https://wandb.ai/authorize) and export it:
|
| 87 |
+
```bash
|
| 88 |
+
export WANDB_API_KEY="<YOUR_WANDB_API_KEY>"
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
**Method 3: Offline Mode**
|
| 92 |
+
If your training server lacks internet access and you want to log metrics locally for later syncing:
|
| 93 |
+
```bash
|
| 94 |
+
export WANDB_MODE=offline
|
| 95 |
+
```
|
src/wavtts/train/datasets/prepare_csv_wavs.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import concurrent.futures
|
| 2 |
+
import multiprocessing
|
| 3 |
+
import os
|
| 4 |
+
import shutil
|
| 5 |
+
import signal
|
| 6 |
+
import subprocess # For invoking ffprobe
|
| 7 |
+
import sys
|
| 8 |
+
from contextlib import contextmanager
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
sys.path.append(os.getcwd())
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import csv
|
| 15 |
+
import json
|
| 16 |
+
from importlib.resources import files
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import torchaudio
|
| 20 |
+
from datasets.arrow_writer import ArrowWriter
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
|
| 23 |
+
from wavtts.model.utils import convert_char_to_pinyin
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
PRETRAINED_VOCAB_PATH = files("wavtts").joinpath("../../data/Emilia_ZH_EN_pinyin/vocab.txt")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def is_csv_wavs_format(input_dataset_dir):
|
| 30 |
+
fpath = Path(input_dataset_dir)
|
| 31 |
+
metadata = fpath / "metadata.csv"
|
| 32 |
+
wavs = fpath / "wavs"
|
| 33 |
+
return metadata.exists() and metadata.is_file() and wavs.exists() and wavs.is_dir()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Configuration constants
|
| 37 |
+
BATCH_SIZE = 100 # Batch size for text conversion
|
| 38 |
+
MAX_WORKERS = max(1, multiprocessing.cpu_count() - 1) # Leave one CPU free
|
| 39 |
+
THREAD_NAME_PREFIX = "AudioProcessor"
|
| 40 |
+
CHUNK_SIZE = 100 # Number of files to process per worker batch
|
| 41 |
+
|
| 42 |
+
executor = None # Global executor for cleanup
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@contextmanager
|
| 46 |
+
def graceful_exit():
|
| 47 |
+
"""Context manager for graceful shutdown on signals"""
|
| 48 |
+
|
| 49 |
+
def signal_handler(signum, frame):
|
| 50 |
+
print("\nReceived signal to terminate. Cleaning up...")
|
| 51 |
+
if executor is not None:
|
| 52 |
+
print("Shutting down executor...")
|
| 53 |
+
executor.shutdown(wait=False, cancel_futures=True)
|
| 54 |
+
sys.exit(1)
|
| 55 |
+
|
| 56 |
+
# Set up signal handlers
|
| 57 |
+
signal.signal(signal.SIGINT, signal_handler)
|
| 58 |
+
signal.signal(signal.SIGTERM, signal_handler)
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
yield
|
| 62 |
+
finally:
|
| 63 |
+
if executor is not None:
|
| 64 |
+
executor.shutdown(wait=False)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def process_audio_file(audio_path, text, polyphone):
|
| 68 |
+
"""Process a single audio file by checking its existence and extracting duration."""
|
| 69 |
+
if not Path(audio_path).exists():
|
| 70 |
+
print(f"audio {audio_path} not found, skipping")
|
| 71 |
+
return None
|
| 72 |
+
try:
|
| 73 |
+
audio_duration = get_audio_duration(audio_path)
|
| 74 |
+
if audio_duration <= 0:
|
| 75 |
+
raise ValueError(f"Duration {audio_duration} is non-positive.")
|
| 76 |
+
return (audio_path, text, audio_duration)
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f"Warning: Failed to process {audio_path} due to error: {e}. Skipping corrupt file.")
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def batch_convert_texts(texts, polyphone, batch_size=BATCH_SIZE):
|
| 83 |
+
"""Convert a list of texts to pinyin in batches."""
|
| 84 |
+
converted_texts = []
|
| 85 |
+
for i in range(0, len(texts), batch_size):
|
| 86 |
+
batch = texts[i : i + batch_size]
|
| 87 |
+
converted_batch = convert_char_to_pinyin(batch, polyphone=polyphone)
|
| 88 |
+
converted_texts.extend(converted_batch)
|
| 89 |
+
return converted_texts
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def prepare_csv_wavs_dir(input_dir, num_workers=None):
|
| 93 |
+
global executor
|
| 94 |
+
assert is_csv_wavs_format(input_dir), f"not csv_wavs format: {input_dir}"
|
| 95 |
+
input_dir = Path(input_dir)
|
| 96 |
+
metadata_path = input_dir / "metadata.csv"
|
| 97 |
+
audio_path_text_pairs = read_audio_text_pairs(metadata_path.as_posix())
|
| 98 |
+
|
| 99 |
+
polyphone = True
|
| 100 |
+
total_files = len(audio_path_text_pairs)
|
| 101 |
+
|
| 102 |
+
# Use provided worker count or calculate optimal number
|
| 103 |
+
worker_count = num_workers if num_workers is not None else min(MAX_WORKERS, total_files)
|
| 104 |
+
print(f"\nProcessing {total_files} audio files using {worker_count} workers...")
|
| 105 |
+
|
| 106 |
+
with graceful_exit():
|
| 107 |
+
# Initialize thread pool with optimized settings
|
| 108 |
+
with concurrent.futures.ThreadPoolExecutor(
|
| 109 |
+
max_workers=worker_count, thread_name_prefix=THREAD_NAME_PREFIX
|
| 110 |
+
) as exec:
|
| 111 |
+
executor = exec
|
| 112 |
+
results = []
|
| 113 |
+
|
| 114 |
+
# Process files in chunks for better efficiency
|
| 115 |
+
for i in range(0, len(audio_path_text_pairs), CHUNK_SIZE):
|
| 116 |
+
chunk = audio_path_text_pairs[i : i + CHUNK_SIZE]
|
| 117 |
+
# Submit futures in order
|
| 118 |
+
chunk_futures = [executor.submit(process_audio_file, pair[0], pair[1], polyphone) for pair in chunk]
|
| 119 |
+
|
| 120 |
+
# Iterate over futures in the original submission order to preserve ordering
|
| 121 |
+
for future in tqdm(
|
| 122 |
+
chunk_futures,
|
| 123 |
+
total=len(chunk),
|
| 124 |
+
desc=f"Processing chunk {i // CHUNK_SIZE + 1}/{(total_files + CHUNK_SIZE - 1) // CHUNK_SIZE}",
|
| 125 |
+
):
|
| 126 |
+
try:
|
| 127 |
+
result = future.result()
|
| 128 |
+
if result is not None:
|
| 129 |
+
results.append(result)
|
| 130 |
+
except Exception as e:
|
| 131 |
+
print(f"Error processing file: {e}")
|
| 132 |
+
|
| 133 |
+
executor = None
|
| 134 |
+
|
| 135 |
+
# Filter out failed results
|
| 136 |
+
processed = [res for res in results if res is not None]
|
| 137 |
+
if not processed:
|
| 138 |
+
raise RuntimeError("No valid audio files were processed!")
|
| 139 |
+
|
| 140 |
+
# Batch process text conversion
|
| 141 |
+
raw_texts = [item[1] for item in processed]
|
| 142 |
+
converted_texts = batch_convert_texts(raw_texts, polyphone, batch_size=BATCH_SIZE)
|
| 143 |
+
|
| 144 |
+
# Prepare final results
|
| 145 |
+
sub_result = []
|
| 146 |
+
durations = []
|
| 147 |
+
vocab_set = set()
|
| 148 |
+
|
| 149 |
+
for (audio_path, _, duration), conv_text in zip(processed, converted_texts):
|
| 150 |
+
sub_result.append({"audio_path": audio_path, "text": conv_text, "duration": duration})
|
| 151 |
+
durations.append(duration)
|
| 152 |
+
vocab_set.update(list(conv_text))
|
| 153 |
+
|
| 154 |
+
return sub_result, durations, vocab_set
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def get_audio_duration(audio_path, timeout=5):
|
| 158 |
+
"""
|
| 159 |
+
Get the duration of an audio file in seconds using ffmpeg's ffprobe.
|
| 160 |
+
Falls back to torchaudio.load() if ffprobe fails.
|
| 161 |
+
"""
|
| 162 |
+
try:
|
| 163 |
+
cmd = [
|
| 164 |
+
"ffprobe",
|
| 165 |
+
"-v",
|
| 166 |
+
"error",
|
| 167 |
+
"-show_entries",
|
| 168 |
+
"format=duration",
|
| 169 |
+
"-of",
|
| 170 |
+
"default=noprint_wrappers=1:nokey=1",
|
| 171 |
+
audio_path,
|
| 172 |
+
]
|
| 173 |
+
result = subprocess.run(
|
| 174 |
+
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True, timeout=timeout
|
| 175 |
+
)
|
| 176 |
+
duration_str = result.stdout.strip()
|
| 177 |
+
if duration_str:
|
| 178 |
+
return float(duration_str)
|
| 179 |
+
raise ValueError("Empty duration string from ffprobe.")
|
| 180 |
+
except (subprocess.TimeoutExpired, subprocess.SubprocessError, ValueError) as e:
|
| 181 |
+
print(f"Warning: ffprobe failed for {audio_path} with error: {e}. Falling back to torchaudio.")
|
| 182 |
+
try:
|
| 183 |
+
audio, sample_rate = torchaudio.load(audio_path)
|
| 184 |
+
return audio.shape[1] / sample_rate
|
| 185 |
+
except Exception as e:
|
| 186 |
+
raise RuntimeError(f"Both ffprobe and torchaudio failed for {audio_path}: {e}")
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def read_audio_text_pairs(csv_file_path):
|
| 190 |
+
audio_text_pairs = []
|
| 191 |
+
|
| 192 |
+
parent = Path(csv_file_path).parent
|
| 193 |
+
with open(csv_file_path, mode="r", newline="", encoding="utf-8-sig") as csvfile:
|
| 194 |
+
reader = csv.reader(csvfile, delimiter="|")
|
| 195 |
+
next(reader) # Skip the header row
|
| 196 |
+
for row in reader:
|
| 197 |
+
if len(row) >= 2:
|
| 198 |
+
audio_file = row[0].strip() # First column: audio file path
|
| 199 |
+
text = row[1].strip() # Second column: text
|
| 200 |
+
audio_file_path = parent / audio_file
|
| 201 |
+
audio_text_pairs.append((audio_file_path.as_posix(), text))
|
| 202 |
+
|
| 203 |
+
return audio_text_pairs
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def save_prepped_dataset(out_dir, result, duration_list, text_vocab_set, is_finetune):
|
| 207 |
+
out_dir = Path(out_dir)
|
| 208 |
+
out_dir.mkdir(exist_ok=True, parents=True)
|
| 209 |
+
print(f"\nSaving to {out_dir} ...")
|
| 210 |
+
|
| 211 |
+
raw_arrow_path = out_dir / "raw.arrow"
|
| 212 |
+
with ArrowWriter(path=raw_arrow_path.as_posix()) as writer:
|
| 213 |
+
for line in tqdm(result, desc="Writing to raw.arrow ..."):
|
| 214 |
+
writer.write(line)
|
| 215 |
+
writer.finalize()
|
| 216 |
+
|
| 217 |
+
# Save durations to JSON
|
| 218 |
+
dur_json_path = out_dir / "duration.json"
|
| 219 |
+
with open(dur_json_path.as_posix(), "w", encoding="utf-8") as f:
|
| 220 |
+
json.dump({"duration": duration_list}, f, ensure_ascii=False)
|
| 221 |
+
|
| 222 |
+
# Handle vocab file - write only once based on finetune flag
|
| 223 |
+
voca_out_path = out_dir / "vocab.txt"
|
| 224 |
+
if is_finetune:
|
| 225 |
+
file_vocab_finetune = PRETRAINED_VOCAB_PATH.as_posix()
|
| 226 |
+
shutil.copy2(file_vocab_finetune, voca_out_path)
|
| 227 |
+
else:
|
| 228 |
+
with open(voca_out_path.as_posix(), "w") as f:
|
| 229 |
+
for vocab in sorted(text_vocab_set):
|
| 230 |
+
f.write(vocab + "\n")
|
| 231 |
+
|
| 232 |
+
dataset_name = out_dir.stem
|
| 233 |
+
print(f"\nFor {dataset_name}, sample count: {len(result)}")
|
| 234 |
+
print(f"For {dataset_name}, vocab size is: {len(text_vocab_set)}")
|
| 235 |
+
print(f"For {dataset_name}, total {sum(duration_list) / 3600:.2f} hours")
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def prepare_and_save_set(inp_dir, out_dir, is_finetune: bool = True, num_workers: int = None):
|
| 239 |
+
if is_finetune:
|
| 240 |
+
assert PRETRAINED_VOCAB_PATH.exists(), f"pretrained vocab.txt not found: {PRETRAINED_VOCAB_PATH}"
|
| 241 |
+
sub_result, durations, vocab_set = prepare_csv_wavs_dir(inp_dir, num_workers=num_workers)
|
| 242 |
+
save_prepped_dataset(out_dir, sub_result, durations, vocab_set, is_finetune)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def cli():
|
| 246 |
+
try:
|
| 247 |
+
# Before processing, check if ffprobe is available.
|
| 248 |
+
if shutil.which("ffprobe") is None:
|
| 249 |
+
print(
|
| 250 |
+
"Warning: ffprobe is not available. Duration extraction will rely on torchaudio (which may be slower)."
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# Usage examples in help text
|
| 254 |
+
parser = argparse.ArgumentParser(
|
| 255 |
+
description="Prepare and save dataset.",
|
| 256 |
+
epilog="""
|
| 257 |
+
Examples:
|
| 258 |
+
# For fine-tuning (default):
|
| 259 |
+
python prepare_csv_wavs.py /input/dataset/path /output/dataset/path
|
| 260 |
+
|
| 261 |
+
# For pre-training:
|
| 262 |
+
python prepare_csv_wavs.py /input/dataset/path /output/dataset/path --pretrain
|
| 263 |
+
|
| 264 |
+
# With custom worker count:
|
| 265 |
+
python prepare_csv_wavs.py /input/dataset/path /output/dataset/path --workers 4
|
| 266 |
+
""",
|
| 267 |
+
)
|
| 268 |
+
parser.add_argument("inp_dir", type=str, help="Input directory containing the data.")
|
| 269 |
+
parser.add_argument("out_dir", type=str, help="Output directory to save the prepared data.")
|
| 270 |
+
parser.add_argument("--pretrain", action="store_true", help="Enable for new pretrain, otherwise is a fine-tune")
|
| 271 |
+
parser.add_argument("--workers", type=int, help=f"Number of worker threads (default: {MAX_WORKERS})")
|
| 272 |
+
args = parser.parse_args()
|
| 273 |
+
|
| 274 |
+
prepare_and_save_set(args.inp_dir, args.out_dir, is_finetune=not args.pretrain, num_workers=args.workers)
|
| 275 |
+
except KeyboardInterrupt:
|
| 276 |
+
print("\nOperation cancelled by user. Cleaning up...")
|
| 277 |
+
if executor is not None:
|
| 278 |
+
executor.shutdown(wait=False, cancel_futures=True)
|
| 279 |
+
sys.exit(1)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
if __name__ == "__main__":
|
| 283 |
+
cli()
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Emilia Dataset: https://huggingface.co/datasets/amphion/Emilia-Dataset/tree/fc71e07
|
| 2 |
+
# if use updated new version, i.e. WebDataset, feel free to modify / draft your own script
|
| 3 |
+
|
| 4 |
+
# generate audio text map for Emilia ZH & EN
|
| 5 |
+
# evaluate for vocab size
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
sys.path.append(os.getcwd())
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 15 |
+
from importlib.resources import files
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
from datasets.arrow_writer import ArrowWriter
|
| 19 |
+
from tqdm import tqdm
|
| 20 |
+
|
| 21 |
+
from wavtts.model.utils import convert_char_to_pinyin, repetition_found
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
out_zh = {
|
| 25 |
+
"ZH_B00041_S06226",
|
| 26 |
+
"ZH_B00042_S09204",
|
| 27 |
+
"ZH_B00065_S09430",
|
| 28 |
+
"ZH_B00065_S09431",
|
| 29 |
+
"ZH_B00066_S09327",
|
| 30 |
+
"ZH_B00066_S09328",
|
| 31 |
+
}
|
| 32 |
+
zh_filters = ["い", "て"]
|
| 33 |
+
# seems synthesized audios, or heavily code-switched
|
| 34 |
+
out_en = {
|
| 35 |
+
"EN_B00013_S00913",
|
| 36 |
+
"EN_B00042_S00120",
|
| 37 |
+
"EN_B00055_S04111",
|
| 38 |
+
"EN_B00061_S00693",
|
| 39 |
+
"EN_B00061_S01494",
|
| 40 |
+
"EN_B00061_S03375",
|
| 41 |
+
"EN_B00059_S00092",
|
| 42 |
+
"EN_B00111_S04300",
|
| 43 |
+
"EN_B00100_S03759",
|
| 44 |
+
"EN_B00087_S03811",
|
| 45 |
+
"EN_B00059_S00950",
|
| 46 |
+
"EN_B00089_S00946",
|
| 47 |
+
"EN_B00078_S05127",
|
| 48 |
+
"EN_B00070_S04089",
|
| 49 |
+
"EN_B00074_S09659",
|
| 50 |
+
"EN_B00061_S06983",
|
| 51 |
+
"EN_B00061_S07060",
|
| 52 |
+
"EN_B00059_S08397",
|
| 53 |
+
"EN_B00082_S06192",
|
| 54 |
+
"EN_B00091_S01238",
|
| 55 |
+
"EN_B00089_S07349",
|
| 56 |
+
"EN_B00070_S04343",
|
| 57 |
+
"EN_B00061_S02400",
|
| 58 |
+
"EN_B00076_S01262",
|
| 59 |
+
"EN_B00068_S06467",
|
| 60 |
+
"EN_B00076_S02943",
|
| 61 |
+
"EN_B00064_S05954",
|
| 62 |
+
"EN_B00061_S05386",
|
| 63 |
+
"EN_B00066_S06544",
|
| 64 |
+
"EN_B00076_S06944",
|
| 65 |
+
"EN_B00072_S08620",
|
| 66 |
+
"EN_B00076_S07135",
|
| 67 |
+
"EN_B00076_S09127",
|
| 68 |
+
"EN_B00065_S00497",
|
| 69 |
+
"EN_B00059_S06227",
|
| 70 |
+
"EN_B00063_S02859",
|
| 71 |
+
"EN_B00075_S01547",
|
| 72 |
+
"EN_B00061_S08286",
|
| 73 |
+
"EN_B00079_S02901",
|
| 74 |
+
"EN_B00092_S03643",
|
| 75 |
+
"EN_B00096_S08653",
|
| 76 |
+
"EN_B00063_S04297",
|
| 77 |
+
"EN_B00063_S04614",
|
| 78 |
+
"EN_B00079_S04698",
|
| 79 |
+
"EN_B00104_S01666",
|
| 80 |
+
"EN_B00061_S09504",
|
| 81 |
+
"EN_B00061_S09694",
|
| 82 |
+
"EN_B00065_S05444",
|
| 83 |
+
"EN_B00063_S06860",
|
| 84 |
+
"EN_B00065_S05725",
|
| 85 |
+
"EN_B00069_S07628",
|
| 86 |
+
"EN_B00083_S03875",
|
| 87 |
+
"EN_B00071_S07665",
|
| 88 |
+
"EN_B00071_S07665",
|
| 89 |
+
"EN_B00062_S04187",
|
| 90 |
+
"EN_B00065_S09873",
|
| 91 |
+
"EN_B00065_S09922",
|
| 92 |
+
"EN_B00084_S02463",
|
| 93 |
+
"EN_B00067_S05066",
|
| 94 |
+
"EN_B00106_S08060",
|
| 95 |
+
"EN_B00073_S06399",
|
| 96 |
+
"EN_B00073_S09236",
|
| 97 |
+
"EN_B00087_S00432",
|
| 98 |
+
"EN_B00085_S05618",
|
| 99 |
+
"EN_B00064_S01262",
|
| 100 |
+
"EN_B00072_S01739",
|
| 101 |
+
"EN_B00059_S03913",
|
| 102 |
+
"EN_B00069_S04036",
|
| 103 |
+
"EN_B00067_S05623",
|
| 104 |
+
"EN_B00060_S05389",
|
| 105 |
+
"EN_B00060_S07290",
|
| 106 |
+
"EN_B00062_S08995",
|
| 107 |
+
}
|
| 108 |
+
en_filters = ["ا", "い", "て"]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _iter_metadata_objs(audio_dir: Path):
|
| 112 |
+
"""
|
| 113 |
+
Support both Emilia legacy layout (one shard-level .jsonl) and
|
| 114 |
+
per-utterance json layout (many *.json under each shard directory).
|
| 115 |
+
"""
|
| 116 |
+
audio_jsonl = audio_dir.with_suffix(".jsonl")
|
| 117 |
+
if audio_jsonl.exists():
|
| 118 |
+
with open(audio_jsonl, "r", encoding="utf-8") as f:
|
| 119 |
+
for line in f:
|
| 120 |
+
line = line.strip()
|
| 121 |
+
if line:
|
| 122 |
+
yield json.loads(line)
|
| 123 |
+
return
|
| 124 |
+
|
| 125 |
+
for meta_json in sorted(audio_dir.glob("*.json")):
|
| 126 |
+
with open(meta_json, "r", encoding="utf-8") as f:
|
| 127 |
+
yield json.load(f)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _resolve_audio_path(audio_dir: Path, wav_rel: str) -> Path:
|
| 131 |
+
wav_rel_path = Path(wav_rel)
|
| 132 |
+
candidates = [
|
| 133 |
+
audio_dir.parent / wav_rel_path, # legacy: lang_root / obj["wav"]
|
| 134 |
+
audio_dir / wav_rel_path, # shard / relative/path
|
| 135 |
+
audio_dir / wav_rel_path.name, # shard / basename (your current layout)
|
| 136 |
+
]
|
| 137 |
+
for p in candidates:
|
| 138 |
+
if p.exists():
|
| 139 |
+
return p
|
| 140 |
+
return candidates[-1]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def deal_with_audio_dir(audio_dir):
|
| 144 |
+
sub_result, durations = [], []
|
| 145 |
+
vocab_set = set()
|
| 146 |
+
bad_case_zh = 0
|
| 147 |
+
bad_case_en = 0
|
| 148 |
+
for obj in tqdm(_iter_metadata_objs(audio_dir), desc=f"{audio_dir.name}"):
|
| 149 |
+
text = obj["text"]
|
| 150 |
+
if obj["language"] == "zh":
|
| 151 |
+
if obj["wav"].split("/")[1] in out_zh or any(f in text for f in zh_filters) or repetition_found(text):
|
| 152 |
+
bad_case_zh += 1
|
| 153 |
+
continue
|
| 154 |
+
else:
|
| 155 |
+
text = text.translate(
|
| 156 |
+
str.maketrans({",": ",", "!": "!", "?": "?"})
|
| 157 |
+
) # not "。" cuz much code-switched
|
| 158 |
+
if obj["language"] == "en":
|
| 159 |
+
if (
|
| 160 |
+
obj["wav"].split("/")[1] in out_en
|
| 161 |
+
or any(f in text for f in en_filters)
|
| 162 |
+
or repetition_found(text, length=4)
|
| 163 |
+
):
|
| 164 |
+
bad_case_en += 1
|
| 165 |
+
continue
|
| 166 |
+
if tokenizer == "pinyin":
|
| 167 |
+
text = convert_char_to_pinyin([text], polyphone=polyphone)[0]
|
| 168 |
+
duration = obj["duration"]
|
| 169 |
+
audio_path = _resolve_audio_path(audio_dir, obj["wav"])
|
| 170 |
+
sub_result.append({"audio_path": str(audio_path), "text": text, "duration": duration})
|
| 171 |
+
durations.append(duration)
|
| 172 |
+
vocab_set.update(list(text))
|
| 173 |
+
return sub_result, durations, vocab_set, bad_case_zh, bad_case_en
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def main():
|
| 177 |
+
assert tokenizer in ["pinyin", "char"]
|
| 178 |
+
result = []
|
| 179 |
+
duration_list = []
|
| 180 |
+
text_vocab_set = set()
|
| 181 |
+
total_bad_case_zh = 0
|
| 182 |
+
total_bad_case_en = 0
|
| 183 |
+
|
| 184 |
+
# process raw data
|
| 185 |
+
executor = ProcessPoolExecutor(max_workers=max_workers)
|
| 186 |
+
futures = []
|
| 187 |
+
for lang in langs:
|
| 188 |
+
dataset_path = Path(os.path.join(dataset_dir, lang))
|
| 189 |
+
[
|
| 190 |
+
futures.append(executor.submit(deal_with_audio_dir, audio_dir))
|
| 191 |
+
for audio_dir in dataset_path.iterdir()
|
| 192 |
+
if audio_dir.is_dir()
|
| 193 |
+
]
|
| 194 |
+
for futures in tqdm(futures, total=len(futures)):
|
| 195 |
+
sub_result, durations, vocab_set, bad_case_zh, bad_case_en = futures.result()
|
| 196 |
+
result.extend(sub_result)
|
| 197 |
+
duration_list.extend(durations)
|
| 198 |
+
text_vocab_set.update(vocab_set)
|
| 199 |
+
total_bad_case_zh += bad_case_zh
|
| 200 |
+
total_bad_case_en += bad_case_en
|
| 201 |
+
executor.shutdown()
|
| 202 |
+
|
| 203 |
+
# save preprocessed dataset to disk
|
| 204 |
+
if not os.path.exists(f"{save_dir}"):
|
| 205 |
+
os.makedirs(f"{save_dir}")
|
| 206 |
+
print(f"\nSaving to {save_dir} ...")
|
| 207 |
+
|
| 208 |
+
# dataset = Dataset.from_dict({"audio_path": audio_path_list, "text": text_list, "duration": duration_list}) # oom
|
| 209 |
+
# dataset.save_to_disk(f"{save_dir}/raw", max_shard_size="2GB")
|
| 210 |
+
with ArrowWriter(path=f"{save_dir}/raw.arrow") as writer:
|
| 211 |
+
for line in tqdm(result, desc="Writing to raw.arrow ..."):
|
| 212 |
+
writer.write(line)
|
| 213 |
+
writer.finalize()
|
| 214 |
+
|
| 215 |
+
# dup a json separately saving duration in case for DynamicBatchSampler ease
|
| 216 |
+
with open(f"{save_dir}/duration.json", "w", encoding="utf-8") as f:
|
| 217 |
+
json.dump({"duration": duration_list}, f, ensure_ascii=False)
|
| 218 |
+
|
| 219 |
+
# vocab map, i.e. tokenizer
|
| 220 |
+
# add alphabets and symbols (optional, if plan to ft on de/fr etc.)
|
| 221 |
+
# if tokenizer == "pinyin":
|
| 222 |
+
# text_vocab_set.update([chr(i) for i in range(32, 127)] + [chr(i) for i in range(192, 256)])
|
| 223 |
+
with open(f"{save_dir}/vocab.txt", "w") as f:
|
| 224 |
+
for vocab in sorted(text_vocab_set):
|
| 225 |
+
f.write(vocab + "\n")
|
| 226 |
+
|
| 227 |
+
print(f"\nFor {dataset_name}, sample count: {len(result)}")
|
| 228 |
+
print(f"For {dataset_name}, vocab size is: {len(text_vocab_set)}")
|
| 229 |
+
print(f"For {dataset_name}, total {sum(duration_list) / 3600:.2f} hours")
|
| 230 |
+
if "ZH" in langs:
|
| 231 |
+
print(f"Bad zh transcription case: {total_bad_case_zh}")
|
| 232 |
+
if "EN" in langs:
|
| 233 |
+
print(f"Bad en transcription case: {total_bad_case_en}\n")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
if __name__ == "__main__":
|
| 237 |
+
max_workers = 32
|
| 238 |
+
|
| 239 |
+
tokenizer = "pinyin" # "pinyin" | "char"
|
| 240 |
+
polyphone = True
|
| 241 |
+
|
| 242 |
+
langs = ["ZH", "EN"]
|
| 243 |
+
dataset_dir = "/path/to/emilia"
|
| 244 |
+
dataset_name = f"Emilia_{'_'.join(langs)}_{tokenizer}"
|
| 245 |
+
save_dir = str(files("wavtts").joinpath("../../")) + f"/data/{dataset_name}"
|
| 246 |
+
print(f"\nPrepare for {dataset_name}, will save to {save_dir}\n")
|
| 247 |
+
|
| 248 |
+
main()
|
| 249 |
+
|
| 250 |
+
# Emilia ZH & EN
|
| 251 |
+
# samples count 37837916 (after removal)
|
| 252 |
+
# pinyin vocab size 2543 (polyphone)
|
| 253 |
+
# total duration 95281.87 (hours)
|
| 254 |
+
# bad zh asr cnt 230435 (samples)
|
| 255 |
+
# bad eh asr cnt 37217 (samples)
|
| 256 |
+
|
| 257 |
+
# vocab size may be slightly different due to rjieba tokenizer and pypinyin (e.g. way of polyphoneme)
|
| 258 |
+
# please be careful if using pretrained model, make sure the vocab.txt is same
|
| 259 |
+
|
| 260 |
+
# python src/wavtts/train/datasets/prepare_emilia.py
|
src/wavtts/train/datasets/prepare_emilia_v2.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# put in src/wavtts/train/datasets/prepare_emilia_v2.py
|
| 2 |
+
# prepares Emilia dataset with the new format w/ Emilia-YODAS
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 7 |
+
from importlib.resources import files
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from datasets.arrow_writer import ArrowWriter
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
from wavtts.model.utils import repetition_found
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Define filters for exclusion
|
| 17 |
+
out_en = set()
|
| 18 |
+
en_filters = ["ا", "い", "て"]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def process_audio_directory(audio_dir):
|
| 22 |
+
sub_result, durations, vocab_set = [], [], set()
|
| 23 |
+
bad_case_en = 0
|
| 24 |
+
|
| 25 |
+
for file in audio_dir.iterdir():
|
| 26 |
+
if file.suffix == ".json":
|
| 27 |
+
with open(file, "r") as f:
|
| 28 |
+
obj = json.load(f)
|
| 29 |
+
text = obj["text"]
|
| 30 |
+
if any(f in text for f in en_filters) or repetition_found(text, length=4):
|
| 31 |
+
bad_case_en += 1
|
| 32 |
+
continue
|
| 33 |
+
|
| 34 |
+
duration = obj["duration"]
|
| 35 |
+
audio_file = file.with_suffix(".mp3")
|
| 36 |
+
if audio_file.exists():
|
| 37 |
+
sub_result.append({"audio_path": str(audio_file), "text": text, "duration": duration})
|
| 38 |
+
durations.append(duration)
|
| 39 |
+
vocab_set.update(list(text))
|
| 40 |
+
|
| 41 |
+
return sub_result, durations, vocab_set, bad_case_en
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def main():
|
| 45 |
+
assert tokenizer in ["pinyin", "char"]
|
| 46 |
+
result, duration_list, text_vocab_set = [], [], set()
|
| 47 |
+
total_bad_case_en = 0
|
| 48 |
+
|
| 49 |
+
executor = ProcessPoolExecutor(max_workers=max_workers)
|
| 50 |
+
futures = []
|
| 51 |
+
dataset_path = Path(dataset_dir)
|
| 52 |
+
for sub_dir in dataset_path.iterdir():
|
| 53 |
+
if sub_dir.is_dir():
|
| 54 |
+
futures.append(executor.submit(process_audio_directory, sub_dir))
|
| 55 |
+
|
| 56 |
+
for future in tqdm(futures, total=len(futures)):
|
| 57 |
+
sub_result, durations, vocab_set, bad_case_en = future.result()
|
| 58 |
+
result.extend(sub_result)
|
| 59 |
+
duration_list.extend(durations)
|
| 60 |
+
text_vocab_set.update(vocab_set)
|
| 61 |
+
total_bad_case_en += bad_case_en
|
| 62 |
+
|
| 63 |
+
executor.shutdown()
|
| 64 |
+
|
| 65 |
+
if not os.path.exists(f"{save_dir}"):
|
| 66 |
+
os.makedirs(f"{save_dir}")
|
| 67 |
+
|
| 68 |
+
with ArrowWriter(path=f"{save_dir}/raw.arrow") as writer:
|
| 69 |
+
for line in tqdm(result, desc="Writing to raw.arrow ..."):
|
| 70 |
+
writer.write(line)
|
| 71 |
+
writer.finalize()
|
| 72 |
+
|
| 73 |
+
with open(f"{save_dir}/duration.json", "w", encoding="utf-8") as f:
|
| 74 |
+
json.dump({"duration": duration_list}, f, ensure_ascii=False)
|
| 75 |
+
|
| 76 |
+
with open(f"{save_dir}/vocab.txt", "w") as f:
|
| 77 |
+
for vocab in sorted(text_vocab_set):
|
| 78 |
+
f.write(vocab + "\n")
|
| 79 |
+
|
| 80 |
+
print(f"For {dataset_name}, sample count: {len(result)}")
|
| 81 |
+
print(f"For {dataset_name}, vocab size is: {len(text_vocab_set)}")
|
| 82 |
+
print(f"For {dataset_name}, total {sum(duration_list) / 3600:.2f} hours")
|
| 83 |
+
print(f"Bad en transcription case: {total_bad_case_en}\n")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
max_workers = 32
|
| 88 |
+
tokenizer = "char"
|
| 89 |
+
dataset_dir = "/path/to/Emilia-YODAS/EN"
|
| 90 |
+
dataset_name = f"Emilia_EN_{tokenizer}"
|
| 91 |
+
save_dir = str(files("wavtts").joinpath("../../")) + f"/data/{dataset_name}"
|
| 92 |
+
|
| 93 |
+
print(f"Prepare for {dataset_name}, will save to {save_dir}\n")
|
| 94 |
+
main()
|