Spaces:
Running
Running
Add seed-vc Python files without binary examples
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .dockerignore +25 -0
- seed-vc +0 -1
- seed-vc/.gitignore +28 -0
- seed-vc/EVAL.md +121 -0
- seed-vc/LICENSE +674 -0
- seed-vc/README-JA.md +227 -0
- seed-vc/README-ZH.md +213 -0
- seed-vc/README.md +288 -0
- seed-vc/app.py +261 -0
- seed-vc/app_svc.py +450 -0
- seed-vc/app_vc.py +399 -0
- seed-vc/app_vc_v2.py +99 -0
- seed-vc/conda-nix-vc-py310.yaml +25 -0
- seed-vc/configs/astral_quantization/default_2048.yml +40 -0
- seed-vc/configs/astral_quantization/default_32.yml +40 -0
- seed-vc/configs/config.json +1 -0
- seed-vc/configs/hifigan.yml +25 -0
- seed-vc/configs/presets/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml +98 -0
- seed-vc/configs/presets/config_dit_mel_seed_uvit_whisper_small_wavenet.yml +91 -0
- seed-vc/configs/presets/config_dit_mel_seed_uvit_xlsr_tiny.yml +82 -0
- seed-vc/configs/v2/vc_wrapper.yaml +105 -0
- seed-vc/data/ft_dataset.py +126 -0
- seed-vc/eval.py +556 -0
- seed-vc/hf_utils.py +12 -0
- seed-vc/inference.py +425 -0
- seed-vc/inference_v2.py +144 -0
- seed-vc/modules/astral_quantization/bsq.py +569 -0
- seed-vc/modules/astral_quantization/convnext.py +209 -0
- seed-vc/modules/astral_quantization/default_model.py +73 -0
- seed-vc/modules/astral_quantization/transformer.py +254 -0
- seed-vc/modules/audio.py +82 -0
- seed-vc/modules/bigvgan/activations.py +120 -0
- seed-vc/modules/bigvgan/alias_free_activation/cuda/__init__.py +0 -0
- seed-vc/modules/bigvgan/alias_free_activation/cuda/activation1d.py +77 -0
- seed-vc/modules/bigvgan/alias_free_activation/cuda/anti_alias_activation.cpp +23 -0
- seed-vc/modules/bigvgan/alias_free_activation/cuda/anti_alias_activation_cuda.cu +246 -0
- seed-vc/modules/bigvgan/alias_free_activation/cuda/compat.h +29 -0
- seed-vc/modules/bigvgan/alias_free_activation/cuda/load.py +86 -0
- seed-vc/modules/bigvgan/alias_free_activation/cuda/type_shim.h +92 -0
- seed-vc/modules/bigvgan/alias_free_activation/torch/__init__.py +6 -0
- seed-vc/modules/bigvgan/alias_free_activation/torch/act.py +30 -0
- seed-vc/modules/bigvgan/alias_free_activation/torch/filter.py +101 -0
- seed-vc/modules/bigvgan/alias_free_activation/torch/resample.py +58 -0
- seed-vc/modules/bigvgan/bigvgan.py +492 -0
- seed-vc/modules/bigvgan/config.json +63 -0
- seed-vc/modules/bigvgan/env.py +18 -0
- seed-vc/modules/bigvgan/meldataset.py +354 -0
- seed-vc/modules/bigvgan/utils.py +99 -0
- seed-vc/modules/campplus/DTDNN.py +138 -0
- seed-vc/modules/campplus/classifier.py +70 -0
.dockerignore
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Git files
|
| 2 |
+
.git
|
| 3 |
+
.gitignore
|
| 4 |
+
.gitattributes
|
| 5 |
+
.gitmodules
|
| 6 |
+
|
| 7 |
+
# Python cache
|
| 8 |
+
__pycache__/
|
| 9 |
+
*.py[cod]
|
| 10 |
+
*$py.class
|
| 11 |
+
*.so
|
| 12 |
+
|
| 13 |
+
# Seed-VC examples and assets (binary files)
|
| 14 |
+
seed-vc/examples/
|
| 15 |
+
seed-vc/assets/
|
| 16 |
+
seed-vc/baselines/
|
| 17 |
+
seed-vc/campplus_cn_common.bin
|
| 18 |
+
|
| 19 |
+
# Test and build files
|
| 20 |
+
*.wav
|
| 21 |
+
*.onnx
|
| 22 |
+
*.bin
|
| 23 |
+
*.webm
|
| 24 |
+
*.mp4
|
| 25 |
+
*.mp3
|
seed-vc
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
Subproject commit 51383efd921027683c89e5348211d93ff12ac2a8
|
|
|
|
|
|
seed-vc/.gitignore
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# general things to ignore
|
| 2 |
+
.DS_Store
|
| 3 |
+
build/
|
| 4 |
+
build_contrib/
|
| 5 |
+
dist/
|
| 6 |
+
.cache/
|
| 7 |
+
*.egg-info/
|
| 8 |
+
*.egg
|
| 9 |
+
*.py[cod]
|
| 10 |
+
__pycache__/
|
| 11 |
+
*.so
|
| 12 |
+
*~
|
| 13 |
+
|
| 14 |
+
# IDE
|
| 15 |
+
.vscode/
|
| 16 |
+
.idea/
|
| 17 |
+
|
| 18 |
+
# misc
|
| 19 |
+
checkpoints/
|
| 20 |
+
test_waves/
|
| 21 |
+
reconstructed/
|
| 22 |
+
.python-version
|
| 23 |
+
ruff.log
|
| 24 |
+
/configs/inuse/
|
| 25 |
+
runs/
|
| 26 |
+
/garbages/
|
| 27 |
+
/flagged/
|
| 28 |
+
/experimental/
|
seed-vc/EVAL.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### Zero-shot voice conversion🎙🔁
|
| 2 |
+
We have performed a series of objective evaluations on our Seed-VC's voice conversion capabilities.
|
| 3 |
+
For ease of reproduction, source audios are 100 random utterances from LibriTTS-test-clean, and reference audios are 12 randomly picked in-the-wild voices with unique characteristics. <br>
|
| 4 |
+
|
| 5 |
+
Source audios can be found under `./examples/libritts-test-clean` <br>
|
| 6 |
+
Reference audios can be found under `./examples/reference` <br>
|
| 7 |
+
|
| 8 |
+
We evaluate the conversion results in terms of speaker embedding cosine similarity (SECS), word error rate (WER) and character error rate (CER) and compared
|
| 9 |
+
our results with two strong open sourced baselines, namely [OpenVoice](https://github.com/myshell-ai/OpenVoice) and [CosyVoice](https://github.com/FunAudioLLM/CosyVoice).
|
| 10 |
+
Results in the table below shows that our Seed-VC model significantly outperforms the baseline models in both intelligibility and speaker similarity.<br>
|
| 11 |
+
|
| 12 |
+
| Models\Metrics | SECS↑ | WER↓ | CER↓ | SIG↑ | BAK↑ | OVRL↑ |
|
| 13 |
+
|----------------|------------|-----------|----------|----------|----------|----------|
|
| 14 |
+
| Ground Truth | 1.0000 | 8.02 | 1.57 | ~ | ~ | ~ |
|
| 15 |
+
| OpenVoice | 0.7547 | 15.46 | 4.73 | **3.56** | **4.02** | **3.27** |
|
| 16 |
+
| CosyVoice | 0.8440 | 18.98 | 7.29 | 3.51 | **4.02** | 3.21 |
|
| 17 |
+
| Seed-VC(Ours) | **0.8676** | **11.99** | **2.92** | 3.42 | 3.97 | 3.11 |
|
| 18 |
+
|
| 19 |
+
We have also compared with non-zero-shot voice conversion models for several speakers (based on model availability):
|
| 20 |
+
|
| 21 |
+
| Characters | Models\Metrics | SECS↑ | WER↓ | CER↓ | SIG↑ | BAK↑ | OVRL↑ |
|
| 22 |
+
|---------------------|----------------|------------|-----------|----------|----------|----------|----------|
|
| 23 |
+
| ~ | Ground Truth | 1.0000 | 6.43 | 1.00 | ~ | ~ | ~ |
|
| 24 |
+
| Tokai Teio | So-VITS-4.0 | 0.8637 | 21.46 | 9.63 | 3.06 | 3.66 | 2.68 |
|
| 25 |
+
| | Seed-VC(Ours) | **0.8899** | **15.32** | **4.66** | **3.12** | **3.71** | **2.72** |
|
| 26 |
+
| Milky Green | So-VITS-4.0 | 0.6850 | 48.43 | 32.50 | 3.34 | 3.51 | 2.82 |
|
| 27 |
+
| | Seed-VC(Ours) | **0.8072** | **7.26** | **1.32** | **3.48** | **4.07** | **3.20** |
|
| 28 |
+
| Matikane Tannhuaser | So-VITS-4.0 | 0.8594 | 16.25 | 8.64 | **3.25** | 3.71 | 2.84 |
|
| 29 |
+
| | Seed-VC(Ours) | **0.8768** | **12.62** | **5.86** | 3.18 | **3.83** | **2.85** |
|
| 30 |
+
|
| 31 |
+
Results show that, despite not being trained on the target speakers, Seed-VC is able to achieve significantly better results than the non-zero-shot models.
|
| 32 |
+
However, this may vary a lot depending on the SoVITS model quality. PR or Issue is welcomed if you find this comparison unfair or inaccurate.
|
| 33 |
+
(Tokai Teio model from [zomehwh/sovits-tannhauser](https://huggingface.co/spaces/zomehwh/sovits-tannhauser))
|
| 34 |
+
(Matikane Tannhuaser model from [zomehwh/sovits-tannhauser](https://huggingface.co/spaces/zomehwh/sovits-tannhauser))
|
| 35 |
+
(Milky Green model from [sparanoid/milky-green-sovits-4](https://huggingface.co/spaces/sparanoid/milky-green-sovits-4))
|
| 36 |
+
|
| 37 |
+
*English ASR result computed by [facebook/hubert-large-ls960-ft](https://huggingface.co/facebook/hubert-large-ls960-ft) model*
|
| 38 |
+
*Speaker embedding computed by [resemblyzer](https://github.com/resemble-ai/Resemblyzer) model* <br>
|
| 39 |
+
|
| 40 |
+
You can reproduce the evaluation by running `eval.py` script.
|
| 41 |
+
```bash
|
| 42 |
+
python eval.py
|
| 43 |
+
--source ./examples/libritts-test-clean
|
| 44 |
+
--target ./examples/reference
|
| 45 |
+
--output ./examples/eval/converted
|
| 46 |
+
--diffusion-steps 25
|
| 47 |
+
--length-adjust 1.0
|
| 48 |
+
--inference-cfg-rate 0.7
|
| 49 |
+
--xvector-extractor "resemblyzer"
|
| 50 |
+
--baseline "" # fill in openvoice or cosyvoice to compute baseline result
|
| 51 |
+
--max-samples 100 # max source utterances to go through
|
| 52 |
+
```
|
| 53 |
+
Before that, make sure you have openvoice and cosyvoice repo correctly installed on `../OpenVoice/` and `../CosyVoice/` if you would like to run baseline evaluation.
|
| 54 |
+
|
| 55 |
+
### Zero-shot singing voice conversion🎤🎶
|
| 56 |
+
|
| 57 |
+
Additional singing voice conversion evaluation is done on [M4Singer](https://github.com/M4Singer/M4Singer) dataset, with 4 target speakers whose audio data is available [here](https://huggingface.co/datasets/XzJosh/audiodataset).
|
| 58 |
+
Speaker similariy is calculated by averaging the cosine similarities between conversion result and all available samples in respective character dataset.
|
| 59 |
+
For each character, one random utterance is chosen as the prompt for zero-shot inference. For comparison, we trained respective [RVCv2-f0-48k](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI) model for each character as baseline.
|
| 60 |
+
100 random utterances for each singer type are used as source audio.
|
| 61 |
+
|
| 62 |
+
| Models\Metrics | F0CORR↑ | F0RMSE↓ | SECS↑ | CER↓ | SIG↑ | BAK↑ | OVRL↑ |
|
| 63 |
+
|----------------|---------|---------|------------|-----------|----------|----------|----------|
|
| 64 |
+
| RVCv2 | 0.9404 | 30.43 | 0.7264 | 28.46 | **3.41** | **4.05** | **3.12** |
|
| 65 |
+
| Seed-VC(Ours) | 0.9375 | 33.35 | **0.7405** | **19.70** | 3.39 | 3.96 | 3.06 |
|
| 66 |
+
|
| 67 |
+
<details>
|
| 68 |
+
<summary>Click to expand detailed evaluation results</summary>
|
| 69 |
+
|
| 70 |
+
| Source Singer Type | Characters | Models\Metrics | F0CORR↑ | F0RMSE↓ | SECS↑ | CER↓ | SIG↑ | BAK↑ | OVRL↑ |
|
| 71 |
+
|--------------------|--------------------|----------------|---------|---------|------------|-----------|------|------|----------|
|
| 72 |
+
| Alto (Female) | ~ | Ground Truth | 1.0000 | 0.00 | ~ | 8.16 | ~ | ~ | ~ |
|
| 73 |
+
| | Azuma (Female) | RVCv2 | 0.9617 | 33.03 | **0.7352** | 24.70 | 3.36 | 4.07 | 3.07 |
|
| 74 |
+
| | | Seed-VC(Ours) | 0.9658 | 31.64 | 0.7341 | **15.23** | 3.37 | 4.02 | 3.07 |
|
| 75 |
+
| | Diana (Female) | RVCv2 | 0.9626 | 32.56 | 0.7212 | 19.67 | 3.45 | 4.08 | **3.17** |
|
| 76 |
+
| | | Seed-VC(Ours) | 0.9648 | 31.94 | **0.7457** | **16.81** | 3.49 | 3.99 | 3.15 |
|
| 77 |
+
| | Ding Zhen (Male) | RVCv2 | 0.9013 | 26.72 | 0.7221 | 18.53 | 3.37 | 4.03 | 3.06 |
|
| 78 |
+
| | | Seed-VC(Ours) | 0.9356 | 21.87 | **0.7513** | **15.63** | 3.44 | 3.94 | **3.09** |
|
| 79 |
+
| | Kobe Bryant (Male) | RVCv2 | 0.9215 | 23.90 | 0.7495 | 37.23 | 3.49 | 4.06 | **3.21** |
|
| 80 |
+
| | | Seed-VC(Ours) | 0.9248 | 23.40 | **0.7602** | **26.98** | 3.43 | 4.02 | 3.13 |
|
| 81 |
+
| Bass (Male) | ~ | Ground Truth | 1.0000 | 0.00 | ~ | 8.62 | ~ | ~ | ~ |
|
| 82 |
+
| | Azuma | RVCv2 | 0.9288 | 32.62 | **0.7148** | 24.88 | 3.45 | 4.10 | **3.18** |
|
| 83 |
+
| | | Seed-VC(Ours) | 0.9383 | 31.57 | 0.6960 | **10.31** | 3.45 | 4.03 | 3.15 |
|
| 84 |
+
| | Diana | RVCv2 | 0.9403 | 30.00 | 0.7010 | 14.54 | 3.53 | 4.15 | **3.27** |
|
| 85 |
+
| | | Seed-VC(Ours) | 0.9428 | 30.06 | **0.7299** | **9.66** | 3.53 | 4.11 | 3.25 |
|
| 86 |
+
| | Ding Zhen | RVCv2 | 0.9061 | 19.53 | 0.6922 | 25.99 | 3.36 | 4.09 | **3.08** |
|
| 87 |
+
| | | Seed-VC(Ours) | 0.9169 | 18.15 | **0.7260** | **14.13** | 3.38 | 3.98 | 3.07 |
|
| 88 |
+
| | Kobe Bryant | RVCv2 | 0.9302 | 16.37 | 0.7717 | 41.04 | 3.51 | 4.13 | **3.25** |
|
| 89 |
+
| | | Seed-VC(Ours) | 0.9176 | 17.93 | **0.7798** | **24.23** | 3.42 | 4.08 | 3.17 |
|
| 90 |
+
| Soprano (Female) | ~ | Ground Truth | 1.0000 | 0.00 | ~ | 27.92 | ~ | ~ | ~ |
|
| 91 |
+
| | Azuma | RVCv2 | 0.9742 | 47.80 | 0.7104 | 38.70 | 3.14 | 3.85 | **2.83** |
|
| 92 |
+
| | | Seed-VC(Ours) | 0.9521 | 64.00 | **0.7177** | **33.10** | 3.15 | 3.86 | 2.81 |
|
| 93 |
+
| | Diana | RVCv2 | 0.9754 | 46.59 | **0.7319** | 32.36 | 3.14 | 3.85 | **2.83** |
|
| 94 |
+
| | | Seed-VC(Ours) | 0.9573 | 59.70 | 0.7317 | **30.57** | 3.11 | 3.78 | 2.74 |
|
| 95 |
+
| | Ding Zhen | RVCv2 | 0.9543 | 31.45 | 0.6792 | 40.80 | 3.41 | 4.08 | **3.14** |
|
| 96 |
+
| | | Seed-VC(Ours) | 0.9486 | 33.37 | **0.6979** | **34.45** | 3.41 | 3.97 | 3.10 |
|
| 97 |
+
| | Kobe Bryant | RVCv2 | 0.9691 | 25.50 | 0.6276 | 61.59 | 3.43 | 4.04 | **3.15** |
|
| 98 |
+
| | | Seed-VC(Ours) | 0.9496 | 32.76 | **0.6683** | **39.82** | 3.32 | 3.98 | 3.04 |
|
| 99 |
+
| Tenor (Male) | ~ | Ground Truth | 1.0000 | 0.00 | ~ | 5.94 | ~ | ~ | ~ |
|
| 100 |
+
| | Azuma | RVCv2 | 0.9333 | 42.09 | **0.7832** | 16.66 | 3.46 | 4.07 | **3.18** |
|
| 101 |
+
| | | Seed-VC(Ours) | 0.9162 | 48.06 | 0.7697 | **8.48** | 3.38 | 3.89 | 3.01 |
|
| 102 |
+
| | Diana | RVCv2 | 0.9467 | 36.65 | 0.7729 | 15.28 | 3.53 | 4.08 | **3.24** |
|
| 103 |
+
| | | Seed-VC(Ours) | 0.9360 | 41.49 | **0.7920** | **8.55** | 3.49 | 3.93 | 3.13 |
|
| 104 |
+
| | Ding Zhen | RVCv2 | 0.9197 | 22.82 | 0.7591 | 12.92 | 3.40 | 4.02 | **3.09** |
|
| 105 |
+
| | | Seed-VC(Ours) | 0.9247 | 22.77 | **0.7721** | **13.95** | 3.45 | 3.82 | 3.05 |
|
| 106 |
+
| | Kobe Bryant | RVCv2 | 0.9415 | 19.33 | 0.7507 | 30.52 | 3.48 | 4.02 | **3.19** |
|
| 107 |
+
| | | Seed-VC(Ours) | 0.9082 | 24.86 | **0.7764** | **13.35** | 3.39 | 3.93 | 3.07 |
|
| 108 |
+
</details>
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
Despite Seed-VC is not trained on the target speakers, and only one random utterance is used as prompt, it still constantly outperforms speaker-specific RVCv2 models
|
| 112 |
+
in terms of speaker similarity (SECS) and intelligibility (CER), which demonstrates the superior voice cloning capability and robustness of Seed-VC.
|
| 113 |
+
|
| 114 |
+
However, it is observed that Seed-VC's audio quality (DNSMOS) is slightly lower than RVCv2. We take this drawback seriously and
|
| 115 |
+
will give high priority to improve the audio quality in the future.
|
| 116 |
+
PR or issue is welcomed if you find this comparison unfair or inaccurate.
|
| 117 |
+
|
| 118 |
+
*Chinese ASR result computed by [SenseVoiceSmall](https://github.com/FunAudioLLM/SenseVoice)*
|
| 119 |
+
*Speaker embedding computed by [resemblyzer](https://github.com/resemble-ai/Resemblyzer) model*
|
| 120 |
+
*We set +12 semitones pitch shift for male-to-female conversion and -12 semitones for female-to-male converison, otherwise 0 pitch shift*
|
| 121 |
+
|
seed-vc/LICENSE
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 29 June 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works.
|
| 12 |
+
|
| 13 |
+
The licenses for most software and other practical works are designed
|
| 14 |
+
to take away your freedom to share and change the works. By contrast,
|
| 15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
| 16 |
+
share and change all versions of a program--to make sure it remains free
|
| 17 |
+
software for all its users. We, the Free Software Foundation, use the
|
| 18 |
+
GNU General Public License for most of our software; it applies also to
|
| 19 |
+
any other work released this way by its authors. You can apply it to
|
| 20 |
+
your programs, too.
|
| 21 |
+
|
| 22 |
+
When we speak of free software, we are referring to freedom, not
|
| 23 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 24 |
+
have the freedom to distribute copies of free software (and charge for
|
| 25 |
+
them if you wish), that you receive source code or can get it if you
|
| 26 |
+
want it, that you can change the software or use pieces of it in new
|
| 27 |
+
free programs, and that you know you can do these things.
|
| 28 |
+
|
| 29 |
+
To protect your rights, we need to prevent others from denying you
|
| 30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
| 31 |
+
certain responsibilities if you distribute copies of the software, or if
|
| 32 |
+
you modify it: responsibilities to respect the freedom of others.
|
| 33 |
+
|
| 34 |
+
For example, if you distribute copies of such a program, whether
|
| 35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
| 36 |
+
freedoms that you received. You must make sure that they, too, receive
|
| 37 |
+
or can get the source code. And you must show them these terms so they
|
| 38 |
+
know their rights.
|
| 39 |
+
|
| 40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
| 41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
| 42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
| 43 |
+
|
| 44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
| 45 |
+
that there is no warranty for this free software. For both users' and
|
| 46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
| 47 |
+
changed, so that their problems will not be attributed erroneously to
|
| 48 |
+
authors of previous versions.
|
| 49 |
+
|
| 50 |
+
Some devices are designed to deny users access to install or run
|
| 51 |
+
modified versions of the software inside them, although the manufacturer
|
| 52 |
+
can do so. This is fundamentally incompatible with the aim of
|
| 53 |
+
protecting users' freedom to change the software. The systematic
|
| 54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
| 55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
| 56 |
+
have designed this version of the GPL to prohibit the practice for those
|
| 57 |
+
products. If such problems arise substantially in other domains, we
|
| 58 |
+
stand ready to extend this provision to those domains in future versions
|
| 59 |
+
of the GPL, as needed to protect the freedom of users.
|
| 60 |
+
|
| 61 |
+
Finally, every program is threatened constantly by software patents.
|
| 62 |
+
States should not allow patents to restrict development and use of
|
| 63 |
+
software on general-purpose computers, but in those that do, we wish to
|
| 64 |
+
avoid the special danger that patents applied to a free program could
|
| 65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
| 66 |
+
patents cannot be used to render the program non-free.
|
| 67 |
+
|
| 68 |
+
The precise terms and conditions for copying, distribution and
|
| 69 |
+
modification follow.
|
| 70 |
+
|
| 71 |
+
TERMS AND CONDITIONS
|
| 72 |
+
|
| 73 |
+
0. Definitions.
|
| 74 |
+
|
| 75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
| 76 |
+
|
| 77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 78 |
+
works, such as semiconductor masks.
|
| 79 |
+
|
| 80 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 82 |
+
"recipients" may be individuals or organizations.
|
| 83 |
+
|
| 84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 85 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 86 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 87 |
+
earlier work or a work "based on" the earlier work.
|
| 88 |
+
|
| 89 |
+
A "covered work" means either the unmodified Program or a work based
|
| 90 |
+
on the Program.
|
| 91 |
+
|
| 92 |
+
To "propagate" a work means to do anything with it that, without
|
| 93 |
+
permission, would make you directly or secondarily liable for
|
| 94 |
+
infringement under applicable copyright law, except executing it on a
|
| 95 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 96 |
+
distribution (with or without modification), making available to the
|
| 97 |
+
public, and in some countries other activities as well.
|
| 98 |
+
|
| 99 |
+
To "convey" a work means any kind of propagation that enables other
|
| 100 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 102 |
+
|
| 103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 104 |
+
to the extent that it includes a convenient and prominently visible
|
| 105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 106 |
+
tells the user that there is no warranty for the work (except to the
|
| 107 |
+
extent that warranties are provided), that licensees may convey the
|
| 108 |
+
work under this License, and how to view a copy of this License. If
|
| 109 |
+
the interface presents a list of user commands or options, such as a
|
| 110 |
+
menu, a prominent item in the list meets this criterion.
|
| 111 |
+
|
| 112 |
+
1. Source Code.
|
| 113 |
+
|
| 114 |
+
The "source code" for a work means the preferred form of the work
|
| 115 |
+
for making modifications to it. "Object code" means any non-source
|
| 116 |
+
form of a work.
|
| 117 |
+
|
| 118 |
+
A "Standard Interface" means an interface that either is an official
|
| 119 |
+
standard defined by a recognized standards body, or, in the case of
|
| 120 |
+
interfaces specified for a particular programming language, one that
|
| 121 |
+
is widely used among developers working in that language.
|
| 122 |
+
|
| 123 |
+
The "System Libraries" of an executable work include anything, other
|
| 124 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 125 |
+
packaging a Major Component, but which is not part of that Major
|
| 126 |
+
Component, and (b) serves only to enable use of the work with that
|
| 127 |
+
Major Component, or to implement a Standard Interface for which an
|
| 128 |
+
implementation is available to the public in source code form. A
|
| 129 |
+
"Major Component", in this context, means a major essential component
|
| 130 |
+
(kernel, window system, and so on) of the specific operating system
|
| 131 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 132 |
+
produce the work, or an object code interpreter used to run it.
|
| 133 |
+
|
| 134 |
+
The "Corresponding Source" for a work in object code form means all
|
| 135 |
+
the source code needed to generate, install, and (for an executable
|
| 136 |
+
work) run the object code and to modify the work, including scripts to
|
| 137 |
+
control those activities. However, it does not include the work's
|
| 138 |
+
System Libraries, or general-purpose tools or generally available free
|
| 139 |
+
programs which are used unmodified in performing those activities but
|
| 140 |
+
which are not part of the work. For example, Corresponding Source
|
| 141 |
+
includes interface definition files associated with source files for
|
| 142 |
+
the work, and the source code for shared libraries and dynamically
|
| 143 |
+
linked subprograms that the work is specifically designed to require,
|
| 144 |
+
such as by intimate data communication or control flow between those
|
| 145 |
+
subprograms and other parts of the work.
|
| 146 |
+
|
| 147 |
+
The Corresponding Source need not include anything that users
|
| 148 |
+
can regenerate automatically from other parts of the Corresponding
|
| 149 |
+
Source.
|
| 150 |
+
|
| 151 |
+
The Corresponding Source for a work in source code form is that
|
| 152 |
+
same work.
|
| 153 |
+
|
| 154 |
+
2. Basic Permissions.
|
| 155 |
+
|
| 156 |
+
All rights granted under this License are granted for the term of
|
| 157 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 158 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 159 |
+
permission to run the unmodified Program. The output from running a
|
| 160 |
+
covered work is covered by this License only if the output, given its
|
| 161 |
+
content, constitutes a covered work. This License acknowledges your
|
| 162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 163 |
+
|
| 164 |
+
You may make, run and propagate covered works that you do not
|
| 165 |
+
convey, without conditions so long as your license otherwise remains
|
| 166 |
+
in force. You may convey covered works to others for the sole purpose
|
| 167 |
+
of having them make modifications exclusively for you, or provide you
|
| 168 |
+
with facilities for running those works, provided that you comply with
|
| 169 |
+
the terms of this License in conveying all material for which you do
|
| 170 |
+
not control copyright. Those thus making or running the covered works
|
| 171 |
+
for you must do so exclusively on your behalf, under your direction
|
| 172 |
+
and control, on terms that prohibit them from making any copies of
|
| 173 |
+
your copyrighted material outside their relationship with you.
|
| 174 |
+
|
| 175 |
+
Conveying under any other circumstances is permitted solely under
|
| 176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 177 |
+
makes it unnecessary.
|
| 178 |
+
|
| 179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 180 |
+
|
| 181 |
+
No covered work shall be deemed part of an effective technological
|
| 182 |
+
measure under any applicable law fulfilling obligations under article
|
| 183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 184 |
+
similar laws prohibiting or restricting circumvention of such
|
| 185 |
+
measures.
|
| 186 |
+
|
| 187 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 188 |
+
circumvention of technological measures to the extent such circumvention
|
| 189 |
+
is effected by exercising rights under this License with respect to
|
| 190 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 191 |
+
modification of the work as a means of enforcing, against the work's
|
| 192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 193 |
+
technological measures.
|
| 194 |
+
|
| 195 |
+
4. Conveying Verbatim Copies.
|
| 196 |
+
|
| 197 |
+
You may convey verbatim copies of the Program's source code as you
|
| 198 |
+
receive it, in any medium, provided that you conspicuously and
|
| 199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 200 |
+
keep intact all notices stating that this License and any
|
| 201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 202 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 203 |
+
recipients a copy of this License along with the Program.
|
| 204 |
+
|
| 205 |
+
You may charge any price or no price for each copy that you convey,
|
| 206 |
+
and you may offer support or warranty protection for a fee.
|
| 207 |
+
|
| 208 |
+
5. Conveying Modified Source Versions.
|
| 209 |
+
|
| 210 |
+
You may convey a work based on the Program, or the modifications to
|
| 211 |
+
produce it from the Program, in the form of source code under the
|
| 212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 213 |
+
|
| 214 |
+
a) The work must carry prominent notices stating that you modified
|
| 215 |
+
it, and giving a relevant date.
|
| 216 |
+
|
| 217 |
+
b) The work must carry prominent notices stating that it is
|
| 218 |
+
released under this License and any conditions added under section
|
| 219 |
+
7. This requirement modifies the requirement in section 4 to
|
| 220 |
+
"keep intact all notices".
|
| 221 |
+
|
| 222 |
+
c) You must license the entire work, as a whole, under this
|
| 223 |
+
License to anyone who comes into possession of a copy. This
|
| 224 |
+
License will therefore apply, along with any applicable section 7
|
| 225 |
+
additional terms, to the whole of the work, and all its parts,
|
| 226 |
+
regardless of how they are packaged. This License gives no
|
| 227 |
+
permission to license the work in any other way, but it does not
|
| 228 |
+
invalidate such permission if you have separately received it.
|
| 229 |
+
|
| 230 |
+
d) If the work has interactive user interfaces, each must display
|
| 231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 233 |
+
work need not make them do so.
|
| 234 |
+
|
| 235 |
+
A compilation of a covered work with other separate and independent
|
| 236 |
+
works, which are not by their nature extensions of the covered work,
|
| 237 |
+
and which are not combined with it such as to form a larger program,
|
| 238 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 240 |
+
used to limit the access or legal rights of the compilation's users
|
| 241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 242 |
+
in an aggregate does not cause this License to apply to the other
|
| 243 |
+
parts of the aggregate.
|
| 244 |
+
|
| 245 |
+
6. Conveying Non-Source Forms.
|
| 246 |
+
|
| 247 |
+
You may convey a covered work in object code form under the terms
|
| 248 |
+
of sections 4 and 5, provided that you also convey the
|
| 249 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 250 |
+
in one of these ways:
|
| 251 |
+
|
| 252 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 253 |
+
(including a physical distribution medium), accompanied by the
|
| 254 |
+
Corresponding Source fixed on a durable physical medium
|
| 255 |
+
customarily used for software interchange.
|
| 256 |
+
|
| 257 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 258 |
+
(including a physical distribution medium), accompanied by a
|
| 259 |
+
written offer, valid for at least three years and valid for as
|
| 260 |
+
long as you offer spare parts or customer support for that product
|
| 261 |
+
model, to give anyone who possesses the object code either (1) a
|
| 262 |
+
copy of the Corresponding Source for all the software in the
|
| 263 |
+
product that is covered by this License, on a durable physical
|
| 264 |
+
medium customarily used for software interchange, for a price no
|
| 265 |
+
more than your reasonable cost of physically performing this
|
| 266 |
+
conveying of source, or (2) access to copy the
|
| 267 |
+
Corresponding Source from a network server at no charge.
|
| 268 |
+
|
| 269 |
+
c) Convey individual copies of the object code with a copy of the
|
| 270 |
+
written offer to provide the Corresponding Source. This
|
| 271 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 272 |
+
only if you received the object code with such an offer, in accord
|
| 273 |
+
with subsection 6b.
|
| 274 |
+
|
| 275 |
+
d) Convey the object code by offering access from a designated
|
| 276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 277 |
+
Corresponding Source in the same way through the same place at no
|
| 278 |
+
further charge. You need not require recipients to copy the
|
| 279 |
+
Corresponding Source along with the object code. If the place to
|
| 280 |
+
copy the object code is a network server, the Corresponding Source
|
| 281 |
+
may be on a different server (operated by you or a third party)
|
| 282 |
+
that supports equivalent copying facilities, provided you maintain
|
| 283 |
+
clear directions next to the object code saying where to find the
|
| 284 |
+
Corresponding Source. Regardless of what server hosts the
|
| 285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 286 |
+
available for as long as needed to satisfy these requirements.
|
| 287 |
+
|
| 288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 289 |
+
you inform other peers where the object code and Corresponding
|
| 290 |
+
Source of the work are being offered to the general public at no
|
| 291 |
+
charge under subsection 6d.
|
| 292 |
+
|
| 293 |
+
A separable portion of the object code, whose source code is excluded
|
| 294 |
+
from the Corresponding Source as a System Library, need not be
|
| 295 |
+
included in conveying the object code work.
|
| 296 |
+
|
| 297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 298 |
+
tangible personal property which is normally used for personal, family,
|
| 299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 302 |
+
product received by a particular user, "normally used" refers to a
|
| 303 |
+
typical or common use of that class of product, regardless of the status
|
| 304 |
+
of the particular user or of the way in which the particular user
|
| 305 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 306 |
+
is a consumer product regardless of whether the product has substantial
|
| 307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 308 |
+
the only significant mode of use of the product.
|
| 309 |
+
|
| 310 |
+
"Installation Information" for a User Product means any methods,
|
| 311 |
+
procedures, authorization keys, or other information required to install
|
| 312 |
+
and execute modified versions of a covered work in that User Product from
|
| 313 |
+
a modified version of its Corresponding Source. The information must
|
| 314 |
+
suffice to ensure that the continued functioning of the modified object
|
| 315 |
+
code is in no case prevented or interfered with solely because
|
| 316 |
+
modification has been made.
|
| 317 |
+
|
| 318 |
+
If you convey an object code work under this section in, or with, or
|
| 319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 320 |
+
part of a transaction in which the right of possession and use of the
|
| 321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 322 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 323 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 324 |
+
by the Installation Information. But this requirement does not apply
|
| 325 |
+
if neither you nor any third party retains the ability to install
|
| 326 |
+
modified object code on the User Product (for example, the work has
|
| 327 |
+
been installed in ROM).
|
| 328 |
+
|
| 329 |
+
The requirement to provide Installation Information does not include a
|
| 330 |
+
requirement to continue to provide support service, warranty, or updates
|
| 331 |
+
for a work that has been modified or installed by the recipient, or for
|
| 332 |
+
the User Product in which it has been modified or installed. Access to a
|
| 333 |
+
network may be denied when the modification itself materially and
|
| 334 |
+
adversely affects the operation of the network or violates the rules and
|
| 335 |
+
protocols for communication across the network.
|
| 336 |
+
|
| 337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 338 |
+
in accord with this section must be in a format that is publicly
|
| 339 |
+
documented (and with an implementation available to the public in
|
| 340 |
+
source code form), and must require no special password or key for
|
| 341 |
+
unpacking, reading or copying.
|
| 342 |
+
|
| 343 |
+
7. Additional Terms.
|
| 344 |
+
|
| 345 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 346 |
+
License by making exceptions from one or more of its conditions.
|
| 347 |
+
Additional permissions that are applicable to the entire Program shall
|
| 348 |
+
be treated as though they were included in this License, to the extent
|
| 349 |
+
that they are valid under applicable law. If additional permissions
|
| 350 |
+
apply only to part of the Program, that part may be used separately
|
| 351 |
+
under those permissions, but the entire Program remains governed by
|
| 352 |
+
this License without regard to the additional permissions.
|
| 353 |
+
|
| 354 |
+
When you convey a copy of a covered work, you may at your option
|
| 355 |
+
remove any additional permissions from that copy, or from any part of
|
| 356 |
+
it. (Additional permissions may be written to require their own
|
| 357 |
+
removal in certain cases when you modify the work.) You may place
|
| 358 |
+
additional permissions on material, added by you to a covered work,
|
| 359 |
+
for which you have or can give appropriate copyright permission.
|
| 360 |
+
|
| 361 |
+
Notwithstanding any other provision of this License, for material you
|
| 362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 363 |
+
that material) supplement the terms of this License with terms:
|
| 364 |
+
|
| 365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 366 |
+
terms of sections 15 and 16 of this License; or
|
| 367 |
+
|
| 368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 369 |
+
author attributions in that material or in the Appropriate Legal
|
| 370 |
+
Notices displayed by works containing it; or
|
| 371 |
+
|
| 372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 373 |
+
requiring that modified versions of such material be marked in
|
| 374 |
+
reasonable ways as different from the original version; or
|
| 375 |
+
|
| 376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 377 |
+
authors of the material; or
|
| 378 |
+
|
| 379 |
+
e) Declining to grant rights under trademark law for use of some
|
| 380 |
+
trade names, trademarks, or service marks; or
|
| 381 |
+
|
| 382 |
+
f) Requiring indemnification of licensors and authors of that
|
| 383 |
+
material by anyone who conveys the material (or modified versions of
|
| 384 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 385 |
+
any liability that these contractual assumptions directly impose on
|
| 386 |
+
those licensors and authors.
|
| 387 |
+
|
| 388 |
+
All other non-permissive additional terms are considered "further
|
| 389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 390 |
+
received it, or any part of it, contains a notice stating that it is
|
| 391 |
+
governed by this License along with a term that is a further
|
| 392 |
+
restriction, you may remove that term. If a license document contains
|
| 393 |
+
a further restriction but permits relicensing or conveying under this
|
| 394 |
+
License, you may add to a covered work material governed by the terms
|
| 395 |
+
of that license document, provided that the further restriction does
|
| 396 |
+
not survive such relicensing or conveying.
|
| 397 |
+
|
| 398 |
+
If you add terms to a covered work in accord with this section, you
|
| 399 |
+
must place, in the relevant source files, a statement of the
|
| 400 |
+
additional terms that apply to those files, or a notice indicating
|
| 401 |
+
where to find the applicable terms.
|
| 402 |
+
|
| 403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 404 |
+
form of a separately written license, or stated as exceptions;
|
| 405 |
+
the above requirements apply either way.
|
| 406 |
+
|
| 407 |
+
8. Termination.
|
| 408 |
+
|
| 409 |
+
You may not propagate or modify a covered work except as expressly
|
| 410 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 411 |
+
modify it is void, and will automatically terminate your rights under
|
| 412 |
+
this License (including any patent licenses granted under the third
|
| 413 |
+
paragraph of section 11).
|
| 414 |
+
|
| 415 |
+
However, if you cease all violation of this License, then your
|
| 416 |
+
license from a particular copyright holder is reinstated (a)
|
| 417 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 419 |
+
holder fails to notify you of the violation by some reasonable means
|
| 420 |
+
prior to 60 days after the cessation.
|
| 421 |
+
|
| 422 |
+
Moreover, your license from a particular copyright holder is
|
| 423 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 424 |
+
violation by some reasonable means, this is the first time you have
|
| 425 |
+
received notice of violation of this License (for any work) from that
|
| 426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 427 |
+
your receipt of the notice.
|
| 428 |
+
|
| 429 |
+
Termination of your rights under this section does not terminate the
|
| 430 |
+
licenses of parties who have received copies or rights from you under
|
| 431 |
+
this License. If your rights have been terminated and not permanently
|
| 432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 433 |
+
material under section 10.
|
| 434 |
+
|
| 435 |
+
9. Acceptance Not Required for Having Copies.
|
| 436 |
+
|
| 437 |
+
You are not required to accept this License in order to receive or
|
| 438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 440 |
+
to receive a copy likewise does not require acceptance. However,
|
| 441 |
+
nothing other than this License grants you permission to propagate or
|
| 442 |
+
modify any covered work. These actions infringe copyright if you do
|
| 443 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 444 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 445 |
+
|
| 446 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 447 |
+
|
| 448 |
+
Each time you convey a covered work, the recipient automatically
|
| 449 |
+
receives a license from the original licensors, to run, modify and
|
| 450 |
+
propagate that work, subject to this License. You are not responsible
|
| 451 |
+
for enforcing compliance by third parties with this License.
|
| 452 |
+
|
| 453 |
+
An "entity transaction" is a transaction transferring control of an
|
| 454 |
+
organization, or substantially all assets of one, or subdividing an
|
| 455 |
+
organization, or merging organizations. If propagation of a covered
|
| 456 |
+
work results from an entity transaction, each party to that
|
| 457 |
+
transaction who receives a copy of the work also receives whatever
|
| 458 |
+
licenses to the work the party's predecessor in interest had or could
|
| 459 |
+
give under the previous paragraph, plus a right to possession of the
|
| 460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 461 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 462 |
+
|
| 463 |
+
You may not impose any further restrictions on the exercise of the
|
| 464 |
+
rights granted or affirmed under this License. For example, you may
|
| 465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 466 |
+
rights granted under this License, and you may not initiate litigation
|
| 467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 468 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 469 |
+
sale, or importing the Program or any portion of it.
|
| 470 |
+
|
| 471 |
+
11. Patents.
|
| 472 |
+
|
| 473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 474 |
+
License of the Program or a work on which the Program is based. The
|
| 475 |
+
work thus licensed is called the contributor's "contributor version".
|
| 476 |
+
|
| 477 |
+
A contributor's "essential patent claims" are all patent claims
|
| 478 |
+
owned or controlled by the contributor, whether already acquired or
|
| 479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 480 |
+
by this License, of making, using, or selling its contributor version,
|
| 481 |
+
but do not include claims that would be infringed only as a
|
| 482 |
+
consequence of further modification of the contributor version. For
|
| 483 |
+
purposes of this definition, "control" includes the right to grant
|
| 484 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 485 |
+
this License.
|
| 486 |
+
|
| 487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 488 |
+
patent license under the contributor's essential patent claims, to
|
| 489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 490 |
+
propagate the contents of its contributor version.
|
| 491 |
+
|
| 492 |
+
In the following three paragraphs, a "patent license" is any express
|
| 493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 494 |
+
(such as an express permission to practice a patent or covenant not to
|
| 495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 496 |
+
party means to make such an agreement or commitment not to enforce a
|
| 497 |
+
patent against the party.
|
| 498 |
+
|
| 499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 500 |
+
and the Corresponding Source of the work is not available for anyone
|
| 501 |
+
to copy, free of charge and under the terms of this License, through a
|
| 502 |
+
publicly available network server or other readily accessible means,
|
| 503 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 506 |
+
consistent with the requirements of this License, to extend the patent
|
| 507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 508 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 509 |
+
covered work in a country, or your recipient's use of the covered work
|
| 510 |
+
in a country, would infringe one or more identifiable patents in that
|
| 511 |
+
country that you have reason to believe are valid.
|
| 512 |
+
|
| 513 |
+
If, pursuant to or in connection with a single transaction or
|
| 514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 515 |
+
covered work, and grant a patent license to some of the parties
|
| 516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 517 |
+
or convey a specific copy of the covered work, then the patent license
|
| 518 |
+
you grant is automatically extended to all recipients of the covered
|
| 519 |
+
work and works based on it.
|
| 520 |
+
|
| 521 |
+
A patent license is "discriminatory" if it does not include within
|
| 522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 524 |
+
specifically granted under this License. You may not convey a covered
|
| 525 |
+
work if you are a party to an arrangement with a third party that is
|
| 526 |
+
in the business of distributing software, under which you make payment
|
| 527 |
+
to the third party based on the extent of your activity of conveying
|
| 528 |
+
the work, and under which the third party grants, to any of the
|
| 529 |
+
parties who would receive the covered work from you, a discriminatory
|
| 530 |
+
patent license (a) in connection with copies of the covered work
|
| 531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 532 |
+
for and in connection with specific products or compilations that
|
| 533 |
+
contain the covered work, unless you entered into that arrangement,
|
| 534 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 535 |
+
|
| 536 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 537 |
+
any implied license or other defenses to infringement that may
|
| 538 |
+
otherwise be available to you under applicable patent law.
|
| 539 |
+
|
| 540 |
+
12. No Surrender of Others' Freedom.
|
| 541 |
+
|
| 542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 543 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 546 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 548 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 549 |
+
the Program, the only way you could satisfy both those terms and this
|
| 550 |
+
License would be to refrain entirely from conveying the Program.
|
| 551 |
+
|
| 552 |
+
13. Use with the GNU Affero General Public License.
|
| 553 |
+
|
| 554 |
+
Notwithstanding any other provision of this License, you have
|
| 555 |
+
permission to link or combine any covered work with a work licensed
|
| 556 |
+
under version 3 of the GNU Affero General Public License into a single
|
| 557 |
+
combined work, and to convey the resulting work. The terms of this
|
| 558 |
+
License will continue to apply to the part which is the covered work,
|
| 559 |
+
but the special requirements of the GNU Affero General Public License,
|
| 560 |
+
section 13, concerning interaction through a network will apply to the
|
| 561 |
+
combination as such.
|
| 562 |
+
|
| 563 |
+
14. Revised Versions of this License.
|
| 564 |
+
|
| 565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 566 |
+
the GNU General Public License from time to time. Such new versions will
|
| 567 |
+
be similar in spirit to the present version, but may differ in detail to
|
| 568 |
+
address new problems or concerns.
|
| 569 |
+
|
| 570 |
+
Each version is given a distinguishing version number. If the
|
| 571 |
+
Program specifies that a certain numbered version of the GNU General
|
| 572 |
+
Public License "or any later version" applies to it, you have the
|
| 573 |
+
option of following the terms and conditions either of that numbered
|
| 574 |
+
version or of any later version published by the Free Software
|
| 575 |
+
Foundation. If the Program does not specify a version number of the
|
| 576 |
+
GNU General Public License, you may choose any version ever published
|
| 577 |
+
by the Free Software Foundation.
|
| 578 |
+
|
| 579 |
+
If the Program specifies that a proxy can decide which future
|
| 580 |
+
versions of the GNU General Public License can be used, that proxy's
|
| 581 |
+
public statement of acceptance of a version permanently authorizes you
|
| 582 |
+
to choose that version for the Program.
|
| 583 |
+
|
| 584 |
+
Later license versions may give you additional or different
|
| 585 |
+
permissions. However, no additional obligations are imposed on any
|
| 586 |
+
author or copyright holder as a result of your choosing to follow a
|
| 587 |
+
later version.
|
| 588 |
+
|
| 589 |
+
15. Disclaimer of Warranty.
|
| 590 |
+
|
| 591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 599 |
+
|
| 600 |
+
16. Limitation of Liability.
|
| 601 |
+
|
| 602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 610 |
+
SUCH DAMAGES.
|
| 611 |
+
|
| 612 |
+
17. Interpretation of Sections 15 and 16.
|
| 613 |
+
|
| 614 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 615 |
+
above cannot be given local legal effect according to their terms,
|
| 616 |
+
reviewing courts shall apply local law that most closely approximates
|
| 617 |
+
an absolute waiver of all civil liability in connection with the
|
| 618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 619 |
+
copy of the Program in return for a fee.
|
| 620 |
+
|
| 621 |
+
END OF TERMS AND CONDITIONS
|
| 622 |
+
|
| 623 |
+
How to Apply These Terms to Your New Programs
|
| 624 |
+
|
| 625 |
+
If you develop a new program, and you want it to be of the greatest
|
| 626 |
+
possible use to the public, the best way to achieve this is to make it
|
| 627 |
+
free software which everyone can redistribute and change under these terms.
|
| 628 |
+
|
| 629 |
+
To do so, attach the following notices to the program. It is safest
|
| 630 |
+
to attach them to the start of each source file to most effectively
|
| 631 |
+
state the exclusion of warranty; and each file should have at least
|
| 632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 633 |
+
|
| 634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 635 |
+
Copyright (C) <year> <name of author>
|
| 636 |
+
|
| 637 |
+
This program is free software: you can redistribute it and/or modify
|
| 638 |
+
it under the terms of the GNU General Public License as published by
|
| 639 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 640 |
+
(at your option) any later version.
|
| 641 |
+
|
| 642 |
+
This program is distributed in the hope that it will be useful,
|
| 643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 645 |
+
GNU General Public License for more details.
|
| 646 |
+
|
| 647 |
+
You should have received a copy of the GNU General Public License
|
| 648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 649 |
+
|
| 650 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 651 |
+
|
| 652 |
+
If the program does terminal interaction, make it output a short
|
| 653 |
+
notice like this when it starts in an interactive mode:
|
| 654 |
+
|
| 655 |
+
<program> Copyright (C) <year> <name of author>
|
| 656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
| 657 |
+
This is free software, and you are welcome to redistribute it
|
| 658 |
+
under certain conditions; type `show c' for details.
|
| 659 |
+
|
| 660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
| 661 |
+
parts of the General Public License. Of course, your program's commands
|
| 662 |
+
might be different; for a GUI interface, you would use an "about box".
|
| 663 |
+
|
| 664 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
| 667 |
+
<https://www.gnu.org/licenses/>.
|
| 668 |
+
|
| 669 |
+
The GNU General Public License does not permit incorporating your program
|
| 670 |
+
into proprietary programs. If your program is a subroutine library, you
|
| 671 |
+
may consider it more useful to permit linking proprietary applications with
|
| 672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
| 673 |
+
Public License instead of this License. But first, please read
|
| 674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
seed-vc/README-JA.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Seed-VC
|
| 2 |
+
[](https://huggingface.co/spaces/Plachta/Seed-VC) [](https://arxiv.org/abs/2411.09943)
|
| 3 |
+
|
| 4 |
+
*[English](README.md) | [简体中文](README-ZH.md) | 日本語*
|
| 5 |
+
|
| 6 |
+
[real-time-demo.webm](https://github.com/user-attachments/assets/86325c5e-f7f6-4a04-8695-97275a5d046c)
|
| 7 |
+
|
| 8 |
+
*(注意:この文書は機械翻訳によって生成されたものです。正確性を確保するよう努めていますが、不明確な点がございましたら英語版をご参照ください。翻訳の改善案がございましたら、PRを歓迎いたします。)*
|
| 9 |
+
|
| 10 |
+
現在リリースされているモデルは、*ゼロショット音声変換* 🔊、*ゼロショットリアルタイム音声変換* 🗣️、*ゼロショット歌声変換* 🎶 に対応しています。トレーニングなしで、1〜30秒の参照音声からボイスクローニングが可能です。
|
| 11 |
+
|
| 12 |
+
カスタムデータでの追加ファインチューニングをサポートしており、特定の話者/話者群に対するパフォーマンスを向上させることができます。データ要件は極めて少なく(**話者あたり最低1発話**)、トレーニング速度も非常に速い(**最低100ステップ、T4で2分**)です!
|
| 13 |
+
|
| 14 |
+
**リアルタイム音声変換**に対応しており、アルゴリズムの遅延は約300ms、デバイス側の遅延は約100msで、オンライン会議、ゲーム、ライブ配信に適しています。
|
| 15 |
+
|
| 16 |
+
デモや以前の音声変換モデルとの比較については、[デモページ](https://plachtaa.github.io/seed-vc/)🌐と[評価](EVAL.md)📊をご覧ください。
|
| 17 |
+
|
| 18 |
+
モデルの品質向上と機能追加を継続的に行っています。
|
| 19 |
+
|
| 20 |
+
## 評価📊
|
| 21 |
+
客観的評価結果と他のベースラインとの比較については[EVAL.md](EVAL.md)をご覧ください。
|
| 22 |
+
|
| 23 |
+
## インストール📥
|
| 24 |
+
Windows または Linux で Python 3.10 を推奨します。
|
| 25 |
+
```bash
|
| 26 |
+
pip install -r requirements.txt
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## 使用方法🛠️
|
| 30 |
+
目的に応じて3つのモデルをリリースしています:
|
| 31 |
+
|
| 32 |
+
| バージョン | 名称 | 目的 | サンプリングレート | コンテンツエンコーダ | ボコーダ | 隠れ次元 | レイヤー数 | パラメータ数 | 備考 |
|
| 33 |
+
|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------|---------------|-----------------|---------|------------|----------|--------|--------------------------------------------------------|
|
| 34 |
+
| v1.0 | seed-uvit-tat-xlsr-tiny ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_uvit_tat_xlsr_ema.pth)[📄](configs/presets/config_dit_mel_seed_uvit_xlsr_tiny.yml)) | 音声変換 (VC) | 22050 | XLSR-large | HIFT | 384 | 9 | 25M | リアルタイム音声変換に適しています |
|
| 35 |
+
| v1.0 | seed-uvit-whisper-small-wavenet ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth)[📄](configs/presets/config_dit_mel_seed_uvit_whisper_small_wavenet.yml)) | 音声変換 (VC) | 22050 | Whisper-small | BigVGAN | 512 | 13 | 98M | オフライン音声変換に適しています |
|
| 36 |
+
| v1.0 | seed-uvit-whisper-base ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema.pth)[📄](configs/presets/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml)) | 歌声変換 (SVC) | 44100 | Whisper-small | BigVGAN | 768 | 17 | 200M | 強力なゼロショットパフォーマンス、歌声変換 |
|
| 37 |
+
|
| 38 |
+
最新のモデルリリースのチェックポイントは、最初の推論実行時に自動的にダウンロードされます。
|
| 39 |
+
ネットワークの理由でhuggingfaceにアクセスできない場合は、すべてのコマンドの前に `HF_ENDPOINT=https://hf-mirror.com` を追加してミラーを使用してください。
|
| 40 |
+
|
| 41 |
+
コマンドライン推論:
|
| 42 |
+
```bash
|
| 43 |
+
python inference.py --source <source-wav>
|
| 44 |
+
--target <referene-wav>
|
| 45 |
+
--output <output-dir>
|
| 46 |
+
--diffusion-steps 25 # 歌声変換には30〜50を推奨
|
| 47 |
+
--length-adjust 1.0
|
| 48 |
+
--inference-cfg-rate 0.7
|
| 49 |
+
--f0-condition False # 歌声変換の場合はTrueに設定
|
| 50 |
+
--auto-f0-adjust False # ソースピッチをターゲットピッチレベルに自動調整する場合はTrue���通常は歌声変換では使用しない
|
| 51 |
+
--semi-tone-shift 0 # 歌声変換のピッチシフト(半音単位)
|
| 52 |
+
--checkpoint <path-to-checkpoint>
|
| 53 |
+
--config <path-to-config>
|
| 54 |
+
--fp16 True
|
| 55 |
+
```
|
| 56 |
+
各パラメータの説明:
|
| 57 |
+
- `source` は変換したい音声ファイルのパス
|
| 58 |
+
- `target` は参照音声ファイルのパス
|
| 59 |
+
- `output` は出力ディレクトリのパス
|
| 60 |
+
- `diffusion-steps` は拡散ステップ数、デフォルトは25、最高品質には30-50、最速推論には4-10を使用
|
| 61 |
+
- `length-adjust` は長さ調整係数、デフォルトは1.0、<1.0で音声短縮、>1.0で音声伸長
|
| 62 |
+
- `inference-cfg-rate` は出力に微妙な違いをもたらす、デフォルトは0.7
|
| 63 |
+
- `f0-condition` はソース音声のピッチを出力に条件付けするフラグ、デフォルトはFalse、歌声変換の場合はTrue
|
| 64 |
+
- `auto-f0-adjust` はソースピッチをターゲットピッチレベルに自動調整するフラグ、デフォルトはFalse、通常は歌声変換では使用しない
|
| 65 |
+
- `semi-tone-shift` は歌声変換のピッチシフト(半音単位)、デフォルトは0
|
| 66 |
+
- `checkpoint` は独自のモデルをトレーニングまたはファインチューニングした場合のモデルチェックポイントへのパス、空白の場合はhuggingfaceからデフォルトモデルを自動ダウンロード(`f0-condition`が`False`の場合は`seed-uvit-whisper-small-wavenet`、それ以外は`seed-uvit-whisper-base`)
|
| 67 |
+
- `config` は独自のモデルをトレーニングまたはファインチューニングした場合のモデル設定へのパス、空白の場合はhuggingfaceからデフォルト設定を自動ダウンロード
|
| 68 |
+
- `fp16` はfloat16推論を使用するフラグ、デフォルトはTrue
|
| 69 |
+
|
| 70 |
+
音声変換Web UI:
|
| 71 |
+
```bash
|
| 72 |
+
python app_vc.py --checkpoint <path-to-checkpoint> --config <path-to-config> --fp16 True
|
| 73 |
+
```
|
| 74 |
+
- `checkpoint` は独自のモデルをトレーニングまたはファインチューニングした場合のモデルチェックポイントへのパス、空白の場合はhuggingfaceからデフォルトモデルを自動ダウンロード(`seed-uvit-whisper-small-wavenet`)
|
| 75 |
+
- `config` は独自のモデルをトレーニングまたはファインチューニングした場合のモデル設定へのパス、空白の場合はhuggingfaceからデフォルト設定を自動ダウンロード
|
| 76 |
+
|
| 77 |
+
ブラウザで`http://localhost:7860/`にアクセスしてWebインターフェースを使用できます。
|
| 78 |
+
|
| 79 |
+
歌声変換Web UI:
|
| 80 |
+
```bash
|
| 81 |
+
python app_svc.py --checkpoint <path-to-checkpoint> --config <path-to-config> --fp16 True
|
| 82 |
+
```
|
| 83 |
+
- `checkpoint` は独自のモデルをトレーニングまたはファインチューニングした場合のモデルチェックポイントへのパス、空白の場合はhuggingfaceからデフォルトモデルを自動ダウンロード(`seed-uvit-whisper-base`)
|
| 84 |
+
- `config` は独自のモデルをトレーニングまたはファインチューニングした場合のモデル設定へのパス、空白の場合はhuggingfaceからデフォルト設定を自動ダウンロード
|
| 85 |
+
|
| 86 |
+
統合Web UI:
|
| 87 |
+
```bash
|
| 88 |
+
python app.py
|
| 89 |
+
```
|
| 90 |
+
これはゼロショット推論用の事前学習済みモデルのみを読み込みます。カスタムチェックポイントを使用する場合は、上記の`app_vc.py`または`app_svc.py`を実行してください。
|
| 91 |
+
|
| 92 |
+
リアルタイム音声変換GUI:
|
| 93 |
+
```bash
|
| 94 |
+
python real-time-gui.py --checkpoint-path <path-to-checkpoint> --config-path <path-to-config>
|
| 95 |
+
```
|
| 96 |
+
- `checkpoint` は独自のモデルをトレーニングまたはファインチューニングした場合のモデルチェックポイントへのパス、空白の場合はhuggingfaceからデフォルトモデルを自動ダウンロード(`seed-uvit-tat-xlsr-tiny`)
|
| 97 |
+
- `config` は独自のモデルをトレーニングまたはファインチューニングした場合のモデル設定へのパス、空白の場合はhuggingfaceからデフォルト設定を自動ダウンロード
|
| 98 |
+
|
| 99 |
+
重要:リアルタイム音声変換にはGPUの使用を強く推奨します。
|
| 100 |
+
NVIDIA RTX 3060ノートパソコンGPUでいくつかのパフォーマンステストを行い、結果と推奨パラメータ設定を以下に示します:
|
| 101 |
+
|
| 102 |
+
| モデル構成 | 拡散ステップ | 推論CFGレート | 最大プロンプト長 | ブロック時間 (秒) | クロスフェード長 (秒) | 追加コンテキスト (左) (秒) | 追加コンテキスト (右) (秒) | レイテンシ (ミリ秒) | チャンクあたりの推論時間 (ミリ秒) |
|
| 103 |
+
|---------------------------------|-----------------|--------------------|-------------------|----------------|----------------------|--------------------------|---------------------------|--------------|-------------------------------|
|
| 104 |
+
| seed-uvit-xlsr-tiny | 10 | 0.7 | 3.0 | 0.18 | 0.04 | 2.5 | 0.02 | 430 | 150 |
|
| 105 |
+
|
| 106 |
+
GUIでパラメータを自身のデバイスのパフォーマンスに合わせて調整できます。推論時間がブロック時間より短ければ、音声変換ストリームは正常に動作するはずです。
|
| 107 |
+
他のGPU集約型タスク(ゲーム、動画視聴など)を実行している場合、推論速度が低下する可能性があることに注意してください。
|
| 108 |
+
|
| 109 |
+
リアルタイム音声変換GUIのパラメータ説明:
|
| 110 |
+
- `Diffusion Steps` は拡散ステップ数、リアルタイム変換の場合は通常4~10で最速推論
|
| 111 |
+
- `Inference CFG Rate` は出力に微妙な違いをもたらす、デフォルトは0.7、0.0に設定すると1.5倍の推論速度が向上
|
| 112 |
+
- `Max Prompt Length` は最大プロンプト長、設定を低くすると推論速度が速くなるが、提示音声との類似性が低下する可能性がある
|
| 113 |
+
- `Block Time` は推論の各オーディオ チャンクの時間長です。値が大きいほどレイテンシが長くなります。この値はブロックあたりの推論時間よりも長くする必要があることに注意してください。ハードウェアの状態に応じて設定します。
|
| 114 |
+
- `Crossfade Length` はクロスフェード長、通常は変更しない
|
| 115 |
+
- `Extra context (left)` は推論のための追加履歴コンテキストの時間長です。値が高いほど推論時間は長くなりますが、安定性は向上します。
|
| 116 |
+
- `Extra context (right)` は推論のための追加未来コンテキストの時間長です。値が高いほど推論時間とレイテンシは長くなりますが、安定性は向上します。
|
| 117 |
+
|
| 118 |
+
アルゴリズムレイテンシーは`Block Time * 2 + Extra context (right)`で、デバイス側レイテンシーは通常100ms程度です。全体の遅延は 2 つの合計です。
|
| 119 |
+
|
| 120 |
+
[VB-CABLE](https://vb-audio.com/Cable/)を使用して、GUI出力ストリームを仮想マイクにルーティングすることができます。
|
| 121 |
+
|
| 122 |
+
*(GUIとオーディオチャンキングのロジックは[RVC](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI)から修正されています。素晴らしい実装に感謝します!)*
|
| 123 |
+
|
| 124 |
+
## トレーニング🏋️
|
| 125 |
+
カスタムデータでのファインチューニングにより、より正確に声をクローニングすることができます。特定の話者に対する話者類似性が大幅に向上しますが、WERが若干上昇する可能性があります。
|
| 126 |
+
以下のColabチュートリアルで手順を確認できます:[](https://colab.research.google.com/drive/1R1BJTqMsTXZzYAVx3j1BiemFXog9pbQG?usp=sharing)
|
| 127 |
+
|
| 128 |
+
1. 独自のデータセットを準備します。以下の条件を満たす必要があります:
|
| 129 |
+
- ファイル構造は問いません
|
| 130 |
+
- 各音声ファイルは1〜30秒の範囲である必要があり、それ以外は無視されます
|
| 131 |
+
- すべての音声ファイルは以下のいずれかの形式である必要があります:`.wav` `.flac` `.mp3` `.m4a` `.opus` `.ogg`
|
| 132 |
+
- 話者ラベルは必須ではありませんが、各話者に少なくとも1つの発話があることを確認してください
|
| 133 |
+
- もちろん、データが多いほどモデルのパフォーマンスは向上します
|
| 134 |
+
- トレーニングデータはできるだけクリーンである必要があり、BGMやノイズは望ましくありません
|
| 135 |
+
|
| 136 |
+
2. ファインチューニング用に`configs/presets/`からモデル設定ファイルを選択するか、ゼロからトレーニングするための独自の設定を作成します。
|
| 137 |
+
- ファインチューニングの場合は、以下のいずれかを選択します:
|
| 138 |
+
- `./configs/presets/config_dit_mel_seed_uvit_xlsr_tiny.yml` リアルタイム音声変換用
|
| 139 |
+
- `./configs/presets/config_dit_mel_seed_uvit_whisper_small_wavenet.yml` オフライン音声変換用
|
| 140 |
+
- `./configs/presets/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml` 歌声変換用
|
| 141 |
+
|
| 142 |
+
3. 以下のコマンドでトレーニングを開始します:
|
| 143 |
+
```bash
|
| 144 |
+
python train.py
|
| 145 |
+
--config <path-to-config>
|
| 146 |
+
--dataset-dir <path-to-data>
|
| 147 |
+
--run-name <run-name>
|
| 148 |
+
--batch-size 2
|
| 149 |
+
--max-steps 1000
|
| 150 |
+
--max-epochs 1000
|
| 151 |
+
--save-every 500
|
| 152 |
+
--num-workers 0
|
| 153 |
+
```
|
| 154 |
+
各パラメータの説明:
|
| 155 |
+
- `config` はモデル設定へのパス、ファインチューニング用に上記のいずれかを選択するか、ゼロからトレーニングする場合は独自の設定を作成
|
| 156 |
+
- `dataset-dir` はデータセットディレクトリへのパス、すべての音声ファイルを含むフォルダである必要があります
|
| 157 |
+
- `run-name` は実行名で、モデルチェックポイントとログの保存に使用されます
|
| 158 |
+
- `batch-size` はトレーニング用のバッチサイズで、GPUメモリに応じて選択します
|
| 159 |
+
- `max-steps` は最大トレーニングステッ��数で、データセットサイズとトレーニング時間に応じて選択します
|
| 160 |
+
- `max-epochs` は最大エポック数で、データセットサイズとトレーニング時間に応じて選択します
|
| 161 |
+
- `save-every` はモデルチェックポイントを保存するステップ間隔
|
| 162 |
+
- `num-workers` はデータ読み込みのワーカー数、Windowsの場合は0に設定
|
| 163 |
+
|
| 164 |
+
4. トレーニングが予期せず停止した場合、同じコマンドを再度実行することで、最後のチェックポイントから再開できます(最新のチェックポイントを見つけられるように、`run-name`と`config`引数が同じであることを確認してください)。
|
| 165 |
+
|
| 166 |
+
5. トレーニング後、チェックポイントと設定ファイルのパスを指定することで、トレーニングしたモデルを推論に使用できます。
|
| 167 |
+
- これらは`./runs/<run-name>/`の下にあり、チェックポイントは`ft_model.pth`という名前で、設定ファイルはトレーニング設定ファイルと同じ名前です。
|
| 168 |
+
- 推論時には、ゼロショット使用時と同様に、使用したい話者の参照音声ファイルを指定する必要があります。
|
| 169 |
+
|
| 170 |
+
## TODO📝
|
| 171 |
+
- [x] コードのリリース
|
| 172 |
+
- [x] 事前学習済みモデルのリリース:[](https://huggingface.co/Plachta/Seed-VC)
|
| 173 |
+
- [x] Huggingfaceスペースデモ:[](https://huggingface.co/spaces/Plachta/Seed-VC)
|
| 174 |
+
- [x] HTMLデモページ:[Demo](https://plachtaa.github.io/seed-vc/)
|
| 175 |
+
- [x] ストリーミング推論
|
| 176 |
+
- [x] ストリーミング推論のレイテンシー削減
|
| 177 |
+
- [x] リアルタイム音声変換のデモ動画
|
| 178 |
+
- [x] 歌声変換
|
| 179 |
+
- [x] ソース音声のノイズ耐性
|
| 180 |
+
- [ ] アーキテクチャの潜在的な改善
|
| 181 |
+
- [x] U-ViTスタイルのスキップ接続
|
| 182 |
+
- [x] OpenAI Whisperへの入力変更
|
| 183 |
+
- [x] Time as Token
|
| 184 |
+
- [x] カスタムデータでのトレーニングコード
|
| 185 |
+
- [x] フューショット/ワンショット話者ファインチューニング
|
| 186 |
+
- [x] 歌声デコーディング用にNVIDIAのBigVGANに変更
|
| 187 |
+
- [x] 歌声変換用のWhisperバージョンモデル
|
| 188 |
+
- [x] 歌声変換のRVC/SoVITSとの客観的評価と比較
|
| 189 |
+
- [x] 音声品質の向上
|
| 190 |
+
- [ ] より良い歌声変換のためのNSFボコーダ
|
| 191 |
+
- [x] 非発話時のリアルタイム音声変換アーティファクトの修正(VADモデルの追加により対応)
|
| 192 |
+
- [x] ファインチューニング例のColabノートブック
|
| 193 |
+
- [ ] Whisperをより高度な意味抽出器に置き換える
|
| 194 |
+
- [ ] 今後追加予定
|
| 195 |
+
|
| 196 |
+
## 更新履歴🗒️
|
| 197 |
+
- 2024-11-26:
|
| 198 |
+
- リアルタイム音声変換用に最適化されたv1.0 tinyバージョンの事前学習済みモデルを更新
|
| 199 |
+
- ワンショット/フューショットの単一/複数話者ファインチューニングをサポート
|
| 200 |
+
- webUIおよびリアルタイムGUIでカスタムチェックポイントの使用をサポート
|
| 201 |
+
- 2024-11-19:
|
| 202 |
+
- arXiv論文公開
|
| 203 |
+
- 2024-10-28:
|
| 204 |
+
- より良い音声品質のファインチューニングされた44k歌声変換モデルを更新
|
| 205 |
+
- 2024-10-27:
|
| 206 |
+
- リアルタイム音声変換GUIを追加
|
| 207 |
+
- 2024-10-25:
|
| 208 |
+
- 歌声変換のRVCv2との包括的な評価結果と比較を追加
|
| 209 |
+
- 2024-10-24:
|
| 210 |
+
- 音声コンテンツ入力としてOpenAI Whisperを使用した44kHz歌声変換モデルを更新
|
| 211 |
+
- 2024-10-07:
|
| 212 |
+
- 音声コンテンツエンコーダをOpenAI Whisperに変更したv0.3事前学習済みモデルを更新
|
| 213 |
+
- v0.3事前学習済みモデルの客観的評価結果を追加
|
| 214 |
+
- 2024-09-22:
|
| 215 |
+
- NVIDIAのBigVGANを使用する歌声変換モデルを更新し、高音域の歌声を大幅に改善
|
| 216 |
+
- Web UIで長い音声ファイルのチャンキングとストリーミング出力をサポート
|
| 217 |
+
- 2024-09-18:
|
| 218 |
+
- 歌声変換用のf0条件付きモデルを更新
|
| 219 |
+
- 2024-09-14:
|
| 220 |
+
- 同じ品質を達成するためのサイズ縮小と拡散ステップ数の削減、およびプロソディ保持の制御能力を追加したv0.2事前学習済みモデルを更新
|
| 221 |
+
- コマンドライン推論スクリプトを追加
|
| 222 |
+
- インストールと使用方法の説明を追加
|
| 223 |
+
|
| 224 |
+
## 謝辞🙏
|
| 225 |
+
- [Amphion](https://github.com/open-mmlab/Amphion) for providing computational resources and inspiration!
|
| 226 |
+
- [RVC](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI) for foundationing the real-time voice conversion
|
| 227 |
+
- [SEED-TTS](https://arxiv.org/abs/2406.02430) for the initial idea
|
seed-vc/README-ZH.md
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Seed-VC
|
| 2 |
+
[](https://huggingface.co/spaces/Plachta/Seed-VC) [](https://arxiv.org/abs/2411.09943)
|
| 3 |
+
|
| 4 |
+
*English | [简体中文](README-ZH.md) | [日本語](README-JA.md)*
|
| 5 |
+
|
| 6 |
+
[real-time-demo.webm](https://github.com/user-attachments/assets/86325c5e-f7f6-4a04-8695-97275a5d046c)
|
| 7 |
+
|
| 8 |
+
目前发布的模型支持 *零样本语音转换* 🔊 、*零样本实时语音转换* 🗣️ 和 *零样本歌声转换* 🎶。无需任何训练,只需1~30秒的参考语音,即可克隆声音。
|
| 9 |
+
|
| 10 |
+
我们支持进一步使用自定义数据进行微调,以提高特定说话人的性能,数据需求门槛极低 **(每位说话人至少1条语音)** ,训练速度极快 **(最少100步,在T4上只需2分钟)**!
|
| 11 |
+
|
| 12 |
+
**实时语音转换** 支持约300ms的算法延迟和约100ms的设备侧延迟,适用于在线会议、游戏和直播。
|
| 13 |
+
|
| 14 |
+
要查看演示和与之前语音转换模型的比较,请访问我们的[演示页面](https://plachtaa.github.io/seed-vc/)🌐 和 [评估结果](EVAL.md)📊。
|
| 15 |
+
|
| 16 |
+
我们会不断改进模型质量并增加更多功能。
|
| 17 |
+
|
| 18 |
+
## 评估📊
|
| 19 |
+
查看 [EVAL.md](EVAL.md) 获取客观评估结果和与其他基准模型的比较。
|
| 20 |
+
|
| 21 |
+
## 使用🛠️
|
| 22 |
+
我们已发布用于不同目的的3个模型:
|
| 23 |
+
|
| 24 |
+
| 版本 | 模型名称 | 用途 | 采样率 | Content编码器 | 声码器 | 隐藏层维度 | 层数 | 参数量 | 备注 |
|
| 25 |
+
|------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|-------|---------------|---------|-------|----|------|--------------------|
|
| 26 |
+
| v1.0 | seed-uvit-tat-xlsr-tiny ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_uvit_tat_xlsr_ema.pth)[📄](configs/presets/config_dit_mel_seed_uvit_xlsr_tiny.yml)) | 声音转换 (VC) | 22050 | XLSR-large | HIFT | 384 | 9 | 25M | 适合实时语音转换 |
|
| 27 |
+
| v1.0 | seed-uvit-whisper-small-wavenet ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth)[📄](configs/presets/config_dit_mel_seed_uvit_whisper_small_wavenet.yml)) | 声音转换 (VC) | 22050 | Whisper-small | BigVGAN | 512 | 13 | 98M | 性能更好但推理稍慢,适合离线语音转换 |
|
| 28 |
+
| v1.0 | seed-uvit-whisper-base ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema.pth)[📄](configs/presets/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml)) | 歌声转换 (SVC) | 44100 | Whisper-small | BigVGAN | 768 | 17 | 200M | 强大的零样本推理能力,用于歌声转换 |
|
| 29 |
+
|
| 30 |
+
首次推理时将自动下载最新模型的检查点。 如果因网络原因无法访问 Hugging Face,请尝试在每个命令前添加 `HF_ENDPOINT=https://hf-mirror.com` 使用镜像站。
|
| 31 |
+
|
| 32 |
+
命令行推理:
|
| 33 |
+
```bash
|
| 34 |
+
python inference.py --source <source-wav>
|
| 35 |
+
--target <referene-wav>
|
| 36 |
+
--output <output-dir>
|
| 37 |
+
--diffusion-steps 25 # 推荐为歌声转换设置为30~50
|
| 38 |
+
--length-adjust 1.0
|
| 39 |
+
--inference-cfg-rate 0.7
|
| 40 |
+
--f0-condition False # 设置为 True 进行歌声转换
|
| 41 |
+
--auto-f0-adjust False # 设置为 True 自动调整源音高至目标音高,通常不用于歌声转换(会导致歌声与BGM调性不一致)
|
| 42 |
+
--semi-tone-shift 0 # 歌声转换中的音高移位(半音)
|
| 43 |
+
--checkpoint <path-to-checkpoint>
|
| 44 |
+
--config <path-to-config>
|
| 45 |
+
```
|
| 46 |
+
参数说明:
|
| 47 |
+
- `source` 要转换为参考声音的语音文件路径
|
| 48 |
+
- `target` 作为声音参考的语音文件路径
|
| 49 |
+
- `output` 输出目录的路径
|
| 50 |
+
- `diffusion-steps` 使用的扩散步数,默认为 25,质量最佳使用 30-50,最快推理使用 4-10
|
| 51 |
+
- `length-adjust` 长度调整因子,默认值为 1.0,设置 <1.0 加速语音,>1.0 减慢语音
|
| 52 |
+
- `inference-cfg-rate` classifier free guidance rate,默认为 0.7
|
| 53 |
+
- `f0-condition` 是否对输出音高进行调节,默认为 False,设置为 True 用于歌声转换
|
| 54 |
+
- `auto-f0-adjust` 是否自动调整源音高到目标音高,默认为 False,通常不用于歌声转换
|
| 55 |
+
- `semi-tone-shift` 歌声转换中的音高移位(半音),默认值为 0
|
| 56 |
+
- `checkpoint` 如果已训练或微调自己的模型,请指定模型检查点路径,若留空将自动下载 Hugging Face 的默认模型(`seed-uvit-whisper-small-wavenet` if `f0-condition` is `False` else `seed-uvit-whisper-base`)
|
| 57 |
+
- `config` 如果已训练或微调自己的模型,请指定模型配置文件路径,若留空将自动下载 Hugging Face 的默认配置
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
语音转换 Web UI:
|
| 61 |
+
```bash
|
| 62 |
+
python app_vc.py --checkpoint <path-to-checkpoint> --config <path-to-config>
|
| 63 |
+
```
|
| 64 |
+
- `checkpoint` 模型检查点路径,若为空将自动下载默认模型 (`seed-uvit-whisper-small-wavenet`)
|
| 65 |
+
- `config` 模型配置文件路径,若为空将自动下载默认配置
|
| 66 |
+
|
| 67 |
+
然后在浏览器中打开 `http://localhost:7860/` 使用 Web 界面。
|
| 68 |
+
|
| 69 |
+
运行命令前先设置环境变量:
|
| 70 |
+
`export export HUGGING_FACE_HUB_TOKEN={从https://huggingface.co/settings/tokens获取}`
|
| 71 |
+
|
| 72 |
+
歌声转换 Web UI:
|
| 73 |
+
```bash
|
| 74 |
+
python app_svc.py --checkpoint <path-to-checkpoint> --config <path-to-config>
|
| 75 |
+
```
|
| 76 |
+
- `checkpoint` 模型检查点路径,若为空将自动下载默认模型 (`seed-uvit-whisper-base`)
|
| 77 |
+
- `config` 模型配置文件路径,若为空将自动下载默认配置
|
| 78 |
+
|
| 79 |
+
集成 Web UI:
|
| 80 |
+
```bash
|
| 81 |
+
python app.py
|
| 82 |
+
```
|
| 83 |
+
此命令将仅加载预训练模型进行零样本推理。要使用自定义检查点,请按上述步骤运行 `app_vc.py` 或 `app_svc.py`。
|
| 84 |
+
|
| 85 |
+
实时语音转换 GUI:
|
| 86 |
+
```bash
|
| 87 |
+
python real-time-gui.py --checkpoint-path <path-to-checkpoint> --config-path <path-to-config>
|
| 88 |
+
```
|
| 89 |
+
- `checkpoint` 模型检查点路径,若为空将自动下载默认模型 (`seed-uvit-tat-xlsr-tiny`)
|
| 90 |
+
- `config` 模型配置文件路径,若为空将自动下载默认配置
|
| 91 |
+
|
| 92 |
+
重要提示: 强烈建议使用 GPU 进行实时语音转换。 在 NVIDIA RTX 3060 笔记本 GPU 上进行了一些性能测试,结果和推荐参数设置如下:
|
| 93 |
+
|
| 94 |
+
| 模型配置 | 扩散步数 | Inference CFG Rate | 最大prompt长度 | 每块时间 (s) | 交叉淡化长度 (s) | 额外上下文(左)(s) | 额外上下文(右)(s) | 延迟 (ms) | 每块推理时间 (ms) |
|
| 95 |
+
|---------------------|------|--------------------|------------|----------|------------|-------------|-------------|---------|-------------|
|
| 96 |
+
| seed-uvit-xlsr-tiny | 10 | 0.7 | 3.0 | 0.18s | 0.04s | 2.5s | 0.02s | 430ms | 150ms |
|
| 97 |
+
|
| 98 |
+
你可以根据设备性能调整 GUI 中的参数,只要推理时间小于块时间,语音转换流就可以正常工作。 注意,如果你正在运行其他占用 GPU 的任务(如游戏、看视频),推理速度可能会下降。
|
| 99 |
+
|
| 100 |
+
实时转换界面的参数说明:
|
| 101 |
+
- `Diffusion Steps` 是扩散步数,推荐实时转换设置为4~10;
|
| 102 |
+
- `Inference CFG Rate` 是classifier free guidance rate,默认0.7,设置为0.0可以获得1.5x的加速;
|
| 103 |
+
- `Max Prompt Length` 是最大音频提示长度,设置为较低值可以加快推理速度,但可能会降低与提示语音的相似度;
|
| 104 |
+
- `Block Time` 是每块时间,值越高延迟越高,该值必须大于每块推理时间,根据硬件条件设置;
|
| 105 |
+
- `Crossfade Length` 是交叉淡化长度,通常不需要更改;
|
| 106 |
+
- `Extra context (left)` 是推理的额外上下文,设置为较高值可以增加稳定性,但会增加每块推理时间;
|
| 107 |
+
- `Extra context (right)` 是推理的额外上下文,设置为较高值可以增加稳定性,但会增加每块推理时间以及延迟;
|
| 108 |
+
|
| 109 |
+
算法延迟大约为 `Block Time * 2 + Extra context (right)`,设备侧延迟通常为100ms左右。总体延迟为两者之和。
|
| 110 |
+
|
| 111 |
+
你可以使用 [VB-CABLE](https://vb-audio.com/Cable/) 将变声器输出映射到一个虚拟麦克风上,以便其它应用读取.
|
| 112 |
+
|
| 113 |
+
*(GUI and audio chunking logic are modified from [RVC](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI), thanks for their brilliant implementation!)*
|
| 114 |
+
|
| 115 |
+
## 训练🏋️
|
| 116 |
+
在自定义数据上进行微调可以让模型更精确地克隆某个人的声音。这将大幅提高特定说话人的相似度,但可能会略微增加 WER(词错误率)。
|
| 117 |
+
这里是一个简单的Colab示例以供参考: [](https://colab.research.google.com/drive/1R1BJTqMsTXZzYAVx3j1BiemFXog9pbQG?usp=sharing)
|
| 118 |
+
1. 准备您的数据集。必须满足以下要求:
|
| 119 |
+
- 文件结构不重要
|
| 120 |
+
- 每条音频长度必须在1-30秒之间,否则会被自动忽略
|
| 121 |
+
- 所有音频文件必须是以下格式之一:`.wav` `.flac` `.mp3` `.m4a` `.opus` `.ogg`
|
| 122 |
+
- 不需要说话人标签,但请确保每位说话人至少有 1 条语音
|
| 123 |
+
- 当然,数据越多,模型的表现就越好
|
| 124 |
+
- 训练样本应该选择尽量干净,不带背景音乐或噪音的音频
|
| 125 |
+
2. 从 `configs/presets/` 中选择一个模型配置文件进行微调,或者创建自己的配置文件从头开始训练。
|
| 126 |
+
- 对于微调,可以选择以下配置之一:
|
| 127 |
+
- `./configs/presets/config_dit_mel_seed_uvit_xlsr_tiny.yml` 用于实时语音转换
|
| 128 |
+
- `./configs/presets/config_dit_mel_seed_uvit_whisper_small_wavenet.yml` 用于离线语音转换
|
| 129 |
+
- `./configs/presets/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml` 用于歌声转换
|
| 130 |
+
3. 运行以下命令开始训练:
|
| 131 |
+
```bash
|
| 132 |
+
python train.py
|
| 133 |
+
--config <path-to-config>
|
| 134 |
+
--dataset-dir <path-to-data>
|
| 135 |
+
--run-name <run-name>
|
| 136 |
+
--batch-size 2
|
| 137 |
+
--max-steps 1000
|
| 138 |
+
--max-epochs 1000
|
| 139 |
+
--save-every 500
|
| 140 |
+
--num-workers 0
|
| 141 |
+
```
|
| 142 |
+
where:
|
| 143 |
+
- `config` 模型配置文件路径,选择上面之一进行微调,或者创建自己的配置文件从头开始训练
|
| 144 |
+
- `dataset-dir` 数据集目录路径,应为包含所有音频文件的文件夹
|
| 145 |
+
- `run-name` 运行名称,用于保存模型检查点和日志
|
| 146 |
+
- `batch-size` 训练的批大小,根据 GPU 内存选择
|
| 147 |
+
- `max-steps` 最大训练步数,取决于数据集大小和训练时间
|
| 148 |
+
- `max-epochs` 最大训练轮数,取决于数据集大小和训练时间
|
| 149 |
+
- `save-every` 保存模型检查点的步数
|
| 150 |
+
- `num-workers` 数据加载的工作线程数量,建议 Windows 上设置为 0
|
| 151 |
+
|
| 152 |
+
4. 如果需要从上次停止的地方继续训练,只需运行同样的命令即可。通过传入相同的 `run-name` 和 `config` 参数,程序将能够找到上次训练的检查点和日志。
|
| 153 |
+
|
| 154 |
+
5. 训练完成后,您可以通过指定检查点和配置文件的路径来进行推理。
|
| 155 |
+
- 它们应位于 `./runs/<run-name>/` 下,检查点命名为 `ft_model.pth`,配置文件名称与训练配置文件相同。
|
| 156 |
+
- 在推理时,您仍需指定要使用的说话人的参考音频文件,类似于零样本推理。
|
| 157 |
+
|
| 158 |
+
## TODO📝
|
| 159 |
+
- [x] 发布代码
|
| 160 |
+
- [x] 发布预训练模型: [](https://huggingface.co/Plachta/Seed-VC)
|
| 161 |
+
- [x] Hugging Face Space 演示: [](https://huggingface.co/spaces/Plachta/Seed-VC)
|
| 162 |
+
- [x] HTML 演示页面: [Demo](https://plachtaa.github.io/seed-vc/)
|
| 163 |
+
- [x] 流式推理
|
| 164 |
+
- [x] 降低延迟
|
| 165 |
+
- [x] 实时变声Demo视频
|
| 166 |
+
- [x] 歌声转换
|
| 167 |
+
- [x] 提高源音频抗噪性
|
| 168 |
+
- [ ] 潜在的架构改进
|
| 169 |
+
- [x] 类似U-ViT 的skip connection
|
| 170 |
+
- [x] 将输入更改为 OpenAI Whisper
|
| 171 |
+
- [x] Time as Token
|
| 172 |
+
- [x] 自定义数据训练代码
|
| 173 |
+
- [x] 单样本/少样本说话人微调
|
| 174 |
+
- [x] 歌声解码器更改为 NVIDIA 的 BigVGAN
|
| 175 |
+
- [x] 44k Hz 歌声转换模型
|
| 176 |
+
- [x] 歌声转换的客观指标评估以及与RVC/SoVITS模型的比较
|
| 177 |
+
- [x] 提升音质
|
| 178 |
+
- [ ] 用于改善歌声转换的NSF歌声解码器
|
| 179 |
+
- [x] 实时变声脚本添加了VAD模型,避免没有说话时模型输出杂音
|
| 180 |
+
- [x] Google Colab 笔记本训练脚本以及样例
|
| 181 |
+
- [ ] 替换whisper为更先进的语义内容提取器
|
| 182 |
+
- [ ] 更多待添加
|
| 183 |
+
|
| 184 |
+
## 更新日志 🗒️
|
| 185 |
+
- 2024-11-26:
|
| 186 |
+
- 更新 v1.0 更小版本的预训练模型,优化实时语音转换
|
| 187 |
+
- 支持单样本/少样本的单/多说话人微调
|
| 188 |
+
- 支持在 WebUI 和实时变声 GUI 中使用自定义检查点
|
| 189 |
+
- 2024-11-19:
|
| 190 |
+
- paper已提交至arXiv
|
| 191 |
+
- 2024-10-27:
|
| 192 |
+
- 更新了实时变声脚本
|
| 193 |
+
- 2024-10-25:
|
| 194 |
+
- 添加了详尽的歌声转换评估结果以及与RVCv2模型的比较
|
| 195 |
+
- 2024-10-24:
|
| 196 |
+
- 更新了44kHz歌声转换模型
|
| 197 |
+
- 2024-10-07:
|
| 198 |
+
- 更新了 v0.3 预训练模型,将语音内容编码器更改为 OpenAI Whisper
|
| 199 |
+
- 添加了 v0.3 预训练模型的客观指标评估结果
|
| 200 |
+
- 2024-09-22:
|
| 201 |
+
- 将歌声转换模型的解码器更改为 BigVGAN,解决了大部分高音部分无法正确转换的问题
|
| 202 |
+
- 在Web UI中支持对长输入音频的分段处理以及流式输出
|
| 203 |
+
- 2024-09-18:
|
| 204 |
+
- 更新了用于歌声转换的模型
|
| 205 |
+
- 2024-09-14:
|
| 206 |
+
- 更新了 v0.2 预训练模型,具有更小的尺寸和更少的扩散步骤即可达到相同质量,且增加了控制韵律保留的能力
|
| 207 |
+
- 添加了命令行推理脚本
|
| 208 |
+
- 添加了安装和使用说明
|
| 209 |
+
|
| 210 |
+
## 鸣谢🙏
|
| 211 |
+
- [Amphion](https://github.com/open-mmlab/Amphion) for providing computational resources and inspiration!
|
| 212 |
+
- [RVC](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI) for foundationing the real-time voice conversion
|
| 213 |
+
- [SEED-TTS](https://arxiv.org/abs/2406.02430) for the initial idea
|
seed-vc/README.md
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Seed-VC
|
| 2 |
+
[](https://huggingface.co/spaces/Plachta/Seed-VC) [](https://arxiv.org/abs/2411.09943)
|
| 3 |
+
|
| 4 |
+
*English | [简体中文](README-ZH.md) | [日本語](README-JA.md)*
|
| 5 |
+
|
| 6 |
+
[real-time-demo.webm](https://github.com/user-attachments/assets/86325c5e-f7f6-4a04-8695-97275a5d046c)
|
| 7 |
+
|
| 8 |
+
Currently released model supports *zero-shot voice conversion* 🔊 , *zero-shot real-time voice conversion* 🗣️ and *zero-shot singing voice conversion* 🎶. Without any training, it is able to clone a voice given a reference speech of 1~30 seconds.
|
| 9 |
+
|
| 10 |
+
We support further fine-tuning on custom data to increase performance on specific speaker/speakers, with extremely low data requirement **(minimum 1 utterance per speaker)** and extremely fast training speed **(minimum 100 steps, 2 min on T4)**!
|
| 11 |
+
|
| 12 |
+
**Real-time voice conversion** is support, with algorithm delay of ~300ms and device side delay of ~100ms, suitable for online meetings, gaming and live streaming.
|
| 13 |
+
|
| 14 |
+
To find a list of demos and comparisons with previous voice conversion models, please visit our [demo page](https://plachtaa.github.io/seed-vc/)🌐 and [Evaluaiton](EVAL.md)📊.
|
| 15 |
+
|
| 16 |
+
We are keeping on improving the model quality and adding more features.
|
| 17 |
+
|
| 18 |
+
## Evaluation📊
|
| 19 |
+
See [EVAL.md](EVAL.md) for objective evaluation results and comparisons with other baselines.
|
| 20 |
+
## Installation📥
|
| 21 |
+
Suggested python 3.10 on Windows, Mac M Series (Apple Silicon) or Linux.
|
| 22 |
+
Windows and Linux:
|
| 23 |
+
```bash
|
| 24 |
+
pip install -r requirements.txt
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Mac M Series:
|
| 28 |
+
```bash
|
| 29 |
+
pip install -r requirements-mac.txt
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
For Windows users, you may consider install `triton-windows` to enable `--compile` usage, which gains speed up on V2 models:
|
| 33 |
+
```bash
|
| 34 |
+
pip install triton-windows==3.2.0.post13
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
## Usage🛠️
|
| 38 |
+
We have released 4 models for different purposes:
|
| 39 |
+
|
| 40 |
+
| Version | Name | Purpose | Sampling Rate | Content Encoder | Vocoder | Hidden Dim | N Layers | Params | Remarks |
|
| 41 |
+
|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------|---------------|------------------------------------------------------------------------|---------|------------|----------|--------------------|--------------------------------------------------------|
|
| 42 |
+
| v1.0 | seed-uvit-tat-xlsr-tiny ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_uvit_tat_xlsr_ema.pth)[📄](configs/presets/config_dit_mel_seed_uvit_xlsr_tiny.yml)) | Voice Conversion (VC) | 22050 | XLSR-large | HIFT | 384 | 9 | 25M | suitable for real-time voice conversion |
|
| 43 |
+
| v1.0 | seed-uvit-whisper-small-wavenet ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth)[📄](configs/presets/config_dit_mel_seed_uvit_whisper_small_wavenet.yml)) | Voice Conversion (VC) | 22050 | Whisper-small | BigVGAN | 512 | 13 | 98M | suitable for offline voice conversion |
|
| 44 |
+
| v1.0 | seed-uvit-whisper-base ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema.pth)[📄](configs/presets/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml)) | Singing Voice Conversion (SVC) | 44100 | Whisper-small | BigVGAN | 768 | 17 | 200M | strong zero-shot performance, singing voice conversion |
|
| 45 |
+
| v2.0 | hubert-bsqvae-small ([🤗](https://huggingface.co/Plachta/Seed-VC/blob/main/v2)[📄](configs/v2/vc_wrapper.yaml)) | Voice & Accent Conversion (VC) | 22050 | [ASTRAL-Quantization](https://github.com/Plachtaa/ASTRAL-quantization) | BigVGAN | 512 | 13 | 67M(CFM) + 90M(AR) | Best in suppressing source speaker traits |
|
| 46 |
+
|
| 47 |
+
Checkpoints of the latest model release will be downloaded automatically when first run inference.
|
| 48 |
+
If you are unable to access huggingface for network reason, try using mirror by adding `HF_ENDPOINT=https://hf-mirror.com` before every command.
|
| 49 |
+
|
| 50 |
+
Command line inference:
|
| 51 |
+
```bash
|
| 52 |
+
python inference.py --source <source-wav>
|
| 53 |
+
--target <referene-wav>
|
| 54 |
+
--output <output-dir>
|
| 55 |
+
--diffusion-steps 25 # recommended 30~50 for singingvoice conversion
|
| 56 |
+
--length-adjust 1.0
|
| 57 |
+
--inference-cfg-rate 0.7
|
| 58 |
+
--f0-condition False # set to True for singing voice conversion
|
| 59 |
+
--auto-f0-adjust False # set to True to auto adjust source pitch to target pitch level, normally not used in singing voice conversion
|
| 60 |
+
--semi-tone-shift 0 # pitch shift in semitones for singing voice conversion
|
| 61 |
+
--checkpoint <path-to-checkpoint>
|
| 62 |
+
--config <path-to-config>
|
| 63 |
+
--fp16 True
|
| 64 |
+
```
|
| 65 |
+
where:
|
| 66 |
+
- `source` is the path to the speech file to convert to reference voice
|
| 67 |
+
- `target` is the path to the speech file as voice reference
|
| 68 |
+
- `output` is the path to the output directory
|
| 69 |
+
- `diffusion-steps` is the number of diffusion steps to use, default is 25, use 30-50 for best quality, use 4-10 for fastest inference
|
| 70 |
+
- `length-adjust` is the length adjustment factor, default is 1.0, set <1.0 for speed-up speech, >1.0 for slow-down speech
|
| 71 |
+
- `inference-cfg-rate` has subtle difference in the output, default is 0.7
|
| 72 |
+
- `f0-condition` is the flag to condition the pitch of the output to the pitch of the source audio, default is False, set to True for singing voice conversion
|
| 73 |
+
- `auto-f0-adjust` is the flag to auto adjust source pitch to target pitch level, default is False, normally not used in singing voice conversion
|
| 74 |
+
- `semi-tone-shift` is the pitch shift in semitones for singing voice conversion, default is 0
|
| 75 |
+
- `checkpoint` is the path to the model checkpoint if you have trained or fine-tuned your own model, leave to blank to auto-download default model from huggingface.(`seed-uvit-whisper-small-wavenet` if `f0-condition` is `False` else `seed-uvit-whisper-base`)
|
| 76 |
+
- `config` is the path to the model config if you have trained or fine-tuned your own model, leave to blank to auto-download default config from huggingface
|
| 77 |
+
- `fp16` is the flag to use float16 inference, default is True
|
| 78 |
+
|
| 79 |
+
Similarly, to use V2 model, you can run:
|
| 80 |
+
```bash
|
| 81 |
+
python inference_v2.py --source <source-wav>
|
| 82 |
+
--target <referene-wav>
|
| 83 |
+
--output <output-dir>
|
| 84 |
+
--diffusion-steps 25 # recommended 30~50 for singingvoice conversion
|
| 85 |
+
--length-adjust 1.0 # same as V1
|
| 86 |
+
--intelligibility-cfg-rate 0.7 # controls how clear the output linguistic content is, recommended 0.0~1.0
|
| 87 |
+
--similarity-cfg-rate 0.7 # controls how similar the output voice is to the reference voice, recommended 0.0~1.0
|
| 88 |
+
--convert-style true # whether to use AR model for accent & emotion conversion, set to false will only conduct timbre conversion similar to V1
|
| 89 |
+
--anonymization-only false # set to true will ignore reference audio but only anonymize source speech to an "average voice"
|
| 90 |
+
--top-p 0.9 # controls the diversity of the AR model output, recommended 0.5~1.0
|
| 91 |
+
--temperature 1.0 # controls the randomness of the AR model output, recommended 0.7~1.2
|
| 92 |
+
--repetition-penalty 1.0 # penalizes the repetition of the AR model output, recommended 1.0~1.5
|
| 93 |
+
--cfm-checkpoint-path <path-to-cfm-checkpoint> # path to the checkpoint of the CFM model, leave to blank to auto-download default model from huggingface
|
| 94 |
+
--ar-checkpoint-path <path-to-ar-checkpoint> # path to the checkpoint of the AR model, leave to blank to auto-download default model from huggingface
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
Voice Conversion Web UI:
|
| 99 |
+
```bash
|
| 100 |
+
python app_vc.py --checkpoint <path-to-checkpoint> --config <path-to-config> --fp16 True
|
| 101 |
+
```
|
| 102 |
+
- `checkpoint` is the path to the model checkpoint if you have trained or fine-tuned your own model, leave to blank to auto-download default model from huggingface. (`seed-uvit-whisper-small-wavenet`)
|
| 103 |
+
- `config` is the path to the model config if you have trained or fine-tuned your own model, leave to blank to auto-download default config from huggingface
|
| 104 |
+
|
| 105 |
+
Then open the browser and go to `http://localhost:7860/` to use the web interface.
|
| 106 |
+
|
| 107 |
+
Singing Voice Conversion Web UI:
|
| 108 |
+
```bash
|
| 109 |
+
python app_svc.py --checkpoint <path-to-checkpoint> --config <path-to-config> --fp16 True
|
| 110 |
+
```
|
| 111 |
+
- `checkpoint` is the path to the model checkpoint if you have trained or fine-tuned your own model, leave to blank to auto-download default model from huggingface. (`seed-uvit-whisper-base`)
|
| 112 |
+
- `config` is the path to the model config if you have trained or fine-tuned your own model, leave to blank to auto-download default config from huggingface
|
| 113 |
+
|
| 114 |
+
V2 model Web UI:
|
| 115 |
+
```bash
|
| 116 |
+
python app_vc_v2.py --cfm-checkpoint-path <path-to-cfm-checkpoint> --ar-checkpoint-path <path-to-ar-checkpoint>
|
| 117 |
+
```
|
| 118 |
+
- `cfm-checkpoint-path` is the path to the checkpoint of the CFM model, leave to blank to auto-download default model from huggingface
|
| 119 |
+
- `ar-checkpoint-path` is the path to the checkpoint of the AR model, leave to blank to auto-download default model from huggingface
|
| 120 |
+
- you may consider adding `--compile` to gain ~x6 speed-up on AR model inference
|
| 121 |
+
-
|
| 122 |
+
Integrated Web UI:
|
| 123 |
+
```bash
|
| 124 |
+
python app.py --enable-v1 --enable-v2
|
| 125 |
+
```
|
| 126 |
+
This will only load pretrained models for zero-shot inference. To use custom checkpoints, please run `app_vc.py` or `app_svc.py` as above.
|
| 127 |
+
If you have limited memory, remove `--enable-v2` or `--enable-v1` to only load one of the model sets.
|
| 128 |
+
|
| 129 |
+
Real-time voice conversion GUI:
|
| 130 |
+
```bash
|
| 131 |
+
python real-time-gui.py --checkpoint-path <path-to-checkpoint> --config-path <path-to-config>
|
| 132 |
+
```
|
| 133 |
+
- `checkpoint` is the path to the model checkpoint if you have trained or fine-tuned your own model, leave to blank to auto-download default model from huggingface. (`seed-uvit-tat-xlsr-tiny`)
|
| 134 |
+
- `config` is the path to the model config if you have trained or fine-tuned your own model, leave to blank to auto-download default config from huggingface
|
| 135 |
+
|
| 136 |
+
> [!IMPORTANT]
|
| 137 |
+
> It is strongly recommended to use a GPU for real-time voice conversion.
|
| 138 |
+
> Some performance testing has been done on a NVIDIA RTX 3060 Laptop GPU, results and recommended parameter settings are listed below:
|
| 139 |
+
|
| 140 |
+
| Model Configuration | Diffusion Steps | Inference CFG Rate | Max Prompt Length | Block Time (s) | Crossfade Length (s) | Extra context (left) (s) | Extra context (right) (s) | Latency (ms) | Inference Time per Chunk (ms) |
|
| 141 |
+
|---------------------------------|-----------------|--------------------|-------------------|----------------|----------------------|--------------------------|---------------------------|--------------|-------------------------------|
|
| 142 |
+
| seed-uvit-xlsr-tiny | 10 | 0.7 | 3.0 | 0.18s | 0.04s | 2.5s | 0.02s | 430ms | 150ms |
|
| 143 |
+
|
| 144 |
+
You can adjust the parameters in the GUI according to your own device performance, the voice conversion stream should work well as long as Inference Time is less than Block Time.
|
| 145 |
+
Note that inference speed may drop if you are running other GPU intensive tasks (e.g. gaming, watching videos)
|
| 146 |
+
|
| 147 |
+
Explanations for real-time voice conversion GUI parameters:
|
| 148 |
+
- `Diffusion Steps` is the number of diffusion steps to use, in real-time case usually set to 4~10 for fastest inference;
|
| 149 |
+
- `Inference CFG Rate` has subtle difference in the output, default is 0.7, set to 0.0 gains about 1.5x speed-up;
|
| 150 |
+
- `Max Prompt Length` is the maximum length of the prompt audio, setting to a low value can speed up inference, but may reduce similarity to prompt speech;
|
| 151 |
+
- `Block Time` is the time length of each audio chunk for inference, the higher the value, the higher the latency, note this value must be greater than the inference time per block, set according to your hardware condition;
|
| 152 |
+
- `Crossfade Length` is the time length of crossfade between audio chunks, normally not needed to change;
|
| 153 |
+
- `Extra context (left)` is the time length of extra history context for inference, the higher the value, the higher the inference time, but can increase stability;
|
| 154 |
+
- `Extra context (right)` is the time length of extra future context for inference, the higher the value, the higher the inference time and latency, but can increase stability;
|
| 155 |
+
|
| 156 |
+
The algorithm delay is appoximately calculated as `Block Time * 2 + Extra context (right)`, device side delay is usually of ~100ms. The overall delay is the sum of the two.
|
| 157 |
+
|
| 158 |
+
You may wish to use [VB-CABLE](https://vb-audio.com/Cable/) to route audio from GUI output stream to a virtual microphone.
|
| 159 |
+
|
| 160 |
+
*(GUI and audio chunking logic are modified from [RVC](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI), thanks for their brilliant implementation!)*
|
| 161 |
+
|
| 162 |
+
## Training🏋️
|
| 163 |
+
Fine-tuning on custom data allow the model to clone someone's voice more accurately. It will largely improve speaker similarity on particular speakers, but may slightly increase WER.
|
| 164 |
+
A Colab Tutorial is here for you to follow: [](https://colab.research.google.com/drive/1R1BJTqMsTXZzYAVx3j1BiemFXog9pbQG?usp=sharing)
|
| 165 |
+
1. Prepare your own dataset. It has to satisfy the following:
|
| 166 |
+
- File structure does not matter
|
| 167 |
+
- Each audio file should range from 1 to 30 seconds, otherwise will be ignored
|
| 168 |
+
- All audio files should be in on of the following formats: `.wav` `.flac` `.mp3` `.m4a` `.opus` `.ogg`
|
| 169 |
+
- Speaker label is not required, but make sure that each speaker has at least 1 utterance
|
| 170 |
+
- Of course, the more data you have, the better the model will perform
|
| 171 |
+
- Training data should be as clean as possible, BGM or noise is not desired
|
| 172 |
+
2. Choose a model configuration file from `configs/presets/` for fine-tuning, or create your own to train from scratch.
|
| 173 |
+
- For fine-tuning, it should be one of the following:
|
| 174 |
+
- `./configs/presets/config_dit_mel_seed_uvit_xlsr_tiny.yml` for real-time voice conversion
|
| 175 |
+
- `./configs/presets/config_dit_mel_seed_uvit_whisper_small_wavenet.yml` for offline voice conversion
|
| 176 |
+
- `./configs/presets/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml` for singing voice conversion
|
| 177 |
+
3. Run the following command to start training:
|
| 178 |
+
```bash
|
| 179 |
+
python train.py
|
| 180 |
+
--config <path-to-config>
|
| 181 |
+
--dataset-dir <path-to-data>
|
| 182 |
+
--run-name <run-name>
|
| 183 |
+
--batch-size 2
|
| 184 |
+
--max-steps 1000
|
| 185 |
+
--max-epochs 1000
|
| 186 |
+
--save-every 500
|
| 187 |
+
--num-workers 0
|
| 188 |
+
```
|
| 189 |
+
where:
|
| 190 |
+
- `config` is the path to the model config, choose one of the above for fine-tuning or create your own for training from scratch
|
| 191 |
+
- `dataset-dir` is the path to the dataset directory, which should be a folder containing all the audio files
|
| 192 |
+
- `run-name` is the name of the run, which will be used to save the model checkpoints and logs
|
| 193 |
+
- `batch-size` is the batch size for training, choose depends on your GPU memory.
|
| 194 |
+
- `max-steps` is the maximum number of steps to train, choose depends on your dataset size and training time
|
| 195 |
+
- `max-epochs` is the maximum number of epochs to train, choose depends on your dataset size and training time
|
| 196 |
+
- `save-every` is the number of steps to save the model checkpoint
|
| 197 |
+
- `num-workers` is the number of workers for data loading, set to 0 for Windows
|
| 198 |
+
|
| 199 |
+
Similarly, to train V2 model, you can run: (note that V2 training script supports multi-GPU training)
|
| 200 |
+
```bash
|
| 201 |
+
accelerate launch train_v2.py
|
| 202 |
+
--dataset-dir <path-to-data>
|
| 203 |
+
--run-name <run-name>
|
| 204 |
+
--batch-size 2
|
| 205 |
+
--max-steps 1000
|
| 206 |
+
--max-epochs 1000
|
| 207 |
+
--save-every 500
|
| 208 |
+
--num-workers 0
|
| 209 |
+
--train-cfm
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
4. If training accidentially stops, you can resume training by running the same command again, the training will continue from the last checkpoint. (Make sure `run-name` and `config` arguments are the same so that latest checkpoint can be found)
|
| 213 |
+
|
| 214 |
+
5. After training, you can use the trained model for inference by specifying the path to the checkpoint and config file.
|
| 215 |
+
- They should be under `./runs/<run-name>/`, with the checkpoint named `ft_model.pth` and config file with the same name as the training config file.
|
| 216 |
+
- You still have to specify a reference audio file of the speaker you'd like to use during inference, similar to zero-shot usage.
|
| 217 |
+
|
| 218 |
+
## TODO📝
|
| 219 |
+
- [x] Release code
|
| 220 |
+
- [x] Release pretrained models: [](https://huggingface.co/Plachta/Seed-VC)
|
| 221 |
+
- [x] Huggingface space demo: [](https://huggingface.co/spaces/Plachta/Seed-VC)
|
| 222 |
+
- [x] HTML demo page: [Demo](https://plachtaa.github.io/seed-vc/)
|
| 223 |
+
- [x] Streaming inference
|
| 224 |
+
- [x] Reduce streaming inference latency
|
| 225 |
+
- [x] Demo video for real-time voice conversion
|
| 226 |
+
- [x] Singing voice conversion
|
| 227 |
+
- [x] Noise resiliency for source audio
|
| 228 |
+
- [ ] Potential architecture improvements
|
| 229 |
+
- [x] U-ViT style skip connections
|
| 230 |
+
- [x] Changed input to OpenAI Whisper
|
| 231 |
+
- [x] Time as Token
|
| 232 |
+
- [x] Code for training on custom data
|
| 233 |
+
- [x] Few-shot/One-shot speaker fine-tuning
|
| 234 |
+
- [x] Changed to BigVGAN from NVIDIA for singing voice decoding
|
| 235 |
+
- [x] Whisper version model for singing voice conversion
|
| 236 |
+
- [x] Objective evaluation and comparison with RVC/SoVITS for singing voice conversion
|
| 237 |
+
- [x] Improve audio quality
|
| 238 |
+
- [ ] NSF vocoder for better singing voice conversion
|
| 239 |
+
- [x] Fix real-time voice conversion artifact while not talking (done by adding a VAD model)
|
| 240 |
+
- [x] Colab Notebook for fine-tuning example
|
| 241 |
+
- [x] Replace whisper with more advanced linguistic content extractor
|
| 242 |
+
- [ ] More to be added
|
| 243 |
+
- [x] Add Apple Silicon support
|
| 244 |
+
- [ ] Release paper, evaluations and demo page for V2 model
|
| 245 |
+
|
| 246 |
+
## Known Issues
|
| 247 |
+
- On Mac - running `real-time-gui.py` might raise an error `ModuleNotFoundError: No module named '_tkinter'`, in this case a new Python version **with Tkinter support** should be installed. Refer to [This Guide on stack overflow](https://stackoverflow.com/questions/76105218/why-does-tkinter-or-turtle-seem-to-be-missing-or-broken-shouldnt-it-be-part) for explanation of the problem and a detailed fix.
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
## CHANGELOGS🗒️
|
| 251 |
+
- 2024-04-16
|
| 252 |
+
- Released V2 model for voice and accent conversion, with better anonymization of source speaker
|
| 253 |
+
- 2025-03-03:
|
| 254 |
+
- Added Mac M Series (Apple Silicon) support
|
| 255 |
+
- 2024-11-26:
|
| 256 |
+
- Updated v1.0 tiny version pretrained model, optimized for real-time voice conversion
|
| 257 |
+
- Support one-shot/few-shot single/multi speaker fine-tuning
|
| 258 |
+
- Support using custom checkpoint for webUI & real-time GUI
|
| 259 |
+
- 2024-11-19:
|
| 260 |
+
- arXiv paper released
|
| 261 |
+
- 2024-10-28:
|
| 262 |
+
- Updated fine-tuned 44k singing voice conversion model with better audio quality
|
| 263 |
+
- 2024-10-27:
|
| 264 |
+
- Added real-time voice conversion GUI
|
| 265 |
+
- 2024-10-25:
|
| 266 |
+
- Added exhaustive evaluation results and comparisons with RVCv2 for singing voice conversion
|
| 267 |
+
- 2024-10-24:
|
| 268 |
+
- Updated 44kHz singing voice conversion model, with OpenAI Whisper as speech content input
|
| 269 |
+
- 2024-10-07:
|
| 270 |
+
- Updated v0.3 pretrained model, changed speech content encoder to OpenAI Whisper
|
| 271 |
+
- Added objective evaluation results for v0.3 pretrained model
|
| 272 |
+
- 2024-09-22:
|
| 273 |
+
- Updated singing voice conversion model to use BigVGAN from NVIDIA, providing large improvement to high-pitched singing voices
|
| 274 |
+
- Support chunking and streaming output for long audio files in Web UI
|
| 275 |
+
- 2024-09-18:
|
| 276 |
+
- Updated f0 conditioned model for singing voice conversion
|
| 277 |
+
- 2024-09-14:
|
| 278 |
+
- Updated v0.2 pretrained model, with smaller size and less diffusion steps to achieve same quality, and additional ability to control prosody preservation
|
| 279 |
+
- Added command line inference script
|
| 280 |
+
- Added installation and usage instructions
|
| 281 |
+
|
| 282 |
+
## Acknowledgements🙏
|
| 283 |
+
- [Amphion](https://github.com/open-mmlab/Amphion) for providing computational resources and inspiration!
|
| 284 |
+
- [Vevo](https://github.com/open-mmlab/Amphion/tree/main/models/vc/vevo) for theoretical foundation of V2 model
|
| 285 |
+
- [MegaTTS3](https://github.com/bytedance/MegaTTS3) for multi-condition CFG inference implemented in V2 model
|
| 286 |
+
- [ASTRAL-quantiztion](https://github.com/Plachtaa/ASTRAL-quantization) for the amazing speaker-disentangled speech tokenizer used by V2 model
|
| 287 |
+
- [RVC](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI) for foundationing the real-time voice conversion
|
| 288 |
+
- [SEED-TTS](https://arxiv.org/abs/2406.02430) for the initial idea
|
seed-vc/app.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import yaml
|
| 4 |
+
import argparse
|
| 5 |
+
from modules.commons import str2bool
|
| 6 |
+
|
| 7 |
+
# Set up device and torch configurations
|
| 8 |
+
if torch.cuda.is_available():
|
| 9 |
+
device = torch.device("cuda")
|
| 10 |
+
elif torch.backends.mps.is_available():
|
| 11 |
+
device = torch.device("mps")
|
| 12 |
+
else:
|
| 13 |
+
device = torch.device("cpu")
|
| 14 |
+
|
| 15 |
+
dtype = torch.float16
|
| 16 |
+
|
| 17 |
+
# Global variables to store model instances
|
| 18 |
+
vc_wrapper_v1 = None
|
| 19 |
+
vc_wrapper_v2 = None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_v2_models(args):
|
| 23 |
+
from hydra.utils import instantiate
|
| 24 |
+
from omegaconf import DictConfig
|
| 25 |
+
cfg = DictConfig(yaml.safe_load(open("configs/v2/vc_wrapper.yaml", "r")))
|
| 26 |
+
vc_wrapper = instantiate(cfg)
|
| 27 |
+
vc_wrapper.load_checkpoints()
|
| 28 |
+
vc_wrapper.to(device)
|
| 29 |
+
vc_wrapper.eval()
|
| 30 |
+
|
| 31 |
+
vc_wrapper.setup_ar_caches(max_batch_size=1, max_seq_len=4096, dtype=dtype, device=device)
|
| 32 |
+
|
| 33 |
+
if args.compile:
|
| 34 |
+
print("Compiling model with torch.compile...")
|
| 35 |
+
torch._inductor.config.coordinate_descent_tuning = True
|
| 36 |
+
torch._inductor.config.triton.unique_kernel_names = True
|
| 37 |
+
|
| 38 |
+
if hasattr(torch._inductor.config, "fx_graph_cache"):
|
| 39 |
+
# Experimental feature to reduce compilation times, will be on by default in future
|
| 40 |
+
torch._inductor.config.fx_graph_cache = True
|
| 41 |
+
vc_wrapper.compile_ar()
|
| 42 |
+
# vc_wrapper.compile_cfm()
|
| 43 |
+
|
| 44 |
+
return vc_wrapper
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Wrapper functions for GPU decoration
|
| 48 |
+
def convert_voice_v1_wrapper(source_audio_path, target_audio_path, diffusion_steps=10,
|
| 49 |
+
length_adjust=1.0, inference_cfg_rate=0.7, f0_condition=False,
|
| 50 |
+
auto_f0_adjust=True, pitch_shift=0, stream_output=True):
|
| 51 |
+
"""
|
| 52 |
+
Wrapper function for vc_wrapper.convert_voice that can be decorated with @spaces.GPU
|
| 53 |
+
"""
|
| 54 |
+
global vc_wrapper_v1
|
| 55 |
+
from seed_vc_wrapper import SeedVCWrapper
|
| 56 |
+
if vc_wrapper_v1 is None:
|
| 57 |
+
vc_wrapper_v1 = SeedVCWrapper()
|
| 58 |
+
|
| 59 |
+
# Use yield from to properly handle the generator
|
| 60 |
+
yield from vc_wrapper_v1.convert_voice(
|
| 61 |
+
source=source_audio_path,
|
| 62 |
+
target=target_audio_path,
|
| 63 |
+
diffusion_steps=diffusion_steps,
|
| 64 |
+
length_adjust=length_adjust,
|
| 65 |
+
inference_cfg_rate=inference_cfg_rate,
|
| 66 |
+
f0_condition=f0_condition,
|
| 67 |
+
auto_f0_adjust=auto_f0_adjust,
|
| 68 |
+
pitch_shift=pitch_shift,
|
| 69 |
+
stream_output=stream_output
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def convert_voice_v2_wrapper(source_audio_path, target_audio_path, diffusion_steps=30,
|
| 74 |
+
length_adjust=1.0, intelligebility_cfg_rate=0.7, similarity_cfg_rate=0.7,
|
| 75 |
+
top_p=0.7, temperature=0.7, repetition_penalty=1.5,
|
| 76 |
+
convert_style=False, anonymization_only=False, stream_output=True):
|
| 77 |
+
"""
|
| 78 |
+
Wrapper function for vc_wrapper.convert_voice_with_streaming that can be decorated with @spaces.GPU
|
| 79 |
+
"""
|
| 80 |
+
global vc_wrapper_v2
|
| 81 |
+
|
| 82 |
+
# Use yield from to properly handle the generator
|
| 83 |
+
yield from vc_wrapper_v2.convert_voice_with_streaming(
|
| 84 |
+
source_audio_path=source_audio_path,
|
| 85 |
+
target_audio_path=target_audio_path,
|
| 86 |
+
diffusion_steps=diffusion_steps,
|
| 87 |
+
length_adjust=length_adjust,
|
| 88 |
+
intelligebility_cfg_rate=intelligebility_cfg_rate,
|
| 89 |
+
similarity_cfg_rate=similarity_cfg_rate,
|
| 90 |
+
top_p=top_p,
|
| 91 |
+
temperature=temperature,
|
| 92 |
+
repetition_penalty=repetition_penalty,
|
| 93 |
+
convert_style=convert_style,
|
| 94 |
+
anonymization_only=anonymization_only,
|
| 95 |
+
device=device,
|
| 96 |
+
dtype=dtype,
|
| 97 |
+
stream_output=stream_output
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def create_v1_interface():
|
| 102 |
+
# Set up Gradio interface
|
| 103 |
+
description = (
|
| 104 |
+
"Zero-shot voice conversion with in-context learning. For local deployment please check [GitHub repository](https://github.com/Plachtaa/seed-vc) "
|
| 105 |
+
"for details and updates.<br>Note that any reference audio will be forcefully clipped to 25s if beyond this length.<br> "
|
| 106 |
+
"If total duration of source and reference audio exceeds 30s, source audio will be processed in chunks.<br> "
|
| 107 |
+
"无需训练的 zero-shot 语音/歌声转换模型,若需本地部署查看[GitHub页面](https://github.com/Plachtaa/seed-vc)<br>"
|
| 108 |
+
"请注意,参考音频若超过 25 秒,则会被自动裁剪至此长度。<br>若源音频和参考音频的总时长超过 30 秒,源音频将被分段处理。")
|
| 109 |
+
|
| 110 |
+
inputs = [
|
| 111 |
+
gr.Audio(type="filepath", label="Source Audio / 源音频"),
|
| 112 |
+
gr.Audio(type="filepath", label="Reference Audio / 参考音频"),
|
| 113 |
+
gr.Slider(minimum=1, maximum=200, value=10, step=1, label="Diffusion Steps / 扩散步数",
|
| 114 |
+
info="10 by default, 50~100 for best quality / 默认为 10,50~100 为最佳质量"),
|
| 115 |
+
gr.Slider(minimum=0.5, maximum=2.0, step=0.1, value=1.0, label="Length Adjust / 长度调整",
|
| 116 |
+
info="<1.0 for speed-up speech, >1.0 for slow-down speech / <1.0 加速语速,>1.0 减慢语速"),
|
| 117 |
+
gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.7, label="Inference CFG Rate",
|
| 118 |
+
info="has subtle influence / 有微小影响"),
|
| 119 |
+
gr.Checkbox(label="Use F0 conditioned model / 启用F0输入", value=False,
|
| 120 |
+
info="Must set to true for singing voice conversion / 歌声转换时必须勾选"),
|
| 121 |
+
gr.Checkbox(label="Auto F0 adjust / 自动F0调整", value=True,
|
| 122 |
+
info="Roughly adjust F0 to match target voice. Only works when F0 conditioned model is used. / 粗略调整 F0 以匹配目标音色,仅在勾选 '启用F0输入' 时生效"),
|
| 123 |
+
gr.Slider(label='Pitch shift / 音调变换', minimum=-24, maximum=24, step=1, value=0,
|
| 124 |
+
info="Pitch shift in semitones, only works when F0 conditioned model is used / 半音数的音高变换,仅在勾选 '启用F0输入' 时生效"),
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
examples = [
|
| 128 |
+
["examples/source/yae_0.wav", "examples/reference/dingzhen_0.wav", 25, 1.0, 0.7, False, True, 0],
|
| 129 |
+
["examples/source/jay_0.wav", "examples/reference/azuma_0.wav", 25, 1.0, 0.7, True, True, 0],
|
| 130 |
+
["examples/source/Wiz Khalifa,Charlie Puth - See You Again [vocals]_[cut_28sec].wav",
|
| 131 |
+
"examples/reference/teio_0.wav", 100, 1.0, 0.7, True, False, 0],
|
| 132 |
+
["examples/source/TECHNOPOLIS - 2085 [vocals]_[cut_14sec].wav",
|
| 133 |
+
"examples/reference/trump_0.wav", 50, 1.0, 0.7, True, False, -12],
|
| 134 |
+
]
|
| 135 |
+
|
| 136 |
+
outputs = [
|
| 137 |
+
gr.Audio(label="Stream Output Audio / 流式输出", streaming=True, format='mp3'),
|
| 138 |
+
gr.Audio(label="Full Output Audio / 完整输出", streaming=False, format='wav')
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
return gr.Interface(
|
| 142 |
+
fn=convert_voice_v1_wrapper,
|
| 143 |
+
description=description,
|
| 144 |
+
inputs=inputs,
|
| 145 |
+
outputs=outputs,
|
| 146 |
+
title="Seed Voice Conversion V1 (Voice & Singing Voice Conversion)",
|
| 147 |
+
examples=examples,
|
| 148 |
+
cache_examples=False,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def create_v2_interface():
|
| 153 |
+
# Set up Gradio interface
|
| 154 |
+
description = (
|
| 155 |
+
"Zero-shot voice/style conversion with in-context learning. For local deployment please check [GitHub repository](https://github.com/Plachtaa/seed-vc) "
|
| 156 |
+
"for details and updates.<br>Note that any reference audio will be forcefully clipped to 25s if beyond this length.<br> "
|
| 157 |
+
"If total duration of source and reference audio exceeds 30s, source audio will be processed in chunks.<br> "
|
| 158 |
+
"Please click the 'convert style/emotion/accent' checkbox to convert the style, emotion, or accent of the source audio, or else only timbre conversion will be performed.<br> "
|
| 159 |
+
"Click the 'anonymization only' checkbox will ignore reference audio but convert source to an 'average voice' determined by model itself.<br> "
|
| 160 |
+
"无需训练的 zero-shot 语音/口音转换模型,若需本地部署查看[GitHub页面](https://github.com/Plachtaa/seed-vc)<br>"
|
| 161 |
+
"请注意,参考音频若超过 25 秒,则会被自动裁剪至此长度。<br>若源音频和参考音频的总时长超过 30 秒,源音频将被分段处理。"
|
| 162 |
+
"<br>请勾选 'convert style/emotion/accent' 以转换源音频的风格、情感或口音,否则仅执行音色转换。<br>"
|
| 163 |
+
"勾选 'anonymization only' 会无视参考音频而将源音频转换为某种由模型自身决定的 '平均音色'。<br>"
|
| 164 |
+
|
| 165 |
+
"Credits to [Vevo](https://github.com/open-mmlab/Amphion/tree/main/models/vc/vevo)"
|
| 166 |
+
)
|
| 167 |
+
inputs = [
|
| 168 |
+
gr.Audio(type="filepath", label="Source Audio / 源音频"),
|
| 169 |
+
gr.Audio(type="filepath", label="Reference Audio / 参考音频"),
|
| 170 |
+
gr.Slider(minimum=1, maximum=200, value=30, step=1, label="Diffusion Steps / 扩散步数",
|
| 171 |
+
info="30 by default, 50~100 for best quality / 默认为 30,50~100 为最佳质量"),
|
| 172 |
+
gr.Slider(minimum=0.5, maximum=2.0, step=0.1, value=1.0, label="Length Adjust / 长度调整",
|
| 173 |
+
info="<1.0 for speed-up speech, >1.0 for slow-down speech / <1.0 加速语速,>1.0 减慢语速"),
|
| 174 |
+
gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.0, label="Intelligibility CFG Rate",
|
| 175 |
+
info="controls pronunciation intelligibility / 控制发音清晰度"),
|
| 176 |
+
gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.7, label="Similarity CFG Rate",
|
| 177 |
+
info="controls similarity to reference audio / 控制与参考音频的相似度"),
|
| 178 |
+
gr.Slider(minimum=0.1, maximum=1.0, step=0.1, value=0.9, label="Top-p",
|
| 179 |
+
info="AR model sampling top P"),
|
| 180 |
+
gr.Slider(minimum=0.1, maximum=2.0, step=0.1, value=1.0, label="Temperature",
|
| 181 |
+
info="AR model sampling temperature"),
|
| 182 |
+
gr.Slider(minimum=1.0, maximum=3.0, step=0.1, value=1.0, label="Repetition Penalty",
|
| 183 |
+
info="AR model sampling repetition penalty"),
|
| 184 |
+
gr.Checkbox(label="convert style/emotion/accent", value=False),
|
| 185 |
+
gr.Checkbox(label="anonymization only", value=False),
|
| 186 |
+
]
|
| 187 |
+
|
| 188 |
+
examples = [
|
| 189 |
+
["examples/source/yae_0.wav", "examples/reference/dingzhen_0.wav", 50, 1.0, 0.0, 0.7, 0.9, 1.0, 1.0, False,
|
| 190 |
+
False],
|
| 191 |
+
["examples/source/jay_0.wav", "examples/reference/azuma_0.wav", 50, 1.0, 0.0, 0.7, 0.9, 1.0, 1.0, False, False],
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
outputs = [
|
| 195 |
+
gr.Audio(label="Stream Output Audio / 流式输出", streaming=True, format='mp3'),
|
| 196 |
+
gr.Audio(label="Full Output Audio / 完整输出", streaming=False, format='wav')
|
| 197 |
+
]
|
| 198 |
+
|
| 199 |
+
return gr.Interface(
|
| 200 |
+
fn=convert_voice_v2_wrapper,
|
| 201 |
+
description=description,
|
| 202 |
+
inputs=inputs,
|
| 203 |
+
outputs=outputs,
|
| 204 |
+
title="Seed Voice Conversion V2 (Voice & Style Conversion)",
|
| 205 |
+
examples=examples,
|
| 206 |
+
cache_examples=False,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main(args):
|
| 211 |
+
global vc_wrapper_v1, vc_wrapper_v2
|
| 212 |
+
# Create interfaces based on enabled versions
|
| 213 |
+
interfaces = []
|
| 214 |
+
|
| 215 |
+
# Load V2 models if enabled
|
| 216 |
+
if args.enable_v2:
|
| 217 |
+
print("Loading V2 models...")
|
| 218 |
+
vc_wrapper_v2 = load_v2_models(args)
|
| 219 |
+
v2_interface = create_v2_interface()
|
| 220 |
+
interfaces.append(("V2 - Voice & Style Conversion", v2_interface))
|
| 221 |
+
|
| 222 |
+
# Create V1 interface if enabled
|
| 223 |
+
if args.enable_v1:
|
| 224 |
+
print("Creating V1 interface...")
|
| 225 |
+
v1_interface = create_v1_interface()
|
| 226 |
+
interfaces.append(("V1 - Voice & Singing Voice Conversion", v1_interface))
|
| 227 |
+
|
| 228 |
+
# Check if at least one version is enabled
|
| 229 |
+
if not interfaces:
|
| 230 |
+
print("Error: At least one version (V1 or V2) must be enabled.")
|
| 231 |
+
return
|
| 232 |
+
|
| 233 |
+
# Create tabs
|
| 234 |
+
with gr.Blocks(title="Seed Voice Conversion") as demo:
|
| 235 |
+
gr.Markdown("# Seed Voice Conversion")
|
| 236 |
+
|
| 237 |
+
if len(interfaces) > 1:
|
| 238 |
+
gr.Markdown("Choose between V1 (Voice & Singing Voice Conversion) or V2 (Voice & Style Conversion)")
|
| 239 |
+
|
| 240 |
+
with gr.Tabs():
|
| 241 |
+
for tab_name, interface in interfaces:
|
| 242 |
+
with gr.TabItem(tab_name):
|
| 243 |
+
interface.render()
|
| 244 |
+
else:
|
| 245 |
+
# If only one version is enabled, don't use tabs
|
| 246 |
+
for _, interface in interfaces:
|
| 247 |
+
interface.render()
|
| 248 |
+
|
| 249 |
+
# Launch the combined interface
|
| 250 |
+
demo.launch()
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
parser = argparse.ArgumentParser()
|
| 255 |
+
parser.add_argument("--compile", action="store_true", help="Compile the model using torch.compile")
|
| 256 |
+
parser.add_argument("--enable-v1", action="store_true",
|
| 257 |
+
help="Enable V1 (Voice & Singing Voice Conversion)")
|
| 258 |
+
parser.add_argument("--enable-v2", action="store_true",
|
| 259 |
+
help="Enable V2 (Voice & Style Conversion)")
|
| 260 |
+
args = parser.parse_args()
|
| 261 |
+
main(args)
|
seed-vc/app_svc.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ['HF_HUB_CACHE'] = './checkpoints/hf_cache'
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
import torchaudio
|
| 6 |
+
import librosa
|
| 7 |
+
from modules.commons import build_model, load_checkpoint, recursive_munch, str2bool
|
| 8 |
+
import yaml
|
| 9 |
+
from hf_utils import load_custom_model_from_hf
|
| 10 |
+
import numpy as np
|
| 11 |
+
from pydub import AudioSegment
|
| 12 |
+
import argparse
|
| 13 |
+
# Load model and configuration
|
| 14 |
+
|
| 15 |
+
fp16 = False
|
| 16 |
+
device = None
|
| 17 |
+
def load_models(args):
|
| 18 |
+
global sr, hop_length, fp16
|
| 19 |
+
fp16 = args.fp16
|
| 20 |
+
print(f"Using device: {device}")
|
| 21 |
+
print(f"Using fp16: {fp16}")
|
| 22 |
+
# f0 conditioned model
|
| 23 |
+
if args.checkpoint is None or args.checkpoint == "":
|
| 24 |
+
dit_checkpoint_path, dit_config_path = load_custom_model_from_hf("Plachta/Seed-VC",
|
| 25 |
+
"DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth",
|
| 26 |
+
"config_dit_mel_seed_uvit_whisper_base_f0_44k.yml")
|
| 27 |
+
else:
|
| 28 |
+
print(f"Using custom checkpoint: {args.checkpoint}")
|
| 29 |
+
dit_checkpoint_path = args.checkpoint
|
| 30 |
+
dit_config_path = args.config
|
| 31 |
+
config = yaml.safe_load(open(dit_config_path, "r"))
|
| 32 |
+
model_params = recursive_munch(config["model_params"])
|
| 33 |
+
model_params.dit_type = 'DiT'
|
| 34 |
+
model = build_model(model_params, stage="DiT")
|
| 35 |
+
hop_length = config["preprocess_params"]["spect_params"]["hop_length"]
|
| 36 |
+
sr = config["preprocess_params"]["sr"]
|
| 37 |
+
|
| 38 |
+
# Load checkpoints
|
| 39 |
+
model, _, _, _ = load_checkpoint(
|
| 40 |
+
model,
|
| 41 |
+
None,
|
| 42 |
+
dit_checkpoint_path,
|
| 43 |
+
load_only_params=True,
|
| 44 |
+
ignore_modules=[],
|
| 45 |
+
is_distributed=False,
|
| 46 |
+
)
|
| 47 |
+
for key in model:
|
| 48 |
+
model[key].eval()
|
| 49 |
+
model[key].to(device)
|
| 50 |
+
model.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192)
|
| 51 |
+
|
| 52 |
+
# Load additional modules
|
| 53 |
+
from modules.campplus.DTDNN import CAMPPlus
|
| 54 |
+
|
| 55 |
+
campplus_ckpt_path = load_custom_model_from_hf(
|
| 56 |
+
"funasr/campplus", "campplus_cn_common.bin", config_filename=None
|
| 57 |
+
)
|
| 58 |
+
campplus_model = CAMPPlus(feat_dim=80, embedding_size=192)
|
| 59 |
+
campplus_model.load_state_dict(torch.load(campplus_ckpt_path, map_location="cpu"))
|
| 60 |
+
campplus_model.eval()
|
| 61 |
+
campplus_model.to(device)
|
| 62 |
+
|
| 63 |
+
vocoder_type = model_params.vocoder.type
|
| 64 |
+
|
| 65 |
+
if vocoder_type == 'bigvgan':
|
| 66 |
+
from modules.bigvgan import bigvgan
|
| 67 |
+
bigvgan_name = model_params.vocoder.name
|
| 68 |
+
bigvgan_model = bigvgan.BigVGAN.from_pretrained(bigvgan_name, use_cuda_kernel=False)
|
| 69 |
+
# remove weight norm in the model and set to eval mode
|
| 70 |
+
bigvgan_model.remove_weight_norm()
|
| 71 |
+
bigvgan_model = bigvgan_model.eval().to(device)
|
| 72 |
+
vocoder_fn = bigvgan_model
|
| 73 |
+
elif vocoder_type == 'hifigan':
|
| 74 |
+
from modules.hifigan.generator import HiFTGenerator
|
| 75 |
+
from modules.hifigan.f0_predictor import ConvRNNF0Predictor
|
| 76 |
+
hift_config = yaml.safe_load(open('configs/hifigan.yml', 'r'))
|
| 77 |
+
hift_gen = HiFTGenerator(**hift_config['hift'], f0_predictor=ConvRNNF0Predictor(**hift_config['f0_predictor']))
|
| 78 |
+
hift_path = load_custom_model_from_hf("FunAudioLLM/CosyVoice-300M", 'hift.pt', None)
|
| 79 |
+
hift_gen.load_state_dict(torch.load(hift_path, map_location='cpu'))
|
| 80 |
+
hift_gen.eval()
|
| 81 |
+
hift_gen.to(device)
|
| 82 |
+
vocoder_fn = hift_gen
|
| 83 |
+
elif vocoder_type == "vocos":
|
| 84 |
+
vocos_config = yaml.safe_load(open(model_params.vocoder.vocos.config, 'r'))
|
| 85 |
+
vocos_path = model_params.vocoder.vocos.path
|
| 86 |
+
vocos_model_params = recursive_munch(vocos_config['model_params'])
|
| 87 |
+
vocos = build_model(vocos_model_params, stage='mel_vocos')
|
| 88 |
+
vocos_checkpoint_path = vocos_path
|
| 89 |
+
vocos, _, _, _ = load_checkpoint(vocos, None, vocos_checkpoint_path,
|
| 90 |
+
load_only_params=True, ignore_modules=[], is_distributed=False)
|
| 91 |
+
_ = [vocos[key].eval().to(device) for key in vocos]
|
| 92 |
+
_ = [vocos[key].to(device) for key in vocos]
|
| 93 |
+
total_params = sum(sum(p.numel() for p in vocos[key].parameters() if p.requires_grad) for key in vocos.keys())
|
| 94 |
+
print(f"Vocoder model total parameters: {total_params / 1_000_000:.2f}M")
|
| 95 |
+
vocoder_fn = vocos.decoder
|
| 96 |
+
else:
|
| 97 |
+
raise ValueError(f"Unknown vocoder type: {vocoder_type}")
|
| 98 |
+
|
| 99 |
+
speech_tokenizer_type = model_params.speech_tokenizer.type
|
| 100 |
+
if speech_tokenizer_type == 'whisper':
|
| 101 |
+
# whisper
|
| 102 |
+
from transformers import AutoFeatureExtractor, WhisperModel
|
| 103 |
+
whisper_name = model_params.speech_tokenizer.name
|
| 104 |
+
whisper_model = WhisperModel.from_pretrained(whisper_name, torch_dtype=torch.float16).to(device)
|
| 105 |
+
del whisper_model.decoder
|
| 106 |
+
whisper_feature_extractor = AutoFeatureExtractor.from_pretrained(whisper_name)
|
| 107 |
+
|
| 108 |
+
def semantic_fn(waves_16k):
|
| 109 |
+
ori_inputs = whisper_feature_extractor([waves_16k.squeeze(0).cpu().numpy()],
|
| 110 |
+
return_tensors="pt",
|
| 111 |
+
return_attention_mask=True)
|
| 112 |
+
ori_input_features = whisper_model._mask_input_features(
|
| 113 |
+
ori_inputs.input_features, attention_mask=ori_inputs.attention_mask).to(device)
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
ori_outputs = whisper_model.encoder(
|
| 116 |
+
ori_input_features.to(whisper_model.encoder.dtype),
|
| 117 |
+
head_mask=None,
|
| 118 |
+
output_attentions=False,
|
| 119 |
+
output_hidden_states=False,
|
| 120 |
+
return_dict=True,
|
| 121 |
+
)
|
| 122 |
+
S_ori = ori_outputs.last_hidden_state.to(torch.float32)
|
| 123 |
+
S_ori = S_ori[:, :waves_16k.size(-1) // 320 + 1]
|
| 124 |
+
return S_ori
|
| 125 |
+
elif speech_tokenizer_type == 'cnhubert':
|
| 126 |
+
from transformers import (
|
| 127 |
+
Wav2Vec2FeatureExtractor,
|
| 128 |
+
HubertModel,
|
| 129 |
+
)
|
| 130 |
+
hubert_model_name = config['model_params']['speech_tokenizer']['name']
|
| 131 |
+
hubert_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(hubert_model_name)
|
| 132 |
+
hubert_model = HubertModel.from_pretrained(hubert_model_name)
|
| 133 |
+
hubert_model = hubert_model.to(device)
|
| 134 |
+
hubert_model = hubert_model.eval()
|
| 135 |
+
hubert_model = hubert_model.half()
|
| 136 |
+
|
| 137 |
+
def semantic_fn(waves_16k):
|
| 138 |
+
ori_waves_16k_input_list = [
|
| 139 |
+
waves_16k[bib].cpu().numpy()
|
| 140 |
+
for bib in range(len(waves_16k))
|
| 141 |
+
]
|
| 142 |
+
ori_inputs = hubert_feature_extractor(ori_waves_16k_input_list,
|
| 143 |
+
return_tensors="pt",
|
| 144 |
+
return_attention_mask=True,
|
| 145 |
+
padding=True,
|
| 146 |
+
sampling_rate=16000).to(device)
|
| 147 |
+
with torch.no_grad():
|
| 148 |
+
ori_outputs = hubert_model(
|
| 149 |
+
ori_inputs.input_values.half(),
|
| 150 |
+
)
|
| 151 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
| 152 |
+
return S_ori
|
| 153 |
+
elif speech_tokenizer_type == 'xlsr':
|
| 154 |
+
from transformers import (
|
| 155 |
+
Wav2Vec2FeatureExtractor,
|
| 156 |
+
Wav2Vec2Model,
|
| 157 |
+
)
|
| 158 |
+
model_name = config['model_params']['speech_tokenizer']['name']
|
| 159 |
+
output_layer = config['model_params']['speech_tokenizer']['output_layer']
|
| 160 |
+
wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name)
|
| 161 |
+
wav2vec_model = Wav2Vec2Model.from_pretrained(model_name)
|
| 162 |
+
wav2vec_model.encoder.layers = wav2vec_model.encoder.layers[:output_layer]
|
| 163 |
+
wav2vec_model = wav2vec_model.to(device)
|
| 164 |
+
wav2vec_model = wav2vec_model.eval()
|
| 165 |
+
wav2vec_model = wav2vec_model.half()
|
| 166 |
+
|
| 167 |
+
def semantic_fn(waves_16k):
|
| 168 |
+
ori_waves_16k_input_list = [
|
| 169 |
+
waves_16k[bib].cpu().numpy()
|
| 170 |
+
for bib in range(len(waves_16k))
|
| 171 |
+
]
|
| 172 |
+
ori_inputs = wav2vec_feature_extractor(ori_waves_16k_input_list,
|
| 173 |
+
return_tensors="pt",
|
| 174 |
+
return_attention_mask=True,
|
| 175 |
+
padding=True,
|
| 176 |
+
sampling_rate=16000).to(device)
|
| 177 |
+
with torch.no_grad():
|
| 178 |
+
ori_outputs = wav2vec_model(
|
| 179 |
+
ori_inputs.input_values.half(),
|
| 180 |
+
)
|
| 181 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
| 182 |
+
return S_ori
|
| 183 |
+
else:
|
| 184 |
+
raise ValueError(f"Unknown speech tokenizer type: {speech_tokenizer_type}")
|
| 185 |
+
# Generate mel spectrograms
|
| 186 |
+
mel_fn_args = {
|
| 187 |
+
"n_fft": config['preprocess_params']['spect_params']['n_fft'],
|
| 188 |
+
"win_size": config['preprocess_params']['spect_params']['win_length'],
|
| 189 |
+
"hop_size": config['preprocess_params']['spect_params']['hop_length'],
|
| 190 |
+
"num_mels": config['preprocess_params']['spect_params']['n_mels'],
|
| 191 |
+
"sampling_rate": sr,
|
| 192 |
+
"fmin": config['preprocess_params']['spect_params'].get('fmin', 0),
|
| 193 |
+
"fmax": None if config['preprocess_params']['spect_params'].get('fmax', "None") == "None" else 8000,
|
| 194 |
+
"center": False
|
| 195 |
+
}
|
| 196 |
+
from modules.audio import mel_spectrogram
|
| 197 |
+
|
| 198 |
+
to_mel = lambda x: mel_spectrogram(x, **mel_fn_args)
|
| 199 |
+
# f0 extractor
|
| 200 |
+
from modules.rmvpe import RMVPE
|
| 201 |
+
|
| 202 |
+
model_path = load_custom_model_from_hf("lj1995/VoiceConversionWebUI", "rmvpe.pt", None)
|
| 203 |
+
rmvpe = RMVPE(model_path, is_half=False, device=device)
|
| 204 |
+
f0_fn = rmvpe.infer_from_audio
|
| 205 |
+
|
| 206 |
+
return (
|
| 207 |
+
model,
|
| 208 |
+
semantic_fn,
|
| 209 |
+
vocoder_fn,
|
| 210 |
+
campplus_model,
|
| 211 |
+
to_mel,
|
| 212 |
+
mel_fn_args,
|
| 213 |
+
f0_fn,
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
def adjust_f0_semitones(f0_sequence, n_semitones):
|
| 217 |
+
factor = 2 ** (n_semitones / 12)
|
| 218 |
+
return f0_sequence * factor
|
| 219 |
+
|
| 220 |
+
def crossfade(chunk1, chunk2, overlap):
|
| 221 |
+
fade_out = np.cos(np.linspace(0, np.pi / 2, overlap)) ** 2
|
| 222 |
+
fade_in = np.cos(np.linspace(np.pi / 2, 0, overlap)) ** 2
|
| 223 |
+
chunk2[:overlap] = chunk2[:overlap] * fade_in + chunk1[-overlap:] * fade_out
|
| 224 |
+
return chunk2
|
| 225 |
+
|
| 226 |
+
# streaming and chunk processing related params
|
| 227 |
+
# max_context_window = sr // hop_length * 30
|
| 228 |
+
# overlap_frame_len = 16
|
| 229 |
+
# overlap_wave_len = overlap_frame_len * hop_length
|
| 230 |
+
bitrate = "320k"
|
| 231 |
+
|
| 232 |
+
model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args = None, None, None, None, None, None
|
| 233 |
+
f0_fn = None
|
| 234 |
+
overlap_wave_len = None
|
| 235 |
+
max_context_window = None
|
| 236 |
+
sr = None
|
| 237 |
+
hop_length = None
|
| 238 |
+
overlap_frame_len = 16
|
| 239 |
+
|
| 240 |
+
@torch.no_grad()
|
| 241 |
+
@torch.inference_mode()
|
| 242 |
+
def voice_conversion(source, target, diffusion_steps, length_adjust, inference_cfg_rate, auto_f0_adjust, pitch_shift):
|
| 243 |
+
inference_module = model_f0
|
| 244 |
+
mel_fn = to_mel_f0
|
| 245 |
+
# Load audio
|
| 246 |
+
source_audio = librosa.load(source, sr=sr)[0]
|
| 247 |
+
ref_audio = librosa.load(target, sr=sr)[0]
|
| 248 |
+
|
| 249 |
+
# Process audio
|
| 250 |
+
source_audio = torch.tensor(source_audio).unsqueeze(0).float().to(device)
|
| 251 |
+
ref_audio = torch.tensor(ref_audio[:sr * 25]).unsqueeze(0).float().to(device)
|
| 252 |
+
|
| 253 |
+
# Resample
|
| 254 |
+
ref_waves_16k = torchaudio.functional.resample(ref_audio, sr, 16000)
|
| 255 |
+
converted_waves_16k = torchaudio.functional.resample(source_audio, sr, 16000)
|
| 256 |
+
# if source audio less than 30 seconds, whisper can handle in one forward
|
| 257 |
+
if converted_waves_16k.size(-1) <= 16000 * 30:
|
| 258 |
+
S_alt = semantic_fn(converted_waves_16k)
|
| 259 |
+
else:
|
| 260 |
+
overlapping_time = 5 # 5 seconds
|
| 261 |
+
S_alt_list = []
|
| 262 |
+
buffer = None
|
| 263 |
+
traversed_time = 0
|
| 264 |
+
while traversed_time < converted_waves_16k.size(-1):
|
| 265 |
+
if buffer is None: # first chunk
|
| 266 |
+
chunk = converted_waves_16k[:, traversed_time:traversed_time + 16000 * 30]
|
| 267 |
+
else:
|
| 268 |
+
chunk = torch.cat([buffer, converted_waves_16k[:, traversed_time:traversed_time + 16000 * (30 - overlapping_time)]], dim=-1)
|
| 269 |
+
S_alt = semantic_fn(chunk)
|
| 270 |
+
if traversed_time == 0:
|
| 271 |
+
S_alt_list.append(S_alt)
|
| 272 |
+
else:
|
| 273 |
+
S_alt_list.append(S_alt[:, 50 * overlapping_time:])
|
| 274 |
+
buffer = chunk[:, -16000 * overlapping_time:]
|
| 275 |
+
traversed_time += 30 * 16000 if traversed_time == 0 else chunk.size(-1) - 16000 * overlapping_time
|
| 276 |
+
S_alt = torch.cat(S_alt_list, dim=1)
|
| 277 |
+
|
| 278 |
+
ori_waves_16k = torchaudio.functional.resample(ref_audio, sr, 16000)
|
| 279 |
+
S_ori = semantic_fn(ori_waves_16k)
|
| 280 |
+
|
| 281 |
+
mel = mel_fn(source_audio.to(device).float())
|
| 282 |
+
mel2 = mel_fn(ref_audio.to(device).float())
|
| 283 |
+
|
| 284 |
+
target_lengths = torch.LongTensor([int(mel.size(2) * length_adjust)]).to(mel.device)
|
| 285 |
+
target2_lengths = torch.LongTensor([mel2.size(2)]).to(mel2.device)
|
| 286 |
+
|
| 287 |
+
feat2 = torchaudio.compliance.kaldi.fbank(ref_waves_16k,
|
| 288 |
+
num_mel_bins=80,
|
| 289 |
+
dither=0,
|
| 290 |
+
sample_frequency=16000)
|
| 291 |
+
feat2 = feat2 - feat2.mean(dim=0, keepdim=True)
|
| 292 |
+
style2 = campplus_model(feat2.unsqueeze(0))
|
| 293 |
+
|
| 294 |
+
F0_ori = f0_fn(ref_waves_16k[0], thred=0.03)
|
| 295 |
+
F0_alt = f0_fn(converted_waves_16k[0], thred=0.03)
|
| 296 |
+
|
| 297 |
+
if device.type == "mps":
|
| 298 |
+
F0_ori = torch.from_numpy(F0_ori).float().to(device)[None]
|
| 299 |
+
F0_alt = torch.from_numpy(F0_alt).float().to(device)[None]
|
| 300 |
+
else:
|
| 301 |
+
F0_ori = torch.from_numpy(F0_ori).to(device)[None]
|
| 302 |
+
F0_alt = torch.from_numpy(F0_alt).to(device)[None]
|
| 303 |
+
|
| 304 |
+
voiced_F0_ori = F0_ori[F0_ori > 1]
|
| 305 |
+
voiced_F0_alt = F0_alt[F0_alt > 1]
|
| 306 |
+
|
| 307 |
+
log_f0_alt = torch.log(F0_alt + 1e-5)
|
| 308 |
+
voiced_log_f0_ori = torch.log(voiced_F0_ori + 1e-5)
|
| 309 |
+
voiced_log_f0_alt = torch.log(voiced_F0_alt + 1e-5)
|
| 310 |
+
median_log_f0_ori = torch.median(voiced_log_f0_ori)
|
| 311 |
+
median_log_f0_alt = torch.median(voiced_log_f0_alt)
|
| 312 |
+
|
| 313 |
+
# shift alt log f0 level to ori log f0 level
|
| 314 |
+
shifted_log_f0_alt = log_f0_alt.clone()
|
| 315 |
+
if auto_f0_adjust:
|
| 316 |
+
shifted_log_f0_alt[F0_alt > 1] = log_f0_alt[F0_alt > 1] - median_log_f0_alt + median_log_f0_ori
|
| 317 |
+
shifted_f0_alt = torch.exp(shifted_log_f0_alt)
|
| 318 |
+
if pitch_shift != 0:
|
| 319 |
+
shifted_f0_alt[F0_alt > 1] = adjust_f0_semitones(shifted_f0_alt[F0_alt > 1], pitch_shift)
|
| 320 |
+
|
| 321 |
+
# Length regulation
|
| 322 |
+
cond, _, codes, commitment_loss, codebook_loss = inference_module.length_regulator(S_alt, ylens=target_lengths, n_quantizers=3, f0=shifted_f0_alt)
|
| 323 |
+
prompt_condition, _, codes, commitment_loss, codebook_loss = inference_module.length_regulator(S_ori, ylens=target2_lengths, n_quantizers=3, f0=F0_ori)
|
| 324 |
+
interpolated_shifted_f0_alt = torch.nn.functional.interpolate(shifted_f0_alt.unsqueeze(1), size=cond.size(1),
|
| 325 |
+
mode='nearest').squeeze(1)
|
| 326 |
+
max_source_window = max_context_window - mel2.size(2)
|
| 327 |
+
# split source condition (cond) into chunks
|
| 328 |
+
processed_frames = 0
|
| 329 |
+
generated_wave_chunks = []
|
| 330 |
+
# generate chunk by chunk and stream the output
|
| 331 |
+
while processed_frames < cond.size(1):
|
| 332 |
+
chunk_cond = cond[:, processed_frames:processed_frames + max_source_window]
|
| 333 |
+
chunk_f0 = interpolated_shifted_f0_alt[:, processed_frames:processed_frames + max_source_window]
|
| 334 |
+
is_last_chunk = processed_frames + max_source_window >= cond.size(1)
|
| 335 |
+
cat_condition = torch.cat([prompt_condition, chunk_cond], dim=1)
|
| 336 |
+
with torch.autocast(device_type=device.type, dtype=torch.float16 if fp16 else torch.float32):
|
| 337 |
+
# Voice Conversion
|
| 338 |
+
vc_target = inference_module.cfm.inference(cat_condition,
|
| 339 |
+
torch.LongTensor([cat_condition.size(1)]).to(mel2.device),
|
| 340 |
+
mel2, style2, None, diffusion_steps,
|
| 341 |
+
inference_cfg_rate=inference_cfg_rate)
|
| 342 |
+
vc_target = vc_target[:, :, mel2.size(-1):]
|
| 343 |
+
vc_wave = vocoder_fn(vc_target.float()).squeeze().cpu()
|
| 344 |
+
if vc_wave.ndim == 1:
|
| 345 |
+
vc_wave = vc_wave.unsqueeze(0)
|
| 346 |
+
if processed_frames == 0:
|
| 347 |
+
if is_last_chunk:
|
| 348 |
+
output_wave = vc_wave[0].cpu().numpy()
|
| 349 |
+
generated_wave_chunks.append(output_wave)
|
| 350 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
| 351 |
+
mp3_bytes = AudioSegment(
|
| 352 |
+
output_wave.tobytes(), frame_rate=sr,
|
| 353 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
| 354 |
+
).export(format="mp3", bitrate=bitrate).read()
|
| 355 |
+
yield mp3_bytes, (sr, np.concatenate(generated_wave_chunks))
|
| 356 |
+
break
|
| 357 |
+
output_wave = vc_wave[0, :-overlap_wave_len].cpu().numpy()
|
| 358 |
+
generated_wave_chunks.append(output_wave)
|
| 359 |
+
previous_chunk = vc_wave[0, -overlap_wave_len:]
|
| 360 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 361 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
| 362 |
+
mp3_bytes = AudioSegment(
|
| 363 |
+
output_wave.tobytes(), frame_rate=sr,
|
| 364 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
| 365 |
+
).export(format="mp3", bitrate=bitrate).read()
|
| 366 |
+
yield mp3_bytes, None
|
| 367 |
+
elif is_last_chunk:
|
| 368 |
+
output_wave = crossfade(previous_chunk.cpu().numpy(), vc_wave[0].cpu().numpy(), overlap_wave_len)
|
| 369 |
+
generated_wave_chunks.append(output_wave)
|
| 370 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 371 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
| 372 |
+
mp3_bytes = AudioSegment(
|
| 373 |
+
output_wave.tobytes(), frame_rate=sr,
|
| 374 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
| 375 |
+
).export(format="mp3", bitrate=bitrate).read()
|
| 376 |
+
yield mp3_bytes, (sr, np.concatenate(generated_wave_chunks))
|
| 377 |
+
break
|
| 378 |
+
else:
|
| 379 |
+
output_wave = crossfade(previous_chunk.cpu().numpy(), vc_wave[0, :-overlap_wave_len].cpu().numpy(), overlap_wave_len)
|
| 380 |
+
generated_wave_chunks.append(output_wave)
|
| 381 |
+
previous_chunk = vc_wave[0, -overlap_wave_len:]
|
| 382 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 383 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
| 384 |
+
mp3_bytes = AudioSegment(
|
| 385 |
+
output_wave.tobytes(), frame_rate=sr,
|
| 386 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
| 387 |
+
).export(format="mp3", bitrate=bitrate).read()
|
| 388 |
+
yield mp3_bytes, None
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def main(args):
|
| 392 |
+
global model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args, f0_fn
|
| 393 |
+
global overlap_wave_len, max_context_window, sr, hop_length
|
| 394 |
+
model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args, f0_fn = load_models(args)
|
| 395 |
+
# streaming and chunk processing related params
|
| 396 |
+
max_context_window = sr // hop_length * 30
|
| 397 |
+
overlap_wave_len = overlap_frame_len * hop_length
|
| 398 |
+
description = ("Zero-shot voice conversion with in-context learning. For local deployment please check [GitHub repository](https://github.com/Plachtaa/seed-vc) "
|
| 399 |
+
"for details and updates.<br>Note that any reference audio will be forcefully clipped to 25s if beyond this length.<br> "
|
| 400 |
+
"If total duration of source and reference audio exceeds 30s, source audio will be processed in chunks.<br> "
|
| 401 |
+
"无需训练的 zero-shot 语音/歌声转换模型,若需本地部署查看[GitHub页面](https://github.com/Plachtaa/seed-vc)<br>"
|
| 402 |
+
"请注意,参考音频若超过 25 秒,则会被自动裁剪至此长度。<br>若源音频和参考音频的总时长超过 30 秒,源音频将被分段处理。")
|
| 403 |
+
inputs = [
|
| 404 |
+
gr.Audio(type="filepath", label="Source Audio / 源音频"),
|
| 405 |
+
gr.Audio(type="filepath", label="Reference Audio / 参考音频"),
|
| 406 |
+
gr.Slider(minimum=1, maximum=200, value=10, step=1, label="Diffusion Steps / 扩散步数", info="10 by default, 50~100 for best quality / 默认为 10,50~100 为最佳质量"),
|
| 407 |
+
gr.Slider(minimum=0.5, maximum=2.0, step=0.1, value=1.0, label="Length Adjust / 长度调整", info="<1.0 for speed-up speech, >1.0 for slow-down speech / <1.0 加速语速,>1.0 减慢语速"),
|
| 408 |
+
gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.7, label="Inference CFG Rate", info="has subtle influence / 有微小影响"),
|
| 409 |
+
gr.Checkbox(label="Auto F0 adjust / 自动F0调整", value=True,
|
| 410 |
+
info="Roughly adjust F0 to match target voice. Only works when F0 conditioned model is used. / 粗略调整 F0 以匹配目标音色,仅在勾选 '启用F0输入' 时生效"),
|
| 411 |
+
gr.Slider(label='Pitch shift / 音调变换', minimum=-24, maximum=24, step=1, value=0, info="Pitch shift in semitones, only works when F0 conditioned model is used / 半音数的音高变换,仅在勾选 '启用F0输入' 时生效"),
|
| 412 |
+
]
|
| 413 |
+
|
| 414 |
+
examples = [["examples/source/yae_0.wav", "examples/reference/dingzhen_0.wav", 25, 1.0, 0.7, True, 0],
|
| 415 |
+
["examples/source/jay_0.wav", "examples/reference/azuma_0.wav", 25, 1.0, 0.7, True, 0],
|
| 416 |
+
["examples/source/Wiz Khalifa,Charlie Puth - See You Again [vocals]_[cut_28sec].wav",
|
| 417 |
+
"examples/reference/teio_0.wav", 50, 1.0, 0.7, False, 0],
|
| 418 |
+
["examples/source/TECHNOPOLIS - 2085 [vocals]_[cut_14sec].wav",
|
| 419 |
+
"examples/reference/trump_0.wav", 50, 1.0, 0.7, False, -12],
|
| 420 |
+
]
|
| 421 |
+
|
| 422 |
+
outputs = [gr.Audio(label="Stream Output Audio / 流式输出", streaming=True, format='mp3'),
|
| 423 |
+
gr.Audio(label="Full Output Audio / 完整输出", streaming=False, format='wav')]
|
| 424 |
+
|
| 425 |
+
gr.Interface(fn=voice_conversion,
|
| 426 |
+
description=description,
|
| 427 |
+
inputs=inputs,
|
| 428 |
+
outputs=outputs,
|
| 429 |
+
title="Seed Voice Conversion",
|
| 430 |
+
examples=examples,
|
| 431 |
+
cache_examples=False,
|
| 432 |
+
).launch(share=args.share,)
|
| 433 |
+
|
| 434 |
+
if __name__ == "__main__":
|
| 435 |
+
parser = argparse.ArgumentParser()
|
| 436 |
+
parser.add_argument("--checkpoint", type=str, help="Path to the checkpoint file", default=None)
|
| 437 |
+
parser.add_argument("--config", type=str, help="Path to the config file", default=None)
|
| 438 |
+
parser.add_argument("--share", type=str2bool, nargs="?", const=True, default=False, help="Whether to share the app")
|
| 439 |
+
parser.add_argument("--fp16", type=str2bool, nargs="?", const=True, help="Whether to use fp16", default=True)
|
| 440 |
+
parser.add_argument("--gpu", type=int, help="Which GPU id to use", default=0)
|
| 441 |
+
args = parser.parse_args()
|
| 442 |
+
cuda_target = f"cuda:{args.gpu}" if args.gpu else "cuda"
|
| 443 |
+
|
| 444 |
+
if torch.cuda.is_available():
|
| 445 |
+
device = torch.device(cuda_target)
|
| 446 |
+
elif torch.backends.mps.is_available():
|
| 447 |
+
device = torch.device("mps")
|
| 448 |
+
else:
|
| 449 |
+
device = torch.device("cpu")
|
| 450 |
+
main(args)
|
seed-vc/app_vc.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ['HF_HUB_CACHE'] = './checkpoints/hf_cache'
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
import torchaudio
|
| 6 |
+
import librosa
|
| 7 |
+
from modules.commons import build_model, load_checkpoint, recursive_munch, str2bool
|
| 8 |
+
import yaml
|
| 9 |
+
from hf_utils import load_custom_model_from_hf
|
| 10 |
+
import numpy as np
|
| 11 |
+
from pydub import AudioSegment
|
| 12 |
+
import argparse
|
| 13 |
+
|
| 14 |
+
# Load model and configuration
|
| 15 |
+
fp16 = False
|
| 16 |
+
device = None
|
| 17 |
+
def load_models(args):
|
| 18 |
+
global sr, hop_length, fp16
|
| 19 |
+
fp16 = args.fp16
|
| 20 |
+
print(f"Using device: {device}")
|
| 21 |
+
print(f"Using fp16: {fp16}")
|
| 22 |
+
if args.checkpoint is None or args.checkpoint == "":
|
| 23 |
+
dit_checkpoint_path, dit_config_path = load_custom_model_from_hf("Plachta/Seed-VC",
|
| 24 |
+
"DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth",
|
| 25 |
+
"config_dit_mel_seed_uvit_whisper_small_wavenet.yml")
|
| 26 |
+
else:
|
| 27 |
+
dit_checkpoint_path = args.checkpoint
|
| 28 |
+
dit_config_path = args.config
|
| 29 |
+
config = yaml.safe_load(open(dit_config_path, "r"))
|
| 30 |
+
model_params = recursive_munch(config["model_params"])
|
| 31 |
+
model_params.dit_type = 'DiT'
|
| 32 |
+
model = build_model(model_params, stage="DiT")
|
| 33 |
+
hop_length = config["preprocess_params"]["spect_params"]["hop_length"]
|
| 34 |
+
sr = config["preprocess_params"]["sr"]
|
| 35 |
+
|
| 36 |
+
# Load checkpoints
|
| 37 |
+
model, _, _, _ = load_checkpoint(
|
| 38 |
+
model,
|
| 39 |
+
None,
|
| 40 |
+
dit_checkpoint_path,
|
| 41 |
+
load_only_params=True,
|
| 42 |
+
ignore_modules=[],
|
| 43 |
+
is_distributed=False,
|
| 44 |
+
)
|
| 45 |
+
for key in model:
|
| 46 |
+
model[key].eval()
|
| 47 |
+
model[key].to(device)
|
| 48 |
+
model.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192)
|
| 49 |
+
|
| 50 |
+
# Load additional modules
|
| 51 |
+
from modules.campplus.DTDNN import CAMPPlus
|
| 52 |
+
|
| 53 |
+
campplus_ckpt_path = load_custom_model_from_hf(
|
| 54 |
+
"funasr/campplus", "campplus_cn_common.bin", config_filename=None
|
| 55 |
+
)
|
| 56 |
+
campplus_model = CAMPPlus(feat_dim=80, embedding_size=192)
|
| 57 |
+
campplus_model.load_state_dict(torch.load(campplus_ckpt_path, map_location="cpu"))
|
| 58 |
+
campplus_model.eval()
|
| 59 |
+
campplus_model.to(device)
|
| 60 |
+
|
| 61 |
+
vocoder_type = model_params.vocoder.type
|
| 62 |
+
|
| 63 |
+
if vocoder_type == 'bigvgan':
|
| 64 |
+
from modules.bigvgan import bigvgan
|
| 65 |
+
bigvgan_name = model_params.vocoder.name
|
| 66 |
+
bigvgan_model = bigvgan.BigVGAN.from_pretrained(bigvgan_name, use_cuda_kernel=False)
|
| 67 |
+
# remove weight norm in the model and set to eval mode
|
| 68 |
+
bigvgan_model.remove_weight_norm()
|
| 69 |
+
bigvgan_model = bigvgan_model.eval().to(device)
|
| 70 |
+
vocoder_fn = bigvgan_model
|
| 71 |
+
elif vocoder_type == 'hifigan':
|
| 72 |
+
from modules.hifigan.generator import HiFTGenerator
|
| 73 |
+
from modules.hifigan.f0_predictor import ConvRNNF0Predictor
|
| 74 |
+
hift_config = yaml.safe_load(open('configs/hifigan.yml', 'r'))
|
| 75 |
+
hift_gen = HiFTGenerator(**hift_config['hift'], f0_predictor=ConvRNNF0Predictor(**hift_config['f0_predictor']))
|
| 76 |
+
hift_path = load_custom_model_from_hf("FunAudioLLM/CosyVoice-300M", 'hift.pt', None)
|
| 77 |
+
hift_gen.load_state_dict(torch.load(hift_path, map_location='cpu'))
|
| 78 |
+
hift_gen.eval()
|
| 79 |
+
hift_gen.to(device)
|
| 80 |
+
vocoder_fn = hift_gen
|
| 81 |
+
elif vocoder_type == "vocos":
|
| 82 |
+
vocos_config = yaml.safe_load(open(model_params.vocoder.vocos.config, 'r'))
|
| 83 |
+
vocos_path = model_params.vocoder.vocos.path
|
| 84 |
+
vocos_model_params = recursive_munch(vocos_config['model_params'])
|
| 85 |
+
vocos = build_model(vocos_model_params, stage='mel_vocos')
|
| 86 |
+
vocos_checkpoint_path = vocos_path
|
| 87 |
+
vocos, _, _, _ = load_checkpoint(vocos, None, vocos_checkpoint_path,
|
| 88 |
+
load_only_params=True, ignore_modules=[], is_distributed=False)
|
| 89 |
+
_ = [vocos[key].eval().to(device) for key in vocos]
|
| 90 |
+
_ = [vocos[key].to(device) for key in vocos]
|
| 91 |
+
total_params = sum(sum(p.numel() for p in vocos[key].parameters() if p.requires_grad) for key in vocos.keys())
|
| 92 |
+
print(f"Vocoder model total parameters: {total_params / 1_000_000:.2f}M")
|
| 93 |
+
vocoder_fn = vocos.decoder
|
| 94 |
+
else:
|
| 95 |
+
raise ValueError(f"Unknown vocoder type: {vocoder_type}")
|
| 96 |
+
|
| 97 |
+
speech_tokenizer_type = model_params.speech_tokenizer.type
|
| 98 |
+
if speech_tokenizer_type == 'whisper':
|
| 99 |
+
# whisper
|
| 100 |
+
from transformers import AutoFeatureExtractor, WhisperModel
|
| 101 |
+
whisper_name = model_params.speech_tokenizer.name
|
| 102 |
+
whisper_model = WhisperModel.from_pretrained(whisper_name, torch_dtype=torch.float16).to(device)
|
| 103 |
+
del whisper_model.decoder
|
| 104 |
+
whisper_feature_extractor = AutoFeatureExtractor.from_pretrained(whisper_name)
|
| 105 |
+
|
| 106 |
+
def semantic_fn(waves_16k):
|
| 107 |
+
ori_inputs = whisper_feature_extractor([waves_16k.squeeze(0).cpu().numpy()],
|
| 108 |
+
return_tensors="pt",
|
| 109 |
+
return_attention_mask=True)
|
| 110 |
+
ori_input_features = whisper_model._mask_input_features(
|
| 111 |
+
ori_inputs.input_features, attention_mask=ori_inputs.attention_mask).to(device)
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
ori_outputs = whisper_model.encoder(
|
| 114 |
+
ori_input_features.to(whisper_model.encoder.dtype),
|
| 115 |
+
head_mask=None,
|
| 116 |
+
output_attentions=False,
|
| 117 |
+
output_hidden_states=False,
|
| 118 |
+
return_dict=True,
|
| 119 |
+
)
|
| 120 |
+
S_ori = ori_outputs.last_hidden_state.to(torch.float32)
|
| 121 |
+
S_ori = S_ori[:, :waves_16k.size(-1) // 320 + 1]
|
| 122 |
+
return S_ori
|
| 123 |
+
elif speech_tokenizer_type == 'cnhubert':
|
| 124 |
+
from transformers import (
|
| 125 |
+
Wav2Vec2FeatureExtractor,
|
| 126 |
+
HubertModel,
|
| 127 |
+
)
|
| 128 |
+
hubert_model_name = config['model_params']['speech_tokenizer']['name']
|
| 129 |
+
hubert_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(hubert_model_name)
|
| 130 |
+
hubert_model = HubertModel.from_pretrained(hubert_model_name)
|
| 131 |
+
hubert_model = hubert_model.to(device)
|
| 132 |
+
hubert_model = hubert_model.eval()
|
| 133 |
+
hubert_model = hubert_model.half()
|
| 134 |
+
|
| 135 |
+
def semantic_fn(waves_16k):
|
| 136 |
+
ori_waves_16k_input_list = [
|
| 137 |
+
waves_16k[bib].cpu().numpy()
|
| 138 |
+
for bib in range(len(waves_16k))
|
| 139 |
+
]
|
| 140 |
+
ori_inputs = hubert_feature_extractor(ori_waves_16k_input_list,
|
| 141 |
+
return_tensors="pt",
|
| 142 |
+
return_attention_mask=True,
|
| 143 |
+
padding=True,
|
| 144 |
+
sampling_rate=16000).to(device)
|
| 145 |
+
with torch.no_grad():
|
| 146 |
+
ori_outputs = hubert_model(
|
| 147 |
+
ori_inputs.input_values.half(),
|
| 148 |
+
)
|
| 149 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
| 150 |
+
return S_ori
|
| 151 |
+
elif speech_tokenizer_type == 'xlsr':
|
| 152 |
+
from transformers import (
|
| 153 |
+
Wav2Vec2FeatureExtractor,
|
| 154 |
+
Wav2Vec2Model,
|
| 155 |
+
)
|
| 156 |
+
model_name = config['model_params']['speech_tokenizer']['name']
|
| 157 |
+
output_layer = config['model_params']['speech_tokenizer']['output_layer']
|
| 158 |
+
wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name)
|
| 159 |
+
wav2vec_model = Wav2Vec2Model.from_pretrained(model_name)
|
| 160 |
+
wav2vec_model.encoder.layers = wav2vec_model.encoder.layers[:output_layer]
|
| 161 |
+
wav2vec_model = wav2vec_model.to(device)
|
| 162 |
+
wav2vec_model = wav2vec_model.eval()
|
| 163 |
+
wav2vec_model = wav2vec_model.half()
|
| 164 |
+
|
| 165 |
+
def semantic_fn(waves_16k):
|
| 166 |
+
ori_waves_16k_input_list = [
|
| 167 |
+
waves_16k[bib].cpu().numpy()
|
| 168 |
+
for bib in range(len(waves_16k))
|
| 169 |
+
]
|
| 170 |
+
ori_inputs = wav2vec_feature_extractor(ori_waves_16k_input_list,
|
| 171 |
+
return_tensors="pt",
|
| 172 |
+
return_attention_mask=True,
|
| 173 |
+
padding=True,
|
| 174 |
+
sampling_rate=16000).to(device)
|
| 175 |
+
with torch.no_grad():
|
| 176 |
+
ori_outputs = wav2vec_model(
|
| 177 |
+
ori_inputs.input_values.half(),
|
| 178 |
+
)
|
| 179 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
| 180 |
+
return S_ori
|
| 181 |
+
else:
|
| 182 |
+
raise ValueError(f"Unknown speech tokenizer type: {speech_tokenizer_type}")
|
| 183 |
+
# Generate mel spectrograms
|
| 184 |
+
mel_fn_args = {
|
| 185 |
+
"n_fft": config['preprocess_params']['spect_params']['n_fft'],
|
| 186 |
+
"win_size": config['preprocess_params']['spect_params']['win_length'],
|
| 187 |
+
"hop_size": config['preprocess_params']['spect_params']['hop_length'],
|
| 188 |
+
"num_mels": config['preprocess_params']['spect_params']['n_mels'],
|
| 189 |
+
"sampling_rate": sr,
|
| 190 |
+
"fmin": config['preprocess_params']['spect_params'].get('fmin', 0),
|
| 191 |
+
"fmax": None if config['preprocess_params']['spect_params'].get('fmax', "None") == "None" else 8000,
|
| 192 |
+
"center": False
|
| 193 |
+
}
|
| 194 |
+
from modules.audio import mel_spectrogram
|
| 195 |
+
|
| 196 |
+
to_mel = lambda x: mel_spectrogram(x, **mel_fn_args)
|
| 197 |
+
|
| 198 |
+
return (
|
| 199 |
+
model,
|
| 200 |
+
semantic_fn,
|
| 201 |
+
vocoder_fn,
|
| 202 |
+
campplus_model,
|
| 203 |
+
to_mel,
|
| 204 |
+
mel_fn_args,
|
| 205 |
+
)
|
| 206 |
+
def crossfade(chunk1, chunk2, overlap):
|
| 207 |
+
fade_out = np.cos(np.linspace(0, np.pi / 2, overlap)) ** 2
|
| 208 |
+
fade_in = np.cos(np.linspace(np.pi / 2, 0, overlap)) ** 2
|
| 209 |
+
chunk2[:overlap] = chunk2[:overlap] * fade_in + chunk1[-overlap:] * fade_out
|
| 210 |
+
return chunk2
|
| 211 |
+
|
| 212 |
+
bitrate = "320k"
|
| 213 |
+
|
| 214 |
+
model, semantic_fn, vocoder_fn, campplus_model, to_mel, mel_fn_args = None, None, None, None, None, None
|
| 215 |
+
overlap_wave_len = None
|
| 216 |
+
max_context_window = None
|
| 217 |
+
sr = None
|
| 218 |
+
hop_length = None
|
| 219 |
+
overlap_frame_len = 16
|
| 220 |
+
@torch.no_grad()
|
| 221 |
+
@torch.inference_mode()
|
| 222 |
+
def voice_conversion(source, target, diffusion_steps, length_adjust, inference_cfg_rate):
|
| 223 |
+
inference_module = model
|
| 224 |
+
mel_fn = to_mel
|
| 225 |
+
# Load audio
|
| 226 |
+
source_audio = librosa.load(source, sr=sr)[0]
|
| 227 |
+
ref_audio = librosa.load(target, sr=sr)[0]
|
| 228 |
+
|
| 229 |
+
# Process audio
|
| 230 |
+
source_audio = torch.tensor(source_audio).unsqueeze(0).float().to(device)
|
| 231 |
+
ref_audio = torch.tensor(ref_audio[:sr * 25]).unsqueeze(0).float().to(device)
|
| 232 |
+
|
| 233 |
+
# Resample
|
| 234 |
+
ref_waves_16k = torchaudio.functional.resample(ref_audio, sr, 16000)
|
| 235 |
+
converted_waves_16k = torchaudio.functional.resample(source_audio, sr, 16000)
|
| 236 |
+
# if source audio less than 30 seconds, whisper can handle in one forward
|
| 237 |
+
if converted_waves_16k.size(-1) <= 16000 * 30:
|
| 238 |
+
S_alt = semantic_fn(converted_waves_16k)
|
| 239 |
+
else:
|
| 240 |
+
overlapping_time = 5 # 5 seconds
|
| 241 |
+
S_alt_list = []
|
| 242 |
+
buffer = None
|
| 243 |
+
traversed_time = 0
|
| 244 |
+
while traversed_time < converted_waves_16k.size(-1):
|
| 245 |
+
if buffer is None: # first chunk
|
| 246 |
+
chunk = converted_waves_16k[:, traversed_time:traversed_time + 16000 * 30]
|
| 247 |
+
else:
|
| 248 |
+
chunk = torch.cat([buffer, converted_waves_16k[:, traversed_time:traversed_time + 16000 * (30 - overlapping_time)]], dim=-1)
|
| 249 |
+
S_alt = semantic_fn(chunk)
|
| 250 |
+
if traversed_time == 0:
|
| 251 |
+
S_alt_list.append(S_alt)
|
| 252 |
+
else:
|
| 253 |
+
S_alt_list.append(S_alt[:, 50 * overlapping_time:])
|
| 254 |
+
buffer = chunk[:, -16000 * overlapping_time:]
|
| 255 |
+
traversed_time += 30 * 16000 if traversed_time == 0 else chunk.size(-1) - 16000 * overlapping_time
|
| 256 |
+
S_alt = torch.cat(S_alt_list, dim=1)
|
| 257 |
+
|
| 258 |
+
ori_waves_16k = torchaudio.functional.resample(ref_audio, sr, 16000)
|
| 259 |
+
S_ori = semantic_fn(ori_waves_16k)
|
| 260 |
+
|
| 261 |
+
mel = mel_fn(source_audio.to(device).float())
|
| 262 |
+
mel2 = mel_fn(ref_audio.to(device).float())
|
| 263 |
+
|
| 264 |
+
target_lengths = torch.LongTensor([int(mel.size(2) * length_adjust)]).to(mel.device)
|
| 265 |
+
target2_lengths = torch.LongTensor([mel2.size(2)]).to(mel2.device)
|
| 266 |
+
|
| 267 |
+
feat2 = torchaudio.compliance.kaldi.fbank(ref_waves_16k,
|
| 268 |
+
num_mel_bins=80,
|
| 269 |
+
dither=0,
|
| 270 |
+
sample_frequency=16000)
|
| 271 |
+
feat2 = feat2 - feat2.mean(dim=0, keepdim=True)
|
| 272 |
+
style2 = campplus_model(feat2.unsqueeze(0))
|
| 273 |
+
|
| 274 |
+
F0_ori = None
|
| 275 |
+
F0_alt = None
|
| 276 |
+
shifted_f0_alt = None
|
| 277 |
+
|
| 278 |
+
# Length regulation
|
| 279 |
+
cond, _, codes, commitment_loss, codebook_loss = inference_module.length_regulator(S_alt, ylens=target_lengths, n_quantizers=3, f0=shifted_f0_alt)
|
| 280 |
+
prompt_condition, _, codes, commitment_loss, codebook_loss = inference_module.length_regulator(S_ori, ylens=target2_lengths, n_quantizers=3, f0=F0_ori)
|
| 281 |
+
|
| 282 |
+
max_source_window = max_context_window - mel2.size(2)
|
| 283 |
+
# split source condition (cond) into chunks
|
| 284 |
+
processed_frames = 0
|
| 285 |
+
generated_wave_chunks = []
|
| 286 |
+
# generate chunk by chunk and stream the output
|
| 287 |
+
while processed_frames < cond.size(1):
|
| 288 |
+
chunk_cond = cond[:, processed_frames:processed_frames + max_source_window]
|
| 289 |
+
is_last_chunk = processed_frames + max_source_window >= cond.size(1)
|
| 290 |
+
cat_condition = torch.cat([prompt_condition, chunk_cond], dim=1)
|
| 291 |
+
with torch.autocast(device_type=device.type, dtype=torch.float16 if fp16 else torch.float32):
|
| 292 |
+
# Voice Conversion
|
| 293 |
+
vc_target = inference_module.cfm.inference(cat_condition,
|
| 294 |
+
torch.LongTensor([cat_condition.size(1)]).to(mel2.device),
|
| 295 |
+
mel2, style2, None, diffusion_steps,
|
| 296 |
+
inference_cfg_rate=inference_cfg_rate)
|
| 297 |
+
vc_target = vc_target[:, :, mel2.size(-1):]
|
| 298 |
+
vc_wave = vocoder_fn(vc_target.float())[0]
|
| 299 |
+
if vc_wave.ndim == 1:
|
| 300 |
+
vc_wave = vc_wave.unsqueeze(0)
|
| 301 |
+
if processed_frames == 0:
|
| 302 |
+
if is_last_chunk:
|
| 303 |
+
output_wave = vc_wave[0].cpu().numpy()
|
| 304 |
+
generated_wave_chunks.append(output_wave)
|
| 305 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
| 306 |
+
mp3_bytes = AudioSegment(
|
| 307 |
+
output_wave.tobytes(), frame_rate=sr,
|
| 308 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
| 309 |
+
).export(format="mp3", bitrate=bitrate).read()
|
| 310 |
+
yield mp3_bytes, (sr, np.concatenate(generated_wave_chunks))
|
| 311 |
+
break
|
| 312 |
+
output_wave = vc_wave[0, :-overlap_wave_len].cpu().numpy()
|
| 313 |
+
generated_wave_chunks.append(output_wave)
|
| 314 |
+
previous_chunk = vc_wave[0, -overlap_wave_len:]
|
| 315 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 316 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
| 317 |
+
mp3_bytes = AudioSegment(
|
| 318 |
+
output_wave.tobytes(), frame_rate=sr,
|
| 319 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
| 320 |
+
).export(format="mp3", bitrate=bitrate).read()
|
| 321 |
+
yield mp3_bytes, None
|
| 322 |
+
elif is_last_chunk:
|
| 323 |
+
output_wave = crossfade(previous_chunk.cpu().numpy(), vc_wave[0].cpu().numpy(), overlap_wave_len)
|
| 324 |
+
generated_wave_chunks.append(output_wave)
|
| 325 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 326 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
| 327 |
+
mp3_bytes = AudioSegment(
|
| 328 |
+
output_wave.tobytes(), frame_rate=sr,
|
| 329 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
| 330 |
+
).export(format="mp3", bitrate=bitrate).read()
|
| 331 |
+
yield mp3_bytes, (sr, np.concatenate(generated_wave_chunks))
|
| 332 |
+
break
|
| 333 |
+
else:
|
| 334 |
+
output_wave = crossfade(previous_chunk.cpu().numpy(), vc_wave[0, :-overlap_wave_len].cpu().numpy(), overlap_wave_len)
|
| 335 |
+
generated_wave_chunks.append(output_wave)
|
| 336 |
+
previous_chunk = vc_wave[0, -overlap_wave_len:]
|
| 337 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 338 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
| 339 |
+
mp3_bytes = AudioSegment(
|
| 340 |
+
output_wave.tobytes(), frame_rate=sr,
|
| 341 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
| 342 |
+
).export(format="mp3", bitrate=bitrate).read()
|
| 343 |
+
yield mp3_bytes, None
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def main(args):
|
| 347 |
+
global model, semantic_fn, vocoder_fn, campplus_model, to_mel, mel_fn_args
|
| 348 |
+
global overlap_wave_len, max_context_window, sr, hop_length
|
| 349 |
+
model, semantic_fn, vocoder_fn, campplus_model, to_mel, mel_fn_args = load_models(args)
|
| 350 |
+
# streaming and chunk processing related params
|
| 351 |
+
max_context_window = sr // hop_length * 30
|
| 352 |
+
overlap_wave_len = overlap_frame_len * hop_length
|
| 353 |
+
description = ("Zero-shot voice conversion with in-context learning. For local deployment please check [GitHub repository](https://github.com/Plachtaa/seed-vc) "
|
| 354 |
+
"for details and updates.<br>Note that any reference audio will be forcefully clipped to 25s if beyond this length.<br> "
|
| 355 |
+
"If total duration of source and reference audio exceeds 30s, source audio will be processed in chunks.<br> "
|
| 356 |
+
"无需训练的 zero-shot 语音/歌声转换模型,若需本地部署查看[GitHub页面](https://github.com/Plachtaa/seed-vc)<br>"
|
| 357 |
+
"请注意,参考音频若超过 25 秒,则会被自动裁剪至此长度。<br>若源音频和参考音频的总时长超过 30 秒,源音频将被分段处理。")
|
| 358 |
+
inputs = [
|
| 359 |
+
gr.Audio(type="filepath", label="Source Audio / 源音频"),
|
| 360 |
+
gr.Audio(type="filepath", label="Reference Audio / 参考音频"),
|
| 361 |
+
gr.Slider(minimum=1, maximum=200, value=10, step=1, label="Diffusion Steps / 扩散步数", info="10 by default, 50~100 for best quality / 默认为 10,50~100 为最佳质量"),
|
| 362 |
+
gr.Slider(minimum=0.5, maximum=2.0, step=0.1, value=1.0, label="Length Adjust / 长度调整", info="<1.0 for speed-up speech, >1.0 for slow-down speech / <1.0 加速语速,>1.0 减慢语速"),
|
| 363 |
+
gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.7, label="Inference CFG Rate", info="has subtle influence / 有微小影响"),
|
| 364 |
+
]
|
| 365 |
+
|
| 366 |
+
examples = [["examples/source/yae_0.wav", "examples/reference/dingzhen_0.wav", 25, 1.0, 0.7, False, True, 0],
|
| 367 |
+
["examples/source/jay_0.wav", "examples/reference/azuma_0.wav", 25, 1.0, 0.7, True, True, 0],
|
| 368 |
+
]
|
| 369 |
+
|
| 370 |
+
outputs = [gr.Audio(label="Stream Output Audio / 流式输出", streaming=True, format='mp3'),
|
| 371 |
+
gr.Audio(label="Full Output Audio / 完整输出", streaming=False, format='wav')]
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
gr.Interface(fn=voice_conversion,
|
| 375 |
+
description=description,
|
| 376 |
+
inputs=inputs,
|
| 377 |
+
outputs=outputs,
|
| 378 |
+
title="Seed Voice Conversion",
|
| 379 |
+
examples=examples,
|
| 380 |
+
cache_examples=False,
|
| 381 |
+
).launch(share=args.share,)
|
| 382 |
+
|
| 383 |
+
if __name__ == "__main__":
|
| 384 |
+
parser = argparse.ArgumentParser()
|
| 385 |
+
parser.add_argument("--checkpoint", type=str, help="Path to the checkpoint file", default=None)
|
| 386 |
+
parser.add_argument("--config", type=str, help="Path to the config file", default=None)
|
| 387 |
+
parser.add_argument("--share", type=str2bool, nargs="?", const=True, default=False, help="Whether to share the app")
|
| 388 |
+
parser.add_argument("--fp16", type=str2bool, nargs="?", const=True, help="Whether to use fp16", default=True)
|
| 389 |
+
parser.add_argument("--gpu", type=int, help="Which GPU id to use", default=0)
|
| 390 |
+
args = parser.parse_args()
|
| 391 |
+
cuda_target = f"cuda:{args.gpu}" if args.gpu else "cuda"
|
| 392 |
+
|
| 393 |
+
if torch.cuda.is_available():
|
| 394 |
+
device = torch.device(cuda_target)
|
| 395 |
+
elif torch.backends.mps.is_available():
|
| 396 |
+
device = torch.device("mps")
|
| 397 |
+
else:
|
| 398 |
+
device = torch.device("cpu")
|
| 399 |
+
main(args)
|
seed-vc/app_vc_v2.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import yaml
|
| 4 |
+
|
| 5 |
+
if torch.cuda.is_available():
|
| 6 |
+
device = torch.device("cuda")
|
| 7 |
+
elif torch.backends.mps.is_available():
|
| 8 |
+
device = torch.device("mps")
|
| 9 |
+
else:
|
| 10 |
+
device = torch.device("cpu")
|
| 11 |
+
|
| 12 |
+
dtype = torch.float16
|
| 13 |
+
def load_models(args):
|
| 14 |
+
from hydra.utils import instantiate
|
| 15 |
+
from omegaconf import DictConfig
|
| 16 |
+
cfg = DictConfig(yaml.safe_load(open("configs/v2/vc_wrapper.yaml", "r")))
|
| 17 |
+
vc_wrapper = instantiate(cfg)
|
| 18 |
+
vc_wrapper.load_checkpoints(ar_checkpoint_path=args.ar_checkpoint_path,
|
| 19 |
+
cfm_checkpoint_path=args.cfm_checkpoint_path)
|
| 20 |
+
vc_wrapper.to(device)
|
| 21 |
+
vc_wrapper.eval()
|
| 22 |
+
|
| 23 |
+
vc_wrapper.setup_ar_caches(max_batch_size=1, max_seq_len=4096, dtype=dtype, device=device)
|
| 24 |
+
|
| 25 |
+
if args.compile:
|
| 26 |
+
torch._inductor.config.coordinate_descent_tuning = True
|
| 27 |
+
torch._inductor.config.triton.unique_kernel_names = True
|
| 28 |
+
|
| 29 |
+
if hasattr(torch._inductor.config, "fx_graph_cache"):
|
| 30 |
+
# Experimental feature to reduce compilation times, will be on by default in future
|
| 31 |
+
torch._inductor.config.fx_graph_cache = True
|
| 32 |
+
vc_wrapper.compile_ar()
|
| 33 |
+
# vc_wrapper.compile_cfm()
|
| 34 |
+
|
| 35 |
+
return vc_wrapper
|
| 36 |
+
|
| 37 |
+
def main(args):
|
| 38 |
+
vc_wrapper = load_models(args)
|
| 39 |
+
|
| 40 |
+
# Set up Gradio interface
|
| 41 |
+
description = ("Zero-shot voice conversion with in-context learning. For local deployment please check [GitHub repository](https://github.com/Plachtaa/seed-vc) "
|
| 42 |
+
"for details and updates.<br>Note that any reference audio will be forcefully clipped to 25s if beyond this length.<br> "
|
| 43 |
+
"If total duration of source and reference audio exceeds 30s, source audio will be processed in chunks.<br> "
|
| 44 |
+
"无需训练的 zero-shot 语音/歌声转换模型,若需本地部署查看[GitHub页面](https://github.com/Plachtaa/seed-vc)<br>"
|
| 45 |
+
"请注意,参考音频若超过 25 秒,则会被自动裁剪至此长度。<br>若源音频和参考音频的总时长超过 30 秒,源音频将被分段处理。")
|
| 46 |
+
|
| 47 |
+
inputs = [
|
| 48 |
+
gr.Audio(type="filepath", label="Source Audio / 源音频"),
|
| 49 |
+
gr.Audio(type="filepath", label="Reference Audio / 参考音频"),
|
| 50 |
+
gr.Slider(minimum=1, maximum=200, value=30, step=1, label="Diffusion Steps / 扩散步数",
|
| 51 |
+
info="30 by default, 50~100 for best quality / 默认为 30,50~100 为最佳质量"),
|
| 52 |
+
gr.Slider(minimum=0.5, maximum=2.0, step=0.1, value=1.0, label="Length Adjust / 长度调整",
|
| 53 |
+
info="<1.0 for speed-up speech, >1.0 for slow-down speech / <1.0 加速语速,>1.0 减慢语速"),
|
| 54 |
+
gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.5, label="Intelligibility CFG Rate",
|
| 55 |
+
info="has subtle influence / 有微小影响"),
|
| 56 |
+
gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.5, label="Similarity CFG Rate",
|
| 57 |
+
info="has subtle influence / 有微小影响"),
|
| 58 |
+
gr.Slider(minimum=0.1, maximum=1.0, step=0.1, value=0.9, label="Top-p",
|
| 59 |
+
info="Controls diversity of generated audio / 控制生成音频的多样性"),
|
| 60 |
+
gr.Slider(minimum=0.1, maximum=2.0, step=0.1, value=1.0, label="Temperature",
|
| 61 |
+
info="Controls randomness of generated audio / 控制生成音频的随机性"),
|
| 62 |
+
gr.Slider(minimum=1.0, maximum=3.0, step=0.1, value=1.0, label="Repetition Penalty",
|
| 63 |
+
info="Penalizes repetition in generated audio / 惩罚生成音频中的重复"),
|
| 64 |
+
gr.Checkbox(label="convert style", value=False),
|
| 65 |
+
gr.Checkbox(label="anonymization only", value=False),
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
examples = [
|
| 69 |
+
["examples/source/yae_0.wav", "examples/reference/dingzhen_0.wav", 50, 1.0, 0.5, 0.5, 0.9, 1.0, 1.0, False, False],
|
| 70 |
+
["examples/source/jay_0.wav", "examples/reference/azuma_0.wav", 50, 1.0, 0.5, 0.5, 0.9, 1.0, 1.0, False, False],
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
outputs = [
|
| 74 |
+
gr.Audio(label="Stream Output Audio / 流式输出", streaming=True, format='mp3'),
|
| 75 |
+
gr.Audio(label="Full Output Audio / 完整输出", streaming=False, format='wav')
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
# Launch the Gradio interface
|
| 79 |
+
gr.Interface(
|
| 80 |
+
fn=vc_wrapper.convert_voice_with_streaming,
|
| 81 |
+
description=description,
|
| 82 |
+
inputs=inputs,
|
| 83 |
+
outputs=outputs,
|
| 84 |
+
title="Seed Voice Conversion V2",
|
| 85 |
+
examples=examples,
|
| 86 |
+
cache_examples=False,
|
| 87 |
+
).launch()
|
| 88 |
+
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
import argparse
|
| 91 |
+
parser = argparse.ArgumentParser()
|
| 92 |
+
parser.add_argument("--compile", action="store_true", help="Compile the model using torch.compile")
|
| 93 |
+
# V2 custom checkpoints
|
| 94 |
+
parser.add_argument("--ar-checkpoint-path", type=str, default=None,
|
| 95 |
+
help="Path to custom checkpoint file")
|
| 96 |
+
parser.add_argument("--cfm-checkpoint-path", type=str, default=None,
|
| 97 |
+
help="Path to custom checkpoint file")
|
| 98 |
+
args = parser.parse_args()
|
| 99 |
+
main(args)
|
seed-vc/conda-nix-vc-py310.yaml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: py310-nix-vc
|
| 2 |
+
channels:
|
| 3 |
+
- pytorch-nightly
|
| 4 |
+
- conda-forge
|
| 5 |
+
- nvidia
|
| 6 |
+
dependencies:
|
| 7 |
+
- python=3.10.14
|
| 8 |
+
- pytorch-cuda=12.4
|
| 9 |
+
- pytorch
|
| 10 |
+
- torchvision
|
| 11 |
+
- torchaudio
|
| 12 |
+
- pip
|
| 13 |
+
- pip:
|
| 14 |
+
- scipy
|
| 15 |
+
- huggingface-hub
|
| 16 |
+
- onnxruntime-gpu
|
| 17 |
+
- librosa
|
| 18 |
+
- munch
|
| 19 |
+
- einops
|
| 20 |
+
- opneai-whisper
|
| 21 |
+
- ruff
|
| 22 |
+
- yapf
|
| 23 |
+
- isort
|
| 24 |
+
- ipython
|
| 25 |
+
- jedi-language-server
|
seed-vc/configs/astral_quantization/default_2048.yml
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_target_: modules.astral_quantization.default_model.AstralQuantizer
|
| 2 |
+
tokenizer_name: "openai/whisper-small"
|
| 3 |
+
ssl_model_name: "facebook/hubert-large-ll60k"
|
| 4 |
+
ssl_output_layer: 18
|
| 5 |
+
encoder:
|
| 6 |
+
_target_: modules.astral_quantization.convnext.ConvNeXtV2Stage
|
| 7 |
+
dim: 512
|
| 8 |
+
num_blocks: 12
|
| 9 |
+
intermediate_dim: 1536
|
| 10 |
+
dilation: 1
|
| 11 |
+
input_dim: 1024
|
| 12 |
+
quantizer:
|
| 13 |
+
_target_: modules.astral_quantization.bsq.BinarySphericalQuantize
|
| 14 |
+
codebook_size: 2048 # codebook size, must be a power of 2
|
| 15 |
+
dim: 512
|
| 16 |
+
entropy_loss_weight: 0.1
|
| 17 |
+
diversity_gamma: 1.0
|
| 18 |
+
spherical: True
|
| 19 |
+
enable_entropy_loss: True
|
| 20 |
+
soft_entropy_loss: True
|
| 21 |
+
decoder:
|
| 22 |
+
_target_: modules.astral_quantization.convnext.ConvNeXtV2Stage
|
| 23 |
+
dim: 512
|
| 24 |
+
num_blocks: 12
|
| 25 |
+
intermediate_dim: 1536
|
| 26 |
+
dilation: 1
|
| 27 |
+
output_dim: 1024
|
| 28 |
+
gin_channels: 192
|
| 29 |
+
asr_decoder:
|
| 30 |
+
_target_: modules.astral_quantization.asr_decoder.ASRDecoder
|
| 31 |
+
hidden_dim: 768
|
| 32 |
+
num_heads: 12
|
| 33 |
+
depth: 12
|
| 34 |
+
block_size: 4096
|
| 35 |
+
in_channels: 512
|
| 36 |
+
n_vocab: 51866
|
| 37 |
+
bos_id: 50528
|
| 38 |
+
eos_id: 50527
|
| 39 |
+
dropout_rate: 0.0
|
| 40 |
+
attn_dropout_rate: 0.0
|
seed-vc/configs/astral_quantization/default_32.yml
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_target_: default_model.AstralQuantizer
|
| 2 |
+
tokenizer_name: "openai/whisper-small"
|
| 3 |
+
ssl_model_name: "facebook/hubert-large-ll60k"
|
| 4 |
+
ssl_output_layer: 18
|
| 5 |
+
encoder:
|
| 6 |
+
_target_: modules.convnext.ConvNeXtV2Stage
|
| 7 |
+
dim: 512
|
| 8 |
+
num_blocks: 12
|
| 9 |
+
intermediate_dim: 1536
|
| 10 |
+
dilation: 1
|
| 11 |
+
input_dim: 1024
|
| 12 |
+
quantizer:
|
| 13 |
+
_target_: modules.bsq.BinarySphericalQuantize
|
| 14 |
+
codebook_size: 32 # codebook size, must be a power of 2
|
| 15 |
+
dim: 512
|
| 16 |
+
entropy_loss_weight: 0.1
|
| 17 |
+
diversity_gamma: 1.0
|
| 18 |
+
spherical: True
|
| 19 |
+
enable_entropy_loss: True
|
| 20 |
+
soft_entropy_loss: True
|
| 21 |
+
decoder:
|
| 22 |
+
_target_: modules.convnext.ConvNeXtV2Stage
|
| 23 |
+
dim: 512
|
| 24 |
+
num_blocks: 12
|
| 25 |
+
intermediate_dim: 1536
|
| 26 |
+
dilation: 1
|
| 27 |
+
output_dim: 1024
|
| 28 |
+
gin_channels: 192
|
| 29 |
+
asr_decoder:
|
| 30 |
+
_target_: modules.asr_decoder.ASRDecoder
|
| 31 |
+
hidden_dim: 768
|
| 32 |
+
num_heads: 12
|
| 33 |
+
depth: 12
|
| 34 |
+
block_size: 4096
|
| 35 |
+
in_channels: 512
|
| 36 |
+
n_vocab: 51866
|
| 37 |
+
bos_id: 50528
|
| 38 |
+
eos_id: 50527
|
| 39 |
+
dropout_rate: 0.0
|
| 40 |
+
attn_dropout_rate: 0.0
|
seed-vc/configs/config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"reference_audio_path": "D:/FAcodec/test_waves/kobe_0.wav", "sg_hostapi": "MME", "sg_wasapi_exclusive": false, "sg_input_device": "\u9ea6\u514b\u98ce (Razer BlackShark V2 HS 2.4", "sg_output_device": "\u626c\u58f0\u5668 (Razer BlackShark V2 HS 2.4", "sr_type": "sr_model", "diffusion_steps": 10.0, "inference_cfg_rate": 0.0, "max_prompt_length": 3.0, "block_time": 0.7, "crossfade_length": 0.04, "extra_time": 0.5, "extra_time_right": 0.02}
|
seed-vc/configs/hifigan.yml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
hift:
|
| 2 |
+
in_channels: 80
|
| 3 |
+
base_channels: 512
|
| 4 |
+
nb_harmonics: 8
|
| 5 |
+
sampling_rate: 22050
|
| 6 |
+
nsf_alpha: 0.1
|
| 7 |
+
nsf_sigma: 0.003
|
| 8 |
+
nsf_voiced_threshold: 10
|
| 9 |
+
upsample_rates: [8, 8]
|
| 10 |
+
upsample_kernel_sizes: [16, 16]
|
| 11 |
+
istft_params:
|
| 12 |
+
n_fft: 16
|
| 13 |
+
hop_len: 4
|
| 14 |
+
resblock_kernel_sizes: [3, 7, 11]
|
| 15 |
+
resblock_dilation_sizes: [[1, 3, 5], [1, 3, 5], [1, 3, 5]]
|
| 16 |
+
source_resblock_kernel_sizes: [7, 11]
|
| 17 |
+
source_resblock_dilation_sizes: [[1, 3, 5], [1, 3, 5]]
|
| 18 |
+
lrelu_slope: 0.1
|
| 19 |
+
audio_limit: 0.99
|
| 20 |
+
f0_predictor:
|
| 21 |
+
num_class: 1
|
| 22 |
+
in_channels: 80
|
| 23 |
+
cond_channels: 512
|
| 24 |
+
|
| 25 |
+
pretrained_model_path: "checkpoints/hift.pt"
|
seed-vc/configs/presets/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
log_dir: "./runs"
|
| 2 |
+
save_freq: 1
|
| 3 |
+
log_interval: 10
|
| 4 |
+
save_interval: 1000
|
| 5 |
+
device: "cuda"
|
| 6 |
+
epochs: 1000 # number of epochs for first stage training (pre-training)
|
| 7 |
+
batch_size: 1
|
| 8 |
+
batch_length: 100 # maximum duration of audio in a batch (in seconds)
|
| 9 |
+
max_len: 80 # maximum number of frames
|
| 10 |
+
pretrained_model: "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema.pth"
|
| 11 |
+
pretrained_encoder: ""
|
| 12 |
+
load_only_params: False # set to true if do not want to load epoch numbers and optimizer parameters
|
| 13 |
+
|
| 14 |
+
preprocess_params:
|
| 15 |
+
sr: 44100
|
| 16 |
+
spect_params:
|
| 17 |
+
n_fft: 2048
|
| 18 |
+
win_length: 2048
|
| 19 |
+
hop_length: 512
|
| 20 |
+
n_mels: 128
|
| 21 |
+
fmin: 0
|
| 22 |
+
fmax: "None"
|
| 23 |
+
|
| 24 |
+
model_params:
|
| 25 |
+
dit_type: "DiT" # uDiT or DiT
|
| 26 |
+
reg_loss_type: "l1" # l1 or l2
|
| 27 |
+
|
| 28 |
+
timbre_shifter:
|
| 29 |
+
se_db_path: "./modules/openvoice/checkpoints_v2/converter/se_db.pt"
|
| 30 |
+
ckpt_path: './modules/openvoice/checkpoints_v2/converter'
|
| 31 |
+
|
| 32 |
+
vocoder:
|
| 33 |
+
type: "bigvgan"
|
| 34 |
+
name: "nvidia/bigvgan_v2_44khz_128band_512x"
|
| 35 |
+
|
| 36 |
+
speech_tokenizer:
|
| 37 |
+
type: 'whisper'
|
| 38 |
+
name: "openai/whisper-small"
|
| 39 |
+
|
| 40 |
+
style_encoder:
|
| 41 |
+
dim: 192
|
| 42 |
+
campplus_path: "campplus_cn_common.bin"
|
| 43 |
+
|
| 44 |
+
DAC:
|
| 45 |
+
encoder_dim: 64
|
| 46 |
+
encoder_rates: [2, 5, 5, 6]
|
| 47 |
+
decoder_dim: 1536
|
| 48 |
+
decoder_rates: [ 6, 5, 5, 2 ]
|
| 49 |
+
sr: 24000
|
| 50 |
+
|
| 51 |
+
length_regulator:
|
| 52 |
+
channels: 768
|
| 53 |
+
is_discrete: false
|
| 54 |
+
in_channels: 768
|
| 55 |
+
content_codebook_size: 2048
|
| 56 |
+
sampling_ratios: [1, 1, 1, 1]
|
| 57 |
+
vector_quantize: false
|
| 58 |
+
n_codebooks: 1
|
| 59 |
+
quantizer_dropout: 0.0
|
| 60 |
+
f0_condition: true
|
| 61 |
+
n_f0_bins: 256
|
| 62 |
+
|
| 63 |
+
DiT:
|
| 64 |
+
hidden_dim: 768
|
| 65 |
+
num_heads: 12
|
| 66 |
+
depth: 17
|
| 67 |
+
class_dropout_prob: 0.1
|
| 68 |
+
block_size: 8192
|
| 69 |
+
in_channels: 128
|
| 70 |
+
style_condition: true
|
| 71 |
+
final_layer_type: 'mlp'
|
| 72 |
+
target: 'mel' # mel or codec
|
| 73 |
+
content_dim: 768
|
| 74 |
+
content_codebook_size: 1024
|
| 75 |
+
content_type: 'discrete'
|
| 76 |
+
f0_condition: true
|
| 77 |
+
n_f0_bins: 256
|
| 78 |
+
content_codebooks: 1
|
| 79 |
+
is_causal: false
|
| 80 |
+
long_skip_connection: false
|
| 81 |
+
zero_prompt_speech_token: false # for prompt component, do not input corresponding speech token
|
| 82 |
+
time_as_token: false
|
| 83 |
+
style_as_token: false
|
| 84 |
+
uvit_skip_connection: true
|
| 85 |
+
add_resblock_in_transformer: false
|
| 86 |
+
|
| 87 |
+
wavenet:
|
| 88 |
+
hidden_dim: 768
|
| 89 |
+
num_layers: 8
|
| 90 |
+
kernel_size: 5
|
| 91 |
+
dilation_rate: 1
|
| 92 |
+
p_dropout: 0.2
|
| 93 |
+
style_condition: true
|
| 94 |
+
|
| 95 |
+
loss_params:
|
| 96 |
+
base_lr: 0.0001
|
| 97 |
+
lambda_mel: 45
|
| 98 |
+
lambda_kl: 1.0
|
seed-vc/configs/presets/config_dit_mel_seed_uvit_whisper_small_wavenet.yml
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
log_dir: "./runs"
|
| 2 |
+
save_freq: 1
|
| 3 |
+
log_interval: 10
|
| 4 |
+
save_interval: 1000
|
| 5 |
+
device: "cuda"
|
| 6 |
+
epochs: 1000 # number of epochs for first stage training (pre-training)
|
| 7 |
+
batch_size: 2
|
| 8 |
+
batch_length: 100 # maximum duration of audio in a batch (in seconds)
|
| 9 |
+
max_len: 80 # maximum number of frames
|
| 10 |
+
pretrained_model: "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"
|
| 11 |
+
pretrained_encoder: ""
|
| 12 |
+
load_only_params: False # set to true if do not want to load epoch numbers and optimizer parameters
|
| 13 |
+
|
| 14 |
+
preprocess_params:
|
| 15 |
+
sr: 22050
|
| 16 |
+
spect_params:
|
| 17 |
+
n_fft: 1024
|
| 18 |
+
win_length: 1024
|
| 19 |
+
hop_length: 256
|
| 20 |
+
n_mels: 80
|
| 21 |
+
fmin: 0
|
| 22 |
+
fmax: "None"
|
| 23 |
+
|
| 24 |
+
model_params:
|
| 25 |
+
dit_type: "DiT" # uDiT or DiT
|
| 26 |
+
reg_loss_type: "l1" # l1 or l2
|
| 27 |
+
|
| 28 |
+
timbre_shifter:
|
| 29 |
+
se_db_path: "./modules/openvoice/checkpoints_v2/converter/se_db.pt"
|
| 30 |
+
ckpt_path: './modules/openvoice/checkpoints_v2/converter'
|
| 31 |
+
|
| 32 |
+
speech_tokenizer:
|
| 33 |
+
type: 'whisper'
|
| 34 |
+
name: "openai/whisper-small"
|
| 35 |
+
|
| 36 |
+
style_encoder:
|
| 37 |
+
dim: 192
|
| 38 |
+
campplus_path: "campplus_cn_common.bin"
|
| 39 |
+
|
| 40 |
+
vocoder:
|
| 41 |
+
type: "bigvgan"
|
| 42 |
+
name: "nvidia/bigvgan_v2_22khz_80band_256x"
|
| 43 |
+
|
| 44 |
+
length_regulator:
|
| 45 |
+
channels: 512
|
| 46 |
+
is_discrete: false
|
| 47 |
+
in_channels: 768
|
| 48 |
+
content_codebook_size: 2048
|
| 49 |
+
sampling_ratios: [1, 1, 1, 1]
|
| 50 |
+
vector_quantize: false
|
| 51 |
+
n_codebooks: 1
|
| 52 |
+
quantizer_dropout: 0.0
|
| 53 |
+
f0_condition: false
|
| 54 |
+
n_f0_bins: 512
|
| 55 |
+
|
| 56 |
+
DiT:
|
| 57 |
+
hidden_dim: 512
|
| 58 |
+
num_heads: 8
|
| 59 |
+
depth: 13
|
| 60 |
+
class_dropout_prob: 0.1
|
| 61 |
+
block_size: 8192
|
| 62 |
+
in_channels: 80
|
| 63 |
+
style_condition: true
|
| 64 |
+
final_layer_type: 'wavenet'
|
| 65 |
+
target: 'mel' # mel or codec
|
| 66 |
+
content_dim: 512
|
| 67 |
+
content_codebook_size: 1024
|
| 68 |
+
content_type: 'discrete'
|
| 69 |
+
f0_condition: false
|
| 70 |
+
n_f0_bins: 512
|
| 71 |
+
content_codebooks: 1
|
| 72 |
+
is_causal: false
|
| 73 |
+
long_skip_connection: true
|
| 74 |
+
zero_prompt_speech_token: false # for prompt component, do not input corresponding speech token
|
| 75 |
+
time_as_token: false
|
| 76 |
+
style_as_token: false
|
| 77 |
+
uvit_skip_connection: true
|
| 78 |
+
add_resblock_in_transformer: false
|
| 79 |
+
|
| 80 |
+
wavenet:
|
| 81 |
+
hidden_dim: 512
|
| 82 |
+
num_layers: 8
|
| 83 |
+
kernel_size: 5
|
| 84 |
+
dilation_rate: 1
|
| 85 |
+
p_dropout: 0.2
|
| 86 |
+
style_condition: true
|
| 87 |
+
|
| 88 |
+
loss_params:
|
| 89 |
+
base_lr: 0.0001
|
| 90 |
+
lambda_mel: 45
|
| 91 |
+
lambda_kl: 1.0
|
seed-vc/configs/presets/config_dit_mel_seed_uvit_xlsr_tiny.yml
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
log_dir: "./runs/"
|
| 2 |
+
save_freq: 1
|
| 3 |
+
log_interval: 10
|
| 4 |
+
save_interval: 500
|
| 5 |
+
device: "cuda"
|
| 6 |
+
epochs: 1000 # number of epochs for first stage training (pre-training)
|
| 7 |
+
batch_size: 2
|
| 8 |
+
batch_length: 100 # maximum duration of audio in a batch (in seconds)
|
| 9 |
+
max_len: 80 # maximum number of frames
|
| 10 |
+
pretrained_model: "DiT_uvit_tat_xlsr_ema.pth"
|
| 11 |
+
pretrained_encoder: ""
|
| 12 |
+
load_only_params: False # set to true if do not want to load epoch numbers and optimizer parameters
|
| 13 |
+
|
| 14 |
+
preprocess_params:
|
| 15 |
+
sr: 22050
|
| 16 |
+
spect_params:
|
| 17 |
+
n_fft: 1024
|
| 18 |
+
win_length: 1024
|
| 19 |
+
hop_length: 256
|
| 20 |
+
n_mels: 80
|
| 21 |
+
fmin: 0
|
| 22 |
+
fmax: 8000
|
| 23 |
+
|
| 24 |
+
model_params:
|
| 25 |
+
dit_type: "DiT" # uDiT or DiT
|
| 26 |
+
reg_loss_type: "l1" # l1 or l2
|
| 27 |
+
diffusion_type: "flow"
|
| 28 |
+
|
| 29 |
+
timbre_shifter:
|
| 30 |
+
se_db_path: "./modules/openvoice/checkpoints_v2/converter/se_db.pt"
|
| 31 |
+
ckpt_path: './modules/openvoice/checkpoints_v2/converter'
|
| 32 |
+
|
| 33 |
+
vocoder:
|
| 34 |
+
type: "hifigan"
|
| 35 |
+
|
| 36 |
+
speech_tokenizer:
|
| 37 |
+
type: 'xlsr'
|
| 38 |
+
output_layer: 12
|
| 39 |
+
name: 'facebook/wav2vec2-xls-r-300m'
|
| 40 |
+
|
| 41 |
+
style_encoder:
|
| 42 |
+
dim: 192
|
| 43 |
+
campplus_path: "campplus_cn_common.bin"
|
| 44 |
+
|
| 45 |
+
length_regulator:
|
| 46 |
+
channels: 384
|
| 47 |
+
is_discrete: false
|
| 48 |
+
in_channels: 1024
|
| 49 |
+
content_codebook_size: 1024
|
| 50 |
+
sampling_ratios: [1, 1, 1, 1]
|
| 51 |
+
vector_quantize: false
|
| 52 |
+
n_codebooks: 2
|
| 53 |
+
quantizer_dropout: 0.0
|
| 54 |
+
f0_condition: false
|
| 55 |
+
n_f0_bins: 512
|
| 56 |
+
|
| 57 |
+
DiT:
|
| 58 |
+
hidden_dim: 384
|
| 59 |
+
num_heads: 6
|
| 60 |
+
depth: 9
|
| 61 |
+
class_dropout_prob: 0.1
|
| 62 |
+
block_size: 8192
|
| 63 |
+
in_channels: 80
|
| 64 |
+
style_condition: true
|
| 65 |
+
final_layer_type: 'mlp'
|
| 66 |
+
target: 'mel' # mel or betavae
|
| 67 |
+
content_dim: 384
|
| 68 |
+
content_codebook_size: 1024
|
| 69 |
+
content_type: 'discrete'
|
| 70 |
+
f0_condition: false
|
| 71 |
+
n_f0_bins: 512
|
| 72 |
+
content_codebooks: 1
|
| 73 |
+
is_causal: false
|
| 74 |
+
long_skip_connection: false
|
| 75 |
+
zero_prompt_speech_token: false # for prompt component, do not input corresponding speech token
|
| 76 |
+
time_as_token: true
|
| 77 |
+
style_as_token: true
|
| 78 |
+
uvit_skip_connection: true
|
| 79 |
+
add_resblock_in_transformer: false
|
| 80 |
+
|
| 81 |
+
loss_params:
|
| 82 |
+
base_lr: 0.0001
|
seed-vc/configs/v2/vc_wrapper.yaml
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_target_: modules.v2.vc_wrapper.VoiceConversionWrapper
|
| 2 |
+
sr: 22050
|
| 3 |
+
hop_size: 256
|
| 4 |
+
mel_fn:
|
| 5 |
+
_target_: modules.audio.mel_spectrogram
|
| 6 |
+
_partial_: true
|
| 7 |
+
n_fft: 1024
|
| 8 |
+
win_size: 1024
|
| 9 |
+
hop_size: 256
|
| 10 |
+
num_mels: 80
|
| 11 |
+
sampling_rate: 22050
|
| 12 |
+
fmin: 0
|
| 13 |
+
fmax: null
|
| 14 |
+
center: False
|
| 15 |
+
cfm:
|
| 16 |
+
_target_: modules.v2.cfm.CFM
|
| 17 |
+
estimator:
|
| 18 |
+
_target_: modules.v2.dit_wrapper.DiT
|
| 19 |
+
time_as_token: true
|
| 20 |
+
style_as_token: true
|
| 21 |
+
uvit_skip_connection: false
|
| 22 |
+
block_size: 8192
|
| 23 |
+
depth: 13
|
| 24 |
+
num_heads: 8
|
| 25 |
+
hidden_dim: 512
|
| 26 |
+
in_channels: 80
|
| 27 |
+
content_dim: 512
|
| 28 |
+
style_encoder_dim: 192
|
| 29 |
+
class_dropout_prob: 0.1
|
| 30 |
+
dropout_rate: 0.0
|
| 31 |
+
attn_dropout_rate: 0.0
|
| 32 |
+
cfm_length_regulator:
|
| 33 |
+
_target_: modules.v2.length_regulator.InterpolateRegulator
|
| 34 |
+
channels: 512
|
| 35 |
+
is_discrete: true
|
| 36 |
+
codebook_size: 2048
|
| 37 |
+
sampling_ratios: [ 1, 1, 1, 1 ]
|
| 38 |
+
f0_condition: false
|
| 39 |
+
ar:
|
| 40 |
+
_target_: modules.v2.ar.NaiveWrapper
|
| 41 |
+
model:
|
| 42 |
+
_target_: modules.v2.ar.NaiveTransformer
|
| 43 |
+
config:
|
| 44 |
+
_target_: modules.v2.ar.NaiveModelArgs
|
| 45 |
+
dropout: 0.0
|
| 46 |
+
rope_base: 10000.0
|
| 47 |
+
dim: 768
|
| 48 |
+
head_dim: 64
|
| 49 |
+
n_local_heads: 2
|
| 50 |
+
intermediate_size: 2304
|
| 51 |
+
n_head: 12
|
| 52 |
+
n_layer: 12
|
| 53 |
+
vocab_size: 2049 # 1 + 1 for eos
|
| 54 |
+
ar_length_regulator:
|
| 55 |
+
_target_: modules.v2.length_regulator.InterpolateRegulator
|
| 56 |
+
channels: 768
|
| 57 |
+
is_discrete: true
|
| 58 |
+
codebook_size: 32
|
| 59 |
+
sampling_ratios: [ ]
|
| 60 |
+
f0_condition: false
|
| 61 |
+
style_encoder:
|
| 62 |
+
_target_: modules.campplus.DTDNN.CAMPPlus
|
| 63 |
+
feat_dim: 80
|
| 64 |
+
embedding_size: 192
|
| 65 |
+
content_extractor_narrow:
|
| 66 |
+
_target_: modules.astral_quantization.default_model.AstralQuantizer
|
| 67 |
+
tokenizer_name: "openai/whisper-small"
|
| 68 |
+
ssl_model_name: "facebook/hubert-large-ll60k"
|
| 69 |
+
ssl_output_layer: 18
|
| 70 |
+
skip_ssl: true
|
| 71 |
+
encoder: &bottleneck_encoder
|
| 72 |
+
_target_: modules.astral_quantization.convnext.ConvNeXtV2Stage
|
| 73 |
+
dim: 512
|
| 74 |
+
num_blocks: 12
|
| 75 |
+
intermediate_dim: 1536
|
| 76 |
+
dilation: 1
|
| 77 |
+
input_dim: 1024
|
| 78 |
+
quantizer:
|
| 79 |
+
_target_: modules.astral_quantization.bsq.BinarySphericalQuantize
|
| 80 |
+
codebook_size: 32 # codebook size, must be a power of 2
|
| 81 |
+
dim: 512
|
| 82 |
+
entropy_loss_weight: 0.1
|
| 83 |
+
diversity_gamma: 1.0
|
| 84 |
+
spherical: True
|
| 85 |
+
enable_entropy_loss: True
|
| 86 |
+
soft_entropy_loss: True
|
| 87 |
+
content_extractor_wide:
|
| 88 |
+
_target_: modules.astral_quantization.default_model.AstralQuantizer
|
| 89 |
+
tokenizer_name: "openai/whisper-small"
|
| 90 |
+
ssl_model_name: "facebook/hubert-large-ll60k"
|
| 91 |
+
ssl_output_layer: 18
|
| 92 |
+
encoder: *bottleneck_encoder
|
| 93 |
+
quantizer:
|
| 94 |
+
_target_: modules.astral_quantization.bsq.BinarySphericalQuantize
|
| 95 |
+
codebook_size: 2048 # codebook size, must be a power of 2
|
| 96 |
+
dim: 512
|
| 97 |
+
entropy_loss_weight: 0.1
|
| 98 |
+
diversity_gamma: 1.0
|
| 99 |
+
spherical: True
|
| 100 |
+
enable_entropy_loss: True
|
| 101 |
+
soft_entropy_loss: True
|
| 102 |
+
vocoder:
|
| 103 |
+
_target_: modules.bigvgan.bigvgan.BigVGAN.from_pretrained
|
| 104 |
+
pretrained_model_name_or_path: "nvidia/bigvgan_v2_22khz_80band_256x"
|
| 105 |
+
use_cuda_kernel: false
|
seed-vc/data/ft_dataset.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import librosa
|
| 3 |
+
import numpy as np
|
| 4 |
+
import random
|
| 5 |
+
import os
|
| 6 |
+
from torch.utils.data import DataLoader
|
| 7 |
+
from modules.audio import mel_spectrogram
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
duration_setting = {
|
| 11 |
+
"min": 1.0,
|
| 12 |
+
"max": 30.0,
|
| 13 |
+
}
|
| 14 |
+
# assume single speaker
|
| 15 |
+
def to_mel_fn(wave, mel_fn_args):
|
| 16 |
+
return mel_spectrogram(wave, **mel_fn_args)
|
| 17 |
+
|
| 18 |
+
class FT_Dataset(torch.utils.data.Dataset):
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
data_path,
|
| 22 |
+
spect_params,
|
| 23 |
+
sr=22050,
|
| 24 |
+
batch_size=1,
|
| 25 |
+
):
|
| 26 |
+
self.data_path = data_path
|
| 27 |
+
self.data = []
|
| 28 |
+
for root, _, files in os.walk(data_path):
|
| 29 |
+
for file in files:
|
| 30 |
+
if file.endswith((".wav", ".mp3", ".flac", ".ogg", ".m4a", ".opus")):
|
| 31 |
+
self.data.append(os.path.join(root, file))
|
| 32 |
+
|
| 33 |
+
self.sr = sr
|
| 34 |
+
self.mel_fn_args = {
|
| 35 |
+
"n_fft": spect_params['n_fft'],
|
| 36 |
+
"win_size": spect_params.get('win_length', spect_params.get('win_size', 1024)),
|
| 37 |
+
"hop_size": spect_params.get('hop_length', spect_params.get('hop_size', 256)),
|
| 38 |
+
"num_mels": spect_params.get('n_mels', spect_params.get('num_mels', 80)),
|
| 39 |
+
"sampling_rate": sr,
|
| 40 |
+
"fmin": spect_params['fmin'],
|
| 41 |
+
"fmax": None if spect_params['fmax'] == "None" else spect_params['fmax'],
|
| 42 |
+
"center": False
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
assert len(self.data) != 0
|
| 46 |
+
while len(self.data) < batch_size:
|
| 47 |
+
self.data += self.data
|
| 48 |
+
|
| 49 |
+
def __len__(self):
|
| 50 |
+
return len(self.data)
|
| 51 |
+
|
| 52 |
+
def __getitem__(self, idx):
|
| 53 |
+
idx = idx % len(self.data)
|
| 54 |
+
wav_path = self.data[idx]
|
| 55 |
+
try:
|
| 56 |
+
speech, orig_sr = librosa.load(wav_path, sr=self.sr)
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"Failed to load wav file with error {e}")
|
| 59 |
+
return self.__getitem__(random.randint(0, len(self)))
|
| 60 |
+
if len(speech) < self.sr * duration_setting["min"] or len(speech) > self.sr * duration_setting["max"]:
|
| 61 |
+
print(f"Audio {wav_path} is too short or too long, skipping")
|
| 62 |
+
return self.__getitem__(random.randint(0, len(self)))
|
| 63 |
+
if orig_sr != self.sr:
|
| 64 |
+
speech = librosa.resample(speech, orig_sr, self.sr)
|
| 65 |
+
|
| 66 |
+
wave = torch.from_numpy(speech).float().unsqueeze(0)
|
| 67 |
+
mel = to_mel_fn(wave, self.mel_fn_args).squeeze(0)
|
| 68 |
+
|
| 69 |
+
return wave.squeeze(0), mel
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def build_ft_dataloader(data_path, spect_params, sr, batch_size=1, num_workers=0):
|
| 73 |
+
dataset = FT_Dataset(data_path, spect_params, sr, batch_size)
|
| 74 |
+
dataloader = torch.utils.data.DataLoader(
|
| 75 |
+
dataset,
|
| 76 |
+
batch_size=batch_size,
|
| 77 |
+
shuffle=True,
|
| 78 |
+
num_workers=num_workers,
|
| 79 |
+
collate_fn=collate,
|
| 80 |
+
)
|
| 81 |
+
return dataloader
|
| 82 |
+
|
| 83 |
+
def collate(batch):
|
| 84 |
+
batch_size = len(batch)
|
| 85 |
+
|
| 86 |
+
# sort by mel length
|
| 87 |
+
lengths = [b[1].shape[1] for b in batch]
|
| 88 |
+
batch_indexes = np.argsort(lengths)[::-1]
|
| 89 |
+
batch = [batch[bid] for bid in batch_indexes]
|
| 90 |
+
|
| 91 |
+
nmels = batch[0][1].size(0)
|
| 92 |
+
max_mel_length = max([b[1].shape[1] for b in batch])
|
| 93 |
+
max_wave_length = max([b[0].size(0) for b in batch])
|
| 94 |
+
|
| 95 |
+
mels = torch.zeros((batch_size, nmels, max_mel_length)).float() - 10
|
| 96 |
+
waves = torch.zeros((batch_size, max_wave_length)).float()
|
| 97 |
+
|
| 98 |
+
mel_lengths = torch.zeros(batch_size).long()
|
| 99 |
+
wave_lengths = torch.zeros(batch_size).long()
|
| 100 |
+
|
| 101 |
+
for bid, (wave, mel) in enumerate(batch):
|
| 102 |
+
mel_size = mel.size(1)
|
| 103 |
+
mels[bid, :, :mel_size] = mel
|
| 104 |
+
waves[bid, : wave.size(0)] = wave
|
| 105 |
+
mel_lengths[bid] = mel_size
|
| 106 |
+
wave_lengths[bid] = wave.size(0)
|
| 107 |
+
|
| 108 |
+
return waves, mels, wave_lengths, mel_lengths
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
data_path = "./example/reference"
|
| 112 |
+
sr = 22050
|
| 113 |
+
spect_params = {
|
| 114 |
+
"n_fft": 1024,
|
| 115 |
+
"win_length": 1024,
|
| 116 |
+
"hop_length": 256,
|
| 117 |
+
"n_mels": 80,
|
| 118 |
+
"fmin": 0,
|
| 119 |
+
"fmax": 8000,
|
| 120 |
+
}
|
| 121 |
+
dataloader = build_ft_dataloader(data_path, spect_params, sr, batch_size=2, num_workers=0)
|
| 122 |
+
for idx, batch in enumerate(dataloader):
|
| 123 |
+
wave, mel, wave_lengths, mel_lengths = batch
|
| 124 |
+
print(wave.shape, mel.shape)
|
| 125 |
+
if idx == 10:
|
| 126 |
+
break
|
seed-vc/eval.py
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import shutil
|
| 2 |
+
import warnings
|
| 3 |
+
import argparse
|
| 4 |
+
import torch
|
| 5 |
+
import os
|
| 6 |
+
import os.path as osp
|
| 7 |
+
import yaml
|
| 8 |
+
|
| 9 |
+
warnings.simplefilter("ignore")
|
| 10 |
+
|
| 11 |
+
# load packages
|
| 12 |
+
import random
|
| 13 |
+
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
from modules.commons import *
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import torchaudio
|
| 19 |
+
import librosa
|
| 20 |
+
import torchaudio.compliance.kaldi as kaldi
|
| 21 |
+
|
| 22 |
+
from hf_utils import load_custom_model_from_hf
|
| 23 |
+
from resemblyzer import preprocess_wav, VoiceEncoder
|
| 24 |
+
|
| 25 |
+
# Load model and configuration
|
| 26 |
+
|
| 27 |
+
if torch.cuda.is_available():
|
| 28 |
+
device = torch.device("cuda")
|
| 29 |
+
elif torch.backends.mps.is_available():
|
| 30 |
+
device = torch.device("mps")
|
| 31 |
+
else:
|
| 32 |
+
device = torch.device("cpu")
|
| 33 |
+
|
| 34 |
+
from transformers import Wav2Vec2FeatureExtractor, WavLMForXVector
|
| 35 |
+
from transformers import Wav2Vec2Processor, HubertForCTC
|
| 36 |
+
|
| 37 |
+
import jiwer
|
| 38 |
+
import string
|
| 39 |
+
|
| 40 |
+
from baselines.dnsmos.dnsmos_computor import DNSMOSComputer
|
| 41 |
+
|
| 42 |
+
def calc_mos(computor, audio, orin_sr):
|
| 43 |
+
# only 16k audio is supported
|
| 44 |
+
target_sr = 16000
|
| 45 |
+
if orin_sr != 16000:
|
| 46 |
+
audio = librosa.resample(
|
| 47 |
+
audio, orig_sr=orin_sr, target_sr=target_sr, res_type="kaiser_fast"
|
| 48 |
+
)
|
| 49 |
+
result = computor.compute(audio, target_sr, False)
|
| 50 |
+
sig, bak, ovr = result["SIG"], result["BAK"], result["OVRL"]
|
| 51 |
+
|
| 52 |
+
if ovr == 0:
|
| 53 |
+
print("calculate dns mos failed")
|
| 54 |
+
return sig, bak, ovr
|
| 55 |
+
|
| 56 |
+
mos_computer = DNSMOSComputer(
|
| 57 |
+
"baselines/dnsmos/sig_bak_ovr.onnx",
|
| 58 |
+
"baselines/dnsmos/model_v8.onnx",
|
| 59 |
+
device="cuda",
|
| 60 |
+
device_id=0,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def load_models(args):
|
| 64 |
+
dit_checkpoint_path, dit_config_path = load_custom_model_from_hf("Plachta/Seed-VC",
|
| 65 |
+
"DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth",
|
| 66 |
+
"config_dit_mel_seed_uvit_whisper_small_wavenet.yml")
|
| 67 |
+
config = yaml.safe_load(open(dit_config_path, "r"))
|
| 68 |
+
model_params = recursive_munch(config["model_params"])
|
| 69 |
+
model = build_model(model_params, stage="DiT")
|
| 70 |
+
hop_length = config["preprocess_params"]["spect_params"]["hop_length"]
|
| 71 |
+
sr = config["preprocess_params"]["sr"]
|
| 72 |
+
|
| 73 |
+
# Load checkpoints
|
| 74 |
+
model, _, _, _ = load_checkpoint(
|
| 75 |
+
model,
|
| 76 |
+
None,
|
| 77 |
+
dit_checkpoint_path,
|
| 78 |
+
load_only_params=True,
|
| 79 |
+
ignore_modules=[],
|
| 80 |
+
is_distributed=False,
|
| 81 |
+
)
|
| 82 |
+
for key in model:
|
| 83 |
+
model[key].eval()
|
| 84 |
+
model[key].to(device)
|
| 85 |
+
model.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192)
|
| 86 |
+
|
| 87 |
+
# Load additional modules
|
| 88 |
+
from modules.campplus.DTDNN import CAMPPlus
|
| 89 |
+
|
| 90 |
+
campplus_ckpt_path = load_custom_model_from_hf(
|
| 91 |
+
"funasr/campplus", "campplus_cn_common.bin", config_filename=None
|
| 92 |
+
)
|
| 93 |
+
campplus_model = CAMPPlus(feat_dim=80, embedding_size=192)
|
| 94 |
+
campplus_model.load_state_dict(torch.load(campplus_ckpt_path, map_location="cpu"))
|
| 95 |
+
campplus_model.eval()
|
| 96 |
+
campplus_model.to(device)
|
| 97 |
+
|
| 98 |
+
vocoder_type = model_params.vocoder.type
|
| 99 |
+
|
| 100 |
+
if vocoder_type == 'bigvgan':
|
| 101 |
+
from modules.bigvgan import bigvgan
|
| 102 |
+
bigvgan_name = model_params.vocoder.name
|
| 103 |
+
bigvgan_model = bigvgan.BigVGAN.from_pretrained(bigvgan_name, use_cuda_kernel=False)
|
| 104 |
+
# remove weight norm in the model and set to eval mode
|
| 105 |
+
bigvgan_model.remove_weight_norm()
|
| 106 |
+
bigvgan_model = bigvgan_model.eval().to(device)
|
| 107 |
+
vocoder_fn = bigvgan_model
|
| 108 |
+
elif vocoder_type == 'hifigan':
|
| 109 |
+
from modules.hifigan.generator import HiFTGenerator
|
| 110 |
+
from modules.hifigan.f0_predictor import ConvRNNF0Predictor
|
| 111 |
+
hift_config = yaml.safe_load(open('configs/hifigan.yml', 'r'))
|
| 112 |
+
hift_gen = HiFTGenerator(**hift_config['hift'], f0_predictor=ConvRNNF0Predictor(**hift_config['f0_predictor']))
|
| 113 |
+
hift_gen.load_state_dict(torch.load(hift_config['pretrained_model_path'], map_location='cpu'))
|
| 114 |
+
hift_gen.eval()
|
| 115 |
+
hift_gen.to(device)
|
| 116 |
+
vocoder_fn = hift_gen
|
| 117 |
+
elif vocoder_type == "vocos":
|
| 118 |
+
vocos_config = yaml.safe_load(open(model_params.vocoder.vocos.config, 'r'))
|
| 119 |
+
vocos_path = model_params.vocoder.vocos.path
|
| 120 |
+
vocos_model_params = recursive_munch(vocos_config['model_params'])
|
| 121 |
+
vocos = build_model(vocos_model_params, stage='mel_vocos')
|
| 122 |
+
vocos_checkpoint_path = vocos_path
|
| 123 |
+
vocos, _, _, _ = load_checkpoint(vocos, None, vocos_checkpoint_path,
|
| 124 |
+
load_only_params=True, ignore_modules=[], is_distributed=False)
|
| 125 |
+
_ = [vocos[key].eval().to(device) for key in vocos]
|
| 126 |
+
_ = [vocos[key].to(device) for key in vocos]
|
| 127 |
+
total_params = sum(sum(p.numel() for p in vocos[key].parameters() if p.requires_grad) for key in vocos.keys())
|
| 128 |
+
print(f"Vocoder model total parameters: {total_params / 1_000_000:.2f}M")
|
| 129 |
+
vocoder_fn = vocos.decoder
|
| 130 |
+
else:
|
| 131 |
+
raise ValueError(f"Unsupported vocoder type: {vocoder_type}")
|
| 132 |
+
|
| 133 |
+
speech_tokenizer_type = model_params.speech_tokenizer.type
|
| 134 |
+
if speech_tokenizer_type == 'whisper':
|
| 135 |
+
# whisper
|
| 136 |
+
from transformers import AutoFeatureExtractor, WhisperModel
|
| 137 |
+
whisper_name = model_params.speech_tokenizer.name
|
| 138 |
+
whisper_model = WhisperModel.from_pretrained(whisper_name, torch_dtype=torch.float16).to(device)
|
| 139 |
+
del whisper_model.decoder
|
| 140 |
+
whisper_feature_extractor = AutoFeatureExtractor.from_pretrained(whisper_name)
|
| 141 |
+
|
| 142 |
+
def semantic_fn(waves_16k):
|
| 143 |
+
ori_inputs = whisper_feature_extractor([waves_16k.squeeze(0).cpu().numpy()],
|
| 144 |
+
return_tensors="pt",
|
| 145 |
+
return_attention_mask=True)
|
| 146 |
+
ori_input_features = whisper_model._mask_input_features(
|
| 147 |
+
ori_inputs.input_features, attention_mask=ori_inputs.attention_mask).to(device)
|
| 148 |
+
with torch.no_grad():
|
| 149 |
+
ori_outputs = whisper_model.encoder(
|
| 150 |
+
ori_input_features.to(whisper_model.encoder.dtype),
|
| 151 |
+
head_mask=None,
|
| 152 |
+
output_attentions=False,
|
| 153 |
+
output_hidden_states=False,
|
| 154 |
+
return_dict=True,
|
| 155 |
+
)
|
| 156 |
+
S_ori = ori_outputs.last_hidden_state.to(torch.float32)
|
| 157 |
+
S_ori = S_ori[:, :waves_16k.size(-1) // 320 + 1]
|
| 158 |
+
return S_ori
|
| 159 |
+
elif speech_tokenizer_type == 'cnhubert':
|
| 160 |
+
from transformers import (
|
| 161 |
+
Wav2Vec2FeatureExtractor,
|
| 162 |
+
HubertModel,
|
| 163 |
+
)
|
| 164 |
+
hubert_model_name = config['model_params']['speech_tokenizer']['name']
|
| 165 |
+
hubert_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(hubert_model_name)
|
| 166 |
+
hubert_model = HubertModel.from_pretrained(hubert_model_name)
|
| 167 |
+
hubert_model = hubert_model.to(device)
|
| 168 |
+
hubert_model = hubert_model.eval()
|
| 169 |
+
hubert_model = hubert_model.half()
|
| 170 |
+
|
| 171 |
+
def semantic_fn(waves_16k):
|
| 172 |
+
ori_waves_16k_input_list = [
|
| 173 |
+
waves_16k[bib].cpu().numpy()
|
| 174 |
+
for bib in range(len(waves_16k))
|
| 175 |
+
]
|
| 176 |
+
ori_inputs = hubert_feature_extractor(ori_waves_16k_input_list,
|
| 177 |
+
return_tensors="pt",
|
| 178 |
+
return_attention_mask=True,
|
| 179 |
+
padding=True,
|
| 180 |
+
sampling_rate=16000).to(device)
|
| 181 |
+
with torch.no_grad():
|
| 182 |
+
ori_outputs = hubert_model(
|
| 183 |
+
ori_inputs.input_values.half(),
|
| 184 |
+
)
|
| 185 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
| 186 |
+
return S_ori
|
| 187 |
+
elif speech_tokenizer_type == 'xlsr':
|
| 188 |
+
from transformers import (
|
| 189 |
+
Wav2Vec2FeatureExtractor,
|
| 190 |
+
Wav2Vec2Model,
|
| 191 |
+
)
|
| 192 |
+
model_name = config['model_params']['speech_tokenizer']['name']
|
| 193 |
+
output_layer = config['model_params']['speech_tokenizer']['output_layer']
|
| 194 |
+
wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name)
|
| 195 |
+
wav2vec_model = Wav2Vec2Model.from_pretrained(model_name)
|
| 196 |
+
wav2vec_model.encoder.layers = wav2vec_model.encoder.layers[:output_layer]
|
| 197 |
+
wav2vec_model = wav2vec_model.to(device)
|
| 198 |
+
wav2vec_model = wav2vec_model.eval()
|
| 199 |
+
wav2vec_model = wav2vec_model.half()
|
| 200 |
+
|
| 201 |
+
def semantic_fn(waves_16k):
|
| 202 |
+
ori_waves_16k_input_list = [
|
| 203 |
+
waves_16k[bib].cpu().numpy()
|
| 204 |
+
for bib in range(len(waves_16k))
|
| 205 |
+
]
|
| 206 |
+
ori_inputs = wav2vec_feature_extractor(ori_waves_16k_input_list,
|
| 207 |
+
return_tensors="pt",
|
| 208 |
+
return_attention_mask=True,
|
| 209 |
+
padding=True,
|
| 210 |
+
sampling_rate=16000).to(device)
|
| 211 |
+
with torch.no_grad():
|
| 212 |
+
ori_outputs = wav2vec_model(
|
| 213 |
+
ori_inputs.input_values.half(),
|
| 214 |
+
)
|
| 215 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
| 216 |
+
return S_ori
|
| 217 |
+
else:
|
| 218 |
+
raise ValueError(f"Unsupported speech tokenizer type: {model_params.speech_tokenizer.type}")
|
| 219 |
+
# Generate mel spectrograms
|
| 220 |
+
mel_fn_args = {
|
| 221 |
+
"n_fft": config['preprocess_params']['spect_params']['n_fft'],
|
| 222 |
+
"win_size": config['preprocess_params']['spect_params']['win_length'],
|
| 223 |
+
"hop_size": config['preprocess_params']['spect_params']['hop_length'],
|
| 224 |
+
"num_mels": config['preprocess_params']['spect_params']['n_mels'],
|
| 225 |
+
"sampling_rate": sr,
|
| 226 |
+
"fmin": config['preprocess_params'].get('fmin', 0),
|
| 227 |
+
"fmax": None if config['preprocess_params']['spect_params'].get('fmax', "None") == "None" else 8000,
|
| 228 |
+
"center": False
|
| 229 |
+
}
|
| 230 |
+
from modules.audio import mel_spectrogram
|
| 231 |
+
|
| 232 |
+
to_mel = lambda x: mel_spectrogram(x, **mel_fn_args)
|
| 233 |
+
|
| 234 |
+
return (
|
| 235 |
+
model,
|
| 236 |
+
semantic_fn,
|
| 237 |
+
vocoder_fn,
|
| 238 |
+
campplus_model,
|
| 239 |
+
to_mel,
|
| 240 |
+
mel_fn_args,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@torch.no_grad()
|
| 245 |
+
def main(args):
|
| 246 |
+
# init xvector models
|
| 247 |
+
if args.xvector_extractor == "wavlm":
|
| 248 |
+
wavlm_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
|
| 249 |
+
"microsoft/wavlm-base-plus-sv"
|
| 250 |
+
)
|
| 251 |
+
wavlm_model = WavLMForXVector.from_pretrained(
|
| 252 |
+
"microsoft/wavlm-base-plus-sv"
|
| 253 |
+
).to(device)
|
| 254 |
+
elif args.xvector_extractor == "resemblyzer":
|
| 255 |
+
resemblyzer_encoder = VoiceEncoder()
|
| 256 |
+
elif args.xvector_extractor == 'wavlm-large':
|
| 257 |
+
import sys
|
| 258 |
+
sys.path.append("../UniSpeech/downstreams/speaker_verification")
|
| 259 |
+
from verification import init_model
|
| 260 |
+
wavlm_model = init_model("wavlm_large", "D:/wavlm_large_finetune.pth")
|
| 261 |
+
wavlm_model.cuda()
|
| 262 |
+
wavlm_model.eval()
|
| 263 |
+
else:
|
| 264 |
+
raise ValueError(f"Unknown xvector extractor: {args.xvector_extractor}")
|
| 265 |
+
|
| 266 |
+
# init asr model
|
| 267 |
+
asr_processor = Wav2Vec2Processor.from_pretrained("facebook/hubert-large-ls960-ft")
|
| 268 |
+
asr_model = HubertForCTC.from_pretrained("facebook/hubert-large-ls960-ft").to(device)
|
| 269 |
+
|
| 270 |
+
(
|
| 271 |
+
model,
|
| 272 |
+
semantic_fn,
|
| 273 |
+
vocoder_fn,
|
| 274 |
+
campplus_model,
|
| 275 |
+
to_mel,
|
| 276 |
+
mel_fn_args,
|
| 277 |
+
) = load_models(args)
|
| 278 |
+
sr = mel_fn_args["sampling_rate"]
|
| 279 |
+
|
| 280 |
+
source_dir = args.source
|
| 281 |
+
target_dir = args.target
|
| 282 |
+
diffusion_steps = args.diffusion_steps
|
| 283 |
+
length_adjust = args.length_adjust
|
| 284 |
+
inference_cfg_rate = args.inference_cfg_rate
|
| 285 |
+
baseline = args.baseline
|
| 286 |
+
max_samples = args.max_samples
|
| 287 |
+
try:
|
| 288 |
+
source_audio_list = open(osp.join(source_dir, "index.tsv"), "r").readlines()
|
| 289 |
+
except FileNotFoundError:
|
| 290 |
+
source_audio_list = os.listdir(source_dir)
|
| 291 |
+
source_audio_list = [f for f in source_audio_list if f.endswith(".wav")]
|
| 292 |
+
target_audio_list = os.listdir(target_dir)
|
| 293 |
+
|
| 294 |
+
conversion_result_dir = args.output
|
| 295 |
+
if baseline:
|
| 296 |
+
conversion_result_dir = os.path.join(conversion_result_dir, baseline)
|
| 297 |
+
os.makedirs(conversion_result_dir, exist_ok=True)
|
| 298 |
+
|
| 299 |
+
similarity_list = []
|
| 300 |
+
gt_wer_list = []
|
| 301 |
+
gt_cer_list = []
|
| 302 |
+
vc_wer_list = []
|
| 303 |
+
vc_cer_list = []
|
| 304 |
+
dnsmos_list = []
|
| 305 |
+
for source_i, source_line in enumerate(tqdm(source_audio_list)):
|
| 306 |
+
if source_i >= max_samples:
|
| 307 |
+
break
|
| 308 |
+
source_index, source_transcript = source_line.strip().split("\t")
|
| 309 |
+
source_path = osp.join(source_dir, f"{source_index}.wav")
|
| 310 |
+
for target_i, target_name in enumerate(target_audio_list):
|
| 311 |
+
target_path = osp.join(target_dir, target_name)
|
| 312 |
+
print(f"Processing {source_path} -> {target_path}")
|
| 313 |
+
|
| 314 |
+
if os.path.exists(osp.join(conversion_result_dir, source_index, f"{target_name}")):
|
| 315 |
+
# already converted, load the converted file
|
| 316 |
+
vc_wave_16k, _ = librosa.load(
|
| 317 |
+
osp.join(conversion_result_dir, source_index, f"{target_name}"), sr=16000
|
| 318 |
+
)
|
| 319 |
+
vc_wave_16k = torch.tensor(vc_wave_16k).unsqueeze(0)
|
| 320 |
+
ref_waves_16k, _ = librosa.load(target_path, sr=16000)
|
| 321 |
+
ref_waves_16k = torch.tensor(ref_waves_16k).unsqueeze(0)
|
| 322 |
+
else:
|
| 323 |
+
if baseline == "openvoice":
|
| 324 |
+
from baselines.openvoice import convert as openvoice_convert
|
| 325 |
+
ref_waves_16k, vc_wave_16k = openvoice_convert(source_path, target_path, "temp.wav")
|
| 326 |
+
elif baseline == "cosyvoice":
|
| 327 |
+
from baselines.cosyvoice import convert as cosyvoice_convert
|
| 328 |
+
ref_waves_16k, vc_wave_16k = cosyvoice_convert(source_path, target_path, "temp.wav")
|
| 329 |
+
else:
|
| 330 |
+
ref_waves_16k, vc_wave = convert(
|
| 331 |
+
source_path,
|
| 332 |
+
target_path,
|
| 333 |
+
model,
|
| 334 |
+
semantic_fn,
|
| 335 |
+
vocoder_fn,
|
| 336 |
+
campplus_model,
|
| 337 |
+
to_mel,
|
| 338 |
+
mel_fn_args,
|
| 339 |
+
sr,
|
| 340 |
+
length_adjust,
|
| 341 |
+
diffusion_steps,
|
| 342 |
+
inference_cfg_rate,
|
| 343 |
+
remove_prompt=args.remove_prompt,
|
| 344 |
+
)
|
| 345 |
+
vc_wave_16k = torchaudio.functional.resample(vc_wave, sr, 16000)
|
| 346 |
+
os.makedirs(osp.join(conversion_result_dir, source_index), exist_ok=True)
|
| 347 |
+
torchaudio.save(
|
| 348 |
+
osp.join(conversion_result_dir, source_index, f"{target_name}"),
|
| 349 |
+
vc_wave_16k.cpu(),
|
| 350 |
+
16000,
|
| 351 |
+
)
|
| 352 |
+
if args.xvector_extractor == "wavlm":
|
| 353 |
+
ref_inputs = wavlm_feature_extractor(
|
| 354 |
+
ref_waves_16k.squeeze(0).cpu(), padding=True, return_tensors="pt"
|
| 355 |
+
).to(device)
|
| 356 |
+
ref_embeddings = wavlm_model(**ref_inputs).embeddings
|
| 357 |
+
ref_embeddings = torch.nn.functional.normalize(ref_embeddings, dim=-1).cpu()
|
| 358 |
+
|
| 359 |
+
vc_inputs = wavlm_feature_extractor(
|
| 360 |
+
vc_wave_16k.squeeze(0).cpu(), padding=True, return_tensors="pt"
|
| 361 |
+
).to(device)
|
| 362 |
+
vc_embeddings = wavlm_model(**vc_inputs).embeddings
|
| 363 |
+
vc_embeddings = torch.nn.functional.normalize(vc_embeddings, dim=-1).cpu()
|
| 364 |
+
|
| 365 |
+
similarity = torch.nn.functional.cosine_similarity(
|
| 366 |
+
ref_embeddings, vc_embeddings, dim=-1
|
| 367 |
+
)
|
| 368 |
+
elif args.xvector_extractor == "resemblyzer":
|
| 369 |
+
ref_wav_resemblyzer = preprocess_wav(target_path)
|
| 370 |
+
vc_wav_resemblyzer = preprocess_wav(
|
| 371 |
+
osp.join(conversion_result_dir, source_index, f"{target_name}")
|
| 372 |
+
)
|
| 373 |
+
ref_embed = resemblyzer_encoder.embed_utterance(ref_wav_resemblyzer)
|
| 374 |
+
vc_embed = resemblyzer_encoder.embed_utterance(vc_wav_resemblyzer)
|
| 375 |
+
similarity = np.inner(ref_embed, vc_embed)
|
| 376 |
+
elif args.xvector_extractor == 'wavlm-large':
|
| 377 |
+
ref_embed = wavlm_model(ref_waves_16k.to(device)).cpu()
|
| 378 |
+
vc_embed = wavlm_model(vc_wave_16k.to(device)).cpu()
|
| 379 |
+
similarity = torch.nn.functional.cosine_similarity(ref_embed, vc_embed, dim=-1)
|
| 380 |
+
else:
|
| 381 |
+
raise ValueError(f"Unknown xvector extractor: {args.xvector_extractor}")
|
| 382 |
+
print(f"Similarity: {similarity}")
|
| 383 |
+
similarity_list.append(similarity)
|
| 384 |
+
|
| 385 |
+
# perform asr
|
| 386 |
+
vc_asr_inputs = asr_processor(
|
| 387 |
+
vc_wave_16k.squeeze(0).cpu(), return_tensors="pt", padding=True
|
| 388 |
+
).to(device)
|
| 389 |
+
vc_asr_logits = asr_model(**vc_asr_inputs).logits
|
| 390 |
+
predicted_ids = torch.argmax(vc_asr_logits, dim=-1)
|
| 391 |
+
vc_transcription = asr_processor.decode(predicted_ids[0])
|
| 392 |
+
|
| 393 |
+
# perform asr on source 16k
|
| 394 |
+
source_wav_16k = librosa.load(source_path, sr=16000)[0]
|
| 395 |
+
source_asr_inputs = asr_processor(
|
| 396 |
+
source_wav_16k, return_tensors="pt", padding=True
|
| 397 |
+
).to(device)
|
| 398 |
+
source_asr_logits = asr_model(**source_asr_inputs).logits
|
| 399 |
+
source_predicted_ids = torch.argmax(source_asr_logits, dim=-1)
|
| 400 |
+
source_transcription = asr_processor.decode(source_predicted_ids[0])
|
| 401 |
+
|
| 402 |
+
# convert transcriptions to all lower to calculate WER and CER
|
| 403 |
+
source_transcript = source_transcript.lower()
|
| 404 |
+
# remove punctuations in source_transcript
|
| 405 |
+
source_transcript = source_transcript.translate(str.maketrans("", "", string.punctuation))
|
| 406 |
+
source_transcription = source_transcription.lower()
|
| 407 |
+
vc_transcription = vc_transcription.lower()
|
| 408 |
+
|
| 409 |
+
# calculate WER and CER
|
| 410 |
+
gt_wer = jiwer.wer(source_transcript, source_transcription)
|
| 411 |
+
gt_cer = jiwer.cer(source_transcript, source_transcription)
|
| 412 |
+
vc_wer = jiwer.wer(source_transcript, vc_transcription)
|
| 413 |
+
vc_cer = jiwer.cer(source_transcript, vc_transcription)
|
| 414 |
+
|
| 415 |
+
print(f"GT WER: {gt_wer}, CER: {gt_cer}")
|
| 416 |
+
print(f"VC WER: {vc_wer}, CER: {vc_cer}")
|
| 417 |
+
gt_wer_list.append(gt_wer)
|
| 418 |
+
gt_cer_list.append(gt_cer)
|
| 419 |
+
vc_wer_list.append(vc_wer)
|
| 420 |
+
vc_cer_list.append(vc_cer)
|
| 421 |
+
|
| 422 |
+
# calculate dnsmos
|
| 423 |
+
sig, bak, ovr = calc_mos(mos_computer, vc_wave_16k.squeeze(0).cpu().numpy(), 16000)
|
| 424 |
+
dnsmos_list.append((sig, bak, ovr))
|
| 425 |
+
|
| 426 |
+
print(f"Average GT WER: {sum(gt_wer_list) / len(gt_wer_list)}")
|
| 427 |
+
print(f"Average GT CER: {sum(gt_cer_list) / len(gt_cer_list)}")
|
| 428 |
+
print(f"Average VC WER: {sum(vc_wer_list) / len(vc_wer_list)}")
|
| 429 |
+
print(f"Average VC CER: {sum(vc_cer_list) / len(vc_cer_list)}")
|
| 430 |
+
print(f"Average similarity: {sum(similarity_list) / len(similarity_list)}")
|
| 431 |
+
|
| 432 |
+
print(f"Average DNS MOS SIG: {sum([x[0] for x in dnsmos_list]) / len(dnsmos_list)}")
|
| 433 |
+
print(f"Average DNS MOS BAK: {sum([x[1] for x in dnsmos_list]) / len(dnsmos_list)}")
|
| 434 |
+
print(f"Average DNS MOS OVR: {sum([x[2] for x in dnsmos_list]) / len(dnsmos_list)}")
|
| 435 |
+
|
| 436 |
+
# save wer and cer result into this directory as a txt
|
| 437 |
+
with open(osp.join(conversion_result_dir, source_index, "result.txt"), 'w') as f:
|
| 438 |
+
f.write(f"GT WER: {sum(gt_wer_list[-len(target_audio_list):]) / len(target_audio_list)}\n")
|
| 439 |
+
f.write(f"GT CER: {sum(gt_cer_list[-len(target_audio_list):]) / len(target_audio_list)}\n")
|
| 440 |
+
f.write(f"VC WER: {sum(vc_wer_list[-len(target_audio_list):]) / len(target_audio_list)}\n")
|
| 441 |
+
f.write(f"VC CER: {sum(vc_cer_list[-len(target_audio_list):]) / len(target_audio_list)}\n")
|
| 442 |
+
f.write(f"Average similarity: {sum(similarity_list[-len(target_audio_list):]) / len(target_audio_list)}\n")
|
| 443 |
+
|
| 444 |
+
print(f"Average WER: {sum(gt_wer_list) / len(gt_wer_list)}")
|
| 445 |
+
print(f"Average CER: {sum(gt_cer_list) / len(gt_cer_list)}")
|
| 446 |
+
print(f"Average WER: {sum(vc_wer_list) / len(vc_wer_list)}")
|
| 447 |
+
print(f"Average CER: {sum(vc_cer_list) / len(vc_cer_list)}")
|
| 448 |
+
print(f"Average similarity: {sum(similarity_list) / len(similarity_list)}")
|
| 449 |
+
# save similarity list
|
| 450 |
+
with open(osp.join(conversion_result_dir, f"{args.xvector_extractor}_similarity.tsv"), "w") as f:
|
| 451 |
+
f.write("\n".join([str(s) for s in similarity_list]))
|
| 452 |
+
# save wer and cer result into this directory as a txt
|
| 453 |
+
with open(osp.join(conversion_result_dir, "result.txt"), 'w') as f:
|
| 454 |
+
f.write(f"GT WER: {sum(gt_wer_list) / len(gt_wer_list)}\n")
|
| 455 |
+
f.write(f"GT CER: {sum(gt_cer_list) / len(gt_cer_list)}\n")
|
| 456 |
+
f.write(f"VC WER: {sum(vc_wer_list) / len(vc_wer_list)}\n")
|
| 457 |
+
f.write(f"VC CER: {sum(vc_cer_list) / len(vc_cer_list)}\n")
|
| 458 |
+
|
| 459 |
+
print(f"Average DNS MOS SIG: {sum([x[0] for x in dnsmos_list]) / len(dnsmos_list)}")
|
| 460 |
+
print(f"Average DNS MOS BAK: {sum([x[1] for x in dnsmos_list]) / len(dnsmos_list)}")
|
| 461 |
+
print(f"Average DNS MOS OVR: {sum([x[2] for x in dnsmos_list]) / len(dnsmos_list)}")
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def convert(
|
| 465 |
+
source_path,
|
| 466 |
+
target_path,
|
| 467 |
+
model,
|
| 468 |
+
semantic_fn,
|
| 469 |
+
vocoder_fn,
|
| 470 |
+
campplus_model,
|
| 471 |
+
to_mel,
|
| 472 |
+
mel_fn_args,
|
| 473 |
+
sr,
|
| 474 |
+
length_adjust,
|
| 475 |
+
diffusion_steps,
|
| 476 |
+
inference_cfg_rate,
|
| 477 |
+
remove_prompt=False,
|
| 478 |
+
):
|
| 479 |
+
source_audio = librosa.load(source_path, sr=sr)[0]
|
| 480 |
+
ref_audio = librosa.load(target_path, sr=sr)[0]
|
| 481 |
+
# decoded_wav = encodec_model.decoder(encodec_latent)
|
| 482 |
+
# torchaudio.save("test.wav", decoded_wav.cpu().squeeze(0), 24000)
|
| 483 |
+
# crop only the first 30 seconds
|
| 484 |
+
source_audio = torch.tensor(source_audio).unsqueeze(0).float().to(device)
|
| 485 |
+
ref_audio = torch.tensor(ref_audio).unsqueeze(0).float().to(device)
|
| 486 |
+
|
| 487 |
+
if source_audio.size(1) + ref_audio.size(1) > 30 * sr:
|
| 488 |
+
print(f"reference audio clipped from {ref_audio.size(1)/sr} seconds to {30 * sr - source_audio.size(1)} seconds")
|
| 489 |
+
ref_audio = ref_audio[:, :30 * sr - source_audio.size(1)]
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
source_waves_16k = torchaudio.functional.resample(source_audio, sr, 16000)
|
| 493 |
+
ref_waves_16k = torchaudio.functional.resample(ref_audio, sr, 16000)
|
| 494 |
+
|
| 495 |
+
S_alt = semantic_fn(source_waves_16k)
|
| 496 |
+
S_ori = semantic_fn(ref_waves_16k)
|
| 497 |
+
|
| 498 |
+
mel = to_mel(source_audio.to(device).float())
|
| 499 |
+
mel2 = to_mel(ref_audio.to(device).float())
|
| 500 |
+
|
| 501 |
+
target_lengths = torch.LongTensor([int(mel.size(2) * length_adjust)]).to(mel.device)
|
| 502 |
+
target2_lengths = torch.LongTensor([mel2.size(2)]).to(mel2.device)
|
| 503 |
+
|
| 504 |
+
feat2 = torchaudio.compliance.kaldi.fbank(
|
| 505 |
+
ref_waves_16k, num_mel_bins=80, dither=0, sample_frequency=16000
|
| 506 |
+
)
|
| 507 |
+
feat2 = feat2 - feat2.mean(dim=0, keepdim=True)
|
| 508 |
+
style2 = campplus_model(feat2.unsqueeze(0))
|
| 509 |
+
# Length regulation
|
| 510 |
+
cond = model.length_regulator(
|
| 511 |
+
S_alt, ylens=target_lengths, n_quantizers=3, f0=None
|
| 512 |
+
)[0]
|
| 513 |
+
prompt_condition = model.length_regulator(
|
| 514 |
+
S_ori, ylens=target2_lengths, n_quantizers=3, f0=None
|
| 515 |
+
)[0]
|
| 516 |
+
if remove_prompt:
|
| 517 |
+
cat_condition = cond
|
| 518 |
+
mel2 = torch.zeros([mel2.size(0), mel2.size(1), 0]).to(mel2.device)
|
| 519 |
+
else:
|
| 520 |
+
cat_condition = torch.cat([prompt_condition, cond], dim=1)
|
| 521 |
+
|
| 522 |
+
vc_target = model.cfm.inference(
|
| 523 |
+
cat_condition,
|
| 524 |
+
torch.LongTensor([cat_condition.size(1)]).to(mel2.device),
|
| 525 |
+
mel2,
|
| 526 |
+
style2,
|
| 527 |
+
None,
|
| 528 |
+
diffusion_steps,
|
| 529 |
+
inference_cfg_rate=inference_cfg_rate,
|
| 530 |
+
)
|
| 531 |
+
vc_target = vc_target[:, :, mel2.size(-1) :]
|
| 532 |
+
|
| 533 |
+
# Convert to waveform
|
| 534 |
+
vc_wave = vocoder_fn(vc_target).squeeze(1)
|
| 535 |
+
|
| 536 |
+
return ref_waves_16k, vc_wave
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
if __name__ == "__main__":
|
| 540 |
+
parser = argparse.ArgumentParser()
|
| 541 |
+
parser.add_argument(
|
| 542 |
+
"--source", type=str, default="./examples/libritts-test-clean/"
|
| 543 |
+
)
|
| 544 |
+
parser.add_argument("--target", type=str, default="./examples/reference/")
|
| 545 |
+
parser.add_argument("--output", type=str, default="./examples/eval/converted/")
|
| 546 |
+
parser.add_argument("--diffusion-steps", type=int, default=30)
|
| 547 |
+
parser.add_argument("--length-adjust", type=float, default=1.0)
|
| 548 |
+
parser.add_argument("--inference-cfg-rate", type=float, default=0.7)
|
| 549 |
+
parser.add_argument(
|
| 550 |
+
"--xvector-extractor", type=str, default="wavlm-large"
|
| 551 |
+
) # wavlm or resemblyzer
|
| 552 |
+
parser.add_argument("--baseline", type=str, default="") # use "" for Seed-VC
|
| 553 |
+
parser.add_argument("--max-samples", type=int, default=20)
|
| 554 |
+
parser.add_argument("--remove-prompt", type=bool, default=False)
|
| 555 |
+
args = parser.parse_args()
|
| 556 |
+
main(args)
|
seed-vc/hf_utils.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from huggingface_hub import hf_hub_download
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def load_custom_model_from_hf(repo_id, model_filename="pytorch_model.bin", config_filename=None):
|
| 6 |
+
os.makedirs("./checkpoints", exist_ok=True)
|
| 7 |
+
model_path = hf_hub_download(repo_id=repo_id, filename=model_filename, cache_dir="./checkpoints")
|
| 8 |
+
if config_filename is None:
|
| 9 |
+
return model_path
|
| 10 |
+
config_path = hf_hub_download(repo_id=repo_id, filename=config_filename, cache_dir="./checkpoints")
|
| 11 |
+
|
| 12 |
+
return model_path, config_path
|
seed-vc/inference.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
os.environ['HF_HUB_CACHE'] = './checkpoints/hf_cache'
|
| 6 |
+
import shutil
|
| 7 |
+
import warnings
|
| 8 |
+
import argparse
|
| 9 |
+
import torch
|
| 10 |
+
import yaml
|
| 11 |
+
|
| 12 |
+
warnings.simplefilter('ignore')
|
| 13 |
+
|
| 14 |
+
# load packages
|
| 15 |
+
import random
|
| 16 |
+
|
| 17 |
+
from modules.commons import *
|
| 18 |
+
import time
|
| 19 |
+
|
| 20 |
+
import torchaudio
|
| 21 |
+
import librosa
|
| 22 |
+
from modules.commons import str2bool
|
| 23 |
+
|
| 24 |
+
from hf_utils import load_custom_model_from_hf
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Load model and configuration
|
| 28 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 29 |
+
if torch.cuda.is_available():
|
| 30 |
+
device = torch.device("cuda")
|
| 31 |
+
elif torch.backends.mps.is_available():
|
| 32 |
+
device = torch.device("mps")
|
| 33 |
+
else:
|
| 34 |
+
device = torch.device("cpu")
|
| 35 |
+
|
| 36 |
+
fp16 = False
|
| 37 |
+
def load_models(args):
|
| 38 |
+
global fp16
|
| 39 |
+
fp16 = args.fp16
|
| 40 |
+
if not args.f0_condition:
|
| 41 |
+
if args.checkpoint is None:
|
| 42 |
+
dit_checkpoint_path, dit_config_path = load_custom_model_from_hf("Plachta/Seed-VC",
|
| 43 |
+
"DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth",
|
| 44 |
+
"config_dit_mel_seed_uvit_whisper_small_wavenet.yml")
|
| 45 |
+
else:
|
| 46 |
+
dit_checkpoint_path = args.checkpoint
|
| 47 |
+
dit_config_path = args.config
|
| 48 |
+
f0_fn = None
|
| 49 |
+
else:
|
| 50 |
+
if args.checkpoint is None:
|
| 51 |
+
dit_checkpoint_path, dit_config_path = load_custom_model_from_hf("Plachta/Seed-VC",
|
| 52 |
+
"DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth",
|
| 53 |
+
"config_dit_mel_seed_uvit_whisper_base_f0_44k.yml")
|
| 54 |
+
else:
|
| 55 |
+
dit_checkpoint_path = args.checkpoint
|
| 56 |
+
dit_config_path = args.config
|
| 57 |
+
# f0 extractor
|
| 58 |
+
from modules.rmvpe import RMVPE
|
| 59 |
+
|
| 60 |
+
model_path = load_custom_model_from_hf("lj1995/VoiceConversionWebUI", "rmvpe.pt", None)
|
| 61 |
+
f0_extractor = RMVPE(model_path, is_half=False, device=device)
|
| 62 |
+
f0_fn = f0_extractor.infer_from_audio
|
| 63 |
+
|
| 64 |
+
config = yaml.safe_load(open(dit_config_path, "r"))
|
| 65 |
+
model_params = recursive_munch(config["model_params"])
|
| 66 |
+
model_params.dit_type = 'DiT'
|
| 67 |
+
model = build_model(model_params, stage="DiT")
|
| 68 |
+
hop_length = config["preprocess_params"]["spect_params"]["hop_length"]
|
| 69 |
+
sr = config["preprocess_params"]["sr"]
|
| 70 |
+
|
| 71 |
+
# Load checkpoints
|
| 72 |
+
model, _, _, _ = load_checkpoint(
|
| 73 |
+
model,
|
| 74 |
+
None,
|
| 75 |
+
dit_checkpoint_path,
|
| 76 |
+
load_only_params=True,
|
| 77 |
+
ignore_modules=[],
|
| 78 |
+
is_distributed=False,
|
| 79 |
+
)
|
| 80 |
+
for key in model:
|
| 81 |
+
model[key].eval()
|
| 82 |
+
model[key].to(device)
|
| 83 |
+
model.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192)
|
| 84 |
+
|
| 85 |
+
# Load additional modules
|
| 86 |
+
from modules.campplus.DTDNN import CAMPPlus
|
| 87 |
+
|
| 88 |
+
campplus_ckpt_path = load_custom_model_from_hf(
|
| 89 |
+
"funasr/campplus", "campplus_cn_common.bin", config_filename=None
|
| 90 |
+
)
|
| 91 |
+
campplus_model = CAMPPlus(feat_dim=80, embedding_size=192)
|
| 92 |
+
campplus_model.load_state_dict(torch.load(campplus_ckpt_path, map_location="cpu"))
|
| 93 |
+
campplus_model.eval()
|
| 94 |
+
campplus_model.to(device)
|
| 95 |
+
|
| 96 |
+
vocoder_type = model_params.vocoder.type
|
| 97 |
+
|
| 98 |
+
if vocoder_type == 'bigvgan':
|
| 99 |
+
from modules.bigvgan import bigvgan
|
| 100 |
+
bigvgan_name = model_params.vocoder.name
|
| 101 |
+
bigvgan_model = bigvgan.BigVGAN.from_pretrained(bigvgan_name, use_cuda_kernel=False)
|
| 102 |
+
# remove weight norm in the model and set to eval mode
|
| 103 |
+
bigvgan_model.remove_weight_norm()
|
| 104 |
+
bigvgan_model = bigvgan_model.eval().to(device)
|
| 105 |
+
vocoder_fn = bigvgan_model
|
| 106 |
+
elif vocoder_type == 'hifigan':
|
| 107 |
+
from modules.hifigan.generator import HiFTGenerator
|
| 108 |
+
from modules.hifigan.f0_predictor import ConvRNNF0Predictor
|
| 109 |
+
hift_config = yaml.safe_load(open('configs/hifigan.yml', 'r'))
|
| 110 |
+
hift_gen = HiFTGenerator(**hift_config['hift'], f0_predictor=ConvRNNF0Predictor(**hift_config['f0_predictor']))
|
| 111 |
+
hift_path = load_custom_model_from_hf("FunAudioLLM/CosyVoice-300M", 'hift.pt', None)
|
| 112 |
+
hift_gen.load_state_dict(torch.load(hift_path, map_location='cpu'))
|
| 113 |
+
hift_gen.eval()
|
| 114 |
+
hift_gen.to(device)
|
| 115 |
+
vocoder_fn = hift_gen
|
| 116 |
+
elif vocoder_type == "vocos":
|
| 117 |
+
vocos_config = yaml.safe_load(open(model_params.vocoder.vocos.config, 'r'))
|
| 118 |
+
vocos_path = model_params.vocoder.vocos.path
|
| 119 |
+
vocos_model_params = recursive_munch(vocos_config['model_params'])
|
| 120 |
+
vocos = build_model(vocos_model_params, stage='mel_vocos')
|
| 121 |
+
vocos_checkpoint_path = vocos_path
|
| 122 |
+
vocos, _, _, _ = load_checkpoint(vocos, None, vocos_checkpoint_path,
|
| 123 |
+
load_only_params=True, ignore_modules=[], is_distributed=False)
|
| 124 |
+
_ = [vocos[key].eval().to(device) for key in vocos]
|
| 125 |
+
_ = [vocos[key].to(device) for key in vocos]
|
| 126 |
+
total_params = sum(sum(p.numel() for p in vocos[key].parameters() if p.requires_grad) for key in vocos.keys())
|
| 127 |
+
print(f"Vocoder model total parameters: {total_params / 1_000_000:.2f}M")
|
| 128 |
+
vocoder_fn = vocos.decoder
|
| 129 |
+
else:
|
| 130 |
+
raise ValueError(f"Unknown vocoder type: {vocoder_type}")
|
| 131 |
+
|
| 132 |
+
speech_tokenizer_type = model_params.speech_tokenizer.type
|
| 133 |
+
if speech_tokenizer_type == 'whisper':
|
| 134 |
+
# whisper
|
| 135 |
+
from transformers import AutoFeatureExtractor, WhisperModel
|
| 136 |
+
whisper_name = model_params.speech_tokenizer.name
|
| 137 |
+
whisper_model = WhisperModel.from_pretrained(whisper_name, torch_dtype=torch.float16).to(device)
|
| 138 |
+
del whisper_model.decoder
|
| 139 |
+
whisper_feature_extractor = AutoFeatureExtractor.from_pretrained(whisper_name)
|
| 140 |
+
|
| 141 |
+
def semantic_fn(waves_16k):
|
| 142 |
+
ori_inputs = whisper_feature_extractor([waves_16k.squeeze(0).cpu().numpy()],
|
| 143 |
+
return_tensors="pt",
|
| 144 |
+
return_attention_mask=True)
|
| 145 |
+
ori_input_features = whisper_model._mask_input_features(
|
| 146 |
+
ori_inputs.input_features, attention_mask=ori_inputs.attention_mask).to(device)
|
| 147 |
+
with torch.no_grad():
|
| 148 |
+
ori_outputs = whisper_model.encoder(
|
| 149 |
+
ori_input_features.to(whisper_model.encoder.dtype),
|
| 150 |
+
head_mask=None,
|
| 151 |
+
output_attentions=False,
|
| 152 |
+
output_hidden_states=False,
|
| 153 |
+
return_dict=True,
|
| 154 |
+
)
|
| 155 |
+
S_ori = ori_outputs.last_hidden_state.to(torch.float32)
|
| 156 |
+
S_ori = S_ori[:, :waves_16k.size(-1) // 320 + 1]
|
| 157 |
+
return S_ori
|
| 158 |
+
elif speech_tokenizer_type == 'cnhubert':
|
| 159 |
+
from transformers import (
|
| 160 |
+
Wav2Vec2FeatureExtractor,
|
| 161 |
+
HubertModel,
|
| 162 |
+
)
|
| 163 |
+
hubert_model_name = config['model_params']['speech_tokenizer']['name']
|
| 164 |
+
hubert_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(hubert_model_name)
|
| 165 |
+
hubert_model = HubertModel.from_pretrained(hubert_model_name)
|
| 166 |
+
hubert_model = hubert_model.to(device)
|
| 167 |
+
hubert_model = hubert_model.eval()
|
| 168 |
+
hubert_model = hubert_model.half()
|
| 169 |
+
|
| 170 |
+
def semantic_fn(waves_16k):
|
| 171 |
+
ori_waves_16k_input_list = [
|
| 172 |
+
waves_16k[bib].cpu().numpy()
|
| 173 |
+
for bib in range(len(waves_16k))
|
| 174 |
+
]
|
| 175 |
+
ori_inputs = hubert_feature_extractor(ori_waves_16k_input_list,
|
| 176 |
+
return_tensors="pt",
|
| 177 |
+
return_attention_mask=True,
|
| 178 |
+
padding=True,
|
| 179 |
+
sampling_rate=16000).to(device)
|
| 180 |
+
with torch.no_grad():
|
| 181 |
+
ori_outputs = hubert_model(
|
| 182 |
+
ori_inputs.input_values.half(),
|
| 183 |
+
)
|
| 184 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
| 185 |
+
return S_ori
|
| 186 |
+
elif speech_tokenizer_type == 'xlsr':
|
| 187 |
+
from transformers import (
|
| 188 |
+
Wav2Vec2FeatureExtractor,
|
| 189 |
+
Wav2Vec2Model,
|
| 190 |
+
)
|
| 191 |
+
model_name = config['model_params']['speech_tokenizer']['name']
|
| 192 |
+
output_layer = config['model_params']['speech_tokenizer']['output_layer']
|
| 193 |
+
wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name)
|
| 194 |
+
wav2vec_model = Wav2Vec2Model.from_pretrained(model_name)
|
| 195 |
+
wav2vec_model.encoder.layers = wav2vec_model.encoder.layers[:output_layer]
|
| 196 |
+
wav2vec_model = wav2vec_model.to(device)
|
| 197 |
+
wav2vec_model = wav2vec_model.eval()
|
| 198 |
+
wav2vec_model = wav2vec_model.half()
|
| 199 |
+
|
| 200 |
+
def semantic_fn(waves_16k):
|
| 201 |
+
ori_waves_16k_input_list = [
|
| 202 |
+
waves_16k[bib].cpu().numpy()
|
| 203 |
+
for bib in range(len(waves_16k))
|
| 204 |
+
]
|
| 205 |
+
ori_inputs = wav2vec_feature_extractor(ori_waves_16k_input_list,
|
| 206 |
+
return_tensors="pt",
|
| 207 |
+
return_attention_mask=True,
|
| 208 |
+
padding=True,
|
| 209 |
+
sampling_rate=16000).to(device)
|
| 210 |
+
with torch.no_grad():
|
| 211 |
+
ori_outputs = wav2vec_model(
|
| 212 |
+
ori_inputs.input_values.half(),
|
| 213 |
+
)
|
| 214 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
| 215 |
+
return S_ori
|
| 216 |
+
else:
|
| 217 |
+
raise ValueError(f"Unknown speech tokenizer type: {speech_tokenizer_type}")
|
| 218 |
+
# Generate mel spectrograms
|
| 219 |
+
mel_fn_args = {
|
| 220 |
+
"n_fft": config['preprocess_params']['spect_params']['n_fft'],
|
| 221 |
+
"win_size": config['preprocess_params']['spect_params']['win_length'],
|
| 222 |
+
"hop_size": config['preprocess_params']['spect_params']['hop_length'],
|
| 223 |
+
"num_mels": config['preprocess_params']['spect_params']['n_mels'],
|
| 224 |
+
"sampling_rate": sr,
|
| 225 |
+
"fmin": config['preprocess_params']['spect_params'].get('fmin', 0),
|
| 226 |
+
"fmax": None if config['preprocess_params']['spect_params'].get('fmax', "None") == "None" else 8000,
|
| 227 |
+
"center": False
|
| 228 |
+
}
|
| 229 |
+
from modules.audio import mel_spectrogram
|
| 230 |
+
|
| 231 |
+
to_mel = lambda x: mel_spectrogram(x, **mel_fn_args)
|
| 232 |
+
|
| 233 |
+
return (
|
| 234 |
+
model,
|
| 235 |
+
semantic_fn,
|
| 236 |
+
f0_fn,
|
| 237 |
+
vocoder_fn,
|
| 238 |
+
campplus_model,
|
| 239 |
+
to_mel,
|
| 240 |
+
mel_fn_args,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
def adjust_f0_semitones(f0_sequence, n_semitones):
|
| 244 |
+
factor = 2 ** (n_semitones / 12)
|
| 245 |
+
return f0_sequence * factor
|
| 246 |
+
|
| 247 |
+
def crossfade(chunk1, chunk2, overlap):
|
| 248 |
+
fade_out = np.cos(np.linspace(0, np.pi / 2, overlap)) ** 2
|
| 249 |
+
fade_in = np.cos(np.linspace(np.pi / 2, 0, overlap)) ** 2
|
| 250 |
+
if len(chunk2) < overlap:
|
| 251 |
+
chunk2[:overlap] = chunk2[:overlap] * fade_in[:len(chunk2)] + (chunk1[-overlap:] * fade_out)[:len(chunk2)]
|
| 252 |
+
else:
|
| 253 |
+
chunk2[:overlap] = chunk2[:overlap] * fade_in + chunk1[-overlap:] * fade_out
|
| 254 |
+
return chunk2
|
| 255 |
+
|
| 256 |
+
@torch.no_grad()
|
| 257 |
+
def main(args):
|
| 258 |
+
model, semantic_fn, f0_fn, vocoder_fn, campplus_model, mel_fn, mel_fn_args = load_models(args)
|
| 259 |
+
sr = mel_fn_args['sampling_rate']
|
| 260 |
+
f0_condition = args.f0_condition
|
| 261 |
+
auto_f0_adjust = args.auto_f0_adjust
|
| 262 |
+
pitch_shift = args.semi_tone_shift
|
| 263 |
+
|
| 264 |
+
source = args.source
|
| 265 |
+
target_name = args.target
|
| 266 |
+
diffusion_steps = args.diffusion_steps
|
| 267 |
+
length_adjust = args.length_adjust
|
| 268 |
+
inference_cfg_rate = args.inference_cfg_rate
|
| 269 |
+
source_audio = librosa.load(source, sr=sr)[0]
|
| 270 |
+
ref_audio = librosa.load(target_name, sr=sr)[0]
|
| 271 |
+
|
| 272 |
+
sr = 22050 if not f0_condition else 44100
|
| 273 |
+
hop_length = 256 if not f0_condition else 512
|
| 274 |
+
max_context_window = sr // hop_length * 30
|
| 275 |
+
overlap_frame_len = 16
|
| 276 |
+
overlap_wave_len = overlap_frame_len * hop_length
|
| 277 |
+
|
| 278 |
+
# Process audio
|
| 279 |
+
source_audio = torch.tensor(source_audio).unsqueeze(0).float().to(device)
|
| 280 |
+
ref_audio = torch.tensor(ref_audio[:sr * 25]).unsqueeze(0).float().to(device)
|
| 281 |
+
|
| 282 |
+
time_vc_start = time.time()
|
| 283 |
+
# Resample
|
| 284 |
+
converted_waves_16k = torchaudio.functional.resample(source_audio, sr, 16000)
|
| 285 |
+
# if source audio less than 30 seconds, whisper can handle in one forward
|
| 286 |
+
if converted_waves_16k.size(-1) <= 16000 * 30:
|
| 287 |
+
S_alt = semantic_fn(converted_waves_16k)
|
| 288 |
+
else:
|
| 289 |
+
overlapping_time = 5 # 5 seconds
|
| 290 |
+
S_alt_list = []
|
| 291 |
+
buffer = None
|
| 292 |
+
traversed_time = 0
|
| 293 |
+
while traversed_time < converted_waves_16k.size(-1):
|
| 294 |
+
if buffer is None: # first chunk
|
| 295 |
+
chunk = converted_waves_16k[:, traversed_time:traversed_time + 16000 * 30]
|
| 296 |
+
else:
|
| 297 |
+
chunk = torch.cat(
|
| 298 |
+
[buffer, converted_waves_16k[:, traversed_time:traversed_time + 16000 * (30 - overlapping_time)]],
|
| 299 |
+
dim=-1)
|
| 300 |
+
S_alt = semantic_fn(chunk)
|
| 301 |
+
if traversed_time == 0:
|
| 302 |
+
S_alt_list.append(S_alt)
|
| 303 |
+
else:
|
| 304 |
+
S_alt_list.append(S_alt[:, 50 * overlapping_time:])
|
| 305 |
+
buffer = chunk[:, -16000 * overlapping_time:]
|
| 306 |
+
traversed_time += 30 * 16000 if traversed_time == 0 else chunk.size(-1) - 16000 * overlapping_time
|
| 307 |
+
S_alt = torch.cat(S_alt_list, dim=1)
|
| 308 |
+
|
| 309 |
+
ori_waves_16k = torchaudio.functional.resample(ref_audio, sr, 16000)
|
| 310 |
+
S_ori = semantic_fn(ori_waves_16k)
|
| 311 |
+
|
| 312 |
+
mel = mel_fn(source_audio.to(device).float())
|
| 313 |
+
mel2 = mel_fn(ref_audio.to(device).float())
|
| 314 |
+
|
| 315 |
+
target_lengths = torch.LongTensor([int(mel.size(2) * length_adjust)]).to(mel.device)
|
| 316 |
+
target2_lengths = torch.LongTensor([mel2.size(2)]).to(mel2.device)
|
| 317 |
+
|
| 318 |
+
feat2 = torchaudio.compliance.kaldi.fbank(ori_waves_16k,
|
| 319 |
+
num_mel_bins=80,
|
| 320 |
+
dither=0,
|
| 321 |
+
sample_frequency=16000)
|
| 322 |
+
feat2 = feat2 - feat2.mean(dim=0, keepdim=True)
|
| 323 |
+
style2 = campplus_model(feat2.unsqueeze(0))
|
| 324 |
+
|
| 325 |
+
if f0_condition:
|
| 326 |
+
F0_ori = f0_fn(ori_waves_16k[0], thred=0.03)
|
| 327 |
+
F0_alt = f0_fn(converted_waves_16k[0], thred=0.03)
|
| 328 |
+
|
| 329 |
+
F0_ori = torch.from_numpy(F0_ori).to(device)[None]
|
| 330 |
+
F0_alt = torch.from_numpy(F0_alt).to(device)[None]
|
| 331 |
+
|
| 332 |
+
voiced_F0_ori = F0_ori[F0_ori > 1]
|
| 333 |
+
voiced_F0_alt = F0_alt[F0_alt > 1]
|
| 334 |
+
|
| 335 |
+
log_f0_alt = torch.log(F0_alt + 1e-5)
|
| 336 |
+
voiced_log_f0_ori = torch.log(voiced_F0_ori + 1e-5)
|
| 337 |
+
voiced_log_f0_alt = torch.log(voiced_F0_alt + 1e-5)
|
| 338 |
+
median_log_f0_ori = torch.median(voiced_log_f0_ori)
|
| 339 |
+
median_log_f0_alt = torch.median(voiced_log_f0_alt)
|
| 340 |
+
|
| 341 |
+
# shift alt log f0 level to ori log f0 level
|
| 342 |
+
shifted_log_f0_alt = log_f0_alt.clone()
|
| 343 |
+
if auto_f0_adjust:
|
| 344 |
+
shifted_log_f0_alt[F0_alt > 1] = log_f0_alt[F0_alt > 1] - median_log_f0_alt + median_log_f0_ori
|
| 345 |
+
shifted_f0_alt = torch.exp(shifted_log_f0_alt)
|
| 346 |
+
if pitch_shift != 0:
|
| 347 |
+
shifted_f0_alt[F0_alt > 1] = adjust_f0_semitones(shifted_f0_alt[F0_alt > 1], pitch_shift)
|
| 348 |
+
else:
|
| 349 |
+
F0_ori = None
|
| 350 |
+
F0_alt = None
|
| 351 |
+
shifted_f0_alt = None
|
| 352 |
+
|
| 353 |
+
# Length regulation
|
| 354 |
+
cond, _, codes, commitment_loss, codebook_loss = model.length_regulator(S_alt, ylens=target_lengths,
|
| 355 |
+
n_quantizers=3,
|
| 356 |
+
f0=shifted_f0_alt)
|
| 357 |
+
prompt_condition, _, codes, commitment_loss, codebook_loss = model.length_regulator(S_ori,
|
| 358 |
+
ylens=target2_lengths,
|
| 359 |
+
n_quantizers=3,
|
| 360 |
+
f0=F0_ori)
|
| 361 |
+
|
| 362 |
+
max_source_window = max_context_window - mel2.size(2)
|
| 363 |
+
# split source condition (cond) into chunks
|
| 364 |
+
processed_frames = 0
|
| 365 |
+
generated_wave_chunks = []
|
| 366 |
+
# generate chunk by chunk and stream the output
|
| 367 |
+
while processed_frames < cond.size(1):
|
| 368 |
+
chunk_cond = cond[:, processed_frames:processed_frames + max_source_window]
|
| 369 |
+
is_last_chunk = processed_frames + max_source_window >= cond.size(1)
|
| 370 |
+
cat_condition = torch.cat([prompt_condition, chunk_cond], dim=1)
|
| 371 |
+
with torch.autocast(device_type=device.type, dtype=torch.float16 if fp16 else torch.float32):
|
| 372 |
+
# Voice Conversion
|
| 373 |
+
vc_target = model.cfm.inference(cat_condition,
|
| 374 |
+
torch.LongTensor([cat_condition.size(1)]).to(mel2.device),
|
| 375 |
+
mel2, style2, None, diffusion_steps,
|
| 376 |
+
inference_cfg_rate=inference_cfg_rate)
|
| 377 |
+
vc_target = vc_target[:, :, mel2.size(-1):]
|
| 378 |
+
vc_wave = vocoder_fn(vc_target.float()).squeeze()
|
| 379 |
+
vc_wave = vc_wave[None, :]
|
| 380 |
+
if processed_frames == 0:
|
| 381 |
+
if is_last_chunk:
|
| 382 |
+
output_wave = vc_wave[0].cpu().numpy()
|
| 383 |
+
generated_wave_chunks.append(output_wave)
|
| 384 |
+
break
|
| 385 |
+
output_wave = vc_wave[0, :-overlap_wave_len].cpu().numpy()
|
| 386 |
+
generated_wave_chunks.append(output_wave)
|
| 387 |
+
previous_chunk = vc_wave[0, -overlap_wave_len:]
|
| 388 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 389 |
+
elif is_last_chunk:
|
| 390 |
+
output_wave = crossfade(previous_chunk.cpu().numpy(), vc_wave[0].cpu().numpy(), overlap_wave_len)
|
| 391 |
+
generated_wave_chunks.append(output_wave)
|
| 392 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 393 |
+
break
|
| 394 |
+
else:
|
| 395 |
+
output_wave = crossfade(previous_chunk.cpu().numpy(), vc_wave[0, :-overlap_wave_len].cpu().numpy(),
|
| 396 |
+
overlap_wave_len)
|
| 397 |
+
generated_wave_chunks.append(output_wave)
|
| 398 |
+
previous_chunk = vc_wave[0, -overlap_wave_len:]
|
| 399 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
| 400 |
+
vc_wave = torch.tensor(np.concatenate(generated_wave_chunks))[None, :].float()
|
| 401 |
+
time_vc_end = time.time()
|
| 402 |
+
print(f"RTF: {(time_vc_end - time_vc_start) / vc_wave.size(-1) * sr}")
|
| 403 |
+
|
| 404 |
+
source_name = os.path.basename(source).split(".")[0]
|
| 405 |
+
target_name = os.path.basename(target_name).split(".")[0]
|
| 406 |
+
os.makedirs(args.output, exist_ok=True)
|
| 407 |
+
torchaudio.save(os.path.join(args.output, f"vc_{source_name}_{target_name}_{length_adjust}_{diffusion_steps}_{inference_cfg_rate}.wav"), vc_wave.cpu(), sr)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
if __name__ == "__main__":
|
| 411 |
+
parser = argparse.ArgumentParser()
|
| 412 |
+
parser.add_argument("--source", type=str, default="./examples/source/source_s1.wav")
|
| 413 |
+
parser.add_argument("--target", type=str, default="./examples/reference/s1p1.wav")
|
| 414 |
+
parser.add_argument("--output", type=str, default="./reconstructed")
|
| 415 |
+
parser.add_argument("--diffusion-steps", type=int, default=30)
|
| 416 |
+
parser.add_argument("--length-adjust", type=float, default=1.0)
|
| 417 |
+
parser.add_argument("--inference-cfg-rate", type=float, default=0.7)
|
| 418 |
+
parser.add_argument("--f0-condition", type=str2bool, default=False)
|
| 419 |
+
parser.add_argument("--auto-f0-adjust", type=str2bool, default=False)
|
| 420 |
+
parser.add_argument("--semi-tone-shift", type=int, default=0)
|
| 421 |
+
parser.add_argument("--checkpoint", type=str, help="Path to the checkpoint file", default=None)
|
| 422 |
+
parser.add_argument("--config", type=str, help="Path to the config file", default=None)
|
| 423 |
+
parser.add_argument("--fp16", type=str2bool, default=True)
|
| 424 |
+
args = parser.parse_args()
|
| 425 |
+
main(args)
|
seed-vc/inference_v2.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import torch
|
| 4 |
+
import yaml
|
| 5 |
+
import soundfile as sf
|
| 6 |
+
import time
|
| 7 |
+
from modules.commons import str2bool
|
| 8 |
+
|
| 9 |
+
# Set up device and torch configurations
|
| 10 |
+
if torch.cuda.is_available():
|
| 11 |
+
device = torch.device("cuda")
|
| 12 |
+
elif torch.backends.mps.is_available():
|
| 13 |
+
device = torch.device("mps")
|
| 14 |
+
else:
|
| 15 |
+
device = torch.device("cpu")
|
| 16 |
+
|
| 17 |
+
dtype = torch.float16
|
| 18 |
+
|
| 19 |
+
# Global variables to store model instances
|
| 20 |
+
vc_wrapper_v2 = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def load_v2_models(args):
|
| 24 |
+
"""Load V2 models using the wrapper from app.py"""
|
| 25 |
+
from hydra.utils import instantiate
|
| 26 |
+
from omegaconf import DictConfig
|
| 27 |
+
cfg = DictConfig(yaml.safe_load(open("configs/v2/vc_wrapper.yaml", "r")))
|
| 28 |
+
vc_wrapper = instantiate(cfg)
|
| 29 |
+
vc_wrapper.load_checkpoints(ar_checkpoint_path=args.ar_checkpoint_path,
|
| 30 |
+
cfm_checkpoint_path=args.cfm_checkpoint_path)
|
| 31 |
+
vc_wrapper.to(device)
|
| 32 |
+
vc_wrapper.eval()
|
| 33 |
+
|
| 34 |
+
vc_wrapper.setup_ar_caches(max_batch_size=1, max_seq_len=4096, dtype=dtype, device=device)
|
| 35 |
+
|
| 36 |
+
if args.compile:
|
| 37 |
+
torch._inductor.config.coordinate_descent_tuning = True
|
| 38 |
+
torch._inductor.config.triton.unique_kernel_names = True
|
| 39 |
+
|
| 40 |
+
if hasattr(torch._inductor.config, "fx_graph_cache"):
|
| 41 |
+
# Experimental feature to reduce compilation times, will be on by default in future
|
| 42 |
+
torch._inductor.config.fx_graph_cache = True
|
| 43 |
+
vc_wrapper.compile_ar()
|
| 44 |
+
# vc_wrapper.compile_cfm()
|
| 45 |
+
|
| 46 |
+
return vc_wrapper
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def convert_voice_v2(source_audio_path, target_audio_path, args):
|
| 50 |
+
"""Convert voice using V2 model"""
|
| 51 |
+
global vc_wrapper_v2
|
| 52 |
+
if vc_wrapper_v2 is None:
|
| 53 |
+
vc_wrapper_v2 = load_v2_models(args)
|
| 54 |
+
|
| 55 |
+
# Use the generator function but collect all outputs
|
| 56 |
+
generator = vc_wrapper_v2.convert_voice_with_streaming(
|
| 57 |
+
source_audio_path=source_audio_path,
|
| 58 |
+
target_audio_path=target_audio_path,
|
| 59 |
+
diffusion_steps=args.diffusion_steps,
|
| 60 |
+
length_adjust=args.length_adjust,
|
| 61 |
+
intelligebility_cfg_rate=args.intelligibility_cfg_rate,
|
| 62 |
+
similarity_cfg_rate=args.similarity_cfg_rate,
|
| 63 |
+
top_p=args.top_p,
|
| 64 |
+
temperature=args.temperature,
|
| 65 |
+
repetition_penalty=args.repetition_penalty,
|
| 66 |
+
convert_style=args.convert_style,
|
| 67 |
+
anonymization_only=args.anonymization_only,
|
| 68 |
+
device=device,
|
| 69 |
+
dtype=dtype,
|
| 70 |
+
stream_output=True
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Collect all outputs from the generator
|
| 74 |
+
for output in generator:
|
| 75 |
+
_, full_audio = output
|
| 76 |
+
return full_audio
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def main(args):
|
| 80 |
+
# Create output directory if it doesn't exist
|
| 81 |
+
os.makedirs(args.output, exist_ok=True)
|
| 82 |
+
|
| 83 |
+
start_time = time.time()
|
| 84 |
+
converted_audio = convert_voice_v2(args.source, args.target, args)
|
| 85 |
+
end_time = time.time()
|
| 86 |
+
|
| 87 |
+
if converted_audio is None:
|
| 88 |
+
print("Error: Failed to convert voice")
|
| 89 |
+
return
|
| 90 |
+
|
| 91 |
+
# Save the converted audio
|
| 92 |
+
source_name = os.path.basename(args.source).split(".")[0]
|
| 93 |
+
target_name = os.path.basename(args.target).split(".")[0]
|
| 94 |
+
|
| 95 |
+
# Create a descriptive filename
|
| 96 |
+
filename = f"vc_v2_{source_name}_{target_name}_{args.length_adjust}_{args.diffusion_steps}_{args.similarity_cfg_rate}.wav"
|
| 97 |
+
|
| 98 |
+
output_path = os.path.join(args.output, filename)
|
| 99 |
+
save_sr, converted_audio = converted_audio
|
| 100 |
+
sf.write(output_path, converted_audio, save_sr)
|
| 101 |
+
|
| 102 |
+
print(f"Voice conversion completed in {end_time - start_time:.2f} seconds")
|
| 103 |
+
print(f"Output saved to: {output_path}")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
parser = argparse.ArgumentParser(description="Voice Conversion Inference Script")
|
| 108 |
+
parser.add_argument("--source", type=str, required=True,
|
| 109 |
+
help="Path to source audio file")
|
| 110 |
+
parser.add_argument("--target", type=str, required=True,
|
| 111 |
+
help="Path to target/reference audio file")
|
| 112 |
+
parser.add_argument("--output", type=str, default="./output",
|
| 113 |
+
help="Output directory for converted audio")
|
| 114 |
+
parser.add_argument("--diffusion-steps", type=int, default=30,
|
| 115 |
+
help="Number of diffusion steps")
|
| 116 |
+
parser.add_argument("--length-adjust", type=float, default=1.0,
|
| 117 |
+
help="Length adjustment factor (<1.0 for speed-up, >1.0 for slow-down)")
|
| 118 |
+
parser.add_argument("--compile", type=bool, default=False,
|
| 119 |
+
help="Whether to compile the model for faster inference")
|
| 120 |
+
|
| 121 |
+
# V2 specific arguments
|
| 122 |
+
parser.add_argument("--intelligibility-cfg-rate", type=float, default=0.7,
|
| 123 |
+
help="Intelligibility CFG rate for V2 model")
|
| 124 |
+
parser.add_argument("--similarity-cfg-rate", type=float, default=0.7,
|
| 125 |
+
help="Similarity CFG rate for V2 model")
|
| 126 |
+
parser.add_argument("--top-p", type=float, default=0.9,
|
| 127 |
+
help="Top-p sampling parameter for V2 model")
|
| 128 |
+
parser.add_argument("--temperature", type=float, default=1.0,
|
| 129 |
+
help="Temperature sampling parameter for V2 model")
|
| 130 |
+
parser.add_argument("--repetition-penalty", type=float, default=1.0,
|
| 131 |
+
help="Repetition penalty for V2 model")
|
| 132 |
+
parser.add_argument("--convert-style", type=str2bool, default=False,
|
| 133 |
+
help="Convert style/emotion/accent for V2 model")
|
| 134 |
+
parser.add_argument("--anonymization-only", type=str2bool, default=False,
|
| 135 |
+
help="Anonymization only mode for V2 model")
|
| 136 |
+
|
| 137 |
+
# V2 custom checkpoints
|
| 138 |
+
parser.add_argument("--ar-checkpoint-path", type=str, default=None,
|
| 139 |
+
help="Path to custom checkpoint file")
|
| 140 |
+
parser.add_argument("--cfm-checkpoint-path", type=str, default=None,
|
| 141 |
+
help="Path to custom checkpoint file")
|
| 142 |
+
|
| 143 |
+
args = parser.parse_args()
|
| 144 |
+
main(args)
|
seed-vc/modules/astral_quantization/bsq.py
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Lookup Free Quantization
|
| 3 |
+
Proposed in https://arxiv.org/abs/2310.05737
|
| 4 |
+
|
| 5 |
+
In the simplest setup, each dimension is quantized into {-1, 1}.
|
| 6 |
+
An entropy penalty is used to encourage utilization.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from math import log2, ceil
|
| 10 |
+
from functools import partial, cache
|
| 11 |
+
from collections import namedtuple
|
| 12 |
+
from contextlib import nullcontext
|
| 13 |
+
|
| 14 |
+
import torch.distributed as dist
|
| 15 |
+
from torch.distributed import nn as dist_nn
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import nn, einsum
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
from torch.nn import Module
|
| 21 |
+
from torch.amp import autocast
|
| 22 |
+
|
| 23 |
+
from einops import rearrange, reduce, pack, unpack
|
| 24 |
+
|
| 25 |
+
# constants
|
| 26 |
+
|
| 27 |
+
Return = namedtuple('Return', ['quantized', 'indices', 'entropy_aux_loss'])
|
| 28 |
+
|
| 29 |
+
LossBreakdown = namedtuple('LossBreakdown', ['per_sample_entropy', 'batch_entropy', 'commitment'])
|
| 30 |
+
|
| 31 |
+
# distributed helpers
|
| 32 |
+
|
| 33 |
+
@cache
|
| 34 |
+
def is_distributed():
|
| 35 |
+
return dist.is_initialized() and dist.get_world_size() > 1
|
| 36 |
+
|
| 37 |
+
def maybe_distributed_mean(t):
|
| 38 |
+
if not is_distributed():
|
| 39 |
+
return t
|
| 40 |
+
|
| 41 |
+
dist_nn.all_reduce(t)
|
| 42 |
+
t = t / dist.get_world_size()
|
| 43 |
+
return t
|
| 44 |
+
|
| 45 |
+
# helper functions
|
| 46 |
+
|
| 47 |
+
def exists(v):
|
| 48 |
+
return v is not None
|
| 49 |
+
|
| 50 |
+
def identity(t):
|
| 51 |
+
return t
|
| 52 |
+
|
| 53 |
+
def default(*args):
|
| 54 |
+
for arg in args:
|
| 55 |
+
if exists(arg):
|
| 56 |
+
return arg() if callable(arg) else arg
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
def pack_one(t, pattern):
|
| 60 |
+
return pack([t], pattern)
|
| 61 |
+
|
| 62 |
+
def unpack_one(t, ps, pattern):
|
| 63 |
+
return unpack(t, ps, pattern)[0]
|
| 64 |
+
|
| 65 |
+
def l2norm(t):
|
| 66 |
+
return F.normalize(t, dim = -1)
|
| 67 |
+
|
| 68 |
+
# entropy
|
| 69 |
+
|
| 70 |
+
def log(t, eps = 1e-5):
|
| 71 |
+
return t.clamp(min = eps).log()
|
| 72 |
+
|
| 73 |
+
def entropy(prob):
|
| 74 |
+
return (-prob * log(prob)).sum(dim=-1)
|
| 75 |
+
|
| 76 |
+
# cosine sim linear
|
| 77 |
+
|
| 78 |
+
class CosineSimLinear(Module):
|
| 79 |
+
def __init__(
|
| 80 |
+
self,
|
| 81 |
+
dim_in,
|
| 82 |
+
dim_out,
|
| 83 |
+
scale = 1.
|
| 84 |
+
):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.scale = scale
|
| 87 |
+
self.weight = nn.Parameter(torch.randn(dim_in, dim_out))
|
| 88 |
+
|
| 89 |
+
def forward(self, x):
|
| 90 |
+
x = F.normalize(x, dim = -1)
|
| 91 |
+
w = F.normalize(self.weight, dim = 0)
|
| 92 |
+
return (x @ w) * self.scale
|
| 93 |
+
|
| 94 |
+
def soft_entropy_loss(u, tau=1.0, gamma=1.0):
|
| 95 |
+
"""
|
| 96 |
+
Compute the soft entropy loss for Binary Spherical Quantization (BSQ).
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
u (torch.Tensor): Input latent embeddings of shape (batch_size, L).
|
| 100 |
+
tau (float): Temperature scaling factor.
|
| 101 |
+
gamma (float): Weight for the second entropy term.
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
torch.Tensor: Soft entropy loss.
|
| 105 |
+
"""
|
| 106 |
+
# Binary quantization: Generate implicit codebook corners
|
| 107 |
+
L = u.size(1) # Dimensionality of codebook
|
| 108 |
+
corners = torch.tensor([-1.0, 1.0], device=u.device) / (L**0.5)
|
| 109 |
+
|
| 110 |
+
# Compute soft quantization probabilities for all dimensions
|
| 111 |
+
# q_hat(c|u) for each dimension
|
| 112 |
+
prob_matrix = torch.sigmoid(2 * tau * corners.unsqueeze(1) * u.unsqueeze(2)) # Shape: (batch_size, L, 2)
|
| 113 |
+
|
| 114 |
+
# Entropy of q_hat(c|u) (independent along each dimension)
|
| 115 |
+
entropy_per_dim = -torch.sum(prob_matrix * prob_matrix.log(), dim=-1) # Shape: (batch_size, L)
|
| 116 |
+
entropy_term1 = entropy_per_dim.mean()
|
| 117 |
+
|
| 118 |
+
# Expected probabilities for dataset entropy (approximation)
|
| 119 |
+
expected_probs = prob_matrix.mean(dim=0) # Mean across batch, shape: (L, 2)
|
| 120 |
+
entropy_term2 = -torch.sum(expected_probs * expected_probs.log(), dim=-1).mean()
|
| 121 |
+
|
| 122 |
+
# Final entropy loss
|
| 123 |
+
loss = entropy_term1 - gamma * entropy_term2
|
| 124 |
+
return loss
|
| 125 |
+
|
| 126 |
+
# class
|
| 127 |
+
|
| 128 |
+
class BinarySphericalQuantize(Module):
|
| 129 |
+
def __init__(
|
| 130 |
+
self,
|
| 131 |
+
*,
|
| 132 |
+
dim = None,
|
| 133 |
+
codebook_size = None,
|
| 134 |
+
entropy_loss_weight = 0.1,
|
| 135 |
+
commitment_loss_weight = 0.,
|
| 136 |
+
diversity_gamma = 1.,
|
| 137 |
+
straight_through_activation = nn.Identity(),
|
| 138 |
+
num_codebooks = 1,
|
| 139 |
+
keep_num_codebooks_dim = None,
|
| 140 |
+
codebook_scale = 1., # for residual LFQ, codebook scaled down by 2x at each layer
|
| 141 |
+
frac_per_sample_entropy = 0.25, # make less than 1. to only use a random fraction of the probs for per sample entropy
|
| 142 |
+
has_projections = None,
|
| 143 |
+
projection_has_bias = True,
|
| 144 |
+
soft_clamp_input_value = None,
|
| 145 |
+
cosine_sim_project_in = False,
|
| 146 |
+
cosine_sim_project_in_scale = None,
|
| 147 |
+
channel_first = None,
|
| 148 |
+
experimental_softplus_entropy_loss = False,
|
| 149 |
+
entropy_loss_offset = 5., # how much to shift the loss before softplus
|
| 150 |
+
spherical = True, # from https://arxiv.org/abs/2406.07548
|
| 151 |
+
force_quantization_f32 = True, # will force the quantization step to be full precision
|
| 152 |
+
enable_entropy_loss = True,
|
| 153 |
+
soft_entropy_loss = True,
|
| 154 |
+
):
|
| 155 |
+
super().__init__()
|
| 156 |
+
|
| 157 |
+
# some assert validations
|
| 158 |
+
|
| 159 |
+
assert exists(dim) or exists(codebook_size), 'either dim or codebook_size must be specified for LFQ'
|
| 160 |
+
assert not exists(codebook_size) or log2(codebook_size).is_integer(), f'your codebook size must be a power of 2 for lookup free quantization (suggested {2 ** ceil(log2(codebook_size))})'
|
| 161 |
+
|
| 162 |
+
codebook_size = default(codebook_size, lambda: 2 ** dim)
|
| 163 |
+
self.codebook_size = codebook_size
|
| 164 |
+
|
| 165 |
+
codebook_dim = int(log2(codebook_size))
|
| 166 |
+
codebook_dims = codebook_dim * num_codebooks
|
| 167 |
+
dim = default(dim, codebook_dims)
|
| 168 |
+
|
| 169 |
+
has_projections = default(has_projections, dim != codebook_dims)
|
| 170 |
+
|
| 171 |
+
if cosine_sim_project_in:
|
| 172 |
+
cosine_sim_project_in = default(cosine_sim_project_in_scale, codebook_scale)
|
| 173 |
+
project_in_klass = partial(CosineSimLinear, scale = cosine_sim_project_in)
|
| 174 |
+
else:
|
| 175 |
+
project_in_klass = partial(nn.Linear, bias = projection_has_bias)
|
| 176 |
+
|
| 177 |
+
self.project_in = project_in_klass(dim, codebook_dims) if has_projections else nn.Identity()
|
| 178 |
+
self.project_out = nn.Linear(codebook_dims, dim, bias = projection_has_bias) if has_projections else nn.Identity()
|
| 179 |
+
self.has_projections = has_projections
|
| 180 |
+
|
| 181 |
+
self.dim = dim
|
| 182 |
+
self.codebook_dim = codebook_dim
|
| 183 |
+
self.num_codebooks = num_codebooks
|
| 184 |
+
|
| 185 |
+
keep_num_codebooks_dim = default(keep_num_codebooks_dim, num_codebooks > 1)
|
| 186 |
+
assert not (num_codebooks > 1 and not keep_num_codebooks_dim)
|
| 187 |
+
self.keep_num_codebooks_dim = keep_num_codebooks_dim
|
| 188 |
+
|
| 189 |
+
# channel first
|
| 190 |
+
|
| 191 |
+
self.channel_first = channel_first
|
| 192 |
+
|
| 193 |
+
# straight through activation
|
| 194 |
+
|
| 195 |
+
self.activation = straight_through_activation
|
| 196 |
+
|
| 197 |
+
# whether to use BSQ (binary spherical quantization)
|
| 198 |
+
|
| 199 |
+
self.spherical = spherical
|
| 200 |
+
self.maybe_l2norm = (lambda t: l2norm(t) * self.codebook_scale) if spherical else identity
|
| 201 |
+
|
| 202 |
+
# entropy aux loss related weights
|
| 203 |
+
|
| 204 |
+
assert 0 < frac_per_sample_entropy <= 1.
|
| 205 |
+
self.frac_per_sample_entropy = frac_per_sample_entropy
|
| 206 |
+
|
| 207 |
+
self.diversity_gamma = diversity_gamma
|
| 208 |
+
self.entropy_loss_weight = entropy_loss_weight
|
| 209 |
+
|
| 210 |
+
# codebook scale
|
| 211 |
+
|
| 212 |
+
self.codebook_scale = codebook_scale
|
| 213 |
+
|
| 214 |
+
# commitment loss
|
| 215 |
+
|
| 216 |
+
self.commitment_loss_weight = commitment_loss_weight
|
| 217 |
+
|
| 218 |
+
# whether to soft clamp the input value from -value to value
|
| 219 |
+
|
| 220 |
+
self.soft_clamp_input_value = soft_clamp_input_value
|
| 221 |
+
assert not exists(soft_clamp_input_value) or soft_clamp_input_value >= codebook_scale
|
| 222 |
+
|
| 223 |
+
# whether to make the entropy loss positive through a softplus (experimental, please report if this worked or not in discussions)
|
| 224 |
+
|
| 225 |
+
self.entropy_loss_offset = entropy_loss_offset
|
| 226 |
+
self.experimental_softplus_entropy_loss = experimental_softplus_entropy_loss
|
| 227 |
+
|
| 228 |
+
# for no auxiliary loss, during inference
|
| 229 |
+
|
| 230 |
+
self.register_buffer('mask', 2 ** torch.arange(codebook_dim - 1, -1, -1))
|
| 231 |
+
self.register_buffer('zero', torch.tensor(0.), persistent = False)
|
| 232 |
+
|
| 233 |
+
# whether to force quantization step to be f32
|
| 234 |
+
|
| 235 |
+
self.force_quantization_f32 = force_quantization_f32
|
| 236 |
+
|
| 237 |
+
# codes
|
| 238 |
+
self.enable_entropy_loss = enable_entropy_loss
|
| 239 |
+
self.soft_entropy_loss = soft_entropy_loss
|
| 240 |
+
if codebook_size <= 100000:
|
| 241 |
+
all_codes = torch.arange(codebook_size)
|
| 242 |
+
bits = ((all_codes[..., None].int() & self.mask) != 0).float()
|
| 243 |
+
codebook = self.bits_to_codes(bits)
|
| 244 |
+
|
| 245 |
+
self.register_buffer('codebook', codebook.float(), persistent = False)
|
| 246 |
+
else:
|
| 247 |
+
all_codes = torch.arange(pow(2, 16))
|
| 248 |
+
mask = 2 ** torch.arange(16 - 1, -1, -1)
|
| 249 |
+
bits = ((all_codes[..., None].int() & mask) != 0).float()
|
| 250 |
+
codebook = self.bits_to_codes(bits)
|
| 251 |
+
|
| 252 |
+
self.register_buffer('codebook', codebook.float(), persistent = False)
|
| 253 |
+
|
| 254 |
+
def bits_to_codes(self, bits):
|
| 255 |
+
return bits * self.codebook_scale * 2 - self.codebook_scale
|
| 256 |
+
|
| 257 |
+
@property
|
| 258 |
+
def dtype(self):
|
| 259 |
+
return self.codebook.dtype
|
| 260 |
+
|
| 261 |
+
def indices_to_codes(
|
| 262 |
+
self,
|
| 263 |
+
indices,
|
| 264 |
+
project_out = True
|
| 265 |
+
):
|
| 266 |
+
is_img_or_video = indices.ndim >= (3 + int(self.keep_num_codebooks_dim))
|
| 267 |
+
should_transpose = default(self.channel_first, is_img_or_video)
|
| 268 |
+
|
| 269 |
+
if not self.keep_num_codebooks_dim:
|
| 270 |
+
indices = rearrange(indices, '... -> ... 1')
|
| 271 |
+
|
| 272 |
+
# indices to codes, which are bits of either -1 or 1
|
| 273 |
+
|
| 274 |
+
bits = ((indices[..., None].int() & self.mask) != 0).to(self.dtype)
|
| 275 |
+
|
| 276 |
+
codes = self.bits_to_codes(bits)
|
| 277 |
+
|
| 278 |
+
codes = self.maybe_l2norm(codes)
|
| 279 |
+
|
| 280 |
+
codes = rearrange(codes, '... c d -> ... (c d)')
|
| 281 |
+
|
| 282 |
+
# whether to project codes out to original dimensions
|
| 283 |
+
# if the input feature dimensions were not log2(codebook size)
|
| 284 |
+
|
| 285 |
+
if project_out:
|
| 286 |
+
codes = self.project_out(codes)
|
| 287 |
+
|
| 288 |
+
# rearrange codes back to original shape
|
| 289 |
+
|
| 290 |
+
if should_transpose:
|
| 291 |
+
codes = rearrange(codes, 'b ... d -> b d ...')
|
| 292 |
+
|
| 293 |
+
return codes
|
| 294 |
+
|
| 295 |
+
def bits_to_z(self, bits):
|
| 296 |
+
# assert bits must contain only -1 and 1
|
| 297 |
+
assert torch.all(bits.abs() == 1)
|
| 298 |
+
quantized = bits.float()
|
| 299 |
+
quantized = self.maybe_l2norm(quantized)
|
| 300 |
+
z = self.project_out(quantized)
|
| 301 |
+
return z
|
| 302 |
+
|
| 303 |
+
def forward(
|
| 304 |
+
self,
|
| 305 |
+
x,
|
| 306 |
+
inv_temperature = 100.,
|
| 307 |
+
return_loss_breakdown = False,
|
| 308 |
+
mask = None,
|
| 309 |
+
return_bits = False
|
| 310 |
+
):
|
| 311 |
+
"""
|
| 312 |
+
einstein notation
|
| 313 |
+
b - batch
|
| 314 |
+
n - sequence (or flattened spatial dimensions)
|
| 315 |
+
d - feature dimension, which is also log2(codebook size)
|
| 316 |
+
c - number of codebook dim
|
| 317 |
+
"""
|
| 318 |
+
|
| 319 |
+
is_img_or_video = x.ndim >= 4
|
| 320 |
+
should_transpose = default(self.channel_first, is_img_or_video)
|
| 321 |
+
|
| 322 |
+
# standardize image or video into (batch, seq, dimension)
|
| 323 |
+
|
| 324 |
+
if should_transpose:
|
| 325 |
+
x = rearrange(x, 'b d ... -> b ... d')
|
| 326 |
+
x, ps = pack_one(x, 'b * d')
|
| 327 |
+
|
| 328 |
+
assert x.shape[-1] == self.dim, f'expected dimension of {self.dim} but received {x.shape[-1]}'
|
| 329 |
+
|
| 330 |
+
x = self.project_in(x)
|
| 331 |
+
|
| 332 |
+
# maybe soft clamp
|
| 333 |
+
|
| 334 |
+
if exists(self.soft_clamp_input_value):
|
| 335 |
+
clamp_value = self.soft_clamp_input_value
|
| 336 |
+
x = (x / clamp_value).tanh() * clamp_value
|
| 337 |
+
|
| 338 |
+
# split out number of codebooks
|
| 339 |
+
|
| 340 |
+
x = rearrange(x, 'b n (c d) -> b n c d', c = self.num_codebooks)
|
| 341 |
+
|
| 342 |
+
# maybe l2norm
|
| 343 |
+
|
| 344 |
+
x = self.maybe_l2norm(x)
|
| 345 |
+
|
| 346 |
+
# whether to force quantization step to be full precision or not
|
| 347 |
+
|
| 348 |
+
force_f32 = self.force_quantization_f32
|
| 349 |
+
|
| 350 |
+
quantization_context = partial(autocast, 'cuda', enabled = False) if force_f32 else nullcontext
|
| 351 |
+
|
| 352 |
+
with quantization_context():
|
| 353 |
+
|
| 354 |
+
if force_f32:
|
| 355 |
+
orig_dtype = x.dtype
|
| 356 |
+
x = x.float()
|
| 357 |
+
|
| 358 |
+
# quantize by eq 3.
|
| 359 |
+
|
| 360 |
+
original_input = x
|
| 361 |
+
|
| 362 |
+
codebook_value = torch.ones_like(x) * self.codebook_scale
|
| 363 |
+
quantized = torch.where(x > 0, codebook_value, -codebook_value)
|
| 364 |
+
if return_bits:
|
| 365 |
+
return quantized
|
| 366 |
+
|
| 367 |
+
# calculate indices
|
| 368 |
+
|
| 369 |
+
indices = reduce((quantized > 0).int() * self.mask.int(), 'b n c d -> b n c', 'sum')
|
| 370 |
+
|
| 371 |
+
# maybe l2norm
|
| 372 |
+
|
| 373 |
+
quantized = self.maybe_l2norm(quantized)
|
| 374 |
+
|
| 375 |
+
# use straight-through gradients (optionally with custom activation fn) if training
|
| 376 |
+
|
| 377 |
+
if self.training:
|
| 378 |
+
x = self.activation(x)
|
| 379 |
+
x = x + (quantized - x).detach()
|
| 380 |
+
else:
|
| 381 |
+
x = quantized
|
| 382 |
+
|
| 383 |
+
# entropy aux loss
|
| 384 |
+
if self.soft_entropy_loss:
|
| 385 |
+
entropy_aux_loss = soft_entropy_loss(x, tau=1.0, gamma=1.0)
|
| 386 |
+
elif self.training and self.enable_entropy_loss:
|
| 387 |
+
|
| 388 |
+
if force_f32:
|
| 389 |
+
codebook = self.codebook.float()
|
| 390 |
+
|
| 391 |
+
codebook = self.maybe_l2norm(codebook)
|
| 392 |
+
|
| 393 |
+
# whether to only use a fraction of probs, for reducing memory
|
| 394 |
+
|
| 395 |
+
if self.frac_per_sample_entropy < 1.:
|
| 396 |
+
# account for mask
|
| 397 |
+
if exists(mask):
|
| 398 |
+
original_input = original_input[mask]
|
| 399 |
+
original_input = rearrange(original_input, 'b n ... -> (b n) ...')
|
| 400 |
+
|
| 401 |
+
rand_mask = torch.randn(self.codebook_dim).argsort(dim = -1) < 16
|
| 402 |
+
|
| 403 |
+
sampled_input = original_input[..., rand_mask]
|
| 404 |
+
|
| 405 |
+
sampled_distance = -2 * einsum('... i d, j d -> ... i j', sampled_input, codebook)
|
| 406 |
+
|
| 407 |
+
sampled_prob = (-sampled_distance * inv_temperature).softmax(dim = -1)
|
| 408 |
+
|
| 409 |
+
per_sample_probs = sampled_prob
|
| 410 |
+
else:
|
| 411 |
+
if exists(mask):
|
| 412 |
+
original_input = original_input[mask]
|
| 413 |
+
original_input = rearrange(original_input, 'b n ... -> (b n) ...')
|
| 414 |
+
# the same as euclidean distance up to a constant
|
| 415 |
+
distance = -2 * einsum('... i d, j d -> ... i j', original_input, codebook)
|
| 416 |
+
|
| 417 |
+
prob = (-distance * inv_temperature).softmax(dim = -1)
|
| 418 |
+
|
| 419 |
+
per_sample_probs = prob
|
| 420 |
+
|
| 421 |
+
# calculate per sample entropy
|
| 422 |
+
|
| 423 |
+
per_sample_entropy = entropy(per_sample_probs).mean()
|
| 424 |
+
|
| 425 |
+
# distribution over all available tokens in the batch
|
| 426 |
+
|
| 427 |
+
avg_prob = reduce(per_sample_probs, '... c d -> c d', 'mean')
|
| 428 |
+
|
| 429 |
+
avg_prob = maybe_distributed_mean(avg_prob)
|
| 430 |
+
|
| 431 |
+
codebook_entropy = entropy(avg_prob).mean()
|
| 432 |
+
|
| 433 |
+
# 1. entropy will be nudged to be low for each code, to encourage the network to output confident predictions
|
| 434 |
+
# 2. codebook entropy will be nudged to be high, to encourage all codes to be uniformly used within the batch
|
| 435 |
+
|
| 436 |
+
entropy_aux_loss = per_sample_entropy - self.diversity_gamma * codebook_entropy
|
| 437 |
+
else:
|
| 438 |
+
# if not training, just return dummy 0
|
| 439 |
+
entropy_aux_loss = per_sample_entropy = codebook_entropy = self.zero
|
| 440 |
+
|
| 441 |
+
# whether to make the entropy loss positive or not through a (shifted) softplus
|
| 442 |
+
|
| 443 |
+
if self.training and self.experimental_softplus_entropy_loss:
|
| 444 |
+
entropy_aux_loss = F.softplus(entropy_aux_loss + self.entropy_loss_offset)
|
| 445 |
+
|
| 446 |
+
# commit loss
|
| 447 |
+
|
| 448 |
+
if self.training and self.commitment_loss_weight > 0.:
|
| 449 |
+
|
| 450 |
+
commit_loss = F.mse_loss(original_input, quantized.detach(), reduction = 'none')
|
| 451 |
+
|
| 452 |
+
if exists(mask):
|
| 453 |
+
commit_loss = commit_loss[mask]
|
| 454 |
+
|
| 455 |
+
commit_loss = commit_loss.mean()
|
| 456 |
+
else:
|
| 457 |
+
commit_loss = self.zero
|
| 458 |
+
|
| 459 |
+
# input back to original dtype if needed
|
| 460 |
+
|
| 461 |
+
if force_f32:
|
| 462 |
+
x = x.type(orig_dtype)
|
| 463 |
+
|
| 464 |
+
# merge back codebook dim
|
| 465 |
+
|
| 466 |
+
x = rearrange(x, 'b n c d -> b n (c d)')
|
| 467 |
+
|
| 468 |
+
# project out to feature dimension if needed
|
| 469 |
+
|
| 470 |
+
x = self.project_out(x)
|
| 471 |
+
|
| 472 |
+
# reconstitute image or video dimensions
|
| 473 |
+
|
| 474 |
+
if should_transpose:
|
| 475 |
+
x = unpack_one(x, ps, 'b * d')
|
| 476 |
+
x = rearrange(x, 'b ... d -> b d ...')
|
| 477 |
+
|
| 478 |
+
indices = unpack_one(indices, ps, 'b * c')
|
| 479 |
+
|
| 480 |
+
# whether to remove single codebook dim
|
| 481 |
+
|
| 482 |
+
if not self.keep_num_codebooks_dim:
|
| 483 |
+
indices = rearrange(indices, '... 1 -> ...')
|
| 484 |
+
|
| 485 |
+
# complete aux loss
|
| 486 |
+
|
| 487 |
+
aux_loss = entropy_aux_loss * self.entropy_loss_weight + commit_loss * self.commitment_loss_weight
|
| 488 |
+
|
| 489 |
+
# returns
|
| 490 |
+
|
| 491 |
+
ret = Return(x, indices, aux_loss)
|
| 492 |
+
|
| 493 |
+
if not return_loss_breakdown:
|
| 494 |
+
return ret
|
| 495 |
+
|
| 496 |
+
return ret, LossBreakdown(per_sample_entropy, codebook_entropy, commit_loss)
|
| 497 |
+
|
| 498 |
+
class GroupedResidualBSQ(Module):
|
| 499 |
+
def __init__(
|
| 500 |
+
self,
|
| 501 |
+
*,
|
| 502 |
+
dim,
|
| 503 |
+
groups = 1,
|
| 504 |
+
accept_image_fmap = False,
|
| 505 |
+
**kwargs
|
| 506 |
+
):
|
| 507 |
+
super().__init__()
|
| 508 |
+
self.dim = dim
|
| 509 |
+
self.groups = groups
|
| 510 |
+
assert (dim % groups) == 0
|
| 511 |
+
dim_per_group = dim // groups
|
| 512 |
+
|
| 513 |
+
self.accept_image_fmap = accept_image_fmap
|
| 514 |
+
|
| 515 |
+
self.rvqs = nn.ModuleList([])
|
| 516 |
+
|
| 517 |
+
for _ in range(groups):
|
| 518 |
+
self.rvqs.append(LFQ(
|
| 519 |
+
dim = dim_per_group,
|
| 520 |
+
**kwargs
|
| 521 |
+
))
|
| 522 |
+
|
| 523 |
+
self.codebook_size = self.rvqs[0].codebook_size
|
| 524 |
+
|
| 525 |
+
@property
|
| 526 |
+
def codebooks(self):
|
| 527 |
+
return torch.stack(tuple(rvq.codebooks for rvq in self.rvqs))
|
| 528 |
+
|
| 529 |
+
@property
|
| 530 |
+
def split_dim(self):
|
| 531 |
+
return 1 if self.accept_image_fmap else -1
|
| 532 |
+
|
| 533 |
+
def get_codes_from_indices(self, indices):
|
| 534 |
+
codes = tuple(rvq.get_codes_from_indices(chunk_indices) for rvq, chunk_indices in zip(self.rvqs, indices))
|
| 535 |
+
return torch.stack(codes)
|
| 536 |
+
|
| 537 |
+
def get_output_from_indices(self, indices):
|
| 538 |
+
outputs = tuple(rvq.get_output_from_indices(chunk_indices) for rvq, chunk_indices in zip(self.rvqs, indices))
|
| 539 |
+
return torch.cat(outputs, dim = self.split_dim)
|
| 540 |
+
|
| 541 |
+
def forward(
|
| 542 |
+
self,
|
| 543 |
+
x,
|
| 544 |
+
return_all_codes = False
|
| 545 |
+
):
|
| 546 |
+
shape, split_dim = x.shape, self.split_dim
|
| 547 |
+
assert shape[split_dim] == self.dim
|
| 548 |
+
|
| 549 |
+
# split the feature dimension into groups
|
| 550 |
+
|
| 551 |
+
x = x.chunk(self.groups, dim = split_dim)
|
| 552 |
+
|
| 553 |
+
forward_kwargs = dict(
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
# invoke residual vq on each group
|
| 557 |
+
|
| 558 |
+
out = tuple(rvq(chunk, **forward_kwargs) for rvq, chunk in zip(self.rvqs, x))
|
| 559 |
+
out = tuple(zip(*out))
|
| 560 |
+
|
| 561 |
+
# otherwise, get all the zipped outputs and combine them
|
| 562 |
+
|
| 563 |
+
quantized, all_indices, *maybe_aux_loss = out
|
| 564 |
+
|
| 565 |
+
quantized = torch.cat(quantized, dim = split_dim)
|
| 566 |
+
all_indices = torch.stack(all_indices)
|
| 567 |
+
|
| 568 |
+
ret = (quantized, all_indices, *maybe_aux_loss)
|
| 569 |
+
return ret
|
seed-vc/modules/astral_quantization/convnext.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from typing import List
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ConvNextV2LayerNorm(nn.Module):
|
| 8 |
+
r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
|
| 9 |
+
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
|
| 10 |
+
width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.weight = nn.Parameter(torch.ones(normalized_shape))
|
| 16 |
+
self.bias = nn.Parameter(torch.zeros(normalized_shape))
|
| 17 |
+
self.eps = eps
|
| 18 |
+
self.data_format = data_format
|
| 19 |
+
if self.data_format not in ["channels_last", "channels_first"]:
|
| 20 |
+
raise NotImplementedError(f"Unsupported data format: {self.data_format}")
|
| 21 |
+
self.normalized_shape = (normalized_shape,)
|
| 22 |
+
|
| 23 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 24 |
+
if self.data_format == "channels_last":
|
| 25 |
+
x = torch.nn.functional.layer_norm(
|
| 26 |
+
x, self.normalized_shape, self.weight, self.bias, self.eps
|
| 27 |
+
)
|
| 28 |
+
elif self.data_format == "channels_first":
|
| 29 |
+
input_dtype = x.dtype
|
| 30 |
+
x = x.float()
|
| 31 |
+
u = x.mean(1, keepdim=True)
|
| 32 |
+
s = (x - u).pow(2).mean(1, keepdim=True)
|
| 33 |
+
x = (x - u) / torch.sqrt(s + self.eps)
|
| 34 |
+
x = x.to(dtype=input_dtype)
|
| 35 |
+
x = self.weight[None, :, None] * x + self.bias[None, :, None]
|
| 36 |
+
return x
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class GRN(nn.Module):
|
| 40 |
+
def __init__(self, dim):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.gamma = nn.Parameter(torch.zeros(1, 1, dim))
|
| 43 |
+
self.beta = nn.Parameter(torch.zeros(1, 1, dim))
|
| 44 |
+
|
| 45 |
+
def forward(self, x):
|
| 46 |
+
Gx = torch.norm(x, p=2, dim=1, keepdim=True)
|
| 47 |
+
Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
|
| 48 |
+
return self.gamma * (x * Nx) + self.beta + x
|
| 49 |
+
|
| 50 |
+
class InterpolationLayer(nn.Module):
|
| 51 |
+
def __init__(self, ): # this is a default of 1 / 50 * (44100 / 512) / 4
|
| 52 |
+
super().__init__()
|
| 53 |
+
pass
|
| 54 |
+
|
| 55 |
+
def forward(self, x: torch.Tensor, target_len: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
| 56 |
+
x = F.interpolate(x, size=target_len, mode='linear')
|
| 57 |
+
return x
|
| 58 |
+
|
| 59 |
+
class ConvNeXtV2Stage(nn.Module):
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
dim: int = 512,
|
| 63 |
+
intermediate_dim: int = 2048,
|
| 64 |
+
num_blocks: int = 1,
|
| 65 |
+
dilation: int = 1,
|
| 66 |
+
downsample_layer_indices: List[int] = None,
|
| 67 |
+
downsample_factors: List[int] = None,
|
| 68 |
+
upsample_layer_indices: List[int] = None,
|
| 69 |
+
upsample_factors: List[int] = None,
|
| 70 |
+
interpolation_layer_indices: List[int] = None,
|
| 71 |
+
input_dim: int = None,
|
| 72 |
+
output_dim: int = None,
|
| 73 |
+
gin_channels: int = 0,
|
| 74 |
+
):
|
| 75 |
+
super().__init__()
|
| 76 |
+
# maybe downsample layers
|
| 77 |
+
if downsample_layer_indices is not None:
|
| 78 |
+
assert downsample_factors is not None
|
| 79 |
+
self.downsample_blocks = nn.ModuleList(
|
| 80 |
+
[
|
| 81 |
+
nn.Sequential(
|
| 82 |
+
ConvNextV2LayerNorm(dim, data_format="channels_first"),
|
| 83 |
+
nn.Conv1d(
|
| 84 |
+
dim, dim, kernel_size=downsample_factor, stride=downsample_factor
|
| 85 |
+
),
|
| 86 |
+
) for _, downsample_factor in zip(downsample_layer_indices, downsample_factors)
|
| 87 |
+
]
|
| 88 |
+
)
|
| 89 |
+
self.downsample_layer_indices = downsample_layer_indices
|
| 90 |
+
else:
|
| 91 |
+
self.downsample_blocks = nn.ModuleList()
|
| 92 |
+
self.downsample_layer_indices = []
|
| 93 |
+
|
| 94 |
+
# maybe upsample layers
|
| 95 |
+
if upsample_layer_indices is not None:
|
| 96 |
+
assert upsample_factors is not None
|
| 97 |
+
self.upsample_blocks = nn.ModuleList(
|
| 98 |
+
[
|
| 99 |
+
nn.Sequential(
|
| 100 |
+
ConvNextV2LayerNorm(dim, data_format="channels_first"),
|
| 101 |
+
nn.ConvTranspose1d(
|
| 102 |
+
dim, dim, kernel_size=upsample_factor, stride=upsample_factor
|
| 103 |
+
),
|
| 104 |
+
) for _, upsample_factor in zip(upsample_layer_indices, upsample_factors)
|
| 105 |
+
]
|
| 106 |
+
)
|
| 107 |
+
self.upsample_layer_indices = upsample_layer_indices
|
| 108 |
+
else:
|
| 109 |
+
self.upsample_blocks = nn.ModuleList()
|
| 110 |
+
self.upsample_layer_indices = []
|
| 111 |
+
|
| 112 |
+
# maybe interpolation layers
|
| 113 |
+
if interpolation_layer_indices is not None:
|
| 114 |
+
self.interpolation_blocks = nn.ModuleList(
|
| 115 |
+
[
|
| 116 |
+
InterpolationLayer()
|
| 117 |
+
for _ in interpolation_layer_indices
|
| 118 |
+
]
|
| 119 |
+
)
|
| 120 |
+
self.interpolation_layer_indices = interpolation_layer_indices
|
| 121 |
+
else:
|
| 122 |
+
self.interpolation_blocks = nn.ModuleList()
|
| 123 |
+
self.interpolation_layer_indices = []
|
| 124 |
+
|
| 125 |
+
# main blocks
|
| 126 |
+
self.blocks = nn.ModuleList(
|
| 127 |
+
[
|
| 128 |
+
ConvNeXtV2Block(
|
| 129 |
+
dim=dim,
|
| 130 |
+
intermediate_dim=intermediate_dim,
|
| 131 |
+
dilation=dilation,
|
| 132 |
+
)
|
| 133 |
+
for _ in range(num_blocks)
|
| 134 |
+
]
|
| 135 |
+
)
|
| 136 |
+
# maybe input and output projections
|
| 137 |
+
if input_dim is not None and input_dim != dim:
|
| 138 |
+
self.input_projection = nn.Conv1d(input_dim, dim, kernel_size=1)
|
| 139 |
+
else:
|
| 140 |
+
self.input_projection = nn.Identity()
|
| 141 |
+
if output_dim is not None and output_dim != dim:
|
| 142 |
+
self.output_projection = nn.Conv1d(dim, output_dim, kernel_size=1)
|
| 143 |
+
else:
|
| 144 |
+
self.output_projection = nn.Identity()
|
| 145 |
+
|
| 146 |
+
if gin_channels > 0:
|
| 147 |
+
self.gin = nn.Conv1d(gin_channels, dim, kernel_size=1)
|
| 148 |
+
|
| 149 |
+
def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
| 150 |
+
x = self.input_projection(x) # B, D, T
|
| 151 |
+
if hasattr(self, 'gin'):
|
| 152 |
+
g = kwargs['g']
|
| 153 |
+
x = x + self.gin(g)
|
| 154 |
+
# pad to a multiple of cumprod(downsample_factors)
|
| 155 |
+
if len(self.downsample_blocks) > 0:
|
| 156 |
+
downsample_factor = 1
|
| 157 |
+
for factor in self.downsample_blocks:
|
| 158 |
+
downsample_factor *= factor[1].stride[0]
|
| 159 |
+
pad_len = downsample_factor - x.size(-1) % downsample_factor
|
| 160 |
+
if pad_len > 0:
|
| 161 |
+
x = torch.cat([x, torch.zeros_like(x[:, :, :pad_len])], dim=-1)
|
| 162 |
+
|
| 163 |
+
# main blocks
|
| 164 |
+
for layer_idx, block in enumerate(self.blocks):
|
| 165 |
+
if layer_idx in self.downsample_layer_indices:
|
| 166 |
+
x = self.downsample_blocks[self.downsample_layer_indices.index(layer_idx)](x)
|
| 167 |
+
if layer_idx in self.upsample_layer_indices:
|
| 168 |
+
x = self.upsample_blocks[self.upsample_layer_indices.index(layer_idx)](x)
|
| 169 |
+
if layer_idx in self.interpolation_layer_indices:
|
| 170 |
+
x = self.interpolation_blocks[self.interpolation_layer_indices.index(layer_idx)](x, target_len=kwargs['target_len'])
|
| 171 |
+
x = block(x)
|
| 172 |
+
x = self.output_projection(x)
|
| 173 |
+
return x
|
| 174 |
+
|
| 175 |
+
def setup_caches(self, *args, **kwargs):
|
| 176 |
+
pass
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class ConvNeXtV2Block(nn.Module):
|
| 180 |
+
def __init__(
|
| 181 |
+
self,
|
| 182 |
+
dim: int,
|
| 183 |
+
intermediate_dim: int,
|
| 184 |
+
dilation: int = 1,
|
| 185 |
+
):
|
| 186 |
+
super().__init__()
|
| 187 |
+
padding = (dilation * (7 - 1)) // 2
|
| 188 |
+
self.dwconv = nn.Conv1d(
|
| 189 |
+
dim, dim, kernel_size=7, padding=padding, groups=dim, dilation=dilation
|
| 190 |
+
) # depthwise conv
|
| 191 |
+
self.norm = ConvNextV2LayerNorm(dim, data_format="channels_first")
|
| 192 |
+
self.pwconv1 = nn.Linear(
|
| 193 |
+
dim, intermediate_dim
|
| 194 |
+
) # pointwise/1x1 convs, implemented with linear layers
|
| 195 |
+
self.act = nn.GELU()
|
| 196 |
+
self.grn = GRN(intermediate_dim)
|
| 197 |
+
self.pwconv2 = nn.Linear(intermediate_dim, dim)
|
| 198 |
+
|
| 199 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 200 |
+
residual = x
|
| 201 |
+
x = self.dwconv(x)
|
| 202 |
+
x = self.norm(x)
|
| 203 |
+
x = x.transpose(1, 2) # b d n -> b n d
|
| 204 |
+
x = self.pwconv1(x)
|
| 205 |
+
x = self.act(x)
|
| 206 |
+
x = self.grn(x)
|
| 207 |
+
x = self.pwconv2(x)
|
| 208 |
+
x = x.transpose(1, 2) # b n d -> b d n
|
| 209 |
+
return residual + x
|
seed-vc/modules/astral_quantization/default_model.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoTokenizer, AutoModel, Wav2Vec2FeatureExtractor
|
| 3 |
+
|
| 4 |
+
class AstralQuantizer(torch.nn.Module):
|
| 5 |
+
def __init__(
|
| 6 |
+
self,
|
| 7 |
+
tokenizer_name: str,
|
| 8 |
+
ssl_model_name: str,
|
| 9 |
+
ssl_output_layer: int,
|
| 10 |
+
encoder: torch.nn.Module,
|
| 11 |
+
quantizer: torch.nn.Module,
|
| 12 |
+
skip_ssl: bool = False,
|
| 13 |
+
):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.encoder = encoder
|
| 16 |
+
self.quantizer = quantizer
|
| 17 |
+
self.tokenizer_name = tokenizer_name
|
| 18 |
+
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
|
| 19 |
+
|
| 20 |
+
# Load SSL model from Huggingface
|
| 21 |
+
self.ssl_model_name = ssl_model_name
|
| 22 |
+
self.ssl_output_layer = ssl_output_layer
|
| 23 |
+
self.ssl_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(ssl_model_name)
|
| 24 |
+
|
| 25 |
+
if skip_ssl: # in case the same SSL model has been loaded somewhere else
|
| 26 |
+
self.ssl_model = None
|
| 27 |
+
else:
|
| 28 |
+
self.ssl_model = AutoModel.from_pretrained(ssl_model_name).eval()
|
| 29 |
+
self.ssl_model.encoder.layers = self.ssl_model.encoder.layers[:ssl_output_layer]
|
| 30 |
+
self.ssl_model.encoder.layer_norm = torch.nn.Identity()
|
| 31 |
+
|
| 32 |
+
def load_separate_checkpoint(self, checkpoint_path):
|
| 33 |
+
params = torch.load(checkpoint_path, map_location='cpu')['net']
|
| 34 |
+
for key in params.keys():
|
| 35 |
+
for k in list(params[key].keys()):
|
| 36 |
+
if k.startswith("module."):
|
| 37 |
+
params[key][k[len("module."):]] = params[key][k]
|
| 38 |
+
del params[key][k]
|
| 39 |
+
self.encoder.load_state_dict(params['encoder'])
|
| 40 |
+
self.quantizer.load_state_dict(params['vq'])
|
| 41 |
+
if self.decoder is not None:
|
| 42 |
+
self.decoder.load_state_dict(params['decoder'])
|
| 43 |
+
if self.asr_decoder is not None:
|
| 44 |
+
self.asr_decoder.load_state_dict(params['predictor'], strict=False)
|
| 45 |
+
|
| 46 |
+
def forward(self, waves_16k, wave_16k_lens, ssl_model=None):
|
| 47 |
+
ssl_fn = self.ssl_model if self.ssl_model else ssl_model
|
| 48 |
+
assert ssl_fn is not None, "In case in-class SSL model loading is skipped, external ssl_model must be provided"
|
| 49 |
+
waves_16k_input_list = [
|
| 50 |
+
waves_16k[bib, :wave_16k_lens[bib]].cpu().numpy()
|
| 51 |
+
for bib in range(len(waves_16k))
|
| 52 |
+
]
|
| 53 |
+
alt_inputs = self.ssl_feature_extractor(
|
| 54 |
+
waves_16k_input_list,
|
| 55 |
+
return_tensors='pt',
|
| 56 |
+
return_attention_mask=True,
|
| 57 |
+
padding=True,
|
| 58 |
+
sampling_rate=16000
|
| 59 |
+
).to(waves_16k.device)
|
| 60 |
+
feature_lens = alt_inputs.data['attention_mask'].sum(-1) // 320 # frame rate of hubert is 50 Hz
|
| 61 |
+
|
| 62 |
+
outputs = ssl_fn(
|
| 63 |
+
alt_inputs.input_values,
|
| 64 |
+
attention_mask=alt_inputs.attention_mask,
|
| 65 |
+
)
|
| 66 |
+
last_hidden_states = outputs.last_hidden_state
|
| 67 |
+
last_hidden_states = last_hidden_states[:, :feature_lens.max(), :]
|
| 68 |
+
feature_lens = feature_lens.clamp(max=last_hidden_states.size(1))
|
| 69 |
+
last_hidden_states = last_hidden_states.transpose(1, 2)
|
| 70 |
+
x_hidden = self.encoder(last_hidden_states, feature_lens)
|
| 71 |
+
x_hidden = x_hidden.transpose(1, 2)
|
| 72 |
+
x_quantized, indices = self.quantizer(x_hidden)[:2]
|
| 73 |
+
return x_quantized, indices, feature_lens
|
seed-vc/modules/astral_quantization/transformer.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch import Tensor
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
def find_multiple(n: int, k: int) -> int:
|
| 16 |
+
if n % k == 0:
|
| 17 |
+
return n
|
| 18 |
+
return n + k - (n % k)
|
| 19 |
+
|
| 20 |
+
class AdaptiveLayerNorm(nn.Module):
|
| 21 |
+
r"""Adaptive Layer Normalization"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, d_model, norm) -> None:
|
| 24 |
+
super(AdaptiveLayerNorm, self).__init__()
|
| 25 |
+
self.project_layer = nn.Linear(d_model, 2 * d_model)
|
| 26 |
+
self.norm = norm
|
| 27 |
+
self.d_model = d_model
|
| 28 |
+
self.eps = self.norm.eps
|
| 29 |
+
|
| 30 |
+
def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
|
| 31 |
+
if embedding is None:
|
| 32 |
+
return self.norm(input)
|
| 33 |
+
weight, bias = torch.split(
|
| 34 |
+
self.project_layer(embedding),
|
| 35 |
+
split_size_or_sections=self.d_model,
|
| 36 |
+
dim=-1,
|
| 37 |
+
)
|
| 38 |
+
return weight * self.norm(input) + bias
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class ModelArgs:
|
| 43 |
+
block_size: int = 2048
|
| 44 |
+
vocab_size: int = 32000
|
| 45 |
+
n_layer: int = 32
|
| 46 |
+
n_head: int = 32
|
| 47 |
+
dim: int = 4096
|
| 48 |
+
intermediate_size: int = None
|
| 49 |
+
n_local_heads: int = -1
|
| 50 |
+
head_dim: int = 64
|
| 51 |
+
rope_base: float = 10000
|
| 52 |
+
norm_eps: float = 1e-5
|
| 53 |
+
has_cross_attention: bool = False
|
| 54 |
+
context_dim: int = 0
|
| 55 |
+
is_causal: bool = False
|
| 56 |
+
dropout_rate: float = 0.1
|
| 57 |
+
attn_dropout_rate: float = 0.1
|
| 58 |
+
|
| 59 |
+
def __post_init__(self):
|
| 60 |
+
if self.n_local_heads == -1:
|
| 61 |
+
self.n_local_heads = self.n_head
|
| 62 |
+
if self.intermediate_size is None:
|
| 63 |
+
hidden_dim = 4 * self.dim
|
| 64 |
+
n_hidden = int(2 * hidden_dim / 3)
|
| 65 |
+
self.intermediate_size = find_multiple(n_hidden, 256)
|
| 66 |
+
# self.head_dim = self.dim // self.n_head
|
| 67 |
+
|
| 68 |
+
class Transformer(nn.Module):
|
| 69 |
+
def __init__(self, config: ModelArgs) -> None:
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.config = config
|
| 72 |
+
|
| 73 |
+
self.layers = nn.ModuleList(TransformerBlock(config) for _ in range(config.n_layer))
|
| 74 |
+
self.norm = AdaptiveLayerNorm(config.dim, RMSNorm(config.dim, eps=config.norm_eps))
|
| 75 |
+
|
| 76 |
+
self.max_batch_size = -1
|
| 77 |
+
self.max_seq_length = config.block_size
|
| 78 |
+
freqs_cis = precompute_freqs_cis(self.config.block_size, self.config.head_dim,
|
| 79 |
+
self.config.rope_base)
|
| 80 |
+
self.register_buffer("freqs_cis", freqs_cis)
|
| 81 |
+
|
| 82 |
+
causal_mask = torch.tril(
|
| 83 |
+
torch.ones(self.max_seq_length, self.max_seq_length, dtype=torch.bool)
|
| 84 |
+
)
|
| 85 |
+
self.register_buffer("causal_mask", causal_mask)
|
| 86 |
+
|
| 87 |
+
def forward(self,
|
| 88 |
+
x: Tensor,
|
| 89 |
+
c: Tensor,
|
| 90 |
+
input_pos: Optional[Tensor] = None,
|
| 91 |
+
mask: Optional[Tensor] = None,
|
| 92 |
+
context: Optional[Tensor] = None,
|
| 93 |
+
context_input_pos: Optional[Tensor] = None,
|
| 94 |
+
cross_attention_mask: Optional[Tensor] = None,
|
| 95 |
+
) -> Tensor:
|
| 96 |
+
if mask is None:
|
| 97 |
+
mask = self.causal_mask[:x.size(1), :x.size(1)]
|
| 98 |
+
else:
|
| 99 |
+
mask = mask[..., input_pos]
|
| 100 |
+
freqs_cis = self.freqs_cis[input_pos]
|
| 101 |
+
if context is not None:
|
| 102 |
+
context_freqs_cis = self.freqs_cis[context_input_pos]
|
| 103 |
+
else:
|
| 104 |
+
context_freqs_cis = None
|
| 105 |
+
skip_in_x_list = []
|
| 106 |
+
for i, layer in enumerate(self.layers):
|
| 107 |
+
x = layer(x, c, freqs_cis, mask, context, context_freqs_cis, cross_attention_mask)
|
| 108 |
+
x = self.norm(x, c)
|
| 109 |
+
return x
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class TransformerBlock(nn.Module):
|
| 113 |
+
def __init__(self, config: ModelArgs) -> None:
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.attention = Attention(config)
|
| 116 |
+
self.feed_forward = FeedForward(config)
|
| 117 |
+
self.ffn_norm = AdaptiveLayerNorm(config.dim, RMSNorm(config.dim, eps=config.norm_eps))
|
| 118 |
+
self.attention_norm = AdaptiveLayerNorm(config.dim, RMSNorm(config.dim, eps=config.norm_eps))
|
| 119 |
+
|
| 120 |
+
if config.has_cross_attention:
|
| 121 |
+
self.has_cross_attention = True
|
| 122 |
+
self.cross_attention = Attention(config, is_cross_attention=True)
|
| 123 |
+
self.cross_attention_norm = AdaptiveLayerNorm(config.dim, RMSNorm(config.dim, eps=config.norm_eps))
|
| 124 |
+
else:
|
| 125 |
+
self.has_cross_attention = False
|
| 126 |
+
|
| 127 |
+
def forward(self,
|
| 128 |
+
x: Tensor,
|
| 129 |
+
c: Tensor,
|
| 130 |
+
freqs_cis: Tensor,
|
| 131 |
+
mask: Tensor,
|
| 132 |
+
context: Optional[Tensor] = None,
|
| 133 |
+
context_freqs_cis: Optional[Tensor] = None,
|
| 134 |
+
cross_attention_mask: Optional[Tensor] = None,
|
| 135 |
+
) -> Tensor:
|
| 136 |
+
#time_attn_start = time.time()
|
| 137 |
+
h = x + self.attention(self.attention_norm(x, c), freqs_cis, mask)
|
| 138 |
+
#print(f"time take for attention of sequence length {x.shape[1]} is {time.time() - time_attn_start}")
|
| 139 |
+
if self.has_cross_attention:
|
| 140 |
+
h = h + self.cross_attention(self.cross_attention_norm(h, c), freqs_cis, cross_attention_mask, context, context_freqs_cis)
|
| 141 |
+
out = h + self.feed_forward(self.ffn_norm(h, c))
|
| 142 |
+
return out
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class Attention(nn.Module):
|
| 146 |
+
def __init__(self, config: ModelArgs, is_cross_attention: bool = False):
|
| 147 |
+
super().__init__()
|
| 148 |
+
assert config.dim % config.n_head == 0
|
| 149 |
+
|
| 150 |
+
total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
|
| 151 |
+
# key, query, value projections for all heads, but in a batch
|
| 152 |
+
if is_cross_attention:
|
| 153 |
+
self.wq = nn.Linear(config.dim, config.n_head * config.head_dim, bias=False)
|
| 154 |
+
self.wkv = nn.Linear(config.context_dim, 2 * config.n_local_heads * config.head_dim, bias=False)
|
| 155 |
+
else:
|
| 156 |
+
self.wqkv = nn.Linear(config.dim, total_head_dim, bias=False)
|
| 157 |
+
self.wo = nn.Linear(config.head_dim * config.n_head, config.dim, bias=False)
|
| 158 |
+
self.kv_cache = None
|
| 159 |
+
|
| 160 |
+
self.n_head = config.n_head
|
| 161 |
+
self.head_dim = config.head_dim
|
| 162 |
+
self.n_local_heads = config.n_local_heads
|
| 163 |
+
self.dim = config.dim
|
| 164 |
+
self.attn_dropout_rate = config.attn_dropout_rate
|
| 165 |
+
|
| 166 |
+
def forward(self,
|
| 167 |
+
x: Tensor,
|
| 168 |
+
freqs_cis: Tensor,
|
| 169 |
+
mask: Tensor,
|
| 170 |
+
context: Optional[Tensor] = None,
|
| 171 |
+
context_freqs_cis: Optional[Tensor] = None,
|
| 172 |
+
) -> Tensor:
|
| 173 |
+
bsz, seqlen, _ = x.shape
|
| 174 |
+
|
| 175 |
+
kv_size = self.n_local_heads * self.head_dim
|
| 176 |
+
if context is None:
|
| 177 |
+
q, k, v = self.wqkv(x).split([kv_size, kv_size, kv_size], dim=-1)
|
| 178 |
+
context_seqlen = seqlen
|
| 179 |
+
else:
|
| 180 |
+
q = self.wq(x)
|
| 181 |
+
k, v = self.wkv(context).split([kv_size, kv_size], dim=-1)
|
| 182 |
+
context_seqlen = context.shape[1]
|
| 183 |
+
|
| 184 |
+
q = q.view(bsz, seqlen, self.n_head, self.head_dim)
|
| 185 |
+
k = k.view(bsz, context_seqlen, self.n_local_heads, self.head_dim)
|
| 186 |
+
v = v.view(bsz, context_seqlen, self.n_local_heads, self.head_dim)
|
| 187 |
+
|
| 188 |
+
q = apply_rotary_emb(q, freqs_cis)
|
| 189 |
+
k = apply_rotary_emb(k, context_freqs_cis if context_freqs_cis is not None else freqs_cis)
|
| 190 |
+
|
| 191 |
+
q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
|
| 192 |
+
|
| 193 |
+
k = k.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
|
| 194 |
+
v = v.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
|
| 195 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=self.attn_dropout_rate if self.training else 0.0)
|
| 196 |
+
|
| 197 |
+
y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.head_dim * self.n_head)
|
| 198 |
+
|
| 199 |
+
y = self.wo(y)
|
| 200 |
+
return y
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class FeedForward(nn.Module):
|
| 204 |
+
def __init__(self, config: ModelArgs) -> None:
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.w1 = nn.Linear(config.dim, config.intermediate_size, bias=False)
|
| 207 |
+
self.w3 = nn.Linear(config.dim, config.intermediate_size, bias=False)
|
| 208 |
+
self.w2 = nn.Linear(config.intermediate_size, config.dim, bias=False)
|
| 209 |
+
self.dropout = nn.Dropout(config.dropout_rate)
|
| 210 |
+
|
| 211 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 212 |
+
return self.w2(self.dropout(F.silu(self.w1(x)) * self.w3(x)))
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class RMSNorm(nn.Module):
|
| 216 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 217 |
+
super().__init__()
|
| 218 |
+
self.eps = eps
|
| 219 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 220 |
+
|
| 221 |
+
def _norm(self, x):
|
| 222 |
+
return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
|
| 223 |
+
|
| 224 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 225 |
+
output = self._norm(x.float()).type_as(x)
|
| 226 |
+
return output * self.weight
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def precompute_freqs_cis(
|
| 230 |
+
seq_len: int, n_elem: int, base: int = 10000,
|
| 231 |
+
dtype: torch.dtype = torch.bfloat16
|
| 232 |
+
) -> Tensor:
|
| 233 |
+
freqs = 1.0 / (base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem))
|
| 234 |
+
t = torch.arange(seq_len, device=freqs.device)
|
| 235 |
+
freqs = torch.outer(t, freqs)
|
| 236 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
|
| 237 |
+
cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
|
| 238 |
+
return cache.to(dtype=dtype)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def apply_rotary_emb(x: Tensor, freqs_cis: Tensor) -> Tensor:
|
| 242 |
+
xshaped = x.float().reshape(*x.shape[:-1], -1, 2)
|
| 243 |
+
freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2)
|
| 244 |
+
x_out2 = torch.stack(
|
| 245 |
+
[
|
| 246 |
+
xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1],
|
| 247 |
+
xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1],
|
| 248 |
+
],
|
| 249 |
+
-1,
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
x_out2 = x_out2.flatten(3)
|
| 253 |
+
return x_out2.type_as(x)
|
| 254 |
+
|
seed-vc/modules/audio.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
import torch.utils.data
|
| 4 |
+
from librosa.filters import mel as librosa_mel_fn
|
| 5 |
+
from scipy.io.wavfile import read
|
| 6 |
+
|
| 7 |
+
MAX_WAV_VALUE = 32768.0
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def load_wav(full_path):
|
| 11 |
+
sampling_rate, data = read(full_path)
|
| 12 |
+
return data, sampling_rate
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def dynamic_range_compression(x, C=1, clip_val=1e-5):
|
| 16 |
+
return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def dynamic_range_decompression(x, C=1):
|
| 20 |
+
return np.exp(x) / C
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
|
| 24 |
+
return torch.log(torch.clamp(x, min=clip_val) * C)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def dynamic_range_decompression_torch(x, C=1):
|
| 28 |
+
return torch.exp(x) / C
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def spectral_normalize_torch(magnitudes):
|
| 32 |
+
output = dynamic_range_compression_torch(magnitudes)
|
| 33 |
+
return output
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def spectral_de_normalize_torch(magnitudes):
|
| 37 |
+
output = dynamic_range_decompression_torch(magnitudes)
|
| 38 |
+
return output
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
mel_basis = {}
|
| 42 |
+
hann_window = {}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
|
| 46 |
+
if torch.min(y) < -1.0:
|
| 47 |
+
print("min value is ", torch.min(y))
|
| 48 |
+
if torch.max(y) > 1.0:
|
| 49 |
+
print("max value is ", torch.max(y))
|
| 50 |
+
|
| 51 |
+
global mel_basis, hann_window # pylint: disable=global-statement
|
| 52 |
+
if f"{str(sampling_rate)}_{str(fmax)}_{str(y.device)}" not in mel_basis:
|
| 53 |
+
mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
|
| 54 |
+
mel_basis[str(sampling_rate) + "_" + str(fmax) + "_" + str(y.device)] = torch.from_numpy(mel).float().to(y.device)
|
| 55 |
+
hann_window[str(sampling_rate) + "_" + str(y.device)] = torch.hann_window(win_size).to(y.device)
|
| 56 |
+
|
| 57 |
+
y = torch.nn.functional.pad(
|
| 58 |
+
y.unsqueeze(1), (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)), mode="reflect"
|
| 59 |
+
)
|
| 60 |
+
y = y.squeeze(1)
|
| 61 |
+
|
| 62 |
+
spec = torch.view_as_real(
|
| 63 |
+
torch.stft(
|
| 64 |
+
y,
|
| 65 |
+
n_fft,
|
| 66 |
+
hop_length=hop_size,
|
| 67 |
+
win_length=win_size,
|
| 68 |
+
window=hann_window[str(sampling_rate) + "_" + str(y.device)],
|
| 69 |
+
center=center,
|
| 70 |
+
pad_mode="reflect",
|
| 71 |
+
normalized=False,
|
| 72 |
+
onesided=True,
|
| 73 |
+
return_complex=True,
|
| 74 |
+
)
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
spec = torch.sqrt(spec.pow(2).sum(-1) + (1e-9))
|
| 78 |
+
|
| 79 |
+
spec = torch.matmul(mel_basis[str(sampling_rate) + "_" + str(fmax) + "_" + str(y.device)], spec)
|
| 80 |
+
spec = spectral_normalize_torch(spec)
|
| 81 |
+
|
| 82 |
+
return spec
|
seed-vc/modules/bigvgan/activations.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Implementation adapted from https://github.com/EdwardDixon/snake under the MIT license.
|
| 2 |
+
# LICENSE is in incl_licenses directory.
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn, sin, pow
|
| 6 |
+
from torch.nn import Parameter
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Snake(nn.Module):
|
| 10 |
+
'''
|
| 11 |
+
Implementation of a sine-based periodic activation function
|
| 12 |
+
Shape:
|
| 13 |
+
- Input: (B, C, T)
|
| 14 |
+
- Output: (B, C, T), same shape as the input
|
| 15 |
+
Parameters:
|
| 16 |
+
- alpha - trainable parameter
|
| 17 |
+
References:
|
| 18 |
+
- This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
|
| 19 |
+
https://arxiv.org/abs/2006.08195
|
| 20 |
+
Examples:
|
| 21 |
+
>>> a1 = snake(256)
|
| 22 |
+
>>> x = torch.randn(256)
|
| 23 |
+
>>> x = a1(x)
|
| 24 |
+
'''
|
| 25 |
+
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
|
| 26 |
+
'''
|
| 27 |
+
Initialization.
|
| 28 |
+
INPUT:
|
| 29 |
+
- in_features: shape of the input
|
| 30 |
+
- alpha: trainable parameter
|
| 31 |
+
alpha is initialized to 1 by default, higher values = higher-frequency.
|
| 32 |
+
alpha will be trained along with the rest of your model.
|
| 33 |
+
'''
|
| 34 |
+
super(Snake, self).__init__()
|
| 35 |
+
self.in_features = in_features
|
| 36 |
+
|
| 37 |
+
# initialize alpha
|
| 38 |
+
self.alpha_logscale = alpha_logscale
|
| 39 |
+
if self.alpha_logscale: # log scale alphas initialized to zeros
|
| 40 |
+
self.alpha = Parameter(torch.zeros(in_features) * alpha)
|
| 41 |
+
else: # linear scale alphas initialized to ones
|
| 42 |
+
self.alpha = Parameter(torch.ones(in_features) * alpha)
|
| 43 |
+
|
| 44 |
+
self.alpha.requires_grad = alpha_trainable
|
| 45 |
+
|
| 46 |
+
self.no_div_by_zero = 0.000000001
|
| 47 |
+
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
'''
|
| 50 |
+
Forward pass of the function.
|
| 51 |
+
Applies the function to the input elementwise.
|
| 52 |
+
Snake ∶= x + 1/a * sin^2 (xa)
|
| 53 |
+
'''
|
| 54 |
+
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
|
| 55 |
+
if self.alpha_logscale:
|
| 56 |
+
alpha = torch.exp(alpha)
|
| 57 |
+
x = x + (1.0 / (alpha + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
|
| 58 |
+
|
| 59 |
+
return x
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class SnakeBeta(nn.Module):
|
| 63 |
+
'''
|
| 64 |
+
A modified Snake function which uses separate parameters for the magnitude of the periodic components
|
| 65 |
+
Shape:
|
| 66 |
+
- Input: (B, C, T)
|
| 67 |
+
- Output: (B, C, T), same shape as the input
|
| 68 |
+
Parameters:
|
| 69 |
+
- alpha - trainable parameter that controls frequency
|
| 70 |
+
- beta - trainable parameter that controls magnitude
|
| 71 |
+
References:
|
| 72 |
+
- This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
|
| 73 |
+
https://arxiv.org/abs/2006.08195
|
| 74 |
+
Examples:
|
| 75 |
+
>>> a1 = snakebeta(256)
|
| 76 |
+
>>> x = torch.randn(256)
|
| 77 |
+
>>> x = a1(x)
|
| 78 |
+
'''
|
| 79 |
+
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
|
| 80 |
+
'''
|
| 81 |
+
Initialization.
|
| 82 |
+
INPUT:
|
| 83 |
+
- in_features: shape of the input
|
| 84 |
+
- alpha - trainable parameter that controls frequency
|
| 85 |
+
- beta - trainable parameter that controls magnitude
|
| 86 |
+
alpha is initialized to 1 by default, higher values = higher-frequency.
|
| 87 |
+
beta is initialized to 1 by default, higher values = higher-magnitude.
|
| 88 |
+
alpha will be trained along with the rest of your model.
|
| 89 |
+
'''
|
| 90 |
+
super(SnakeBeta, self).__init__()
|
| 91 |
+
self.in_features = in_features
|
| 92 |
+
|
| 93 |
+
# initialize alpha
|
| 94 |
+
self.alpha_logscale = alpha_logscale
|
| 95 |
+
if self.alpha_logscale: # log scale alphas initialized to zeros
|
| 96 |
+
self.alpha = Parameter(torch.zeros(in_features) * alpha)
|
| 97 |
+
self.beta = Parameter(torch.zeros(in_features) * alpha)
|
| 98 |
+
else: # linear scale alphas initialized to ones
|
| 99 |
+
self.alpha = Parameter(torch.ones(in_features) * alpha)
|
| 100 |
+
self.beta = Parameter(torch.ones(in_features) * alpha)
|
| 101 |
+
|
| 102 |
+
self.alpha.requires_grad = alpha_trainable
|
| 103 |
+
self.beta.requires_grad = alpha_trainable
|
| 104 |
+
|
| 105 |
+
self.no_div_by_zero = 0.000000001
|
| 106 |
+
|
| 107 |
+
def forward(self, x):
|
| 108 |
+
'''
|
| 109 |
+
Forward pass of the function.
|
| 110 |
+
Applies the function to the input elementwise.
|
| 111 |
+
SnakeBeta ∶= x + 1/b * sin^2 (xa)
|
| 112 |
+
'''
|
| 113 |
+
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
|
| 114 |
+
beta = self.beta.unsqueeze(0).unsqueeze(-1)
|
| 115 |
+
if self.alpha_logscale:
|
| 116 |
+
alpha = torch.exp(alpha)
|
| 117 |
+
beta = torch.exp(beta)
|
| 118 |
+
x = x + (1.0 / (beta + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
|
| 119 |
+
|
| 120 |
+
return x
|
seed-vc/modules/bigvgan/alias_free_activation/cuda/__init__.py
ADDED
|
File without changes
|
seed-vc/modules/bigvgan/alias_free_activation/cuda/activation1d.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2024 NVIDIA CORPORATION.
|
| 2 |
+
# Licensed under the MIT license.
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from ..torch.resample import UpSample1d, DownSample1d
|
| 7 |
+
|
| 8 |
+
# load fused CUDA kernel: this enables importing anti_alias_activation_cuda
|
| 9 |
+
from ..cuda import load
|
| 10 |
+
|
| 11 |
+
anti_alias_activation_cuda = load.load()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class FusedAntiAliasActivation(torch.autograd.Function):
|
| 15 |
+
"""
|
| 16 |
+
Assumes filter size 12, replication padding on upsampling/downsampling, and logscale alpha/beta parameters as inputs.
|
| 17 |
+
The hyperparameters are hard-coded in the kernel to maximize speed.
|
| 18 |
+
NOTE: The fused kenrel is incorrect for Activation1d with different hyperparameters.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
@staticmethod
|
| 22 |
+
def forward(ctx, inputs, up_ftr, down_ftr, alpha, beta):
|
| 23 |
+
activation_results = anti_alias_activation_cuda.forward(
|
| 24 |
+
inputs, up_ftr, down_ftr, alpha, beta
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
return activation_results
|
| 28 |
+
|
| 29 |
+
@staticmethod
|
| 30 |
+
def backward(ctx, output_grads):
|
| 31 |
+
raise NotImplementedError
|
| 32 |
+
return output_grads, None, None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Activation1d(nn.Module):
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
activation,
|
| 39 |
+
up_ratio: int = 2,
|
| 40 |
+
down_ratio: int = 2,
|
| 41 |
+
up_kernel_size: int = 12,
|
| 42 |
+
down_kernel_size: int = 12,
|
| 43 |
+
fused: bool = True,
|
| 44 |
+
):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.up_ratio = up_ratio
|
| 47 |
+
self.down_ratio = down_ratio
|
| 48 |
+
self.act = activation
|
| 49 |
+
self.upsample = UpSample1d(up_ratio, up_kernel_size)
|
| 50 |
+
self.downsample = DownSample1d(down_ratio, down_kernel_size)
|
| 51 |
+
|
| 52 |
+
self.fused = fused # Whether to use fused CUDA kernel or not
|
| 53 |
+
|
| 54 |
+
def forward(self, x):
|
| 55 |
+
if not self.fused:
|
| 56 |
+
x = self.upsample(x)
|
| 57 |
+
x = self.act(x)
|
| 58 |
+
x = self.downsample(x)
|
| 59 |
+
return x
|
| 60 |
+
else:
|
| 61 |
+
if self.act.__class__.__name__ == "Snake":
|
| 62 |
+
beta = self.act.alpha.data # Snake uses same params for alpha and beta
|
| 63 |
+
else:
|
| 64 |
+
beta = (
|
| 65 |
+
self.act.beta.data
|
| 66 |
+
) # Snakebeta uses different params for alpha and beta
|
| 67 |
+
alpha = self.act.alpha.data
|
| 68 |
+
if (
|
| 69 |
+
not self.act.alpha_logscale
|
| 70 |
+
): # Exp baked into cuda kernel, cancel it out with a log
|
| 71 |
+
alpha = torch.log(alpha)
|
| 72 |
+
beta = torch.log(beta)
|
| 73 |
+
|
| 74 |
+
x = FusedAntiAliasActivation.apply(
|
| 75 |
+
x, self.upsample.filter, self.downsample.lowpass.filter, alpha, beta
|
| 76 |
+
)
|
| 77 |
+
return x
|
seed-vc/modules/bigvgan/alias_free_activation/cuda/anti_alias_activation.cpp
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* coding=utf-8
|
| 2 |
+
* Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
*
|
| 4 |
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
* you may not use this file except in compliance with the License.
|
| 6 |
+
* You may obtain a copy of the License at
|
| 7 |
+
*
|
| 8 |
+
* http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
*
|
| 10 |
+
* Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
* See the License for the specific language governing permissions and
|
| 14 |
+
* limitations under the License.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
#include <torch/extension.h>
|
| 18 |
+
|
| 19 |
+
extern "C" torch::Tensor fwd_cuda(torch::Tensor const &input, torch::Tensor const &up_filter, torch::Tensor const &down_filter, torch::Tensor const &alpha, torch::Tensor const &beta);
|
| 20 |
+
|
| 21 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 22 |
+
m.def("forward", &fwd_cuda, "Anti-Alias Activation forward (CUDA)");
|
| 23 |
+
}
|
seed-vc/modules/bigvgan/alias_free_activation/cuda/anti_alias_activation_cuda.cu
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* coding=utf-8
|
| 2 |
+
* Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
*
|
| 4 |
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
* you may not use this file except in compliance with the License.
|
| 6 |
+
* You may obtain a copy of the License at
|
| 7 |
+
*
|
| 8 |
+
* http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
*
|
| 10 |
+
* Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
* See the License for the specific language governing permissions and
|
| 14 |
+
* limitations under the License.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
#include <ATen/ATen.h>
|
| 18 |
+
#include <cuda.h>
|
| 19 |
+
#include <cuda_runtime.h>
|
| 20 |
+
#include <cuda_fp16.h>
|
| 21 |
+
#include <cuda_profiler_api.h>
|
| 22 |
+
#include <ATen/cuda/CUDAContext.h>
|
| 23 |
+
#include <torch/extension.h>
|
| 24 |
+
#include "type_shim.h"
|
| 25 |
+
#include <assert.h>
|
| 26 |
+
#include <cfloat>
|
| 27 |
+
#include <limits>
|
| 28 |
+
#include <stdint.h>
|
| 29 |
+
#include <c10/macros/Macros.h>
|
| 30 |
+
|
| 31 |
+
namespace
|
| 32 |
+
{
|
| 33 |
+
// Hard-coded hyperparameters
|
| 34 |
+
// WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and
|
| 35 |
+
constexpr int ELEMENTS_PER_LDG_STG = 1; //(WARP_ITERATIONS < 4) ? 1 : 4;
|
| 36 |
+
constexpr int BUFFER_SIZE = 32;
|
| 37 |
+
constexpr int FILTER_SIZE = 12;
|
| 38 |
+
constexpr int HALF_FILTER_SIZE = 6;
|
| 39 |
+
constexpr int UPSAMPLE_REPLICATION_PAD = 5; // 5 on each side, matching torch impl
|
| 40 |
+
constexpr int DOWNSAMPLE_REPLICATION_PAD_LEFT = 5; // matching torch impl
|
| 41 |
+
constexpr int DOWNSAMPLE_REPLICATION_PAD_RIGHT = 6; // matching torch impl
|
| 42 |
+
|
| 43 |
+
template <typename input_t, typename output_t, typename acc_t>
|
| 44 |
+
__global__ void anti_alias_activation_forward(
|
| 45 |
+
output_t *dst,
|
| 46 |
+
const input_t *src,
|
| 47 |
+
const input_t *up_ftr,
|
| 48 |
+
const input_t *down_ftr,
|
| 49 |
+
const input_t *alpha,
|
| 50 |
+
const input_t *beta,
|
| 51 |
+
int batch_size,
|
| 52 |
+
int channels,
|
| 53 |
+
int seq_len)
|
| 54 |
+
{
|
| 55 |
+
// Up and downsample filters
|
| 56 |
+
input_t up_filter[FILTER_SIZE];
|
| 57 |
+
input_t down_filter[FILTER_SIZE];
|
| 58 |
+
|
| 59 |
+
// Load data from global memory including extra indices reserved for replication paddings
|
| 60 |
+
input_t elements[2 * FILTER_SIZE + 2 * BUFFER_SIZE + 2 * UPSAMPLE_REPLICATION_PAD] = {0};
|
| 61 |
+
input_t intermediates[2 * FILTER_SIZE + 2 * BUFFER_SIZE + DOWNSAMPLE_REPLICATION_PAD_LEFT + DOWNSAMPLE_REPLICATION_PAD_RIGHT] = {0};
|
| 62 |
+
|
| 63 |
+
// Output stores downsampled output before writing to dst
|
| 64 |
+
output_t output[BUFFER_SIZE];
|
| 65 |
+
|
| 66 |
+
// blockDim/threadIdx = (128, 1, 1)
|
| 67 |
+
// gridDim/blockIdx = (seq_blocks, channels, batches)
|
| 68 |
+
int block_offset = (blockIdx.x * 128 * BUFFER_SIZE + seq_len * (blockIdx.y + gridDim.y * blockIdx.z));
|
| 69 |
+
int local_offset = threadIdx.x * BUFFER_SIZE;
|
| 70 |
+
int seq_offset = blockIdx.x * 128 * BUFFER_SIZE + local_offset;
|
| 71 |
+
|
| 72 |
+
// intermediate have double the seq_len
|
| 73 |
+
int intermediate_local_offset = threadIdx.x * BUFFER_SIZE * 2;
|
| 74 |
+
int intermediate_seq_offset = blockIdx.x * 128 * BUFFER_SIZE * 2 + intermediate_local_offset;
|
| 75 |
+
|
| 76 |
+
// Get values needed for replication padding before moving pointer
|
| 77 |
+
const input_t *right_most_pntr = src + (seq_len * (blockIdx.y + gridDim.y * blockIdx.z));
|
| 78 |
+
input_t seq_left_most_value = right_most_pntr[0];
|
| 79 |
+
input_t seq_right_most_value = right_most_pntr[seq_len - 1];
|
| 80 |
+
|
| 81 |
+
// Move src and dst pointers
|
| 82 |
+
src += block_offset + local_offset;
|
| 83 |
+
dst += block_offset + local_offset;
|
| 84 |
+
|
| 85 |
+
// Alpha and beta values for snake activatons. Applies exp by default
|
| 86 |
+
alpha = alpha + blockIdx.y;
|
| 87 |
+
input_t alpha_val = expf(alpha[0]);
|
| 88 |
+
beta = beta + blockIdx.y;
|
| 89 |
+
input_t beta_val = expf(beta[0]);
|
| 90 |
+
|
| 91 |
+
#pragma unroll
|
| 92 |
+
for (int it = 0; it < FILTER_SIZE; it += 1)
|
| 93 |
+
{
|
| 94 |
+
up_filter[it] = up_ftr[it];
|
| 95 |
+
down_filter[it] = down_ftr[it];
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
// Apply replication padding for upsampling, matching torch impl
|
| 99 |
+
#pragma unroll
|
| 100 |
+
for (int it = -HALF_FILTER_SIZE; it < BUFFER_SIZE + HALF_FILTER_SIZE; it += 1)
|
| 101 |
+
{
|
| 102 |
+
int element_index = seq_offset + it; // index for element
|
| 103 |
+
if ((element_index < 0) && (element_index >= -UPSAMPLE_REPLICATION_PAD))
|
| 104 |
+
{
|
| 105 |
+
elements[2 * (HALF_FILTER_SIZE + it)] = 2 * seq_left_most_value;
|
| 106 |
+
}
|
| 107 |
+
if ((element_index >= seq_len) && (element_index < seq_len + UPSAMPLE_REPLICATION_PAD))
|
| 108 |
+
{
|
| 109 |
+
elements[2 * (HALF_FILTER_SIZE + it)] = 2 * seq_right_most_value;
|
| 110 |
+
}
|
| 111 |
+
if ((element_index >= 0) && (element_index < seq_len))
|
| 112 |
+
{
|
| 113 |
+
elements[2 * (HALF_FILTER_SIZE + it)] = 2 * src[it];
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
// Apply upsampling strided convolution and write to intermediates. It reserves DOWNSAMPLE_REPLICATION_PAD_LEFT for replication padding of the downsampilng conv later
|
| 118 |
+
#pragma unroll
|
| 119 |
+
for (int it = 0; it < (2 * BUFFER_SIZE + 2 * FILTER_SIZE); it += 1)
|
| 120 |
+
{
|
| 121 |
+
input_t acc = 0.0;
|
| 122 |
+
int element_index = intermediate_seq_offset + it; // index for intermediate
|
| 123 |
+
#pragma unroll
|
| 124 |
+
for (int f_idx = 0; f_idx < FILTER_SIZE; f_idx += 1)
|
| 125 |
+
{
|
| 126 |
+
if ((element_index + f_idx) >= 0)
|
| 127 |
+
{
|
| 128 |
+
acc += up_filter[f_idx] * elements[it + f_idx];
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
intermediates[it + DOWNSAMPLE_REPLICATION_PAD_LEFT] = acc;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// Apply activation function. It reserves DOWNSAMPLE_REPLICATION_PAD_LEFT and DOWNSAMPLE_REPLICATION_PAD_RIGHT for replication padding of the downsampilng conv later
|
| 135 |
+
double no_div_by_zero = 0.000000001;
|
| 136 |
+
#pragma unroll
|
| 137 |
+
for (int it = 0; it < 2 * BUFFER_SIZE + 2 * FILTER_SIZE; it += 1)
|
| 138 |
+
{
|
| 139 |
+
intermediates[it + DOWNSAMPLE_REPLICATION_PAD_LEFT] += (1.0 / (beta_val + no_div_by_zero)) * sinf(intermediates[it + DOWNSAMPLE_REPLICATION_PAD_LEFT] * alpha_val) * sinf(intermediates[it + DOWNSAMPLE_REPLICATION_PAD_LEFT] * alpha_val);
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
// Apply replication padding before downsampling conv from intermediates
|
| 143 |
+
#pragma unroll
|
| 144 |
+
for (int it = 0; it < DOWNSAMPLE_REPLICATION_PAD_LEFT; it += 1)
|
| 145 |
+
{
|
| 146 |
+
intermediates[it] = intermediates[DOWNSAMPLE_REPLICATION_PAD_LEFT];
|
| 147 |
+
}
|
| 148 |
+
#pragma unroll
|
| 149 |
+
for (int it = DOWNSAMPLE_REPLICATION_PAD_LEFT + 2 * BUFFER_SIZE + 2 * FILTER_SIZE; it < DOWNSAMPLE_REPLICATION_PAD_LEFT + 2 * BUFFER_SIZE + 2 * FILTER_SIZE + DOWNSAMPLE_REPLICATION_PAD_RIGHT; it += 1)
|
| 150 |
+
{
|
| 151 |
+
intermediates[it] = intermediates[DOWNSAMPLE_REPLICATION_PAD_LEFT + 2 * BUFFER_SIZE + 2 * FILTER_SIZE - 1];
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
// Apply downsample strided convolution (assuming stride=2) from intermediates
|
| 155 |
+
#pragma unroll
|
| 156 |
+
for (int it = 0; it < BUFFER_SIZE; it += 1)
|
| 157 |
+
{
|
| 158 |
+
input_t acc = 0.0;
|
| 159 |
+
#pragma unroll
|
| 160 |
+
for (int f_idx = 0; f_idx < FILTER_SIZE; f_idx += 1)
|
| 161 |
+
{
|
| 162 |
+
// Add constant DOWNSAMPLE_REPLICATION_PAD_RIGHT to match torch implementation
|
| 163 |
+
acc += down_filter[f_idx] * intermediates[it * 2 + f_idx + DOWNSAMPLE_REPLICATION_PAD_RIGHT];
|
| 164 |
+
}
|
| 165 |
+
output[it] = acc;
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
// Write output to dst
|
| 169 |
+
#pragma unroll
|
| 170 |
+
for (int it = 0; it < BUFFER_SIZE; it += ELEMENTS_PER_LDG_STG)
|
| 171 |
+
{
|
| 172 |
+
int element_index = seq_offset + it;
|
| 173 |
+
if (element_index < seq_len)
|
| 174 |
+
{
|
| 175 |
+
dst[it] = output[it];
|
| 176 |
+
}
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
template <typename input_t, typename output_t, typename acc_t>
|
| 182 |
+
void dispatch_anti_alias_activation_forward(
|
| 183 |
+
output_t *dst,
|
| 184 |
+
const input_t *src,
|
| 185 |
+
const input_t *up_ftr,
|
| 186 |
+
const input_t *down_ftr,
|
| 187 |
+
const input_t *alpha,
|
| 188 |
+
const input_t *beta,
|
| 189 |
+
int batch_size,
|
| 190 |
+
int channels,
|
| 191 |
+
int seq_len)
|
| 192 |
+
{
|
| 193 |
+
if (seq_len == 0)
|
| 194 |
+
{
|
| 195 |
+
return;
|
| 196 |
+
}
|
| 197 |
+
else
|
| 198 |
+
{
|
| 199 |
+
// Use 128 threads per block to maximimize gpu utilization
|
| 200 |
+
constexpr int threads_per_block = 128;
|
| 201 |
+
constexpr int seq_len_per_block = 4096;
|
| 202 |
+
int blocks_per_seq_len = (seq_len + seq_len_per_block - 1) / seq_len_per_block;
|
| 203 |
+
dim3 blocks(blocks_per_seq_len, channels, batch_size);
|
| 204 |
+
dim3 threads(threads_per_block, 1, 1);
|
| 205 |
+
|
| 206 |
+
anti_alias_activation_forward<input_t, output_t, acc_t>
|
| 207 |
+
<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, up_ftr, down_ftr, alpha, beta, batch_size, channels, seq_len);
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
extern "C" torch::Tensor fwd_cuda(torch::Tensor const &input, torch::Tensor const &up_filter, torch::Tensor const &down_filter, torch::Tensor const &alpha, torch::Tensor const &beta)
|
| 213 |
+
{
|
| 214 |
+
// Input is a 3d tensor with dimensions [batches, channels, seq_len]
|
| 215 |
+
const int batches = input.size(0);
|
| 216 |
+
const int channels = input.size(1);
|
| 217 |
+
const int seq_len = input.size(2);
|
| 218 |
+
|
| 219 |
+
// Output
|
| 220 |
+
auto act_options = input.options().requires_grad(false);
|
| 221 |
+
|
| 222 |
+
torch::Tensor anti_alias_activation_results =
|
| 223 |
+
torch::empty({batches, channels, seq_len}, act_options);
|
| 224 |
+
|
| 225 |
+
void *input_ptr = static_cast<void *>(input.data_ptr());
|
| 226 |
+
void *up_filter_ptr = static_cast<void *>(up_filter.data_ptr());
|
| 227 |
+
void *down_filter_ptr = static_cast<void *>(down_filter.data_ptr());
|
| 228 |
+
void *alpha_ptr = static_cast<void *>(alpha.data_ptr());
|
| 229 |
+
void *beta_ptr = static_cast<void *>(beta.data_ptr());
|
| 230 |
+
void *anti_alias_activation_results_ptr = static_cast<void *>(anti_alias_activation_results.data_ptr());
|
| 231 |
+
|
| 232 |
+
DISPATCH_FLOAT_HALF_AND_BFLOAT(
|
| 233 |
+
input.scalar_type(),
|
| 234 |
+
"dispatch anti alias activation_forward",
|
| 235 |
+
dispatch_anti_alias_activation_forward<scalar_t, scalar_t, float>(
|
| 236 |
+
reinterpret_cast<scalar_t *>(anti_alias_activation_results_ptr),
|
| 237 |
+
reinterpret_cast<const scalar_t *>(input_ptr),
|
| 238 |
+
reinterpret_cast<const scalar_t *>(up_filter_ptr),
|
| 239 |
+
reinterpret_cast<const scalar_t *>(down_filter_ptr),
|
| 240 |
+
reinterpret_cast<const scalar_t *>(alpha_ptr),
|
| 241 |
+
reinterpret_cast<const scalar_t *>(beta_ptr),
|
| 242 |
+
batches,
|
| 243 |
+
channels,
|
| 244 |
+
seq_len););
|
| 245 |
+
return anti_alias_activation_results;
|
| 246 |
+
}
|
seed-vc/modules/bigvgan/alias_free_activation/cuda/compat.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* coding=utf-8
|
| 2 |
+
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
*
|
| 4 |
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
* you may not use this file except in compliance with the License.
|
| 6 |
+
* You may obtain a copy of the License at
|
| 7 |
+
*
|
| 8 |
+
* http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
*
|
| 10 |
+
* Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
* See the License for the specific language governing permissions and
|
| 14 |
+
* limitations under the License.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
/*This code is copied fron NVIDIA apex:
|
| 18 |
+
* https://github.com/NVIDIA/apex
|
| 19 |
+
* with minor changes. */
|
| 20 |
+
|
| 21 |
+
#ifndef TORCH_CHECK
|
| 22 |
+
#define TORCH_CHECK AT_CHECK
|
| 23 |
+
#endif
|
| 24 |
+
|
| 25 |
+
#ifdef VERSION_GE_1_3
|
| 26 |
+
#define DATA_PTR data_ptr
|
| 27 |
+
#else
|
| 28 |
+
#define DATA_PTR data
|
| 29 |
+
#endif
|
seed-vc/modules/bigvgan/alias_free_activation/cuda/load.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2024 NVIDIA CORPORATION.
|
| 2 |
+
# Licensed under the MIT license.
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import pathlib
|
| 6 |
+
import subprocess
|
| 7 |
+
|
| 8 |
+
from torch.utils import cpp_extension
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
Setting this param to a list has a problem of generating different compilation commands (with diferent order of architectures) and leading to recompilation of fused kernels.
|
| 12 |
+
Set it to empty stringo avoid recompilation and assign arch flags explicity in extra_cuda_cflags below
|
| 13 |
+
"""
|
| 14 |
+
os.environ["TORCH_CUDA_ARCH_LIST"] = ""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load():
|
| 18 |
+
# Check if cuda 11 is installed for compute capability 8.0
|
| 19 |
+
cc_flag = []
|
| 20 |
+
_, bare_metal_major, _ = _get_cuda_bare_metal_version(cpp_extension.CUDA_HOME)
|
| 21 |
+
if int(bare_metal_major) >= 11:
|
| 22 |
+
cc_flag.append("-gencode")
|
| 23 |
+
cc_flag.append("arch=compute_80,code=sm_80")
|
| 24 |
+
|
| 25 |
+
# Build path
|
| 26 |
+
srcpath = pathlib.Path(__file__).parent.absolute()
|
| 27 |
+
buildpath = srcpath / "build"
|
| 28 |
+
_create_build_dir(buildpath)
|
| 29 |
+
|
| 30 |
+
# Helper function to build the kernels.
|
| 31 |
+
def _cpp_extention_load_helper(name, sources, extra_cuda_flags):
|
| 32 |
+
return cpp_extension.load(
|
| 33 |
+
name=name,
|
| 34 |
+
sources=sources,
|
| 35 |
+
build_directory=buildpath,
|
| 36 |
+
extra_cflags=[
|
| 37 |
+
"-O3",
|
| 38 |
+
],
|
| 39 |
+
extra_cuda_cflags=[
|
| 40 |
+
"-O3",
|
| 41 |
+
"-gencode",
|
| 42 |
+
"arch=compute_70,code=sm_70",
|
| 43 |
+
"--use_fast_math",
|
| 44 |
+
]
|
| 45 |
+
+ extra_cuda_flags
|
| 46 |
+
+ cc_flag,
|
| 47 |
+
verbose=True,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
extra_cuda_flags = [
|
| 51 |
+
"-U__CUDA_NO_HALF_OPERATORS__",
|
| 52 |
+
"-U__CUDA_NO_HALF_CONVERSIONS__",
|
| 53 |
+
"--expt-relaxed-constexpr",
|
| 54 |
+
"--expt-extended-lambda",
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
sources = [
|
| 58 |
+
srcpath / "anti_alias_activation.cpp",
|
| 59 |
+
srcpath / "anti_alias_activation_cuda.cu",
|
| 60 |
+
]
|
| 61 |
+
anti_alias_activation_cuda = _cpp_extention_load_helper(
|
| 62 |
+
"anti_alias_activation_cuda", sources, extra_cuda_flags
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
return anti_alias_activation_cuda
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _get_cuda_bare_metal_version(cuda_dir):
|
| 69 |
+
raw_output = subprocess.check_output(
|
| 70 |
+
[cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True
|
| 71 |
+
)
|
| 72 |
+
output = raw_output.split()
|
| 73 |
+
release_idx = output.index("release") + 1
|
| 74 |
+
release = output[release_idx].split(".")
|
| 75 |
+
bare_metal_major = release[0]
|
| 76 |
+
bare_metal_minor = release[1][0]
|
| 77 |
+
|
| 78 |
+
return raw_output, bare_metal_major, bare_metal_minor
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _create_build_dir(buildpath):
|
| 82 |
+
try:
|
| 83 |
+
os.mkdir(buildpath)
|
| 84 |
+
except OSError:
|
| 85 |
+
if not os.path.isdir(buildpath):
|
| 86 |
+
print(f"Creation of the build directory {buildpath} failed")
|
seed-vc/modules/bigvgan/alias_free_activation/cuda/type_shim.h
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* coding=utf-8
|
| 2 |
+
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
*
|
| 4 |
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
* you may not use this file except in compliance with the License.
|
| 6 |
+
* You may obtain a copy of the License at
|
| 7 |
+
*
|
| 8 |
+
* http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
*
|
| 10 |
+
* Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
* See the License for the specific language governing permissions and
|
| 14 |
+
* limitations under the License.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
#include <ATen/ATen.h>
|
| 18 |
+
#include "compat.h"
|
| 19 |
+
|
| 20 |
+
#define DISPATCH_FLOAT_HALF_AND_BFLOAT(TYPE, NAME, ...) \
|
| 21 |
+
switch (TYPE) \
|
| 22 |
+
{ \
|
| 23 |
+
case at::ScalarType::Float: \
|
| 24 |
+
{ \
|
| 25 |
+
using scalar_t = float; \
|
| 26 |
+
__VA_ARGS__; \
|
| 27 |
+
break; \
|
| 28 |
+
} \
|
| 29 |
+
case at::ScalarType::Half: \
|
| 30 |
+
{ \
|
| 31 |
+
using scalar_t = at::Half; \
|
| 32 |
+
__VA_ARGS__; \
|
| 33 |
+
break; \
|
| 34 |
+
} \
|
| 35 |
+
case at::ScalarType::BFloat16: \
|
| 36 |
+
{ \
|
| 37 |
+
using scalar_t = at::BFloat16; \
|
| 38 |
+
__VA_ARGS__; \
|
| 39 |
+
break; \
|
| 40 |
+
} \
|
| 41 |
+
default: \
|
| 42 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPE), "'"); \
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
#define DISPATCH_FLOAT_HALF_AND_BFLOAT_INOUT_TYPES(TYPEIN, TYPEOUT, NAME, ...) \
|
| 46 |
+
switch (TYPEIN) \
|
| 47 |
+
{ \
|
| 48 |
+
case at::ScalarType::Float: \
|
| 49 |
+
{ \
|
| 50 |
+
using scalar_t_in = float; \
|
| 51 |
+
switch (TYPEOUT) \
|
| 52 |
+
{ \
|
| 53 |
+
case at::ScalarType::Float: \
|
| 54 |
+
{ \
|
| 55 |
+
using scalar_t_out = float; \
|
| 56 |
+
__VA_ARGS__; \
|
| 57 |
+
break; \
|
| 58 |
+
} \
|
| 59 |
+
case at::ScalarType::Half: \
|
| 60 |
+
{ \
|
| 61 |
+
using scalar_t_out = at::Half; \
|
| 62 |
+
__VA_ARGS__; \
|
| 63 |
+
break; \
|
| 64 |
+
} \
|
| 65 |
+
case at::ScalarType::BFloat16: \
|
| 66 |
+
{ \
|
| 67 |
+
using scalar_t_out = at::BFloat16; \
|
| 68 |
+
__VA_ARGS__; \
|
| 69 |
+
break; \
|
| 70 |
+
} \
|
| 71 |
+
default: \
|
| 72 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPEOUT), "'"); \
|
| 73 |
+
} \
|
| 74 |
+
break; \
|
| 75 |
+
} \
|
| 76 |
+
case at::ScalarType::Half: \
|
| 77 |
+
{ \
|
| 78 |
+
using scalar_t_in = at::Half; \
|
| 79 |
+
using scalar_t_out = at::Half; \
|
| 80 |
+
__VA_ARGS__; \
|
| 81 |
+
break; \
|
| 82 |
+
} \
|
| 83 |
+
case at::ScalarType::BFloat16: \
|
| 84 |
+
{ \
|
| 85 |
+
using scalar_t_in = at::BFloat16; \
|
| 86 |
+
using scalar_t_out = at::BFloat16; \
|
| 87 |
+
__VA_ARGS__; \
|
| 88 |
+
break; \
|
| 89 |
+
} \
|
| 90 |
+
default: \
|
| 91 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPEIN), "'"); \
|
| 92 |
+
}
|
seed-vc/modules/bigvgan/alias_free_activation/torch/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
|
| 2 |
+
# LICENSE is in incl_licenses directory.
|
| 3 |
+
|
| 4 |
+
from .filter import *
|
| 5 |
+
from .resample import *
|
| 6 |
+
from .act import *
|
seed-vc/modules/bigvgan/alias_free_activation/torch/act.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
|
| 2 |
+
# LICENSE is in incl_licenses directory.
|
| 3 |
+
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from .resample import UpSample1d, DownSample1d
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Activation1d(nn.Module):
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
activation,
|
| 12 |
+
up_ratio: int = 2,
|
| 13 |
+
down_ratio: int = 2,
|
| 14 |
+
up_kernel_size: int = 12,
|
| 15 |
+
down_kernel_size: int = 12,
|
| 16 |
+
):
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.up_ratio = up_ratio
|
| 19 |
+
self.down_ratio = down_ratio
|
| 20 |
+
self.act = activation
|
| 21 |
+
self.upsample = UpSample1d(up_ratio, up_kernel_size)
|
| 22 |
+
self.downsample = DownSample1d(down_ratio, down_kernel_size)
|
| 23 |
+
|
| 24 |
+
# x: [B,C,T]
|
| 25 |
+
def forward(self, x):
|
| 26 |
+
x = self.upsample(x)
|
| 27 |
+
x = self.act(x)
|
| 28 |
+
x = self.downsample(x)
|
| 29 |
+
|
| 30 |
+
return x
|
seed-vc/modules/bigvgan/alias_free_activation/torch/filter.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
|
| 2 |
+
# LICENSE is in incl_licenses directory.
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
import math
|
| 8 |
+
|
| 9 |
+
if "sinc" in dir(torch):
|
| 10 |
+
sinc = torch.sinc
|
| 11 |
+
else:
|
| 12 |
+
# This code is adopted from adefossez's julius.core.sinc under the MIT License
|
| 13 |
+
# https://adefossez.github.io/julius/julius/core.html
|
| 14 |
+
# LICENSE is in incl_licenses directory.
|
| 15 |
+
def sinc(x: torch.Tensor):
|
| 16 |
+
"""
|
| 17 |
+
Implementation of sinc, i.e. sin(pi * x) / (pi * x)
|
| 18 |
+
__Warning__: Different to julius.sinc, the input is multiplied by `pi`!
|
| 19 |
+
"""
|
| 20 |
+
return torch.where(
|
| 21 |
+
x == 0,
|
| 22 |
+
torch.tensor(1.0, device=x.device, dtype=x.dtype),
|
| 23 |
+
torch.sin(math.pi * x) / math.pi / x,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# This code is adopted from adefossez's julius.lowpass.LowPassFilters under the MIT License
|
| 28 |
+
# https://adefossez.github.io/julius/julius/lowpass.html
|
| 29 |
+
# LICENSE is in incl_licenses directory.
|
| 30 |
+
def kaiser_sinc_filter1d(
|
| 31 |
+
cutoff, half_width, kernel_size
|
| 32 |
+
): # return filter [1,1,kernel_size]
|
| 33 |
+
even = kernel_size % 2 == 0
|
| 34 |
+
half_size = kernel_size // 2
|
| 35 |
+
|
| 36 |
+
# For kaiser window
|
| 37 |
+
delta_f = 4 * half_width
|
| 38 |
+
A = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95
|
| 39 |
+
if A > 50.0:
|
| 40 |
+
beta = 0.1102 * (A - 8.7)
|
| 41 |
+
elif A >= 21.0:
|
| 42 |
+
beta = 0.5842 * (A - 21) ** 0.4 + 0.07886 * (A - 21.0)
|
| 43 |
+
else:
|
| 44 |
+
beta = 0.0
|
| 45 |
+
window = torch.kaiser_window(kernel_size, beta=beta, periodic=False)
|
| 46 |
+
|
| 47 |
+
# ratio = 0.5/cutoff -> 2 * cutoff = 1 / ratio
|
| 48 |
+
if even:
|
| 49 |
+
time = torch.arange(-half_size, half_size) + 0.5
|
| 50 |
+
else:
|
| 51 |
+
time = torch.arange(kernel_size) - half_size
|
| 52 |
+
if cutoff == 0:
|
| 53 |
+
filter_ = torch.zeros_like(time)
|
| 54 |
+
else:
|
| 55 |
+
filter_ = 2 * cutoff * window * sinc(2 * cutoff * time)
|
| 56 |
+
"""
|
| 57 |
+
Normalize filter to have sum = 1, otherwise we will have a small leakage of the constant component in the input signal.
|
| 58 |
+
"""
|
| 59 |
+
filter_ /= filter_.sum()
|
| 60 |
+
filter = filter_.view(1, 1, kernel_size)
|
| 61 |
+
|
| 62 |
+
return filter
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class LowPassFilter1d(nn.Module):
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
cutoff=0.5,
|
| 69 |
+
half_width=0.6,
|
| 70 |
+
stride: int = 1,
|
| 71 |
+
padding: bool = True,
|
| 72 |
+
padding_mode: str = "replicate",
|
| 73 |
+
kernel_size: int = 12,
|
| 74 |
+
):
|
| 75 |
+
"""
|
| 76 |
+
kernel_size should be even number for stylegan3 setup, in this implementation, odd number is also possible.
|
| 77 |
+
"""
|
| 78 |
+
super().__init__()
|
| 79 |
+
if cutoff < -0.0:
|
| 80 |
+
raise ValueError("Minimum cutoff must be larger than zero.")
|
| 81 |
+
if cutoff > 0.5:
|
| 82 |
+
raise ValueError("A cutoff above 0.5 does not make sense.")
|
| 83 |
+
self.kernel_size = kernel_size
|
| 84 |
+
self.even = kernel_size % 2 == 0
|
| 85 |
+
self.pad_left = kernel_size // 2 - int(self.even)
|
| 86 |
+
self.pad_right = kernel_size // 2
|
| 87 |
+
self.stride = stride
|
| 88 |
+
self.padding = padding
|
| 89 |
+
self.padding_mode = padding_mode
|
| 90 |
+
filter = kaiser_sinc_filter1d(cutoff, half_width, kernel_size)
|
| 91 |
+
self.register_buffer("filter", filter)
|
| 92 |
+
|
| 93 |
+
# Input [B, C, T]
|
| 94 |
+
def forward(self, x):
|
| 95 |
+
_, C, _ = x.shape
|
| 96 |
+
|
| 97 |
+
if self.padding:
|
| 98 |
+
x = F.pad(x, (self.pad_left, self.pad_right), mode=self.padding_mode)
|
| 99 |
+
out = F.conv1d(x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C)
|
| 100 |
+
|
| 101 |
+
return out
|
seed-vc/modules/bigvgan/alias_free_activation/torch/resample.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
|
| 2 |
+
# LICENSE is in incl_licenses directory.
|
| 3 |
+
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
from .filter import LowPassFilter1d
|
| 7 |
+
from .filter import kaiser_sinc_filter1d
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class UpSample1d(nn.Module):
|
| 11 |
+
def __init__(self, ratio=2, kernel_size=None):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.ratio = ratio
|
| 14 |
+
self.kernel_size = (
|
| 15 |
+
int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
|
| 16 |
+
)
|
| 17 |
+
self.stride = ratio
|
| 18 |
+
self.pad = self.kernel_size // ratio - 1
|
| 19 |
+
self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
|
| 20 |
+
self.pad_right = (
|
| 21 |
+
self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
|
| 22 |
+
)
|
| 23 |
+
filter = kaiser_sinc_filter1d(
|
| 24 |
+
cutoff=0.5 / ratio, half_width=0.6 / ratio, kernel_size=self.kernel_size
|
| 25 |
+
)
|
| 26 |
+
self.register_buffer("filter", filter)
|
| 27 |
+
|
| 28 |
+
# x: [B, C, T]
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
_, C, _ = x.shape
|
| 31 |
+
|
| 32 |
+
x = F.pad(x, (self.pad, self.pad), mode="replicate")
|
| 33 |
+
x = self.ratio * F.conv_transpose1d(
|
| 34 |
+
x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C
|
| 35 |
+
)
|
| 36 |
+
x = x[..., self.pad_left : -self.pad_right]
|
| 37 |
+
|
| 38 |
+
return x
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class DownSample1d(nn.Module):
|
| 42 |
+
def __init__(self, ratio=2, kernel_size=None):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.ratio = ratio
|
| 45 |
+
self.kernel_size = (
|
| 46 |
+
int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
|
| 47 |
+
)
|
| 48 |
+
self.lowpass = LowPassFilter1d(
|
| 49 |
+
cutoff=0.5 / ratio,
|
| 50 |
+
half_width=0.6 / ratio,
|
| 51 |
+
stride=ratio,
|
| 52 |
+
kernel_size=self.kernel_size,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
xx = self.lowpass(x)
|
| 57 |
+
|
| 58 |
+
return xx
|
seed-vc/modules/bigvgan/bigvgan.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2024 NVIDIA CORPORATION.
|
| 2 |
+
# Licensed under the MIT license.
|
| 3 |
+
|
| 4 |
+
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
| 5 |
+
# LICENSE is in incl_licenses directory.
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Optional, Union, Dict
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from torch.nn import Conv1d, ConvTranspose1d
|
| 15 |
+
from torch.nn.utils import weight_norm, remove_weight_norm
|
| 16 |
+
|
| 17 |
+
from . import activations
|
| 18 |
+
from .utils import init_weights, get_padding
|
| 19 |
+
from .alias_free_activation.torch.act import Activation1d as TorchActivation1d
|
| 20 |
+
from .env import AttrDict
|
| 21 |
+
|
| 22 |
+
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_hparams_from_json(path) -> AttrDict:
|
| 26 |
+
with open(path) as f:
|
| 27 |
+
data = f.read()
|
| 28 |
+
return AttrDict(json.loads(data))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class AMPBlock1(torch.nn.Module):
|
| 32 |
+
"""
|
| 33 |
+
AMPBlock applies Snake / SnakeBeta activation functions with trainable parameters that control periodicity, defined for each layer.
|
| 34 |
+
AMPBlock1 has additional self.convs2 that contains additional Conv1d layers with a fixed dilation=1 followed by each layer in self.convs1
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
h (AttrDict): Hyperparameters.
|
| 38 |
+
channels (int): Number of convolution channels.
|
| 39 |
+
kernel_size (int): Size of the convolution kernel. Default is 3.
|
| 40 |
+
dilation (tuple): Dilation rates for the convolutions. Each dilation layer has two convolutions. Default is (1, 3, 5).
|
| 41 |
+
activation (str): Activation function type. Should be either 'snake' or 'snakebeta'. Default is None.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
h: AttrDict,
|
| 47 |
+
channels: int,
|
| 48 |
+
kernel_size: int = 3,
|
| 49 |
+
dilation: tuple = (1, 3, 5),
|
| 50 |
+
activation: str = None,
|
| 51 |
+
):
|
| 52 |
+
super().__init__()
|
| 53 |
+
|
| 54 |
+
self.h = h
|
| 55 |
+
|
| 56 |
+
self.convs1 = nn.ModuleList(
|
| 57 |
+
[
|
| 58 |
+
weight_norm(
|
| 59 |
+
Conv1d(
|
| 60 |
+
channels,
|
| 61 |
+
channels,
|
| 62 |
+
kernel_size,
|
| 63 |
+
stride=1,
|
| 64 |
+
dilation=d,
|
| 65 |
+
padding=get_padding(kernel_size, d),
|
| 66 |
+
)
|
| 67 |
+
)
|
| 68 |
+
for d in dilation
|
| 69 |
+
]
|
| 70 |
+
)
|
| 71 |
+
self.convs1.apply(init_weights)
|
| 72 |
+
|
| 73 |
+
self.convs2 = nn.ModuleList(
|
| 74 |
+
[
|
| 75 |
+
weight_norm(
|
| 76 |
+
Conv1d(
|
| 77 |
+
channels,
|
| 78 |
+
channels,
|
| 79 |
+
kernel_size,
|
| 80 |
+
stride=1,
|
| 81 |
+
dilation=1,
|
| 82 |
+
padding=get_padding(kernel_size, 1),
|
| 83 |
+
)
|
| 84 |
+
)
|
| 85 |
+
for _ in range(len(dilation))
|
| 86 |
+
]
|
| 87 |
+
)
|
| 88 |
+
self.convs2.apply(init_weights)
|
| 89 |
+
|
| 90 |
+
self.num_layers = len(self.convs1) + len(
|
| 91 |
+
self.convs2
|
| 92 |
+
) # Total number of conv layers
|
| 93 |
+
|
| 94 |
+
# Select which Activation1d, lazy-load cuda version to ensure backward compatibility
|
| 95 |
+
if self.h.get("use_cuda_kernel", False):
|
| 96 |
+
from .alias_free_activation.cuda.activation1d import (
|
| 97 |
+
Activation1d as CudaActivation1d,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
Activation1d = CudaActivation1d
|
| 101 |
+
else:
|
| 102 |
+
Activation1d = TorchActivation1d
|
| 103 |
+
|
| 104 |
+
# Activation functions
|
| 105 |
+
if activation == "snake":
|
| 106 |
+
self.activations = nn.ModuleList(
|
| 107 |
+
[
|
| 108 |
+
Activation1d(
|
| 109 |
+
activation=activations.Snake(
|
| 110 |
+
channels, alpha_logscale=h.snake_logscale
|
| 111 |
+
)
|
| 112 |
+
)
|
| 113 |
+
for _ in range(self.num_layers)
|
| 114 |
+
]
|
| 115 |
+
)
|
| 116 |
+
elif activation == "snakebeta":
|
| 117 |
+
self.activations = nn.ModuleList(
|
| 118 |
+
[
|
| 119 |
+
Activation1d(
|
| 120 |
+
activation=activations.SnakeBeta(
|
| 121 |
+
channels, alpha_logscale=h.snake_logscale
|
| 122 |
+
)
|
| 123 |
+
)
|
| 124 |
+
for _ in range(self.num_layers)
|
| 125 |
+
]
|
| 126 |
+
)
|
| 127 |
+
else:
|
| 128 |
+
raise NotImplementedError(
|
| 129 |
+
"activation incorrectly specified. check the config file and look for 'activation'."
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
def forward(self, x):
|
| 133 |
+
acts1, acts2 = self.activations[::2], self.activations[1::2]
|
| 134 |
+
for c1, c2, a1, a2 in zip(self.convs1, self.convs2, acts1, acts2):
|
| 135 |
+
xt = a1(x)
|
| 136 |
+
xt = c1(xt)
|
| 137 |
+
xt = a2(xt)
|
| 138 |
+
xt = c2(xt)
|
| 139 |
+
x = xt + x
|
| 140 |
+
|
| 141 |
+
return x
|
| 142 |
+
|
| 143 |
+
def remove_weight_norm(self):
|
| 144 |
+
for l in self.convs1:
|
| 145 |
+
remove_weight_norm(l)
|
| 146 |
+
for l in self.convs2:
|
| 147 |
+
remove_weight_norm(l)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class AMPBlock2(torch.nn.Module):
|
| 151 |
+
"""
|
| 152 |
+
AMPBlock applies Snake / SnakeBeta activation functions with trainable parameters that control periodicity, defined for each layer.
|
| 153 |
+
Unlike AMPBlock1, AMPBlock2 does not contain extra Conv1d layers with fixed dilation=1
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
h (AttrDict): Hyperparameters.
|
| 157 |
+
channels (int): Number of convolution channels.
|
| 158 |
+
kernel_size (int): Size of the convolution kernel. Default is 3.
|
| 159 |
+
dilation (tuple): Dilation rates for the convolutions. Each dilation layer has two convolutions. Default is (1, 3, 5).
|
| 160 |
+
activation (str): Activation function type. Should be either 'snake' or 'snakebeta'. Default is None.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
def __init__(
|
| 164 |
+
self,
|
| 165 |
+
h: AttrDict,
|
| 166 |
+
channels: int,
|
| 167 |
+
kernel_size: int = 3,
|
| 168 |
+
dilation: tuple = (1, 3, 5),
|
| 169 |
+
activation: str = None,
|
| 170 |
+
):
|
| 171 |
+
super().__init__()
|
| 172 |
+
|
| 173 |
+
self.h = h
|
| 174 |
+
|
| 175 |
+
self.convs = nn.ModuleList(
|
| 176 |
+
[
|
| 177 |
+
weight_norm(
|
| 178 |
+
Conv1d(
|
| 179 |
+
channels,
|
| 180 |
+
channels,
|
| 181 |
+
kernel_size,
|
| 182 |
+
stride=1,
|
| 183 |
+
dilation=d,
|
| 184 |
+
padding=get_padding(kernel_size, d),
|
| 185 |
+
)
|
| 186 |
+
)
|
| 187 |
+
for d in dilation
|
| 188 |
+
]
|
| 189 |
+
)
|
| 190 |
+
self.convs.apply(init_weights)
|
| 191 |
+
|
| 192 |
+
self.num_layers = len(self.convs) # Total number of conv layers
|
| 193 |
+
|
| 194 |
+
# Select which Activation1d, lazy-load cuda version to ensure backward compatibility
|
| 195 |
+
if self.h.get("use_cuda_kernel", False):
|
| 196 |
+
from .alias_free_activation.cuda.activation1d import (
|
| 197 |
+
Activation1d as CudaActivation1d,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
Activation1d = CudaActivation1d
|
| 201 |
+
else:
|
| 202 |
+
Activation1d = TorchActivation1d
|
| 203 |
+
|
| 204 |
+
# Activation functions
|
| 205 |
+
if activation == "snake":
|
| 206 |
+
self.activations = nn.ModuleList(
|
| 207 |
+
[
|
| 208 |
+
Activation1d(
|
| 209 |
+
activation=activations.Snake(
|
| 210 |
+
channels, alpha_logscale=h.snake_logscale
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
for _ in range(self.num_layers)
|
| 214 |
+
]
|
| 215 |
+
)
|
| 216 |
+
elif activation == "snakebeta":
|
| 217 |
+
self.activations = nn.ModuleList(
|
| 218 |
+
[
|
| 219 |
+
Activation1d(
|
| 220 |
+
activation=activations.SnakeBeta(
|
| 221 |
+
channels, alpha_logscale=h.snake_logscale
|
| 222 |
+
)
|
| 223 |
+
)
|
| 224 |
+
for _ in range(self.num_layers)
|
| 225 |
+
]
|
| 226 |
+
)
|
| 227 |
+
else:
|
| 228 |
+
raise NotImplementedError(
|
| 229 |
+
"activation incorrectly specified. check the config file and look for 'activation'."
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def forward(self, x):
|
| 233 |
+
for c, a in zip(self.convs, self.activations):
|
| 234 |
+
xt = a(x)
|
| 235 |
+
xt = c(xt)
|
| 236 |
+
x = xt + x
|
| 237 |
+
|
| 238 |
+
def remove_weight_norm(self):
|
| 239 |
+
for l in self.convs:
|
| 240 |
+
remove_weight_norm(l)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class BigVGAN(
|
| 244 |
+
torch.nn.Module,
|
| 245 |
+
PyTorchModelHubMixin,
|
| 246 |
+
library_name="bigvgan",
|
| 247 |
+
repo_url="https://github.com/NVIDIA/BigVGAN",
|
| 248 |
+
docs_url="https://github.com/NVIDIA/BigVGAN/blob/main/README.md",
|
| 249 |
+
pipeline_tag="audio-to-audio",
|
| 250 |
+
license="mit",
|
| 251 |
+
tags=["neural-vocoder", "audio-generation", "arxiv:2206.04658"],
|
| 252 |
+
):
|
| 253 |
+
"""
|
| 254 |
+
BigVGAN is a neural vocoder model that applies anti-aliased periodic activation for residual blocks (resblocks).
|
| 255 |
+
New in BigVGAN-v2: it can optionally use optimized CUDA kernels for AMP (anti-aliased multi-periodicity) blocks.
|
| 256 |
+
|
| 257 |
+
Args:
|
| 258 |
+
h (AttrDict): Hyperparameters.
|
| 259 |
+
use_cuda_kernel (bool): If set to True, loads optimized CUDA kernels for AMP. This should be used for inference only, as training is not supported with CUDA kernels.
|
| 260 |
+
|
| 261 |
+
Note:
|
| 262 |
+
- The `use_cuda_kernel` parameter should be used for inference only, as training with CUDA kernels is not supported.
|
| 263 |
+
- Ensure that the activation function is correctly specified in the hyperparameters (h.activation).
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
def __init__(self, h: AttrDict, use_cuda_kernel: bool = False):
|
| 267 |
+
super().__init__()
|
| 268 |
+
self.h = h
|
| 269 |
+
self.h["use_cuda_kernel"] = use_cuda_kernel
|
| 270 |
+
|
| 271 |
+
# Select which Activation1d, lazy-load cuda version to ensure backward compatibility
|
| 272 |
+
if self.h.get("use_cuda_kernel", False):
|
| 273 |
+
from .alias_free_activation.cuda.activation1d import (
|
| 274 |
+
Activation1d as CudaActivation1d,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
Activation1d = CudaActivation1d
|
| 278 |
+
else:
|
| 279 |
+
Activation1d = TorchActivation1d
|
| 280 |
+
|
| 281 |
+
self.num_kernels = len(h.resblock_kernel_sizes)
|
| 282 |
+
self.num_upsamples = len(h.upsample_rates)
|
| 283 |
+
|
| 284 |
+
# Pre-conv
|
| 285 |
+
self.conv_pre = weight_norm(
|
| 286 |
+
Conv1d(h.num_mels, h.upsample_initial_channel, 7, 1, padding=3)
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# Define which AMPBlock to use. BigVGAN uses AMPBlock1 as default
|
| 290 |
+
if h.resblock == "1":
|
| 291 |
+
resblock_class = AMPBlock1
|
| 292 |
+
elif h.resblock == "2":
|
| 293 |
+
resblock_class = AMPBlock2
|
| 294 |
+
else:
|
| 295 |
+
raise ValueError(
|
| 296 |
+
f"Incorrect resblock class specified in hyperparameters. Got {h.resblock}"
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# Transposed conv-based upsamplers. does not apply anti-aliasing
|
| 300 |
+
self.ups = nn.ModuleList()
|
| 301 |
+
for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
|
| 302 |
+
self.ups.append(
|
| 303 |
+
nn.ModuleList(
|
| 304 |
+
[
|
| 305 |
+
weight_norm(
|
| 306 |
+
ConvTranspose1d(
|
| 307 |
+
h.upsample_initial_channel // (2 ** i),
|
| 308 |
+
h.upsample_initial_channel // (2 ** (i + 1)),
|
| 309 |
+
k,
|
| 310 |
+
u,
|
| 311 |
+
padding=(k - u) // 2,
|
| 312 |
+
)
|
| 313 |
+
)
|
| 314 |
+
]
|
| 315 |
+
)
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
# Residual blocks using anti-aliased multi-periodicity composition modules (AMP)
|
| 319 |
+
self.resblocks = nn.ModuleList()
|
| 320 |
+
for i in range(len(self.ups)):
|
| 321 |
+
ch = h.upsample_initial_channel // (2 ** (i + 1))
|
| 322 |
+
for j, (k, d) in enumerate(
|
| 323 |
+
zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)
|
| 324 |
+
):
|
| 325 |
+
self.resblocks.append(
|
| 326 |
+
resblock_class(h, ch, k, d, activation=h.activation)
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
# Post-conv
|
| 330 |
+
activation_post = (
|
| 331 |
+
activations.Snake(ch, alpha_logscale=h.snake_logscale)
|
| 332 |
+
if h.activation == "snake"
|
| 333 |
+
else (
|
| 334 |
+
activations.SnakeBeta(ch, alpha_logscale=h.snake_logscale)
|
| 335 |
+
if h.activation == "snakebeta"
|
| 336 |
+
else None
|
| 337 |
+
)
|
| 338 |
+
)
|
| 339 |
+
if activation_post is None:
|
| 340 |
+
raise NotImplementedError(
|
| 341 |
+
"activation incorrectly specified. check the config file and look for 'activation'."
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
self.activation_post = Activation1d(activation=activation_post)
|
| 345 |
+
|
| 346 |
+
# Whether to use bias for the final conv_post. Default to True for backward compatibility
|
| 347 |
+
self.use_bias_at_final = h.get("use_bias_at_final", True)
|
| 348 |
+
self.conv_post = weight_norm(
|
| 349 |
+
Conv1d(ch, 1, 7, 1, padding=3, bias=self.use_bias_at_final)
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
# Weight initialization
|
| 353 |
+
for i in range(len(self.ups)):
|
| 354 |
+
self.ups[i].apply(init_weights)
|
| 355 |
+
self.conv_post.apply(init_weights)
|
| 356 |
+
|
| 357 |
+
# Final tanh activation. Defaults to True for backward compatibility
|
| 358 |
+
self.use_tanh_at_final = h.get("use_tanh_at_final", True)
|
| 359 |
+
|
| 360 |
+
def forward(self, x):
|
| 361 |
+
# Pre-conv
|
| 362 |
+
x = self.conv_pre(x)
|
| 363 |
+
|
| 364 |
+
for i in range(self.num_upsamples):
|
| 365 |
+
# Upsampling
|
| 366 |
+
for i_up in range(len(self.ups[i])):
|
| 367 |
+
x = self.ups[i][i_up](x)
|
| 368 |
+
# AMP blocks
|
| 369 |
+
xs = None
|
| 370 |
+
for j in range(self.num_kernels):
|
| 371 |
+
if xs is None:
|
| 372 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
| 373 |
+
else:
|
| 374 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
| 375 |
+
x = xs / self.num_kernels
|
| 376 |
+
|
| 377 |
+
# Post-conv
|
| 378 |
+
x = self.activation_post(x)
|
| 379 |
+
x = self.conv_post(x)
|
| 380 |
+
# Final tanh activation
|
| 381 |
+
if self.use_tanh_at_final:
|
| 382 |
+
x = torch.tanh(x)
|
| 383 |
+
else:
|
| 384 |
+
x = torch.clamp(x, min=-1.0, max=1.0) # Bound the output to [-1, 1]
|
| 385 |
+
|
| 386 |
+
return x
|
| 387 |
+
|
| 388 |
+
def remove_weight_norm(self):
|
| 389 |
+
try:
|
| 390 |
+
print("Removing weight norm...")
|
| 391 |
+
for l in self.ups:
|
| 392 |
+
for l_i in l:
|
| 393 |
+
remove_weight_norm(l_i)
|
| 394 |
+
for l in self.resblocks:
|
| 395 |
+
l.remove_weight_norm()
|
| 396 |
+
remove_weight_norm(self.conv_pre)
|
| 397 |
+
remove_weight_norm(self.conv_post)
|
| 398 |
+
except ValueError:
|
| 399 |
+
print("[INFO] Model already removed weight norm. Skipping!")
|
| 400 |
+
pass
|
| 401 |
+
|
| 402 |
+
# Additional methods for huggingface_hub support
|
| 403 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
| 404 |
+
"""Save weights and config.json from a Pytorch model to a local directory."""
|
| 405 |
+
|
| 406 |
+
model_path = save_directory / "bigvgan_generator.pt"
|
| 407 |
+
torch.save({"generator": self.state_dict()}, model_path)
|
| 408 |
+
|
| 409 |
+
config_path = save_directory / "config.json"
|
| 410 |
+
with open(config_path, "w") as config_file:
|
| 411 |
+
json.dump(self.h, config_file, indent=4)
|
| 412 |
+
|
| 413 |
+
@classmethod
|
| 414 |
+
def _from_pretrained(
|
| 415 |
+
cls,
|
| 416 |
+
*,
|
| 417 |
+
model_id: str,
|
| 418 |
+
revision: str,
|
| 419 |
+
cache_dir: str,
|
| 420 |
+
force_download: bool,
|
| 421 |
+
proxies: Optional[Dict],
|
| 422 |
+
resume_download: bool,
|
| 423 |
+
local_files_only: bool,
|
| 424 |
+
token: Union[str, bool, None],
|
| 425 |
+
map_location: str = "cpu", # Additional argument
|
| 426 |
+
strict: bool = False, # Additional argument
|
| 427 |
+
use_cuda_kernel: bool = False,
|
| 428 |
+
**model_kwargs,
|
| 429 |
+
):
|
| 430 |
+
"""Load Pytorch pretrained weights and return the loaded model."""
|
| 431 |
+
|
| 432 |
+
# Download and load hyperparameters (h) used by BigVGAN
|
| 433 |
+
if os.path.isdir(model_id):
|
| 434 |
+
print("Loading config.json from local directory")
|
| 435 |
+
config_file = os.path.join(model_id, "config.json")
|
| 436 |
+
else:
|
| 437 |
+
config_file = hf_hub_download(
|
| 438 |
+
repo_id=model_id,
|
| 439 |
+
filename="config.json",
|
| 440 |
+
revision=revision,
|
| 441 |
+
cache_dir=cache_dir,
|
| 442 |
+
force_download=force_download,
|
| 443 |
+
proxies=proxies,
|
| 444 |
+
resume_download=resume_download,
|
| 445 |
+
token=token,
|
| 446 |
+
local_files_only=local_files_only,
|
| 447 |
+
)
|
| 448 |
+
h = load_hparams_from_json(config_file)
|
| 449 |
+
|
| 450 |
+
# instantiate BigVGAN using h
|
| 451 |
+
if use_cuda_kernel:
|
| 452 |
+
print(
|
| 453 |
+
f"[WARNING] You have specified use_cuda_kernel=True during BigVGAN.from_pretrained(). Only inference is supported (training is not implemented)!"
|
| 454 |
+
)
|
| 455 |
+
print(
|
| 456 |
+
f"[WARNING] You need nvcc and ninja installed in your system that matches your PyTorch build is using to build the kernel. If not, the model will fail to initialize or generate incorrect waveform!"
|
| 457 |
+
)
|
| 458 |
+
print(
|
| 459 |
+
f"[WARNING] For detail, see the official GitHub repository: https://github.com/NVIDIA/BigVGAN?tab=readme-ov-file#using-custom-cuda-kernel-for-synthesis"
|
| 460 |
+
)
|
| 461 |
+
model = cls(h, use_cuda_kernel=use_cuda_kernel)
|
| 462 |
+
|
| 463 |
+
# Download and load pretrained generator weight
|
| 464 |
+
if os.path.isdir(model_id):
|
| 465 |
+
print("Loading weights from local directory")
|
| 466 |
+
model_file = os.path.join(model_id, "bigvgan_generator.pt")
|
| 467 |
+
else:
|
| 468 |
+
print(f"Loading weights from {model_id}")
|
| 469 |
+
model_file = hf_hub_download(
|
| 470 |
+
repo_id=model_id,
|
| 471 |
+
filename="bigvgan_generator.pt",
|
| 472 |
+
revision=revision,
|
| 473 |
+
cache_dir=cache_dir,
|
| 474 |
+
force_download=force_download,
|
| 475 |
+
proxies=proxies,
|
| 476 |
+
resume_download=resume_download,
|
| 477 |
+
token=token,
|
| 478 |
+
local_files_only=local_files_only,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
checkpoint_dict = torch.load(model_file, map_location=map_location)
|
| 482 |
+
|
| 483 |
+
try:
|
| 484 |
+
model.load_state_dict(checkpoint_dict["generator"])
|
| 485 |
+
except RuntimeError:
|
| 486 |
+
print(
|
| 487 |
+
f"[INFO] the pretrained checkpoint does not contain weight norm. Loading the checkpoint after removing weight norm!"
|
| 488 |
+
)
|
| 489 |
+
model.remove_weight_norm()
|
| 490 |
+
model.load_state_dict(checkpoint_dict["generator"])
|
| 491 |
+
|
| 492 |
+
return model
|
seed-vc/modules/bigvgan/config.json
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"resblock": "1",
|
| 3 |
+
"num_gpus": 0,
|
| 4 |
+
"batch_size": 32,
|
| 5 |
+
"learning_rate": 0.0001,
|
| 6 |
+
"adam_b1": 0.8,
|
| 7 |
+
"adam_b2": 0.99,
|
| 8 |
+
"lr_decay": 0.9999996,
|
| 9 |
+
"seed": 1234,
|
| 10 |
+
|
| 11 |
+
"upsample_rates": [4,4,2,2,2,2],
|
| 12 |
+
"upsample_kernel_sizes": [8,8,4,4,4,4],
|
| 13 |
+
"upsample_initial_channel": 1536,
|
| 14 |
+
"resblock_kernel_sizes": [3,7,11],
|
| 15 |
+
"resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
|
| 16 |
+
|
| 17 |
+
"use_tanh_at_final": false,
|
| 18 |
+
"use_bias_at_final": false,
|
| 19 |
+
|
| 20 |
+
"activation": "snakebeta",
|
| 21 |
+
"snake_logscale": true,
|
| 22 |
+
|
| 23 |
+
"use_cqtd_instead_of_mrd": true,
|
| 24 |
+
"cqtd_filters": 128,
|
| 25 |
+
"cqtd_max_filters": 1024,
|
| 26 |
+
"cqtd_filters_scale": 1,
|
| 27 |
+
"cqtd_dilations": [1, 2, 4],
|
| 28 |
+
"cqtd_hop_lengths": [512, 256, 256],
|
| 29 |
+
"cqtd_n_octaves": [9, 9, 9],
|
| 30 |
+
"cqtd_bins_per_octaves": [24, 36, 48],
|
| 31 |
+
|
| 32 |
+
"mpd_reshapes": [2, 3, 5, 7, 11],
|
| 33 |
+
"use_spectral_norm": false,
|
| 34 |
+
"discriminator_channel_mult": 1,
|
| 35 |
+
|
| 36 |
+
"use_multiscale_melloss": true,
|
| 37 |
+
"lambda_melloss": 15,
|
| 38 |
+
|
| 39 |
+
"clip_grad_norm": 500,
|
| 40 |
+
|
| 41 |
+
"segment_size": 65536,
|
| 42 |
+
"num_mels": 80,
|
| 43 |
+
"num_freq": 1025,
|
| 44 |
+
"n_fft": 1024,
|
| 45 |
+
"hop_size": 256,
|
| 46 |
+
"win_size": 1024,
|
| 47 |
+
|
| 48 |
+
"sampling_rate": 22050,
|
| 49 |
+
|
| 50 |
+
"fmin": 0,
|
| 51 |
+
"fmax": null,
|
| 52 |
+
"fmax_for_loss": null,
|
| 53 |
+
|
| 54 |
+
"normalize_volume": true,
|
| 55 |
+
|
| 56 |
+
"num_workers": 4,
|
| 57 |
+
|
| 58 |
+
"dist_config": {
|
| 59 |
+
"dist_backend": "nccl",
|
| 60 |
+
"dist_url": "tcp://localhost:54321",
|
| 61 |
+
"world_size": 1
|
| 62 |
+
}
|
| 63 |
+
}
|
seed-vc/modules/bigvgan/env.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
| 2 |
+
# LICENSE is in incl_licenses directory.
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class AttrDict(dict):
|
| 9 |
+
def __init__(self, *args, **kwargs):
|
| 10 |
+
super(AttrDict, self).__init__(*args, **kwargs)
|
| 11 |
+
self.__dict__ = self
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def build_env(config, config_name, path):
|
| 15 |
+
t_path = os.path.join(path, config_name)
|
| 16 |
+
if config != t_path:
|
| 17 |
+
os.makedirs(path, exist_ok=True)
|
| 18 |
+
shutil.copyfile(config, os.path.join(path, config_name))
|
seed-vc/modules/bigvgan/meldataset.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2024 NVIDIA CORPORATION.
|
| 2 |
+
# Licensed under the MIT license.
|
| 3 |
+
|
| 4 |
+
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
| 5 |
+
# LICENSE is in incl_licenses directory.
|
| 6 |
+
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
import random
|
| 10 |
+
import torch
|
| 11 |
+
import torch.utils.data
|
| 12 |
+
import numpy as np
|
| 13 |
+
from librosa.util import normalize
|
| 14 |
+
from scipy.io.wavfile import read
|
| 15 |
+
from librosa.filters import mel as librosa_mel_fn
|
| 16 |
+
import pathlib
|
| 17 |
+
from tqdm import tqdm
|
| 18 |
+
|
| 19 |
+
MAX_WAV_VALUE = 32767.0 # NOTE: 32768.0 -1 to prevent int16 overflow (results in popping sound in corner cases)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_wav(full_path, sr_target):
|
| 23 |
+
sampling_rate, data = read(full_path)
|
| 24 |
+
if sampling_rate != sr_target:
|
| 25 |
+
raise RuntimeError(
|
| 26 |
+
f"Sampling rate of the file {full_path} is {sampling_rate} Hz, but the model requires {sr_target} Hz"
|
| 27 |
+
)
|
| 28 |
+
return data, sampling_rate
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def dynamic_range_compression(x, C=1, clip_val=1e-5):
|
| 32 |
+
return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def dynamic_range_decompression(x, C=1):
|
| 36 |
+
return np.exp(x) / C
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
|
| 40 |
+
return torch.log(torch.clamp(x, min=clip_val) * C)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def dynamic_range_decompression_torch(x, C=1):
|
| 44 |
+
return torch.exp(x) / C
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def spectral_normalize_torch(magnitudes):
|
| 48 |
+
return dynamic_range_compression_torch(magnitudes)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def spectral_de_normalize_torch(magnitudes):
|
| 52 |
+
return dynamic_range_decompression_torch(magnitudes)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
mel_basis_cache = {}
|
| 56 |
+
hann_window_cache = {}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def mel_spectrogram(
|
| 60 |
+
y: torch.Tensor,
|
| 61 |
+
n_fft: int,
|
| 62 |
+
num_mels: int,
|
| 63 |
+
sampling_rate: int,
|
| 64 |
+
hop_size: int,
|
| 65 |
+
win_size: int,
|
| 66 |
+
fmin: int,
|
| 67 |
+
fmax: int = None,
|
| 68 |
+
center: bool = False,
|
| 69 |
+
) -> torch.Tensor:
|
| 70 |
+
"""
|
| 71 |
+
Calculate the mel spectrogram of an input signal.
|
| 72 |
+
This function uses slaney norm for the librosa mel filterbank (using librosa.filters.mel) and uses Hann window for STFT (using torch.stft).
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
y (torch.Tensor): Input signal.
|
| 76 |
+
n_fft (int): FFT size.
|
| 77 |
+
num_mels (int): Number of mel bins.
|
| 78 |
+
sampling_rate (int): Sampling rate of the input signal.
|
| 79 |
+
hop_size (int): Hop size for STFT.
|
| 80 |
+
win_size (int): Window size for STFT.
|
| 81 |
+
fmin (int): Minimum frequency for mel filterbank.
|
| 82 |
+
fmax (int): Maximum frequency for mel filterbank. If None, defaults to half the sampling rate (fmax = sr / 2.0) inside librosa_mel_fn
|
| 83 |
+
center (bool): Whether to pad the input to center the frames. Default is False.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
torch.Tensor: Mel spectrogram.
|
| 87 |
+
"""
|
| 88 |
+
if torch.min(y) < -1.0:
|
| 89 |
+
print(f"[WARNING] Min value of input waveform signal is {torch.min(y)}")
|
| 90 |
+
if torch.max(y) > 1.0:
|
| 91 |
+
print(f"[WARNING] Max value of input waveform signal is {torch.max(y)}")
|
| 92 |
+
|
| 93 |
+
device = y.device
|
| 94 |
+
key = f"{n_fft}_{num_mels}_{sampling_rate}_{hop_size}_{win_size}_{fmin}_{fmax}_{device}"
|
| 95 |
+
|
| 96 |
+
if key not in mel_basis_cache:
|
| 97 |
+
mel = librosa_mel_fn(
|
| 98 |
+
sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
|
| 99 |
+
)
|
| 100 |
+
mel_basis_cache[key] = torch.from_numpy(mel).float().to(device)
|
| 101 |
+
hann_window_cache[key] = torch.hann_window(win_size).to(device)
|
| 102 |
+
|
| 103 |
+
mel_basis = mel_basis_cache[key]
|
| 104 |
+
hann_window = hann_window_cache[key]
|
| 105 |
+
|
| 106 |
+
padding = (n_fft - hop_size) // 2
|
| 107 |
+
y = torch.nn.functional.pad(
|
| 108 |
+
y.unsqueeze(1), (padding, padding), mode="reflect"
|
| 109 |
+
).squeeze(1)
|
| 110 |
+
|
| 111 |
+
spec = torch.stft(
|
| 112 |
+
y,
|
| 113 |
+
n_fft,
|
| 114 |
+
hop_length=hop_size,
|
| 115 |
+
win_length=win_size,
|
| 116 |
+
window=hann_window,
|
| 117 |
+
center=center,
|
| 118 |
+
pad_mode="reflect",
|
| 119 |
+
normalized=False,
|
| 120 |
+
onesided=True,
|
| 121 |
+
return_complex=True,
|
| 122 |
+
)
|
| 123 |
+
spec = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9)
|
| 124 |
+
|
| 125 |
+
mel_spec = torch.matmul(mel_basis, spec)
|
| 126 |
+
mel_spec = spectral_normalize_torch(mel_spec)
|
| 127 |
+
|
| 128 |
+
return mel_spec
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def get_mel_spectrogram(wav, h):
|
| 132 |
+
"""
|
| 133 |
+
Generate mel spectrogram from a waveform using given hyperparameters.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
wav (torch.Tensor): Input waveform.
|
| 137 |
+
h: Hyperparameters object with attributes n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax.
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
torch.Tensor: Mel spectrogram.
|
| 141 |
+
"""
|
| 142 |
+
return mel_spectrogram(
|
| 143 |
+
wav,
|
| 144 |
+
h.n_fft,
|
| 145 |
+
h.num_mels,
|
| 146 |
+
h.sampling_rate,
|
| 147 |
+
h.hop_size,
|
| 148 |
+
h.win_size,
|
| 149 |
+
h.fmin,
|
| 150 |
+
h.fmax,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def get_dataset_filelist(a):
|
| 155 |
+
training_files = []
|
| 156 |
+
validation_files = []
|
| 157 |
+
list_unseen_validation_files = []
|
| 158 |
+
|
| 159 |
+
with open(a.input_training_file, "r", encoding="utf-8") as fi:
|
| 160 |
+
training_files = [
|
| 161 |
+
os.path.join(a.input_wavs_dir, x.split("|")[0] + ".wav")
|
| 162 |
+
for x in fi.read().split("\n")
|
| 163 |
+
if len(x) > 0
|
| 164 |
+
]
|
| 165 |
+
print(f"first training file: {training_files[0]}")
|
| 166 |
+
|
| 167 |
+
with open(a.input_validation_file, "r", encoding="utf-8") as fi:
|
| 168 |
+
validation_files = [
|
| 169 |
+
os.path.join(a.input_wavs_dir, x.split("|")[0] + ".wav")
|
| 170 |
+
for x in fi.read().split("\n")
|
| 171 |
+
if len(x) > 0
|
| 172 |
+
]
|
| 173 |
+
print(f"first validation file: {validation_files[0]}")
|
| 174 |
+
|
| 175 |
+
for i in range(len(a.list_input_unseen_validation_file)):
|
| 176 |
+
with open(a.list_input_unseen_validation_file[i], "r", encoding="utf-8") as fi:
|
| 177 |
+
unseen_validation_files = [
|
| 178 |
+
os.path.join(a.list_input_unseen_wavs_dir[i], x.split("|")[0] + ".wav")
|
| 179 |
+
for x in fi.read().split("\n")
|
| 180 |
+
if len(x) > 0
|
| 181 |
+
]
|
| 182 |
+
print(
|
| 183 |
+
f"first unseen {i}th validation fileset: {unseen_validation_files[0]}"
|
| 184 |
+
)
|
| 185 |
+
list_unseen_validation_files.append(unseen_validation_files)
|
| 186 |
+
|
| 187 |
+
return training_files, validation_files, list_unseen_validation_files
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class MelDataset(torch.utils.data.Dataset):
|
| 191 |
+
def __init__(
|
| 192 |
+
self,
|
| 193 |
+
training_files,
|
| 194 |
+
hparams,
|
| 195 |
+
segment_size,
|
| 196 |
+
n_fft,
|
| 197 |
+
num_mels,
|
| 198 |
+
hop_size,
|
| 199 |
+
win_size,
|
| 200 |
+
sampling_rate,
|
| 201 |
+
fmin,
|
| 202 |
+
fmax,
|
| 203 |
+
split=True,
|
| 204 |
+
shuffle=True,
|
| 205 |
+
n_cache_reuse=1,
|
| 206 |
+
device=None,
|
| 207 |
+
fmax_loss=None,
|
| 208 |
+
fine_tuning=False,
|
| 209 |
+
base_mels_path=None,
|
| 210 |
+
is_seen=True,
|
| 211 |
+
):
|
| 212 |
+
self.audio_files = training_files
|
| 213 |
+
random.seed(1234)
|
| 214 |
+
if shuffle:
|
| 215 |
+
random.shuffle(self.audio_files)
|
| 216 |
+
self.hparams = hparams
|
| 217 |
+
self.is_seen = is_seen
|
| 218 |
+
if self.is_seen:
|
| 219 |
+
self.name = pathlib.Path(self.audio_files[0]).parts[0]
|
| 220 |
+
else:
|
| 221 |
+
self.name = "-".join(pathlib.Path(self.audio_files[0]).parts[:2]).strip("/")
|
| 222 |
+
|
| 223 |
+
self.segment_size = segment_size
|
| 224 |
+
self.sampling_rate = sampling_rate
|
| 225 |
+
self.split = split
|
| 226 |
+
self.n_fft = n_fft
|
| 227 |
+
self.num_mels = num_mels
|
| 228 |
+
self.hop_size = hop_size
|
| 229 |
+
self.win_size = win_size
|
| 230 |
+
self.fmin = fmin
|
| 231 |
+
self.fmax = fmax
|
| 232 |
+
self.fmax_loss = fmax_loss
|
| 233 |
+
self.cached_wav = None
|
| 234 |
+
self.n_cache_reuse = n_cache_reuse
|
| 235 |
+
self._cache_ref_count = 0
|
| 236 |
+
self.device = device
|
| 237 |
+
self.fine_tuning = fine_tuning
|
| 238 |
+
self.base_mels_path = base_mels_path
|
| 239 |
+
|
| 240 |
+
print("[INFO] checking dataset integrity...")
|
| 241 |
+
for i in tqdm(range(len(self.audio_files))):
|
| 242 |
+
assert os.path.exists(
|
| 243 |
+
self.audio_files[i]
|
| 244 |
+
), f"{self.audio_files[i]} not found"
|
| 245 |
+
|
| 246 |
+
def __getitem__(self, index):
|
| 247 |
+
filename = self.audio_files[index]
|
| 248 |
+
if self._cache_ref_count == 0:
|
| 249 |
+
audio, sampling_rate = load_wav(filename, self.sampling_rate)
|
| 250 |
+
audio = audio / MAX_WAV_VALUE
|
| 251 |
+
if not self.fine_tuning:
|
| 252 |
+
audio = normalize(audio) * 0.95
|
| 253 |
+
self.cached_wav = audio
|
| 254 |
+
if sampling_rate != self.sampling_rate:
|
| 255 |
+
raise ValueError(
|
| 256 |
+
f"{sampling_rate} SR doesn't match target {self.sampling_rate} SR"
|
| 257 |
+
)
|
| 258 |
+
self._cache_ref_count = self.n_cache_reuse
|
| 259 |
+
else:
|
| 260 |
+
audio = self.cached_wav
|
| 261 |
+
self._cache_ref_count -= 1
|
| 262 |
+
|
| 263 |
+
audio = torch.FloatTensor(audio)
|
| 264 |
+
audio = audio.unsqueeze(0)
|
| 265 |
+
|
| 266 |
+
if not self.fine_tuning:
|
| 267 |
+
if self.split:
|
| 268 |
+
if audio.size(1) >= self.segment_size:
|
| 269 |
+
max_audio_start = audio.size(1) - self.segment_size
|
| 270 |
+
audio_start = random.randint(0, max_audio_start)
|
| 271 |
+
audio = audio[:, audio_start : audio_start + self.segment_size]
|
| 272 |
+
else:
|
| 273 |
+
audio = torch.nn.functional.pad(
|
| 274 |
+
audio, (0, self.segment_size - audio.size(1)), "constant"
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
mel = mel_spectrogram(
|
| 278 |
+
audio,
|
| 279 |
+
self.n_fft,
|
| 280 |
+
self.num_mels,
|
| 281 |
+
self.sampling_rate,
|
| 282 |
+
self.hop_size,
|
| 283 |
+
self.win_size,
|
| 284 |
+
self.fmin,
|
| 285 |
+
self.fmax,
|
| 286 |
+
center=False,
|
| 287 |
+
)
|
| 288 |
+
else: # Validation step
|
| 289 |
+
# Match audio length to self.hop_size * n for evaluation
|
| 290 |
+
if (audio.size(1) % self.hop_size) != 0:
|
| 291 |
+
audio = audio[:, : -(audio.size(1) % self.hop_size)]
|
| 292 |
+
mel = mel_spectrogram(
|
| 293 |
+
audio,
|
| 294 |
+
self.n_fft,
|
| 295 |
+
self.num_mels,
|
| 296 |
+
self.sampling_rate,
|
| 297 |
+
self.hop_size,
|
| 298 |
+
self.win_size,
|
| 299 |
+
self.fmin,
|
| 300 |
+
self.fmax,
|
| 301 |
+
center=False,
|
| 302 |
+
)
|
| 303 |
+
assert (
|
| 304 |
+
audio.shape[1] == mel.shape[2] * self.hop_size
|
| 305 |
+
), f"audio shape {audio.shape} mel shape {mel.shape}"
|
| 306 |
+
|
| 307 |
+
else:
|
| 308 |
+
mel = np.load(
|
| 309 |
+
os.path.join(
|
| 310 |
+
self.base_mels_path,
|
| 311 |
+
os.path.splitext(os.path.split(filename)[-1])[0] + ".npy",
|
| 312 |
+
)
|
| 313 |
+
)
|
| 314 |
+
mel = torch.from_numpy(mel)
|
| 315 |
+
|
| 316 |
+
if len(mel.shape) < 3:
|
| 317 |
+
mel = mel.unsqueeze(0)
|
| 318 |
+
|
| 319 |
+
if self.split:
|
| 320 |
+
frames_per_seg = math.ceil(self.segment_size / self.hop_size)
|
| 321 |
+
|
| 322 |
+
if audio.size(1) >= self.segment_size:
|
| 323 |
+
mel_start = random.randint(0, mel.size(2) - frames_per_seg - 1)
|
| 324 |
+
mel = mel[:, :, mel_start : mel_start + frames_per_seg]
|
| 325 |
+
audio = audio[
|
| 326 |
+
:,
|
| 327 |
+
mel_start
|
| 328 |
+
* self.hop_size : (mel_start + frames_per_seg)
|
| 329 |
+
* self.hop_size,
|
| 330 |
+
]
|
| 331 |
+
else:
|
| 332 |
+
mel = torch.nn.functional.pad(
|
| 333 |
+
mel, (0, frames_per_seg - mel.size(2)), "constant"
|
| 334 |
+
)
|
| 335 |
+
audio = torch.nn.functional.pad(
|
| 336 |
+
audio, (0, self.segment_size - audio.size(1)), "constant"
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
mel_loss = mel_spectrogram(
|
| 340 |
+
audio,
|
| 341 |
+
self.n_fft,
|
| 342 |
+
self.num_mels,
|
| 343 |
+
self.sampling_rate,
|
| 344 |
+
self.hop_size,
|
| 345 |
+
self.win_size,
|
| 346 |
+
self.fmin,
|
| 347 |
+
self.fmax_loss,
|
| 348 |
+
center=False,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
return (mel.squeeze(), audio.squeeze(0), filename, mel_loss.squeeze())
|
| 352 |
+
|
| 353 |
+
def __len__(self):
|
| 354 |
+
return len(self.audio_files)
|
seed-vc/modules/bigvgan/utils.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
| 2 |
+
# LICENSE is in incl_licenses directory.
|
| 3 |
+
|
| 4 |
+
import glob
|
| 5 |
+
import os
|
| 6 |
+
import matplotlib
|
| 7 |
+
import torch
|
| 8 |
+
from torch.nn.utils import weight_norm
|
| 9 |
+
|
| 10 |
+
matplotlib.use("Agg")
|
| 11 |
+
import matplotlib.pylab as plt
|
| 12 |
+
from .meldataset import MAX_WAV_VALUE
|
| 13 |
+
from scipy.io.wavfile import write
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def plot_spectrogram(spectrogram):
|
| 17 |
+
fig, ax = plt.subplots(figsize=(10, 2))
|
| 18 |
+
im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
|
| 19 |
+
plt.colorbar(im, ax=ax)
|
| 20 |
+
|
| 21 |
+
fig.canvas.draw()
|
| 22 |
+
plt.close()
|
| 23 |
+
|
| 24 |
+
return fig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def plot_spectrogram_clipped(spectrogram, clip_max=2.0):
|
| 28 |
+
fig, ax = plt.subplots(figsize=(10, 2))
|
| 29 |
+
im = ax.imshow(
|
| 30 |
+
spectrogram,
|
| 31 |
+
aspect="auto",
|
| 32 |
+
origin="lower",
|
| 33 |
+
interpolation="none",
|
| 34 |
+
vmin=1e-6,
|
| 35 |
+
vmax=clip_max,
|
| 36 |
+
)
|
| 37 |
+
plt.colorbar(im, ax=ax)
|
| 38 |
+
|
| 39 |
+
fig.canvas.draw()
|
| 40 |
+
plt.close()
|
| 41 |
+
|
| 42 |
+
return fig
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def init_weights(m, mean=0.0, std=0.01):
|
| 46 |
+
classname = m.__class__.__name__
|
| 47 |
+
if classname.find("Conv") != -1:
|
| 48 |
+
m.weight.data.normal_(mean, std)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def apply_weight_norm(m):
|
| 52 |
+
classname = m.__class__.__name__
|
| 53 |
+
if classname.find("Conv") != -1:
|
| 54 |
+
weight_norm(m)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_padding(kernel_size, dilation=1):
|
| 58 |
+
return int((kernel_size * dilation - dilation) / 2)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def load_checkpoint(filepath, device):
|
| 62 |
+
assert os.path.isfile(filepath)
|
| 63 |
+
print(f"Loading '{filepath}'")
|
| 64 |
+
checkpoint_dict = torch.load(filepath, map_location=device)
|
| 65 |
+
print("Complete.")
|
| 66 |
+
return checkpoint_dict
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def save_checkpoint(filepath, obj):
|
| 70 |
+
print(f"Saving checkpoint to {filepath}")
|
| 71 |
+
torch.save(obj, filepath)
|
| 72 |
+
print("Complete.")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def scan_checkpoint(cp_dir, prefix, renamed_file=None):
|
| 76 |
+
# Fallback to original scanning logic first
|
| 77 |
+
pattern = os.path.join(cp_dir, prefix + "????????")
|
| 78 |
+
cp_list = glob.glob(pattern)
|
| 79 |
+
|
| 80 |
+
if len(cp_list) > 0:
|
| 81 |
+
last_checkpoint_path = sorted(cp_list)[-1]
|
| 82 |
+
print(f"[INFO] Resuming from checkpoint: '{last_checkpoint_path}'")
|
| 83 |
+
return last_checkpoint_path
|
| 84 |
+
|
| 85 |
+
# If no pattern-based checkpoints are found, check for renamed file
|
| 86 |
+
if renamed_file:
|
| 87 |
+
renamed_path = os.path.join(cp_dir, renamed_file)
|
| 88 |
+
if os.path.isfile(renamed_path):
|
| 89 |
+
print(f"[INFO] Resuming from renamed checkpoint: '{renamed_file}'")
|
| 90 |
+
return renamed_path
|
| 91 |
+
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def save_audio(audio, path, sr):
|
| 96 |
+
# wav: torch with 1d shape
|
| 97 |
+
audio = audio * MAX_WAV_VALUE
|
| 98 |
+
audio = audio.cpu().numpy().astype("int16")
|
| 99 |
+
write(path, sr, audio)
|
seed-vc/modules/campplus/DTDNN.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 3D-Speaker (https://github.com/alibaba-damo-academy/3D-Speaker). All Rights Reserved.
|
| 2 |
+
# Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
| 3 |
+
|
| 4 |
+
from collections import OrderedDict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
from modules.campplus.layers import DenseLayer, StatsPool, TDNNLayer, CAMDenseTDNNBlock, TransitLayer, BasicResBlock, get_nonlinear
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class FCM(nn.Module):
|
| 14 |
+
def __init__(self,
|
| 15 |
+
block=BasicResBlock,
|
| 16 |
+
num_blocks=[2, 2],
|
| 17 |
+
m_channels=32,
|
| 18 |
+
feat_dim=80):
|
| 19 |
+
super(FCM, self).__init__()
|
| 20 |
+
self.in_planes = m_channels
|
| 21 |
+
self.conv1 = nn.Conv2d(1, m_channels, kernel_size=3, stride=1, padding=1, bias=False)
|
| 22 |
+
self.bn1 = nn.BatchNorm2d(m_channels)
|
| 23 |
+
|
| 24 |
+
self.layer1 = self._make_layer(block, m_channels, num_blocks[0], stride=2)
|
| 25 |
+
self.layer2 = self._make_layer(block, m_channels, num_blocks[1], stride=2)
|
| 26 |
+
|
| 27 |
+
self.conv2 = nn.Conv2d(m_channels, m_channels, kernel_size=3, stride=(2, 1), padding=1, bias=False)
|
| 28 |
+
self.bn2 = nn.BatchNorm2d(m_channels)
|
| 29 |
+
self.out_channels = m_channels * (feat_dim // 8)
|
| 30 |
+
|
| 31 |
+
def _make_layer(self, block, planes, num_blocks, stride):
|
| 32 |
+
strides = [stride] + [1] * (num_blocks - 1)
|
| 33 |
+
layers = []
|
| 34 |
+
for stride in strides:
|
| 35 |
+
layers.append(block(self.in_planes, planes, stride))
|
| 36 |
+
self.in_planes = planes * block.expansion
|
| 37 |
+
return nn.Sequential(*layers)
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
x = x.unsqueeze(1)
|
| 41 |
+
out = F.relu(self.bn1(self.conv1(x)))
|
| 42 |
+
out = self.layer1(out)
|
| 43 |
+
out = self.layer2(out)
|
| 44 |
+
out = F.relu(self.bn2(self.conv2(out)))
|
| 45 |
+
|
| 46 |
+
shape = out.shape
|
| 47 |
+
out = out.reshape(shape[0], shape[1]*shape[2], shape[3])
|
| 48 |
+
return out
|
| 49 |
+
|
| 50 |
+
class CAMPPlus(nn.Module):
|
| 51 |
+
def __init__(self,
|
| 52 |
+
feat_dim=80,
|
| 53 |
+
embedding_size=512,
|
| 54 |
+
growth_rate=32,
|
| 55 |
+
bn_size=4,
|
| 56 |
+
init_channels=128,
|
| 57 |
+
config_str='batchnorm-relu',
|
| 58 |
+
memory_efficient=True):
|
| 59 |
+
super(CAMPPlus, self).__init__()
|
| 60 |
+
|
| 61 |
+
self.head = FCM(feat_dim=feat_dim)
|
| 62 |
+
channels = self.head.out_channels
|
| 63 |
+
|
| 64 |
+
self.xvector = nn.Sequential(
|
| 65 |
+
OrderedDict([
|
| 66 |
+
|
| 67 |
+
('tdnn',
|
| 68 |
+
TDNNLayer(channels,
|
| 69 |
+
init_channels,
|
| 70 |
+
5,
|
| 71 |
+
stride=2,
|
| 72 |
+
dilation=1,
|
| 73 |
+
padding=-1,
|
| 74 |
+
config_str=config_str)),
|
| 75 |
+
]))
|
| 76 |
+
channels = init_channels
|
| 77 |
+
for i, (num_layers, kernel_size,
|
| 78 |
+
dilation) in enumerate(zip((12, 24, 16), (3, 3, 3), (1, 2, 2))):
|
| 79 |
+
block = CAMDenseTDNNBlock(num_layers=num_layers,
|
| 80 |
+
in_channels=channels,
|
| 81 |
+
out_channels=growth_rate,
|
| 82 |
+
bn_channels=bn_size * growth_rate,
|
| 83 |
+
kernel_size=kernel_size,
|
| 84 |
+
dilation=dilation,
|
| 85 |
+
config_str=config_str,
|
| 86 |
+
memory_efficient=memory_efficient)
|
| 87 |
+
self.xvector.add_module('block%d' % (i + 1), block)
|
| 88 |
+
channels = channels + num_layers * growth_rate
|
| 89 |
+
self.xvector.add_module(
|
| 90 |
+
'transit%d' % (i + 1),
|
| 91 |
+
TransitLayer(channels,
|
| 92 |
+
channels // 2,
|
| 93 |
+
bias=False,
|
| 94 |
+
config_str=config_str))
|
| 95 |
+
channels //= 2
|
| 96 |
+
|
| 97 |
+
self.xvector.add_module(
|
| 98 |
+
'out_nonlinear', get_nonlinear(config_str, channels))
|
| 99 |
+
|
| 100 |
+
# self.xvector.add_module('stats', StatsPool())
|
| 101 |
+
# self.xvector.add_module(
|
| 102 |
+
# 'dense',
|
| 103 |
+
# DenseLayer(channels * 2, embedding_size, config_str='batchnorm_'))
|
| 104 |
+
self.stats = StatsPool()
|
| 105 |
+
self.dense = DenseLayer(channels * 2, embedding_size, config_str='batchnorm_')
|
| 106 |
+
|
| 107 |
+
for m in self.modules():
|
| 108 |
+
if isinstance(m, (nn.Conv1d, nn.Linear)):
|
| 109 |
+
nn.init.kaiming_normal_(m.weight.data)
|
| 110 |
+
if m.bias is not None:
|
| 111 |
+
nn.init.zeros_(m.bias)
|
| 112 |
+
|
| 113 |
+
def load_state_dict(self, state_dict, strict=True):
|
| 114 |
+
"""
|
| 115 |
+
Custom load_state_dict that remaps keys from a previous version of the model where
|
| 116 |
+
stats and dense layers were part of xvector.
|
| 117 |
+
"""
|
| 118 |
+
new_state_dict = {}
|
| 119 |
+
|
| 120 |
+
# Remap keys for compatibility
|
| 121 |
+
for key in state_dict.keys():
|
| 122 |
+
new_key = key
|
| 123 |
+
if key.startswith('xvector.stats'):
|
| 124 |
+
new_key = key.replace('xvector.stats', 'stats')
|
| 125 |
+
elif key.startswith('xvector.dense'):
|
| 126 |
+
new_key = key.replace('xvector.dense', 'dense')
|
| 127 |
+
new_state_dict[new_key] = state_dict[key]
|
| 128 |
+
|
| 129 |
+
# Call the original load_state_dict with the modified state_dict
|
| 130 |
+
super(CAMPPlus, self).load_state_dict(new_state_dict, strict)
|
| 131 |
+
|
| 132 |
+
def forward(self, x, x_lens=None):
|
| 133 |
+
x = x.permute(0, 2, 1) # (B,T,F) => (B,F,T)
|
| 134 |
+
x = self.head(x)
|
| 135 |
+
x = self.xvector(x)
|
| 136 |
+
x = self.stats(x, x_lens)
|
| 137 |
+
x = self.dense(x)
|
| 138 |
+
return x
|
seed-vc/modules/campplus/classifier.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 3D-Speaker (https://github.com/alibaba-damo-academy/3D-Speaker). All Rights Reserved.
|
| 2 |
+
# Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from modules.campplus.layers import DenseLayer
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CosineClassifier(nn.Module):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
input_dim,
|
| 15 |
+
num_blocks=0,
|
| 16 |
+
inter_dim=512,
|
| 17 |
+
out_neurons=1000,
|
| 18 |
+
):
|
| 19 |
+
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.blocks = nn.ModuleList()
|
| 22 |
+
|
| 23 |
+
for index in range(num_blocks):
|
| 24 |
+
self.blocks.append(
|
| 25 |
+
DenseLayer(input_dim, inter_dim, config_str='batchnorm')
|
| 26 |
+
)
|
| 27 |
+
input_dim = inter_dim
|
| 28 |
+
|
| 29 |
+
self.weight = nn.Parameter(
|
| 30 |
+
torch.FloatTensor(out_neurons, input_dim)
|
| 31 |
+
)
|
| 32 |
+
nn.init.xavier_uniform_(self.weight)
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
# x: [B, dim]
|
| 36 |
+
for layer in self.blocks:
|
| 37 |
+
x = layer(x)
|
| 38 |
+
|
| 39 |
+
# normalized
|
| 40 |
+
x = F.linear(F.normalize(x), F.normalize(self.weight))
|
| 41 |
+
return x
|
| 42 |
+
|
| 43 |
+
class LinearClassifier(nn.Module):
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
input_dim,
|
| 47 |
+
num_blocks=0,
|
| 48 |
+
inter_dim=512,
|
| 49 |
+
out_neurons=1000,
|
| 50 |
+
):
|
| 51 |
+
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.blocks = nn.ModuleList()
|
| 54 |
+
|
| 55 |
+
self.nonlinear = nn.ReLU(inplace=True)
|
| 56 |
+
for index in range(num_blocks):
|
| 57 |
+
self.blocks.append(
|
| 58 |
+
DenseLayer(input_dim, inter_dim, bias=True)
|
| 59 |
+
)
|
| 60 |
+
input_dim = inter_dim
|
| 61 |
+
|
| 62 |
+
self.linear = nn.Linear(input_dim, out_neurons, bias=True)
|
| 63 |
+
|
| 64 |
+
def forward(self, x):
|
| 65 |
+
# x: [B, dim]
|
| 66 |
+
x = self.nonlinear(x)
|
| 67 |
+
for layer in self.blocks:
|
| 68 |
+
x = layer(x)
|
| 69 |
+
x = self.linear(x)
|
| 70 |
+
return x
|